sqlite3.c
Go to the documentation of this file.
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.15.2. By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit. This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately. Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite. To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library. (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file. Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 /************** Begin file sqliteInt.h ***************************************/
26 /*
27 ** 2001 September 15
28 **
29 ** The author disclaims copyright to this source code. In place of
30 ** a legal notice, here is a blessing:
31 **
32 ** May you do good and not evil.
33 ** May you find forgiveness for yourself and forgive others.
34 ** May you share freely, never taking more than you give.
35 **
36 *************************************************************************
37 ** Internal interface definitions for SQLite.
38 **
39 */
40 #ifndef SQLITEINT_H
41 #define SQLITEINT_H
42 
43 /* Special Comments:
44 **
45 ** Some comments have special meaning to the tools that measure test
46 ** coverage:
47 **
48 ** NO_TEST - The branches on this line are not
49 ** measured by branch coverage. This is
50 ** used on lines of code that actually
51 ** implement parts of coverage testing.
52 **
53 ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
54 ** and the correct answer is still obtained,
55 ** though perhaps more slowly.
56 **
57 ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
58 ** and the correct answer is still obtained,
59 ** though perhaps more slowly.
60 **
61 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
62 ** that would be harmless and undetectable
63 ** if it did occur.
64 **
65 ** In all cases, the special comment must be enclosed in the usual
66 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
67 ** asterisks and the comment text.
68 */
69 
70 /*
71 ** Make sure the Tcl calling convention macro is defined. This macro is
72 ** only used by test code and Tcl integration code.
73 */
74 #ifndef SQLITE_TCLAPI
75 # define SQLITE_TCLAPI
76 #endif
77 
78 /*
79 ** Make sure that rand_s() is available on Windows systems with MSVC 2005
80 ** or higher.
81 */
82 #if defined(_MSC_VER) && _MSC_VER>=1400
83 # define _CRT_RAND_S
84 #endif
85 
86 /*
87 ** Include the header file used to customize the compiler options for MSVC.
88 ** This should be done first so that it can successfully prevent spurious
89 ** compiler warnings due to subsequent content in this file and other files
90 ** that are included by this file.
91 */
92 /************** Include msvc.h in the middle of sqliteInt.h ******************/
93 /************** Begin file msvc.h ********************************************/
94 /*
95 ** 2015 January 12
96 **
97 ** The author disclaims copyright to this source code. In place of
98 ** a legal notice, here is a blessing:
99 **
100 ** May you do good and not evil.
101 ** May you find forgiveness for yourself and forgive others.
102 ** May you share freely, never taking more than you give.
103 **
104 ******************************************************************************
105 **
106 ** This file contains code that is specific to MSVC.
107 */
108 #ifndef SQLITE_MSVC_H
109 #define SQLITE_MSVC_H
110 
111 #if defined(_MSC_VER)
112 #pragma warning(disable : 4054)
113 #pragma warning(disable : 4055)
114 #pragma warning(disable : 4100)
115 #pragma warning(disable : 4127)
116 #pragma warning(disable : 4130)
117 #pragma warning(disable : 4152)
118 #pragma warning(disable : 4189)
119 #pragma warning(disable : 4206)
120 #pragma warning(disable : 4210)
121 #pragma warning(disable : 4232)
122 #pragma warning(disable : 4244)
123 #pragma warning(disable : 4305)
124 #pragma warning(disable : 4306)
125 #pragma warning(disable : 4702)
126 #pragma warning(disable : 4706)
127 #endif /* defined(_MSC_VER) */
128 
129 #endif /* SQLITE_MSVC_H */
130 
131 /************** End of msvc.h ************************************************/
132 /************** Continuing where we left off in sqliteInt.h ******************/
133 
134 /*
135 ** Special setup for VxWorks
136 */
137 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
138 /************** Begin file vxworks.h *****************************************/
139 /*
140 ** 2015-03-02
141 **
142 ** The author disclaims copyright to this source code. In place of
143 ** a legal notice, here is a blessing:
144 **
145 ** May you do good and not evil.
146 ** May you find forgiveness for yourself and forgive others.
147 ** May you share freely, never taking more than you give.
148 **
149 ******************************************************************************
150 **
151 ** This file contains code that is specific to Wind River's VxWorks
152 */
153 #if defined(__RTP__) || defined(_WRS_KERNEL)
154 /* This is VxWorks. Set up things specially for that OS
155 */
156 #include <vxWorks.h>
157 #include <pthread.h> /* amalgamator: dontcache */
158 #define OS_VXWORKS 1
159 #define SQLITE_OS_OTHER 0
160 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
161 #define SQLITE_OMIT_LOAD_EXTENSION 1
162 #define SQLITE_ENABLE_LOCKING_STYLE 0
163 #define HAVE_UTIME 1
164 #else
165 /* This is not VxWorks. */
166 #define OS_VXWORKS 0
167 #define HAVE_FCHOWN 1
168 #define HAVE_READLINK 1
169 #define HAVE_LSTAT 1
170 #endif /* defined(_WRS_KERNEL) */
171 
172 /************** End of vxworks.h *********************************************/
173 /************** Continuing where we left off in sqliteInt.h ******************/
174 
175 /*
176 ** These #defines should enable >2GB file support on POSIX if the
177 ** underlying operating system supports it. If the OS lacks
178 ** large file support, or if the OS is windows, these should be no-ops.
179 **
180 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
181 ** system #includes. Hence, this block of code must be the very first
182 ** code in all source files.
183 **
184 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
185 ** on the compiler command line. This is necessary if you are compiling
186 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
187 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
188 ** without this option, LFS is enable. But LFS does not exist in the kernel
189 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
190 ** portability you should omit LFS.
191 **
192 ** The previous paragraph was written in 2005. (This paragraph is written
193 ** on 2008-11-28.) These days, all Linux kernels support large files, so
194 ** you should probably leave LFS enabled. But some embedded platforms might
195 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
196 **
197 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
198 */
199 #ifndef SQLITE_DISABLE_LFS
200 # define _LARGE_FILE 1
201 # ifndef _FILE_OFFSET_BITS
202 # define _FILE_OFFSET_BITS 64
203 # endif
204 # define _LARGEFILE_SOURCE 1
205 #endif
206 
207 /* What version of GCC is being used. 0 means GCC is not being used */
208 #ifdef __GNUC__
209 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
210 #else
211 # define GCC_VERSION 0
212 #endif
213 
214 /* Needed for various definitions... */
215 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
216 # define _GNU_SOURCE
217 #endif
218 
219 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
220 # define _BSD_SOURCE
221 #endif
222 
223 /*
224 ** For MinGW, check to see if we can include the header file containing its
225 ** version information, among other things. Normally, this internal MinGW
226 ** header file would [only] be included automatically by other MinGW header
227 ** files; however, the contained version information is now required by this
228 ** header file to work around binary compatibility issues (see below) and
229 ** this is the only known way to reliably obtain it. This entire #if block
230 ** would be completely unnecessary if there was any other way of detecting
231 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
232 ** some MinGW-specific macros). When compiling for MinGW, either the
233 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
234 ** defined; otherwise, detection of conditions specific to MinGW will be
235 ** disabled.
236 */
237 #if defined(_HAVE_MINGW_H)
238 # include "mingw.h"
239 #elif defined(_HAVE__MINGW_H)
240 # include "_mingw.h"
241 #endif
242 
243 /*
244 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
245 ** define is required to maintain binary compatibility with the MSVC runtime
246 ** library in use (e.g. for Windows XP).
247 */
248 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
249  defined(_WIN32) && !defined(_WIN64) && \
250  defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
251  defined(__MSVCRT__)
252 # define _USE_32BIT_TIME_T
253 #endif
254 
255 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
256 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
257 ** MinGW.
258 */
259 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
260 /************** Begin file sqlite3.h *****************************************/
261 /*
262 ** 2001 September 15
263 **
264 ** The author disclaims copyright to this source code. In place of
265 ** a legal notice, here is a blessing:
266 **
267 ** May you do good and not evil.
268 ** May you find forgiveness for yourself and forgive others.
269 ** May you share freely, never taking more than you give.
270 **
271 *************************************************************************
272 ** This header file defines the interface that the SQLite library
273 ** presents to client programs. If a C-function, structure, datatype,
274 ** or constant definition does not appear in this file, then it is
275 ** not a published API of SQLite, is subject to change without
276 ** notice, and should not be referenced by programs that use SQLite.
277 **
278 ** Some of the definitions that are in this file are marked as
279 ** "experimental". Experimental interfaces are normally new
280 ** features recently added to SQLite. We do not anticipate changes
281 ** to experimental interfaces but reserve the right to make minor changes
282 ** if experience from use "in the wild" suggest such changes are prudent.
283 **
284 ** The official C-language API documentation for SQLite is derived
285 ** from comments in this file. This file is the authoritative source
286 ** on how SQLite interfaces are supposed to operate.
287 **
288 ** The name of this file under configuration management is "sqlite.h.in".
289 ** The makefile makes some minor changes to this file (such as inserting
290 ** the version number) and changes its name to "sqlite3.h" as
291 ** part of the build process.
292 */
293 #ifndef SQLITE3_H
294 #define SQLITE3_H
295 #include <stdarg.h> /* Needed for the definition of va_list */
296 
297 /*
298 ** Make sure we can call this stuff from C++.
299 */
300 #if 0
301 extern "C" {
302 #endif
303 
304 
305 /*
306 ** Provide the ability to override linkage features of the interface.
307 */
308 #ifndef SQLITE_EXTERN
309 # define SQLITE_EXTERN extern
310 #endif
311 #ifndef SQLITE_API
312 # define SQLITE_API
313 #endif
314 #ifndef SQLITE_CDECL
315 # define SQLITE_CDECL
316 #endif
317 #ifndef SQLITE_APICALL
318 # define SQLITE_APICALL
319 #endif
320 #ifndef SQLITE_STDCALL
321 # define SQLITE_STDCALL SQLITE_APICALL
322 #endif
323 #ifndef SQLITE_CALLBACK
324 # define SQLITE_CALLBACK
325 #endif
326 #ifndef SQLITE_SYSAPI
327 # define SQLITE_SYSAPI
328 #endif
329 
330 /*
331 ** These no-op macros are used in front of interfaces to mark those
332 ** interfaces as either deprecated or experimental. New applications
333 ** should not use deprecated interfaces - they are supported for backwards
334 ** compatibility only. Application writers should be aware that
335 ** experimental interfaces are subject to change in point releases.
336 **
337 ** These macros used to resolve to various kinds of compiler magic that
338 ** would generate warning messages when they were used. But that
339 ** compiler magic ended up generating such a flurry of bug reports
340 ** that we have taken it all out and gone back to using simple
341 ** noop macros.
342 */
343 #define SQLITE_DEPRECATED
344 #define SQLITE_EXPERIMENTAL
345 
346 /*
347 ** Ensure these symbols were not defined by some previous header file.
348 */
349 #ifdef SQLITE_VERSION
350 # undef SQLITE_VERSION
351 #endif
352 #ifdef SQLITE_VERSION_NUMBER
353 # undef SQLITE_VERSION_NUMBER
354 #endif
355 
356 /*
357 ** CAPI3REF: Compile-Time Library Version Numbers
358 **
359 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
360 ** evaluates to a string literal that is the SQLite version in the
361 ** format "X.Y.Z" where X is the major version number (always 3 for
362 ** SQLite3) and Y is the minor version number and Z is the release number.)^
363 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
364 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
365 ** numbers used in [SQLITE_VERSION].)^
366 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
367 ** be larger than the release from which it is derived. Either Y will
368 ** be held constant and Z will be incremented or else Y will be incremented
369 ** and Z will be reset to zero.
370 **
371 ** Since [version 3.6.18] ([dateof:3.6.18]),
372 ** SQLite source code has been stored in the
373 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
374 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
375 ** a string which identifies a particular check-in of SQLite
376 ** within its configuration management system. ^The SQLITE_SOURCE_ID
377 ** string contains the date and time of the check-in (UTC) and an SHA1
378 ** hash of the entire source tree.
379 **
380 ** See also: [sqlite3_libversion()],
381 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
382 ** [sqlite_version()] and [sqlite_source_id()].
383 */
384 #define SQLITE_VERSION "3.15.2"
385 #define SQLITE_VERSION_NUMBER 3015002
386 #define SQLITE_SOURCE_ID "2016-11-28 19:13:37 bbd85d235f7037c6a033a9690534391ffeacecc8"
387 
388 /*
389 ** CAPI3REF: Run-Time Library Version Numbers
390 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
391 **
392 ** These interfaces provide the same information as the [SQLITE_VERSION],
393 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
394 ** but are associated with the library instead of the header file. ^(Cautious
395 ** programmers might include assert() statements in their application to
396 ** verify that values returned by these interfaces match the macros in
397 ** the header, and thus ensure that the application is
398 ** compiled with matching library and header files.
399 **
400 ** <blockquote><pre>
401 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
402 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
403 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
404 ** </pre></blockquote>)^
405 **
406 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
407 ** macro. ^The sqlite3_libversion() function returns a pointer to the
408 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
409 ** function is provided for use in DLLs since DLL users usually do not have
410 ** direct access to string constants within the DLL. ^The
411 ** sqlite3_libversion_number() function returns an integer equal to
412 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
413 ** a pointer to a string constant whose value is the same as the
414 ** [SQLITE_SOURCE_ID] C preprocessor macro.
415 **
416 ** See also: [sqlite_version()] and [sqlite_source_id()].
417 */
419 SQLITE_API const char *sqlite3_libversion(void);
420 SQLITE_API const char *sqlite3_sourceid(void);
422 
423 /*
424 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
425 **
426 ** ^The sqlite3_compileoption_used() function returns 0 or 1
427 ** indicating whether the specified option was defined at
428 ** compile time. ^The SQLITE_ prefix may be omitted from the
429 ** option name passed to sqlite3_compileoption_used().
430 **
431 ** ^The sqlite3_compileoption_get() function allows iterating
432 ** over the list of options that were defined at compile time by
433 ** returning the N-th compile time option string. ^If N is out of range,
434 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
435 ** prefix is omitted from any strings returned by
436 ** sqlite3_compileoption_get().
437 **
438 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
439 ** and sqlite3_compileoption_get() may be omitted by specifying the
440 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
441 **
442 ** See also: SQL functions [sqlite_compileoption_used()] and
443 ** [sqlite_compileoption_get()] and the [compile_options pragma].
444 */
445 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
446 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
447 SQLITE_API const char *sqlite3_compileoption_get(int N);
448 #endif
449 
450 /*
451 ** CAPI3REF: Test To See If The Library Is Threadsafe
452 **
453 ** ^The sqlite3_threadsafe() function returns zero if and only if
454 ** SQLite was compiled with mutexing code omitted due to the
455 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
456 **
457 ** SQLite can be compiled with or without mutexes. When
458 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
459 ** are enabled and SQLite is threadsafe. When the
460 ** [SQLITE_THREADSAFE] macro is 0,
461 ** the mutexes are omitted. Without the mutexes, it is not safe
462 ** to use SQLite concurrently from more than one thread.
463 **
464 ** Enabling mutexes incurs a measurable performance penalty.
465 ** So if speed is of utmost importance, it makes sense to disable
466 ** the mutexes. But for maximum safety, mutexes should be enabled.
467 ** ^The default behavior is for mutexes to be enabled.
468 **
469 ** This interface can be used by an application to make sure that the
470 ** version of SQLite that it is linking against was compiled with
471 ** the desired setting of the [SQLITE_THREADSAFE] macro.
472 **
473 ** This interface only reports on the compile-time mutex setting
474 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
475 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
476 ** can be fully or partially disabled using a call to [sqlite3_config()]
477 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
478 ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
479 ** sqlite3_threadsafe() function shows only the compile-time setting of
480 ** thread safety, not any run-time changes to that setting made by
481 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
482 ** is unchanged by calls to sqlite3_config().)^
483 **
484 ** See the [threading mode] documentation for additional information.
485 */
487 
488 /*
489 ** CAPI3REF: Database Connection Handle
490 ** KEYWORDS: {database connection} {database connections}
491 **
492 ** Each open SQLite database is represented by a pointer to an instance of
493 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
494 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
495 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
496 ** and [sqlite3_close_v2()] are its destructors. There are many other
497 ** interfaces (such as
498 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
499 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
500 ** sqlite3 object.
501 */
502 typedef struct sqlite3 sqlite3;
503 
504 /*
505 ** CAPI3REF: 64-Bit Integer Types
506 ** KEYWORDS: sqlite_int64 sqlite_uint64
507 **
508 ** Because there is no cross-platform way to specify 64-bit integer types
509 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
510 **
511 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
512 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
513 ** compatibility only.
514 **
515 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
516 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
517 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
518 ** between 0 and +18446744073709551615 inclusive.
519 */
520 #ifdef SQLITE_INT64_TYPE
521  typedef SQLITE_INT64_TYPE sqlite_int64;
522  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
523 #elif defined(_MSC_VER) || defined(__BORLANDC__)
524  typedef __int64 sqlite_int64;
525  typedef unsigned __int64 sqlite_uint64;
526 #else
527  typedef long long int sqlite_int64;
528  typedef unsigned long long int sqlite_uint64;
529 #endif
530 typedef sqlite_int64 sqlite3_int64;
531 typedef sqlite_uint64 sqlite3_uint64;
532 
533 /*
534 ** If compiling for a processor that lacks floating point support,
535 ** substitute integer for floating-point.
536 */
537 #ifdef SQLITE_OMIT_FLOATING_POINT
538 # define double sqlite3_int64
539 #endif
540 
541 /*
542 ** CAPI3REF: Closing A Database Connection
543 ** DESTRUCTOR: sqlite3
544 **
545 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
546 ** for the [sqlite3] object.
547 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
548 ** the [sqlite3] object is successfully destroyed and all associated
549 ** resources are deallocated.
550 **
551 ** ^If the database connection is associated with unfinalized prepared
552 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
553 ** will leave the database connection open and return [SQLITE_BUSY].
554 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
555 ** and/or unfinished sqlite3_backups, then the database connection becomes
556 ** an unusable "zombie" which will automatically be deallocated when the
557 ** last prepared statement is finalized or the last sqlite3_backup is
558 ** finished. The sqlite3_close_v2() interface is intended for use with
559 ** host languages that are garbage collected, and where the order in which
560 ** destructors are called is arbitrary.
561 **
562 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
563 ** [sqlite3_blob_close | close] all [BLOB handles], and
564 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
565 ** with the [sqlite3] object prior to attempting to close the object. ^If
566 ** sqlite3_close_v2() is called on a [database connection] that still has
567 ** outstanding [prepared statements], [BLOB handles], and/or
568 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
569 ** of resources is deferred until all [prepared statements], [BLOB handles],
570 ** and [sqlite3_backup] objects are also destroyed.
571 **
572 ** ^If an [sqlite3] object is destroyed while a transaction is open,
573 ** the transaction is automatically rolled back.
574 **
575 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
576 ** must be either a NULL
577 ** pointer or an [sqlite3] object pointer obtained
578 ** from [sqlite3_open()], [sqlite3_open16()], or
579 ** [sqlite3_open_v2()], and not previously closed.
580 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
581 ** argument is a harmless no-op.
582 */
585 
586 /*
587 ** The type for a callback function.
588 ** This is legacy and deprecated. It is included for historical
589 ** compatibility and is not documented.
590 */
591 typedef int (*sqlite3_callback)(void*,int,char**, char**);
592 
593 /*
594 ** CAPI3REF: One-Step Query Execution Interface
595 ** METHOD: sqlite3
596 **
597 ** The sqlite3_exec() interface is a convenience wrapper around
598 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
599 ** that allows an application to run multiple statements of SQL
600 ** without having to use a lot of C code.
601 **
602 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
603 ** semicolon-separate SQL statements passed into its 2nd argument,
604 ** in the context of the [database connection] passed in as its 1st
605 ** argument. ^If the callback function of the 3rd argument to
606 ** sqlite3_exec() is not NULL, then it is invoked for each result row
607 ** coming out of the evaluated SQL statements. ^The 4th argument to
608 ** sqlite3_exec() is relayed through to the 1st argument of each
609 ** callback invocation. ^If the callback pointer to sqlite3_exec()
610 ** is NULL, then no callback is ever invoked and result rows are
611 ** ignored.
612 **
613 ** ^If an error occurs while evaluating the SQL statements passed into
614 ** sqlite3_exec(), then execution of the current statement stops and
615 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
616 ** is not NULL then any error message is written into memory obtained
617 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
618 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
619 ** on error message strings returned through the 5th parameter of
620 ** sqlite3_exec() after the error message string is no longer needed.
621 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
622 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
623 ** NULL before returning.
624 **
625 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
626 ** routine returns SQLITE_ABORT without invoking the callback again and
627 ** without running any subsequent SQL statements.
628 **
629 ** ^The 2nd argument to the sqlite3_exec() callback function is the
630 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
631 ** callback is an array of pointers to strings obtained as if from
632 ** [sqlite3_column_text()], one for each column. ^If an element of a
633 ** result row is NULL then the corresponding string pointer for the
634 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
635 ** sqlite3_exec() callback is an array of pointers to strings where each
636 ** entry represents the name of corresponding result column as obtained
637 ** from [sqlite3_column_name()].
638 **
639 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
640 ** to an empty string, or a pointer that contains only whitespace and/or
641 ** SQL comments, then no SQL statements are evaluated and the database
642 ** is not changed.
643 **
644 ** Restrictions:
645 **
646 ** <ul>
647 ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
648 ** is a valid and open [database connection].
649 ** <li> The application must not close the [database connection] specified by
650 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
651 ** <li> The application must not modify the SQL statement text passed into
652 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
653 ** </ul>
654 */
656  sqlite3*, /* An open database */
657  const char *sql, /* SQL to be evaluated */
658  int (*callback)(void*,int,char**,char**), /* Callback function */
659  void *, /* 1st argument to callback */
660  char **errmsg /* Error msg written here */
661 );
662 
663 /*
664 ** CAPI3REF: Result Codes
665 ** KEYWORDS: {result code definitions}
666 **
667 ** Many SQLite functions return an integer result code from the set shown
668 ** here in order to indicate success or failure.
669 **
670 ** New error codes may be added in future versions of SQLite.
671 **
672 ** See also: [extended result code definitions]
673 */
674 #define SQLITE_OK 0 /* Successful result */
675 /* beginning-of-error-codes */
676 #define SQLITE_ERROR 1 /* SQL error or missing database */
677 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
678 #define SQLITE_PERM 3 /* Access permission denied */
679 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
680 #define SQLITE_BUSY 5 /* The database file is locked */
681 #define SQLITE_LOCKED 6 /* A table in the database is locked */
682 #define SQLITE_NOMEM 7 /* A malloc() failed */
683 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
684 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
685 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
686 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
687 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
688 #define SQLITE_FULL 13 /* Insertion failed because database is full */
689 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
690 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
691 #define SQLITE_EMPTY 16 /* Database is empty */
692 #define SQLITE_SCHEMA 17 /* The database schema changed */
693 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
694 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
695 #define SQLITE_MISMATCH 20 /* Data type mismatch */
696 #define SQLITE_MISUSE 21 /* Library used incorrectly */
697 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
698 #define SQLITE_AUTH 23 /* Authorization denied */
699 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
700 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
701 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
702 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
703 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
704 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
705 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
706 /* end-of-error-codes */
707 
708 /*
709 ** CAPI3REF: Extended Result Codes
710 ** KEYWORDS: {extended result code definitions}
711 **
712 ** In its default configuration, SQLite API routines return one of 30 integer
713 ** [result codes]. However, experience has shown that many of
714 ** these result codes are too coarse-grained. They do not provide as
715 ** much information about problems as programmers might like. In an effort to
716 ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
717 ** and later) include
718 ** support for additional result codes that provide more detailed information
719 ** about errors. These [extended result codes] are enabled or disabled
720 ** on a per database connection basis using the
721 ** [sqlite3_extended_result_codes()] API. Or, the extended code for
722 ** the most recent error can be obtained using
723 ** [sqlite3_extended_errcode()].
724 */
725 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
726 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
727 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
728 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
729 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
730 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
731 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
732 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
733 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
734 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
735 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
736 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
737 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
738 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
739 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
740 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
741 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
742 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
743 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
744 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
745 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
746 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
747 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
748 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
749 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
750 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
751 #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
752 #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
753 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
754 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
755 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
756 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
757 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
758 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
759 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
760 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
761 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
762 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
763 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
764 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
765 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
766 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
767 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
768 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
769 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
770 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
771 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
772 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
773 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
774 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
775 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
776 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
777 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
778 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
779 #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
780 #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
781 
782 /*
783 ** CAPI3REF: Flags For File Open Operations
784 **
785 ** These bit values are intended for use in the
786 ** 3rd parameter to the [sqlite3_open_v2()] interface and
787 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
788 */
789 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
790 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
791 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
792 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
793 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
794 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
795 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
796 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
797 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
798 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
799 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
800 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
801 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
802 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
803 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
804 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
805 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
806 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
807 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
808 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
809 
810 /* Reserved: 0x00F00000 */
811 
812 /*
813 ** CAPI3REF: Device Characteristics
814 **
815 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
816 ** object returns an integer which is a vector of these
817 ** bit values expressing I/O characteristics of the mass storage
818 ** device that holds the file that the [sqlite3_io_methods]
819 ** refers to.
820 **
821 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
822 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
823 ** mean that writes of blocks that are nnn bytes in size and
824 ** are aligned to an address which is an integer multiple of
825 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
826 ** that when data is appended to a file, the data is appended
827 ** first then the size of the file is extended, never the other
828 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
829 ** information is written to disk in the same order as calls
830 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
831 ** after reboot following a crash or power loss, the only bytes in a
832 ** file that were written at the application level might have changed
833 ** and that adjacent bytes, even bytes within the same sector are
834 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
835 ** flag indicate that a file cannot be deleted when open. The
836 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
837 ** read-only media and cannot be changed even by processes with
838 ** elevated privileges.
839 */
840 #define SQLITE_IOCAP_ATOMIC 0x00000001
841 #define SQLITE_IOCAP_ATOMIC512 0x00000002
842 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
843 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
844 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
845 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
846 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
847 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
848 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
849 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
850 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
851 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
852 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
853 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
854 
855 /*
856 ** CAPI3REF: File Locking Levels
857 **
858 ** SQLite uses one of these integer values as the second
859 ** argument to calls it makes to the xLock() and xUnlock() methods
860 ** of an [sqlite3_io_methods] object.
861 */
862 #define SQLITE_LOCK_NONE 0
863 #define SQLITE_LOCK_SHARED 1
864 #define SQLITE_LOCK_RESERVED 2
865 #define SQLITE_LOCK_PENDING 3
866 #define SQLITE_LOCK_EXCLUSIVE 4
867 
868 /*
869 ** CAPI3REF: Synchronization Type Flags
870 **
871 ** When SQLite invokes the xSync() method of an
872 ** [sqlite3_io_methods] object it uses a combination of
873 ** these integer values as the second argument.
874 **
875 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
876 ** sync operation only needs to flush data to mass storage. Inode
877 ** information need not be flushed. If the lower four bits of the flag
878 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
879 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
880 ** to use Mac OS X style fullsync instead of fsync().
881 **
882 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
883 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
884 ** settings. The [synchronous pragma] determines when calls to the
885 ** xSync VFS method occur and applies uniformly across all platforms.
886 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
887 ** energetic or rigorous or forceful the sync operations are and
888 ** only make a difference on Mac OSX for the default SQLite code.
889 ** (Third-party VFS implementations might also make the distinction
890 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
891 ** operating systems natively supported by SQLite, only Mac OSX
892 ** cares about the difference.)
893 */
894 #define SQLITE_SYNC_NORMAL 0x00002
895 #define SQLITE_SYNC_FULL 0x00003
896 #define SQLITE_SYNC_DATAONLY 0x00010
897 
898 /*
899 ** CAPI3REF: OS Interface Open File Handle
900 **
901 ** An [sqlite3_file] object represents an open file in the
902 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
903 ** implementations will
904 ** want to subclass this object by appending additional fields
905 ** for their own use. The pMethods entry is a pointer to an
906 ** [sqlite3_io_methods] object that defines methods for performing
907 ** I/O operations on the open file.
908 */
909 typedef struct sqlite3_file sqlite3_file;
910 struct sqlite3_file {
911  const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
912 };
913 
914 /*
915 ** CAPI3REF: OS Interface File Virtual Methods Object
916 **
917 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
918 ** [sqlite3_file] object (or, more commonly, a subclass of the
919 ** [sqlite3_file] object) with a pointer to an instance of this object.
920 ** This object defines the methods used to perform various operations
921 ** against the open file represented by the [sqlite3_file] object.
922 **
923 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
924 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
925 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
926 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
927 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
928 ** to NULL.
929 **
930 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
931 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
932 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
933 ** flag may be ORed in to indicate that only the data of the file
934 ** and not its inode needs to be synced.
935 **
936 ** The integer values to xLock() and xUnlock() are one of
937 ** <ul>
938 ** <li> [SQLITE_LOCK_NONE],
939 ** <li> [SQLITE_LOCK_SHARED],
940 ** <li> [SQLITE_LOCK_RESERVED],
941 ** <li> [SQLITE_LOCK_PENDING], or
942 ** <li> [SQLITE_LOCK_EXCLUSIVE].
943 ** </ul>
944 ** xLock() increases the lock. xUnlock() decreases the lock.
945 ** The xCheckReservedLock() method checks whether any database connection,
946 ** either in this process or in some other process, is holding a RESERVED,
947 ** PENDING, or EXCLUSIVE lock on the file. It returns true
948 ** if such a lock exists and false otherwise.
949 **
950 ** The xFileControl() method is a generic interface that allows custom
951 ** VFS implementations to directly control an open file using the
952 ** [sqlite3_file_control()] interface. The second "op" argument is an
953 ** integer opcode. The third argument is a generic pointer intended to
954 ** point to a structure that may contain arguments or space in which to
955 ** write return values. Potential uses for xFileControl() might be
956 ** functions to enable blocking locks with timeouts, to change the
957 ** locking strategy (for example to use dot-file locks), to inquire
958 ** about the status of a lock, or to break stale locks. The SQLite
959 ** core reserves all opcodes less than 100 for its own use.
960 ** A [file control opcodes | list of opcodes] less than 100 is available.
961 ** Applications that define a custom xFileControl method should use opcodes
962 ** greater than 100 to avoid conflicts. VFS implementations should
963 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
964 ** recognize.
965 **
966 ** The xSectorSize() method returns the sector size of the
967 ** device that underlies the file. The sector size is the
968 ** minimum write that can be performed without disturbing
969 ** other bytes in the file. The xDeviceCharacteristics()
970 ** method returns a bit vector describing behaviors of the
971 ** underlying device:
972 **
973 ** <ul>
974 ** <li> [SQLITE_IOCAP_ATOMIC]
975 ** <li> [SQLITE_IOCAP_ATOMIC512]
976 ** <li> [SQLITE_IOCAP_ATOMIC1K]
977 ** <li> [SQLITE_IOCAP_ATOMIC2K]
978 ** <li> [SQLITE_IOCAP_ATOMIC4K]
979 ** <li> [SQLITE_IOCAP_ATOMIC8K]
980 ** <li> [SQLITE_IOCAP_ATOMIC16K]
981 ** <li> [SQLITE_IOCAP_ATOMIC32K]
982 ** <li> [SQLITE_IOCAP_ATOMIC64K]
983 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
984 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
985 ** </ul>
986 **
987 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
988 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
989 ** mean that writes of blocks that are nnn bytes in size and
990 ** are aligned to an address which is an integer multiple of
991 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
992 ** that when data is appended to a file, the data is appended
993 ** first then the size of the file is extended, never the other
994 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
995 ** information is written to disk in the same order as calls
996 ** to xWrite().
997 **
998 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
999 ** in the unread portions of the buffer with zeros. A VFS that
1000 ** fails to zero-fill short reads might seem to work. However,
1001 ** failure to zero-fill short reads will eventually lead to
1002 ** database corruption.
1003 */
1007  int (*xClose)(sqlite3_file*);
1008  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1009  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1010  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1011  int (*xSync)(sqlite3_file*, int flags);
1012  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1013  int (*xLock)(sqlite3_file*, int);
1014  int (*xUnlock)(sqlite3_file*, int);
1015  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1016  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1017  int (*xSectorSize)(sqlite3_file*);
1018  int (*xDeviceCharacteristics)(sqlite3_file*);
1019  /* Methods above are valid for version 1 */
1020  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1021  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1022  void (*xShmBarrier)(sqlite3_file*);
1023  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1024  /* Methods above are valid for version 2 */
1025  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1026  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1027  /* Methods above are valid for version 3 */
1028  /* Additional methods may be added in future releases */
1029 };
1030 
1031 /*
1032 ** CAPI3REF: Standard File Control Opcodes
1033 ** KEYWORDS: {file control opcodes} {file control opcode}
1034 **
1035 ** These integer constants are opcodes for the xFileControl method
1036 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1037 ** interface.
1038 **
1039 ** <ul>
1040 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1041 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1042 ** opcode causes the xFileControl method to write the current state of
1043 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1044 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1045 ** into an integer that the pArg argument points to. This capability
1046 ** is used during testing and is only available when the SQLITE_TEST
1047 ** compile-time option is used.
1048 **
1049 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1050 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1051 ** layer a hint of how large the database file will grow to be during the
1052 ** current transaction. This hint is not guaranteed to be accurate but it
1053 ** is often close. The underlying VFS might choose to preallocate database
1054 ** file space based on this hint in order to help writes to the database
1055 ** file run faster.
1056 **
1057 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1058 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1059 ** extends and truncates the database file in chunks of a size specified
1060 ** by the user. The fourth argument to [sqlite3_file_control()] should
1061 ** point to an integer (type int) containing the new chunk-size to use
1062 ** for the nominated database. Allocating database file space in large
1063 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1064 ** improve performance on some systems.
1065 **
1066 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1067 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1068 ** to the [sqlite3_file] object associated with a particular database
1069 ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1070 **
1071 ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1072 ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1073 ** to the [sqlite3_file] object associated with the journal file (either
1074 ** the [rollback journal] or the [write-ahead log]) for a particular database
1075 ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1076 **
1077 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1078 ** No longer in use.
1079 **
1080 ** <li>[[SQLITE_FCNTL_SYNC]]
1081 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1082 ** sent to the VFS immediately before the xSync method is invoked on a
1083 ** database file descriptor. Or, if the xSync method is not invoked
1084 ** because the user has configured SQLite with
1085 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1086 ** of the xSync method. In most cases, the pointer argument passed with
1087 ** this file-control is NULL. However, if the database file is being synced
1088 ** as part of a multi-database commit, the argument points to a nul-terminated
1089 ** string containing the transactions master-journal file name. VFSes that
1090 ** do not need this signal should silently ignore this opcode. Applications
1091 ** should not call [sqlite3_file_control()] with this opcode as doing so may
1092 ** disrupt the operation of the specialized VFSes that do require it.
1093 **
1094 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1095 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1096 ** and sent to the VFS after a transaction has been committed immediately
1097 ** but before the database is unlocked. VFSes that do not need this signal
1098 ** should silently ignore this opcode. Applications should not call
1099 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1100 ** operation of the specialized VFSes that do require it.
1101 **
1102 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1103 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1104 ** retry counts and intervals for certain disk I/O operations for the
1105 ** windows [VFS] in order to provide robustness in the presence of
1106 ** anti-virus programs. By default, the windows VFS will retry file read,
1107 ** file write, and file delete operations up to 10 times, with a delay
1108 ** of 25 milliseconds before the first retry and with the delay increasing
1109 ** by an additional 25 milliseconds with each subsequent retry. This
1110 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1111 ** to be adjusted. The values are changed for all database connections
1112 ** within the same process. The argument is a pointer to an array of two
1113 ** integers where the first integer i the new retry count and the second
1114 ** integer is the delay. If either integer is negative, then the setting
1115 ** is not changed but instead the prior value of that setting is written
1116 ** into the array entry, allowing the current retry settings to be
1117 ** interrogated. The zDbName parameter is ignored.
1118 **
1119 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1120 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1121 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1122 ** write ahead log and shared memory files used for transaction control
1123 ** are automatically deleted when the latest connection to the database
1124 ** closes. Setting persistent WAL mode causes those files to persist after
1125 ** close. Persisting the files is useful when other processes that do not
1126 ** have write permission on the directory containing the database file want
1127 ** to read the database file, as the WAL and shared memory files must exist
1128 ** in order for the database to be readable. The fourth parameter to
1129 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1130 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1131 ** WAL mode. If the integer is -1, then it is overwritten with the current
1132 ** WAL persistence setting.
1133 **
1134 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1135 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1136 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1137 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1138 ** xDeviceCharacteristics methods. The fourth parameter to
1139 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1140 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1141 ** mode. If the integer is -1, then it is overwritten with the current
1142 ** zero-damage mode setting.
1143 **
1144 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1145 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1146 ** a write transaction to indicate that, unless it is rolled back for some
1147 ** reason, the entire database file will be overwritten by the current
1148 ** transaction. This is used by VACUUM operations.
1149 **
1150 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1151 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1152 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1153 ** final bottom-level VFS are written into memory obtained from
1154 ** [sqlite3_malloc()] and the result is stored in the char* variable
1155 ** that the fourth parameter of [sqlite3_file_control()] points to.
1156 ** The caller is responsible for freeing the memory when done. As with
1157 ** all file-control actions, there is no guarantee that this will actually
1158 ** do anything. Callers should initialize the char* variable to a NULL
1159 ** pointer in case this file-control is not implemented. This file-control
1160 ** is intended for diagnostic use only.
1161 **
1162 ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1163 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1164 ** [VFSes] currently in use. ^(The argument X in
1165 ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1166 ** of type "[sqlite3_vfs] **". This opcodes will set *X
1167 ** to a pointer to the top-level VFS.)^
1168 ** ^When there are multiple VFS shims in the stack, this opcode finds the
1169 ** upper-most shim only.
1170 **
1171 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1172 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1173 ** file control is sent to the open [sqlite3_file] object corresponding
1174 ** to the database file to which the pragma statement refers. ^The argument
1175 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1176 ** pointers to strings (char**) in which the second element of the array
1177 ** is the name of the pragma and the third element is the argument to the
1178 ** pragma or NULL if the pragma has no argument. ^The handler for an
1179 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1180 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1181 ** or the equivalent and that string will become the result of the pragma or
1182 ** the error message if the pragma fails. ^If the
1183 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1184 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1185 ** file control returns [SQLITE_OK], then the parser assumes that the
1186 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1187 ** prepared statement if result string is NULL, or that returns a copy
1188 ** of the result string if the string is non-NULL.
1189 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1190 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1191 ** that the VFS encountered an error while handling the [PRAGMA] and the
1192 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1193 ** file control occurs at the beginning of pragma statement analysis and so
1194 ** it is able to override built-in [PRAGMA] statements.
1195 **
1196 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1197 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1198 ** file-control may be invoked by SQLite on the database file handle
1199 ** shortly after it is opened in order to provide a custom VFS with access
1200 ** to the connections busy-handler callback. The argument is of type (void **)
1201 ** - an array of two (void *) values. The first (void *) actually points
1202 ** to a function of type (int (*)(void *)). In order to invoke the connections
1203 ** busy-handler, this function should be invoked with the second (void *) in
1204 ** the array as the only argument. If it returns non-zero, then the operation
1205 ** should be retried. If it returns zero, the custom VFS should abandon the
1206 ** current operation.
1207 **
1208 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1209 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1210 ** to have SQLite generate a
1211 ** temporary filename using the same algorithm that is followed to generate
1212 ** temporary filenames for TEMP tables and other internal uses. The
1213 ** argument should be a char** which will be filled with the filename
1214 ** written into memory obtained from [sqlite3_malloc()]. The caller should
1215 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1216 **
1217 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1218 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1219 ** maximum number of bytes that will be used for memory-mapped I/O.
1220 ** The argument is a pointer to a value of type sqlite3_int64 that
1221 ** is an advisory maximum number of bytes in the file to memory map. The
1222 ** pointer is overwritten with the old value. The limit is not changed if
1223 ** the value originally pointed to is negative, and so the current limit
1224 ** can be queried by passing in a pointer to a negative number. This
1225 ** file-control is used internally to implement [PRAGMA mmap_size].
1226 **
1227 ** <li>[[SQLITE_FCNTL_TRACE]]
1228 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1229 ** to the VFS about what the higher layers of the SQLite stack are doing.
1230 ** This file control is used by some VFS activity tracing [shims].
1231 ** The argument is a zero-terminated string. Higher layers in the
1232 ** SQLite stack may generate instances of this file control if
1233 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1234 **
1235 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1236 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1237 ** pointer to an integer and it writes a boolean into that integer depending
1238 ** on whether or not the file has been renamed, moved, or deleted since it
1239 ** was first opened.
1240 **
1241 ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
1242 ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
1243 ** underlying native file handle associated with a file handle. This file
1244 ** control interprets its argument as a pointer to a native file handle and
1245 ** writes the resulting value there.
1246 **
1247 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1248 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1249 ** opcode causes the xFileControl method to swap the file handle with the one
1250 ** pointed to by the pArg argument. This capability is used during testing
1251 ** and only needs to be supported when SQLITE_TEST is defined.
1252 **
1253 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1254 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1255 ** be advantageous to block on the next WAL lock if the lock is not immediately
1256 ** available. The WAL subsystem issues this signal during rare
1257 ** circumstances in order to fix a problem with priority inversion.
1258 ** Applications should <em>not</em> use this file-control.
1259 **
1260 ** <li>[[SQLITE_FCNTL_ZIPVFS]]
1261 ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1262 ** VFS should return SQLITE_NOTFOUND for this opcode.
1263 **
1264 ** <li>[[SQLITE_FCNTL_RBU]]
1265 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1266 ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1267 ** this opcode.
1268 ** </ul>
1269 */
1270 #define SQLITE_FCNTL_LOCKSTATE 1
1271 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1272 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1273 #define SQLITE_FCNTL_LAST_ERRNO 4
1274 #define SQLITE_FCNTL_SIZE_HINT 5
1275 #define SQLITE_FCNTL_CHUNK_SIZE 6
1276 #define SQLITE_FCNTL_FILE_POINTER 7
1277 #define SQLITE_FCNTL_SYNC_OMITTED 8
1278 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1279 #define SQLITE_FCNTL_PERSIST_WAL 10
1280 #define SQLITE_FCNTL_OVERWRITE 11
1281 #define SQLITE_FCNTL_VFSNAME 12
1282 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1283 #define SQLITE_FCNTL_PRAGMA 14
1284 #define SQLITE_FCNTL_BUSYHANDLER 15
1285 #define SQLITE_FCNTL_TEMPFILENAME 16
1286 #define SQLITE_FCNTL_MMAP_SIZE 18
1287 #define SQLITE_FCNTL_TRACE 19
1288 #define SQLITE_FCNTL_HAS_MOVED 20
1289 #define SQLITE_FCNTL_SYNC 21
1290 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
1291 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1292 #define SQLITE_FCNTL_WAL_BLOCK 24
1293 #define SQLITE_FCNTL_ZIPVFS 25
1294 #define SQLITE_FCNTL_RBU 26
1295 #define SQLITE_FCNTL_VFS_POINTER 27
1296 #define SQLITE_FCNTL_JOURNAL_POINTER 28
1297 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
1298 
1299 /* deprecated names */
1300 #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1301 #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1302 #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1303 
1304 
1305 /*
1306 ** CAPI3REF: Mutex Handle
1307 **
1308 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1309 ** abstract type for a mutex object. The SQLite core never looks
1310 ** at the internal representation of an [sqlite3_mutex]. It only
1311 ** deals with pointers to the [sqlite3_mutex] object.
1312 **
1313 ** Mutexes are created using [sqlite3_mutex_alloc()].
1314 */
1316 
1317 /*
1318 ** CAPI3REF: Loadable Extension Thunk
1319 **
1320 ** A pointer to the opaque sqlite3_api_routines structure is passed as
1321 ** the third parameter to entry points of [loadable extensions]. This
1322 ** structure must be typedefed in order to work around compiler warnings
1323 ** on some platforms.
1324 */
1326 
1327 /*
1328 ** CAPI3REF: OS Interface Object
1329 **
1330 ** An instance of the sqlite3_vfs object defines the interface between
1331 ** the SQLite core and the underlying operating system. The "vfs"
1332 ** in the name of the object stands for "virtual file system". See
1333 ** the [VFS | VFS documentation] for further information.
1334 **
1335 ** The value of the iVersion field is initially 1 but may be larger in
1336 ** future versions of SQLite. Additional fields may be appended to this
1337 ** object when the iVersion value is increased. Note that the structure
1338 ** of the sqlite3_vfs object changes in the transaction between
1339 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1340 ** modified.
1341 **
1342 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1343 ** structure used by this VFS. mxPathname is the maximum length of
1344 ** a pathname in this VFS.
1345 **
1346 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1347 ** the pNext pointer. The [sqlite3_vfs_register()]
1348 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1349 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1350 ** searches the list. Neither the application code nor the VFS
1351 ** implementation should use the pNext pointer.
1352 **
1353 ** The pNext field is the only field in the sqlite3_vfs
1354 ** structure that SQLite will ever modify. SQLite will only access
1355 ** or modify this field while holding a particular static mutex.
1356 ** The application should never modify anything within the sqlite3_vfs
1357 ** object once the object has been registered.
1358 **
1359 ** The zName field holds the name of the VFS module. The name must
1360 ** be unique across all VFS modules.
1361 **
1362 ** [[sqlite3_vfs.xOpen]]
1363 ** ^SQLite guarantees that the zFilename parameter to xOpen
1364 ** is either a NULL pointer or string obtained
1365 ** from xFullPathname() with an optional suffix added.
1366 ** ^If a suffix is added to the zFilename parameter, it will
1367 ** consist of a single "-" character followed by no more than
1368 ** 11 alphanumeric and/or "-" characters.
1369 ** ^SQLite further guarantees that
1370 ** the string will be valid and unchanged until xClose() is
1371 ** called. Because of the previous sentence,
1372 ** the [sqlite3_file] can safely store a pointer to the
1373 ** filename if it needs to remember the filename for some reason.
1374 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1375 ** must invent its own temporary name for the file. ^Whenever the
1376 ** xFilename parameter is NULL it will also be the case that the
1377 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1378 **
1379 ** The flags argument to xOpen() includes all bits set in
1380 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1381 ** or [sqlite3_open16()] is used, then flags includes at least
1382 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1383 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1384 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1385 **
1386 ** ^(SQLite will also add one of the following flags to the xOpen()
1387 ** call, depending on the object being opened:
1388 **
1389 ** <ul>
1390 ** <li> [SQLITE_OPEN_MAIN_DB]
1391 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1392 ** <li> [SQLITE_OPEN_TEMP_DB]
1393 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1394 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1395 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1396 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1397 ** <li> [SQLITE_OPEN_WAL]
1398 ** </ul>)^
1399 **
1400 ** The file I/O implementation can use the object type flags to
1401 ** change the way it deals with files. For example, an application
1402 ** that does not care about crash recovery or rollback might make
1403 ** the open of a journal file a no-op. Writes to this journal would
1404 ** also be no-ops, and any attempt to read the journal would return
1405 ** SQLITE_IOERR. Or the implementation might recognize that a database
1406 ** file will be doing page-aligned sector reads and writes in a random
1407 ** order and set up its I/O subsystem accordingly.
1408 **
1409 ** SQLite might also add one of the following flags to the xOpen method:
1410 **
1411 ** <ul>
1412 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1413 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1414 ** </ul>
1415 **
1416 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1417 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1418 ** will be set for TEMP databases and their journals, transient
1419 ** databases, and subjournals.
1420 **
1421 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1422 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1423 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1424 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1425 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1426 ** be created, and that it is an error if it already exists.
1427 ** It is <i>not</i> used to indicate the file should be opened
1428 ** for exclusive access.
1429 **
1430 ** ^At least szOsFile bytes of memory are allocated by SQLite
1431 ** to hold the [sqlite3_file] structure passed as the third
1432 ** argument to xOpen. The xOpen method does not have to
1433 ** allocate the structure; it should just fill it in. Note that
1434 ** the xOpen method must set the sqlite3_file.pMethods to either
1435 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1436 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1437 ** element will be valid after xOpen returns regardless of the success
1438 ** or failure of the xOpen call.
1439 **
1440 ** [[sqlite3_vfs.xAccess]]
1441 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1442 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1443 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1444 ** to test whether a file is at least readable. The file can be a
1445 ** directory.
1446 **
1447 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1448 ** output buffer xFullPathname. The exact size of the output buffer
1449 ** is also passed as a parameter to both methods. If the output buffer
1450 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1451 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1452 ** to prevent this by setting mxPathname to a sufficiently large value.
1453 **
1454 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1455 ** interfaces are not strictly a part of the filesystem, but they are
1456 ** included in the VFS structure for completeness.
1457 ** The xRandomness() function attempts to return nBytes bytes
1458 ** of good-quality randomness into zOut. The return value is
1459 ** the actual number of bytes of randomness obtained.
1460 ** The xSleep() method causes the calling thread to sleep for at
1461 ** least the number of microseconds given. ^The xCurrentTime()
1462 ** method returns a Julian Day Number for the current date and time as
1463 ** a floating point value.
1464 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1465 ** Day Number multiplied by 86400000 (the number of milliseconds in
1466 ** a 24-hour day).
1467 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1468 ** date and time if that method is available (if iVersion is 2 or
1469 ** greater and the function pointer is not NULL) and will fall back
1470 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1471 **
1472 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1473 ** are not used by the SQLite core. These optional interfaces are provided
1474 ** by some VFSes to facilitate testing of the VFS code. By overriding
1475 ** system calls with functions under its control, a test program can
1476 ** simulate faults and error conditions that would otherwise be difficult
1477 ** or impossible to induce. The set of system calls that can be overridden
1478 ** varies from one VFS to another, and from one version of the same VFS to the
1479 ** next. Applications that use these interfaces must be prepared for any
1480 ** or all of these interfaces to be NULL or for their behavior to change
1481 ** from one release to the next. Applications must not attempt to access
1482 ** any of these methods if the iVersion of the VFS is less than 3.
1483 */
1484 typedef struct sqlite3_vfs sqlite3_vfs;
1485 typedef void (*sqlite3_syscall_ptr)(void);
1486 struct sqlite3_vfs {
1487  int iVersion; /* Structure version number (currently 3) */
1488  int szOsFile; /* Size of subclassed sqlite3_file */
1489  int mxPathname; /* Maximum file pathname length */
1490  sqlite3_vfs *pNext; /* Next registered VFS */
1491  const char *zName; /* Name of this virtual file system */
1492  void *pAppData; /* Pointer to application-specific data */
1493  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1494  int flags, int *pOutFlags);
1495  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1496  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1497  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1498  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1499  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1500  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1501  void (*xDlClose)(sqlite3_vfs*, void*);
1502  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1503  int (*xSleep)(sqlite3_vfs*, int microseconds);
1504  int (*xCurrentTime)(sqlite3_vfs*, double*);
1505  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1506  /*
1507  ** The methods above are in version 1 of the sqlite_vfs object
1508  ** definition. Those that follow are added in version 2 or later
1509  */
1510  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1511  /*
1512  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1513  ** Those below are for version 3 and greater.
1514  */
1515  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1516  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1517  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1518  /*
1519  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1520  ** New fields may be appended in future versions. The iVersion
1521  ** value will increment whenever this happens.
1522  */
1523 };
1524 
1525 /*
1526 ** CAPI3REF: Flags for the xAccess VFS method
1527 **
1528 ** These integer constants can be used as the third parameter to
1529 ** the xAccess method of an [sqlite3_vfs] object. They determine
1530 ** what kind of permissions the xAccess method is looking for.
1531 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1532 ** simply checks whether the file exists.
1533 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1534 ** checks whether the named directory is both readable and writable
1535 ** (in other words, if files can be added, removed, and renamed within
1536 ** the directory).
1537 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1538 ** [temp_store_directory pragma], though this could change in a future
1539 ** release of SQLite.
1540 ** With SQLITE_ACCESS_READ, the xAccess method
1541 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1542 ** currently unused, though it might be used in a future release of
1543 ** SQLite.
1544 */
1545 #define SQLITE_ACCESS_EXISTS 0
1546 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1547 #define SQLITE_ACCESS_READ 2 /* Unused */
1548 
1549 /*
1550 ** CAPI3REF: Flags for the xShmLock VFS method
1551 **
1552 ** These integer constants define the various locking operations
1553 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1554 ** following are the only legal combinations of flags to the
1555 ** xShmLock method:
1556 **
1557 ** <ul>
1558 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1559 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1560 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1561 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1562 ** </ul>
1563 **
1564 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1565 ** was given on the corresponding lock.
1566 **
1567 ** The xShmLock method can transition between unlocked and SHARED or
1568 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1569 ** and EXCLUSIVE.
1570 */
1571 #define SQLITE_SHM_UNLOCK 1
1572 #define SQLITE_SHM_LOCK 2
1573 #define SQLITE_SHM_SHARED 4
1574 #define SQLITE_SHM_EXCLUSIVE 8
1575 
1576 /*
1577 ** CAPI3REF: Maximum xShmLock index
1578 **
1579 ** The xShmLock method on [sqlite3_io_methods] may use values
1580 ** between 0 and this upper bound as its "offset" argument.
1581 ** The SQLite core will never attempt to acquire or release a
1582 ** lock outside of this range
1583 */
1584 #define SQLITE_SHM_NLOCK 8
1585 
1586 
1587 /*
1588 ** CAPI3REF: Initialize The SQLite Library
1589 **
1590 ** ^The sqlite3_initialize() routine initializes the
1591 ** SQLite library. ^The sqlite3_shutdown() routine
1592 ** deallocates any resources that were allocated by sqlite3_initialize().
1593 ** These routines are designed to aid in process initialization and
1594 ** shutdown on embedded systems. Workstation applications using
1595 ** SQLite normally do not need to invoke either of these routines.
1596 **
1597 ** A call to sqlite3_initialize() is an "effective" call if it is
1598 ** the first time sqlite3_initialize() is invoked during the lifetime of
1599 ** the process, or if it is the first time sqlite3_initialize() is invoked
1600 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1601 ** of sqlite3_initialize() does any initialization. All other calls
1602 ** are harmless no-ops.)^
1603 **
1604 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1605 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1606 ** an effective call to sqlite3_shutdown() does any deinitialization.
1607 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1608 **
1609 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1610 ** is not. The sqlite3_shutdown() interface must only be called from a
1611 ** single thread. All open [database connections] must be closed and all
1612 ** other SQLite resources must be deallocated prior to invoking
1613 ** sqlite3_shutdown().
1614 **
1615 ** Among other things, ^sqlite3_initialize() will invoke
1616 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1617 ** will invoke sqlite3_os_end().
1618 **
1619 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1620 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1621 ** the library (perhaps it is unable to allocate a needed resource such
1622 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1623 **
1624 ** ^The sqlite3_initialize() routine is called internally by many other
1625 ** SQLite interfaces so that an application usually does not need to
1626 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1627 ** calls sqlite3_initialize() so the SQLite library will be automatically
1628 ** initialized when [sqlite3_open()] is called if it has not be initialized
1629 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1630 ** compile-time option, then the automatic calls to sqlite3_initialize()
1631 ** are omitted and the application must call sqlite3_initialize() directly
1632 ** prior to using any other SQLite interface. For maximum portability,
1633 ** it is recommended that applications always invoke sqlite3_initialize()
1634 ** directly prior to using any other SQLite interface. Future releases
1635 ** of SQLite may require this. In other words, the behavior exhibited
1636 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1637 ** default behavior in some future release of SQLite.
1638 **
1639 ** The sqlite3_os_init() routine does operating-system specific
1640 ** initialization of the SQLite library. The sqlite3_os_end()
1641 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1642 ** performed by these routines include allocation or deallocation
1643 ** of static resources, initialization of global variables,
1644 ** setting up a default [sqlite3_vfs] module, or setting up
1645 ** a default configuration using [sqlite3_config()].
1646 **
1647 ** The application should never invoke either sqlite3_os_init()
1648 ** or sqlite3_os_end() directly. The application should only invoke
1649 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1650 ** interface is called automatically by sqlite3_initialize() and
1651 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1652 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1653 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1654 ** When [custom builds | built for other platforms]
1655 ** (using the [SQLITE_OS_OTHER=1] compile-time
1656 ** option) the application must supply a suitable implementation for
1657 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1658 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1659 ** must return [SQLITE_OK] on success and some other [error code] upon
1660 ** failure.
1661 */
1662 SQLITE_API int sqlite3_initialize(void);
1663 SQLITE_API int sqlite3_shutdown(void);
1664 SQLITE_API int sqlite3_os_init(void);
1665 SQLITE_API int sqlite3_os_end(void);
1666 
1667 /*
1668 ** CAPI3REF: Configuring The SQLite Library
1669 **
1670 ** The sqlite3_config() interface is used to make global configuration
1671 ** changes to SQLite in order to tune SQLite to the specific needs of
1672 ** the application. The default configuration is recommended for most
1673 ** applications and so this routine is usually not necessary. It is
1674 ** provided to support rare applications with unusual needs.
1675 **
1676 ** <b>The sqlite3_config() interface is not threadsafe. The application
1677 ** must ensure that no other SQLite interfaces are invoked by other
1678 ** threads while sqlite3_config() is running.</b>
1679 **
1680 ** The sqlite3_config() interface
1681 ** may only be invoked prior to library initialization using
1682 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1683 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1684 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1685 ** Note, however, that ^sqlite3_config() can be called as part of the
1686 ** implementation of an application-defined [sqlite3_os_init()].
1687 **
1688 ** The first argument to sqlite3_config() is an integer
1689 ** [configuration option] that determines
1690 ** what property of SQLite is to be configured. Subsequent arguments
1691 ** vary depending on the [configuration option]
1692 ** in the first argument.
1693 **
1694 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1695 ** ^If the option is unknown or SQLite is unable to set the option
1696 ** then this routine returns a non-zero [error code].
1697 */
1698 SQLITE_API int sqlite3_config(int, ...);
1699 
1700 /*
1701 ** CAPI3REF: Configure database connections
1702 ** METHOD: sqlite3
1703 **
1704 ** The sqlite3_db_config() interface is used to make configuration
1705 ** changes to a [database connection]. The interface is similar to
1706 ** [sqlite3_config()] except that the changes apply to a single
1707 ** [database connection] (specified in the first argument).
1708 **
1709 ** The second argument to sqlite3_db_config(D,V,...) is the
1710 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1711 ** that indicates what aspect of the [database connection] is being configured.
1712 ** Subsequent arguments vary depending on the configuration verb.
1713 **
1714 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1715 ** the call is considered successful.
1716 */
1717 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1718 
1719 /*
1720 ** CAPI3REF: Memory Allocation Routines
1721 **
1722 ** An instance of this object defines the interface between SQLite
1723 ** and low-level memory allocation routines.
1724 **
1725 ** This object is used in only one place in the SQLite interface.
1726 ** A pointer to an instance of this object is the argument to
1727 ** [sqlite3_config()] when the configuration option is
1728 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1729 ** By creating an instance of this object
1730 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1731 ** during configuration, an application can specify an alternative
1732 ** memory allocation subsystem for SQLite to use for all of its
1733 ** dynamic memory needs.
1734 **
1735 ** Note that SQLite comes with several [built-in memory allocators]
1736 ** that are perfectly adequate for the overwhelming majority of applications
1737 ** and that this object is only useful to a tiny minority of applications
1738 ** with specialized memory allocation requirements. This object is
1739 ** also used during testing of SQLite in order to specify an alternative
1740 ** memory allocator that simulates memory out-of-memory conditions in
1741 ** order to verify that SQLite recovers gracefully from such
1742 ** conditions.
1743 **
1744 ** The xMalloc, xRealloc, and xFree methods must work like the
1745 ** malloc(), realloc() and free() functions from the standard C library.
1746 ** ^SQLite guarantees that the second argument to
1747 ** xRealloc is always a value returned by a prior call to xRoundup.
1748 **
1749 ** xSize should return the allocated size of a memory allocation
1750 ** previously obtained from xMalloc or xRealloc. The allocated size
1751 ** is always at least as big as the requested size but may be larger.
1752 **
1753 ** The xRoundup method returns what would be the allocated size of
1754 ** a memory allocation given a particular requested size. Most memory
1755 ** allocators round up memory allocations at least to the next multiple
1756 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1757 ** Every memory allocation request coming in through [sqlite3_malloc()]
1758 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1759 ** that causes the corresponding memory allocation to fail.
1760 **
1761 ** The xInit method initializes the memory allocator. For example,
1762 ** it might allocate any require mutexes or initialize internal data
1763 ** structures. The xShutdown method is invoked (indirectly) by
1764 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1765 ** by xInit. The pAppData pointer is used as the only parameter to
1766 ** xInit and xShutdown.
1767 **
1768 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1769 ** the xInit method, so the xInit method need not be threadsafe. The
1770 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1771 ** not need to be threadsafe either. For all other methods, SQLite
1772 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1773 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1774 ** it is by default) and so the methods are automatically serialized.
1775 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1776 ** methods must be threadsafe or else make their own arrangements for
1777 ** serialization.
1778 **
1779 ** SQLite will never invoke xInit() more than once without an intervening
1780 ** call to xShutdown().
1781 */
1784  void *(*xMalloc)(int); /* Memory allocation function */
1785  void (*xFree)(void*); /* Free a prior allocation */
1786  void *(*xRealloc)(void*,int); /* Resize an allocation */
1787  int (*xSize)(void*); /* Return the size of an allocation */
1788  int (*xRoundup)(int); /* Round up request size to allocation size */
1789  int (*xInit)(void*); /* Initialize the memory allocator */
1790  void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1791  void *pAppData; /* Argument to xInit() and xShutdown() */
1792 };
1793 
1794 /*
1795 ** CAPI3REF: Configuration Options
1796 ** KEYWORDS: {configuration option}
1797 **
1798 ** These constants are the available integer configuration options that
1799 ** can be passed as the first argument to the [sqlite3_config()] interface.
1800 **
1801 ** New configuration options may be added in future releases of SQLite.
1802 ** Existing configuration options might be discontinued. Applications
1803 ** should check the return code from [sqlite3_config()] to make sure that
1804 ** the call worked. The [sqlite3_config()] interface will return a
1805 ** non-zero [error code] if a discontinued or unsupported configuration option
1806 ** is invoked.
1807 **
1808 ** <dl>
1809 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1810 ** <dd>There are no arguments to this option. ^This option sets the
1811 ** [threading mode] to Single-thread. In other words, it disables
1812 ** all mutexing and puts SQLite into a mode where it can only be used
1813 ** by a single thread. ^If SQLite is compiled with
1814 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1815 ** it is not possible to change the [threading mode] from its default
1816 ** value of Single-thread and so [sqlite3_config()] will return
1817 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1818 ** configuration option.</dd>
1819 **
1820 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1821 ** <dd>There are no arguments to this option. ^This option sets the
1822 ** [threading mode] to Multi-thread. In other words, it disables
1823 ** mutexing on [database connection] and [prepared statement] objects.
1824 ** The application is responsible for serializing access to
1825 ** [database connections] and [prepared statements]. But other mutexes
1826 ** are enabled so that SQLite will be safe to use in a multi-threaded
1827 ** environment as long as no two threads attempt to use the same
1828 ** [database connection] at the same time. ^If SQLite is compiled with
1829 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1830 ** it is not possible to set the Multi-thread [threading mode] and
1831 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1832 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1833 **
1834 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1835 ** <dd>There are no arguments to this option. ^This option sets the
1836 ** [threading mode] to Serialized. In other words, this option enables
1837 ** all mutexes including the recursive
1838 ** mutexes on [database connection] and [prepared statement] objects.
1839 ** In this mode (which is the default when SQLite is compiled with
1840 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1841 ** to [database connections] and [prepared statements] so that the
1842 ** application is free to use the same [database connection] or the
1843 ** same [prepared statement] in different threads at the same time.
1844 ** ^If SQLite is compiled with
1845 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1846 ** it is not possible to set the Serialized [threading mode] and
1847 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1848 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1849 **
1850 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1851 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1852 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
1853 ** The argument specifies
1854 ** alternative low-level memory allocation routines to be used in place of
1855 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1856 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1857 ** before the [sqlite3_config()] call returns.</dd>
1858 **
1859 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1860 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1861 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1862 ** The [sqlite3_mem_methods]
1863 ** structure is filled with the currently defined memory allocation routines.)^
1864 ** This option can be used to overload the default memory allocation
1865 ** routines with a wrapper that simulations memory allocation failure or
1866 ** tracks memory usage, for example. </dd>
1867 **
1868 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1869 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1870 ** interpreted as a boolean, which enables or disables the collection of
1871 ** memory allocation statistics. ^(When memory allocation statistics are
1872 ** disabled, the following SQLite interfaces become non-operational:
1873 ** <ul>
1874 ** <li> [sqlite3_memory_used()]
1875 ** <li> [sqlite3_memory_highwater()]
1876 ** <li> [sqlite3_soft_heap_limit64()]
1877 ** <li> [sqlite3_status64()]
1878 ** </ul>)^
1879 ** ^Memory allocation statistics are enabled by default unless SQLite is
1880 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1881 ** allocation statistics are disabled by default.
1882 ** </dd>
1883 **
1884 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1885 ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1886 ** that SQLite can use for scratch memory. ^(There are three arguments
1887 ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
1888 ** aligned memory buffer from which the scratch allocations will be
1889 ** drawn, the size of each scratch allocation (sz),
1890 ** and the maximum number of scratch allocations (N).)^
1891 ** The first argument must be a pointer to an 8-byte aligned buffer
1892 ** of at least sz*N bytes of memory.
1893 ** ^SQLite will not use more than one scratch buffers per thread.
1894 ** ^SQLite will never request a scratch buffer that is more than 6
1895 ** times the database page size.
1896 ** ^If SQLite needs needs additional
1897 ** scratch memory beyond what is provided by this configuration option, then
1898 ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1899 ** ^When the application provides any amount of scratch memory using
1900 ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1901 ** [sqlite3_malloc|heap allocations].
1902 ** This can help [Robson proof|prevent memory allocation failures] due to heap
1903 ** fragmentation in low-memory embedded systems.
1904 ** </dd>
1905 **
1906 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1907 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
1908 ** that SQLite can use for the database page cache with the default page
1909 ** cache implementation.
1910 ** This configuration option is a no-op if an application-define page
1911 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
1912 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1913 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
1914 ** and the number of cache lines (N).
1915 ** The sz argument should be the size of the largest database page
1916 ** (a power of two between 512 and 65536) plus some extra bytes for each
1917 ** page header. ^The number of extra bytes needed by the page header
1918 ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
1919 ** ^It is harmless, apart from the wasted memory,
1920 ** for the sz parameter to be larger than necessary. The pMem
1921 ** argument must be either a NULL pointer or a pointer to an 8-byte
1922 ** aligned block of memory of at least sz*N bytes, otherwise
1923 ** subsequent behavior is undefined.
1924 ** ^When pMem is not NULL, SQLite will strive to use the memory provided
1925 ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
1926 ** a page cache line is larger than sz bytes or if all of the pMem buffer
1927 ** is exhausted.
1928 ** ^If pMem is NULL and N is non-zero, then each database connection
1929 ** does an initial bulk allocation for page cache memory
1930 ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
1931 ** of -1024*N bytes if N is negative, . ^If additional
1932 ** page cache memory is needed beyond what is provided by the initial
1933 ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
1934 ** additional cache line. </dd>
1935 **
1936 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1937 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1938 ** that SQLite will use for all of its dynamic memory allocation needs
1939 ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1940 ** [SQLITE_CONFIG_PAGECACHE].
1941 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1942 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1943 ** [SQLITE_ERROR] if invoked otherwise.
1944 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
1945 ** An 8-byte aligned pointer to the memory,
1946 ** the number of bytes in the memory buffer, and the minimum allocation size.
1947 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1948 ** to using its default memory allocator (the system malloc() implementation),
1949 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1950 ** memory pointer is not NULL then the alternative memory
1951 ** allocator is engaged to handle all of SQLites memory allocation needs.
1952 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1953 ** boundary or subsequent behavior of SQLite will be undefined.
1954 ** The minimum allocation size is capped at 2**12. Reasonable values
1955 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1956 **
1957 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1958 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1959 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
1960 ** The argument specifies alternative low-level mutex routines to be used
1961 ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
1962 ** the content of the [sqlite3_mutex_methods] structure before the call to
1963 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1964 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1965 ** the entire mutexing subsystem is omitted from the build and hence calls to
1966 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1967 ** return [SQLITE_ERROR].</dd>
1968 **
1969 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1970 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1971 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
1972 ** [sqlite3_mutex_methods]
1973 ** structure is filled with the currently defined mutex routines.)^
1974 ** This option can be used to overload the default mutex allocation
1975 ** routines with a wrapper used to track mutex usage for performance
1976 ** profiling or testing, for example. ^If SQLite is compiled with
1977 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1978 ** the entire mutexing subsystem is omitted from the build and hence calls to
1979 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1980 ** return [SQLITE_ERROR].</dd>
1981 **
1982 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1983 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1984 ** the default size of lookaside memory on each [database connection].
1985 ** The first argument is the
1986 ** size of each lookaside buffer slot and the second is the number of
1987 ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
1988 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1989 ** option to [sqlite3_db_config()] can be used to change the lookaside
1990 ** configuration on individual connections.)^ </dd>
1991 **
1992 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1993 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
1994 ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
1995 ** the interface to a custom page cache implementation.)^
1996 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1997 **
1998 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1999 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
2000 ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
2001 ** the current page cache implementation into that object.)^ </dd>
2002 **
2003 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2004 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2005 ** global [error log].
2006 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2007 ** function with a call signature of void(*)(void*,int,const char*),
2008 ** and a pointer to void. ^If the function pointer is not NULL, it is
2009 ** invoked by [sqlite3_log()] to process each logging event. ^If the
2010 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2011 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2012 ** passed through as the first parameter to the application-defined logger
2013 ** function whenever that function is invoked. ^The second parameter to
2014 ** the logger function is a copy of the first parameter to the corresponding
2015 ** [sqlite3_log()] call and is intended to be a [result code] or an
2016 ** [extended result code]. ^The third parameter passed to the logger is
2017 ** log message after formatting via [sqlite3_snprintf()].
2018 ** The SQLite logging interface is not reentrant; the logger function
2019 ** supplied by the application must not invoke any SQLite interface.
2020 ** In a multi-threaded application, the application-defined logger
2021 ** function must be threadsafe. </dd>
2022 **
2023 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2024 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
2025 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2026 ** then URI handling is globally disabled.)^ ^If URI handling is globally
2027 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
2028 ** [sqlite3_open16()] or
2029 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2030 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2031 ** connection is opened. ^If it is globally disabled, filenames are
2032 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2033 ** database connection is opened. ^(By default, URI handling is globally
2034 ** disabled. The default value may be changed by compiling with the
2035 ** [SQLITE_USE_URI] symbol defined.)^
2036 **
2037 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2038 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2039 ** argument which is interpreted as a boolean in order to enable or disable
2040 ** the use of covering indices for full table scans in the query optimizer.
2041 ** ^The default setting is determined
2042 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2043 ** if that compile-time option is omitted.
2044 ** The ability to disable the use of covering indices for full table scans
2045 ** is because some incorrectly coded legacy applications might malfunction
2046 ** when the optimization is enabled. Providing the ability to
2047 ** disable the optimization allows the older, buggy application code to work
2048 ** without change even with newer versions of SQLite.
2049 **
2050 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2051 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2052 ** <dd> These options are obsolete and should not be used by new code.
2053 ** They are retained for backwards compatibility but are now no-ops.
2054 ** </dd>
2055 **
2056 ** [[SQLITE_CONFIG_SQLLOG]]
2057 ** <dt>SQLITE_CONFIG_SQLLOG
2058 ** <dd>This option is only available if sqlite is compiled with the
2059 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2060 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2061 ** The second should be of type (void*). The callback is invoked by the library
2062 ** in three separate circumstances, identified by the value passed as the
2063 ** fourth parameter. If the fourth parameter is 0, then the database connection
2064 ** passed as the second argument has just been opened. The third argument
2065 ** points to a buffer containing the name of the main database file. If the
2066 ** fourth parameter is 1, then the SQL statement that the third parameter
2067 ** points to has just been executed. Or, if the fourth parameter is 2, then
2068 ** the connection being passed as the second parameter is being closed. The
2069 ** third parameter is passed NULL In this case. An example of using this
2070 ** configuration option can be seen in the "test_sqllog.c" source file in
2071 ** the canonical SQLite source tree.</dd>
2072 **
2073 ** [[SQLITE_CONFIG_MMAP_SIZE]]
2074 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2075 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2076 ** that are the default mmap size limit (the default setting for
2077 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2078 ** ^The default setting can be overridden by each database connection using
2079 ** either the [PRAGMA mmap_size] command, or by using the
2080 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2081 ** will be silently truncated if necessary so that it does not exceed the
2082 ** compile-time maximum mmap size set by the
2083 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2084 ** ^If either argument to this option is negative, then that argument is
2085 ** changed to its compile-time default.
2086 **
2087 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2088 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2089 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2090 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2091 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2092 ** that specifies the maximum size of the created heap.
2093 **
2094 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2095 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2096 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2097 ** is a pointer to an integer and writes into that integer the number of extra
2098 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2099 ** The amount of extra space required can change depending on the compiler,
2100 ** target platform, and SQLite version.
2101 **
2102 ** [[SQLITE_CONFIG_PMASZ]]
2103 ** <dt>SQLITE_CONFIG_PMASZ
2104 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2105 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2106 ** sorter to that integer. The default minimum PMA Size is set by the
2107 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2108 ** to help with sort operations when multithreaded sorting
2109 ** is enabled (using the [PRAGMA threads] command) and the amount of content
2110 ** to be sorted exceeds the page size times the minimum of the
2111 ** [PRAGMA cache_size] setting and this value.
2112 **
2113 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2114 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2115 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2116 ** becomes the [statement journal] spill-to-disk threshold.
2117 ** [Statement journals] are held in memory until their size (in bytes)
2118 ** exceeds this threshold, at which point they are written to disk.
2119 ** Or if the threshold is -1, statement journals are always held
2120 ** exclusively in memory.
2121 ** Since many statement journals never become large, setting the spill
2122 ** threshold to a value such as 64KiB can greatly reduce the amount of
2123 ** I/O required to support statement rollback.
2124 ** The default value for this setting is controlled by the
2125 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
2126 ** </dl>
2127 */
2128 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2129 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2130 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2131 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2132 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2133 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
2134 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2135 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2136 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2137 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2138 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2139 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2140 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2141 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2142 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2143 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2144 #define SQLITE_CONFIG_URI 17 /* int */
2145 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2146 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2147 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2148 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2149 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2150 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
2151 #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
2152 #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
2153 #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
2154 
2155 /*
2156 ** CAPI3REF: Database Connection Configuration Options
2157 **
2158 ** These constants are the available integer configuration options that
2159 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2160 **
2161 ** New configuration options may be added in future releases of SQLite.
2162 ** Existing configuration options might be discontinued. Applications
2163 ** should check the return code from [sqlite3_db_config()] to make sure that
2164 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2165 ** non-zero [error code] if a discontinued or unsupported configuration option
2166 ** is invoked.
2167 **
2168 ** <dl>
2169 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2170 ** <dd> ^This option takes three additional arguments that determine the
2171 ** [lookaside memory allocator] configuration for the [database connection].
2172 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2173 ** pointer to a memory buffer to use for lookaside memory.
2174 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2175 ** may be NULL in which case SQLite will allocate the
2176 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2177 ** size of each lookaside buffer slot. ^The third argument is the number of
2178 ** slots. The size of the buffer in the first argument must be greater than
2179 ** or equal to the product of the second and third arguments. The buffer
2180 ** must be aligned to an 8-byte boundary. ^If the second argument to
2181 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2182 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2183 ** configuration for a database connection can only be changed when that
2184 ** connection is not currently using lookaside memory, or in other words
2185 ** when the "current value" returned by
2186 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2187 ** Any attempt to change the lookaside memory configuration when lookaside
2188 ** memory is in use leaves the configuration unchanged and returns
2189 ** [SQLITE_BUSY].)^</dd>
2190 **
2191 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2192 ** <dd> ^This option is used to enable or disable the enforcement of
2193 ** [foreign key constraints]. There should be two additional arguments.
2194 ** The first argument is an integer which is 0 to disable FK enforcement,
2195 ** positive to enable FK enforcement or negative to leave FK enforcement
2196 ** unchanged. The second parameter is a pointer to an integer into which
2197 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2198 ** following this call. The second parameter may be a NULL pointer, in
2199 ** which case the FK enforcement setting is not reported back. </dd>
2200 **
2201 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2202 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2203 ** There should be two additional arguments.
2204 ** The first argument is an integer which is 0 to disable triggers,
2205 ** positive to enable triggers or negative to leave the setting unchanged.
2206 ** The second parameter is a pointer to an integer into which
2207 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2208 ** following this call. The second parameter may be a NULL pointer, in
2209 ** which case the trigger setting is not reported back. </dd>
2210 **
2211 ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2212 ** <dd> ^This option is used to enable or disable the two-argument
2213 ** version of the [fts3_tokenizer()] function which is part of the
2214 ** [FTS3] full-text search engine extension.
2215 ** There should be two additional arguments.
2216 ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2217 ** positive to enable fts3_tokenizer() or negative to leave the setting
2218 ** unchanged.
2219 ** The second parameter is a pointer to an integer into which
2220 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2221 ** following this call. The second parameter may be a NULL pointer, in
2222 ** which case the new setting is not reported back. </dd>
2223 **
2224 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2225 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2226 ** interface independently of the [load_extension()] SQL function.
2227 ** The [sqlite3_enable_load_extension()] API enables or disables both the
2228 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2229 ** There should be two additional arguments.
2230 ** When the first argument to this interface is 1, then only the C-API is
2231 ** enabled and the SQL function remains disabled. If the first argument to
2232 ** this interface is 0, then both the C-API and the SQL function are disabled.
2233 ** If the first argument is -1, then no changes are made to state of either the
2234 ** C-API or the SQL function.
2235 ** The second parameter is a pointer to an integer into which
2236 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2237 ** is disabled or enabled following this call. The second parameter may
2238 ** be a NULL pointer, in which case the new setting is not reported back.
2239 ** </dd>
2240 **
2241 ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
2242 ** <dd> ^This option is used to change the name of the "main" database
2243 ** schema. ^The sole argument is a pointer to a constant UTF8 string
2244 ** which will become the new schema name in place of "main". ^SQLite
2245 ** does not make a copy of the new main schema name string, so the application
2246 ** must ensure that the argument passed into this DBCONFIG option is unchanged
2247 ** until after the database connection closes.
2248 ** </dd>
2249 **
2250 ** </dl>
2251 */
2252 #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
2253 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2254 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2255 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2256 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2257 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2258 
2259 
2260 /*
2261 ** CAPI3REF: Enable Or Disable Extended Result Codes
2262 ** METHOD: sqlite3
2263 **
2264 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2265 ** [extended result codes] feature of SQLite. ^The extended result
2266 ** codes are disabled by default for historical compatibility.
2267 */
2269 
2270 /*
2271 ** CAPI3REF: Last Insert Rowid
2272 ** METHOD: sqlite3
2273 **
2274 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2275 ** has a unique 64-bit signed
2276 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2277 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2278 ** names are not also used by explicitly declared columns. ^If
2279 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2280 ** is another alias for the rowid.
2281 **
2282 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2283 ** most recent successful [INSERT] into a rowid table or [virtual table]
2284 ** on database connection D.
2285 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2286 ** ^If no successful [INSERT]s into rowid tables
2287 ** have ever occurred on the database connection D,
2288 ** then sqlite3_last_insert_rowid(D) returns zero.
2289 **
2290 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2291 ** method, then this routine will return the [rowid] of the inserted
2292 ** row as long as the trigger or virtual table method is running.
2293 ** But once the trigger or virtual table method ends, the value returned
2294 ** by this routine reverts to what it was before the trigger or virtual
2295 ** table method began.)^
2296 **
2297 ** ^An [INSERT] that fails due to a constraint violation is not a
2298 ** successful [INSERT] and does not change the value returned by this
2299 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2300 ** and INSERT OR ABORT make no changes to the return value of this
2301 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2302 ** encounters a constraint violation, it does not fail. The
2303 ** INSERT continues to completion after deleting rows that caused
2304 ** the constraint problem so INSERT OR REPLACE will always change
2305 ** the return value of this interface.)^
2306 **
2307 ** ^For the purposes of this routine, an [INSERT] is considered to
2308 ** be successful even if it is subsequently rolled back.
2309 **
2310 ** This function is accessible to SQL statements via the
2311 ** [last_insert_rowid() SQL function].
2312 **
2313 ** If a separate thread performs a new [INSERT] on the same
2314 ** database connection while the [sqlite3_last_insert_rowid()]
2315 ** function is running and thus changes the last insert [rowid],
2316 ** then the value returned by [sqlite3_last_insert_rowid()] is
2317 ** unpredictable and might not equal either the old or the new
2318 ** last insert [rowid].
2319 */
2321 
2322 /*
2323 ** CAPI3REF: Count The Number Of Rows Modified
2324 ** METHOD: sqlite3
2325 **
2326 ** ^This function returns the number of rows modified, inserted or
2327 ** deleted by the most recently completed INSERT, UPDATE or DELETE
2328 ** statement on the database connection specified by the only parameter.
2329 ** ^Executing any other type of SQL statement does not modify the value
2330 ** returned by this function.
2331 **
2332 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2333 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2334 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2335 **
2336 ** Changes to a view that are intercepted by
2337 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2338 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2339 ** DELETE statement run on a view is always zero. Only changes made to real
2340 ** tables are counted.
2341 **
2342 ** Things are more complicated if the sqlite3_changes() function is
2343 ** executed while a trigger program is running. This may happen if the
2344 ** program uses the [changes() SQL function], or if some other callback
2345 ** function invokes sqlite3_changes() directly. Essentially:
2346 **
2347 ** <ul>
2348 ** <li> ^(Before entering a trigger program the value returned by
2349 ** sqlite3_changes() function is saved. After the trigger program
2350 ** has finished, the original value is restored.)^
2351 **
2352 ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2353 ** statement sets the value returned by sqlite3_changes()
2354 ** upon completion as normal. Of course, this value will not include
2355 ** any changes performed by sub-triggers, as the sqlite3_changes()
2356 ** value will be saved and restored after each sub-trigger has run.)^
2357 ** </ul>
2358 **
2359 ** ^This means that if the changes() SQL function (or similar) is used
2360 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2361 ** returns the value as set when the calling statement began executing.
2362 ** ^If it is used by the second or subsequent such statement within a trigger
2363 ** program, the value returned reflects the number of rows modified by the
2364 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
2365 **
2366 ** See also the [sqlite3_total_changes()] interface, the
2367 ** [count_changes pragma], and the [changes() SQL function].
2368 **
2369 ** If a separate thread makes changes on the same database connection
2370 ** while [sqlite3_changes()] is running then the value returned
2371 ** is unpredictable and not meaningful.
2372 */
2374 
2375 /*
2376 ** CAPI3REF: Total Number Of Rows Modified
2377 ** METHOD: sqlite3
2378 **
2379 ** ^This function returns the total number of rows inserted, modified or
2380 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2381 ** since the database connection was opened, including those executed as
2382 ** part of trigger programs. ^Executing any other type of SQL statement
2383 ** does not affect the value returned by sqlite3_total_changes().
2384 **
2385 ** ^Changes made as part of [foreign key actions] are included in the
2386 ** count, but those made as part of REPLACE constraint resolution are
2387 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2388 ** are not counted.
2389 **
2390 ** See also the [sqlite3_changes()] interface, the
2391 ** [count_changes pragma], and the [total_changes() SQL function].
2392 **
2393 ** If a separate thread makes changes on the same database connection
2394 ** while [sqlite3_total_changes()] is running then the value
2395 ** returned is unpredictable and not meaningful.
2396 */
2398 
2399 /*
2400 ** CAPI3REF: Interrupt A Long-Running Query
2401 ** METHOD: sqlite3
2402 **
2403 ** ^This function causes any pending database operation to abort and
2404 ** return at its earliest opportunity. This routine is typically
2405 ** called in response to a user action such as pressing "Cancel"
2406 ** or Ctrl-C where the user wants a long query operation to halt
2407 ** immediately.
2408 **
2409 ** ^It is safe to call this routine from a thread different from the
2410 ** thread that is currently running the database operation. But it
2411 ** is not safe to call this routine with a [database connection] that
2412 ** is closed or might close before sqlite3_interrupt() returns.
2413 **
2414 ** ^If an SQL operation is very nearly finished at the time when
2415 ** sqlite3_interrupt() is called, then it might not have an opportunity
2416 ** to be interrupted and might continue to completion.
2417 **
2418 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2419 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2420 ** that is inside an explicit transaction, then the entire transaction
2421 ** will be rolled back automatically.
2422 **
2423 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2424 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2425 ** that are started after the sqlite3_interrupt() call and before the
2426 ** running statements reaches zero are interrupted as if they had been
2427 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2428 ** that are started after the running statement count reaches zero are
2429 ** not effected by the sqlite3_interrupt().
2430 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2431 ** SQL statements is a no-op and has no effect on SQL statements
2432 ** that are started after the sqlite3_interrupt() call returns.
2433 **
2434 ** If the database connection closes while [sqlite3_interrupt()]
2435 ** is running then bad things will likely happen.
2436 */
2438 
2439 /*
2440 ** CAPI3REF: Determine If An SQL Statement Is Complete
2441 **
2442 ** These routines are useful during command-line input to determine if the
2443 ** currently entered text seems to form a complete SQL statement or
2444 ** if additional input is needed before sending the text into
2445 ** SQLite for parsing. ^These routines return 1 if the input string
2446 ** appears to be a complete SQL statement. ^A statement is judged to be
2447 ** complete if it ends with a semicolon token and is not a prefix of a
2448 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2449 ** string literals or quoted identifier names or comments are not
2450 ** independent tokens (they are part of the token in which they are
2451 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2452 ** and comments that follow the final semicolon are ignored.
2453 **
2454 ** ^These routines return 0 if the statement is incomplete. ^If a
2455 ** memory allocation fails, then SQLITE_NOMEM is returned.
2456 **
2457 ** ^These routines do not parse the SQL statements thus
2458 ** will not detect syntactically incorrect SQL.
2459 **
2460 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2461 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2462 ** automatically by sqlite3_complete16(). If that initialization fails,
2463 ** then the return value from sqlite3_complete16() will be non-zero
2464 ** regardless of whether or not the input SQL is complete.)^
2465 **
2466 ** The input to [sqlite3_complete()] must be a zero-terminated
2467 ** UTF-8 string.
2468 **
2469 ** The input to [sqlite3_complete16()] must be a zero-terminated
2470 ** UTF-16 string in native byte order.
2471 */
2472 SQLITE_API int sqlite3_complete(const char *sql);
2473 SQLITE_API int sqlite3_complete16(const void *sql);
2474 
2475 /*
2476 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2477 ** KEYWORDS: {busy-handler callback} {busy handler}
2478 ** METHOD: sqlite3
2479 **
2480 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2481 ** that might be invoked with argument P whenever
2482 ** an attempt is made to access a database table associated with
2483 ** [database connection] D when another thread
2484 ** or process has the table locked.
2485 ** The sqlite3_busy_handler() interface is used to implement
2486 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2487 **
2488 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2489 ** is returned immediately upon encountering the lock. ^If the busy callback
2490 ** is not NULL, then the callback might be invoked with two arguments.
2491 **
2492 ** ^The first argument to the busy handler is a copy of the void* pointer which
2493 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2494 ** the busy handler callback is the number of times that the busy handler has
2495 ** been invoked previously for the same locking event. ^If the
2496 ** busy callback returns 0, then no additional attempts are made to
2497 ** access the database and [SQLITE_BUSY] is returned
2498 ** to the application.
2499 ** ^If the callback returns non-zero, then another attempt
2500 ** is made to access the database and the cycle repeats.
2501 **
2502 ** The presence of a busy handler does not guarantee that it will be invoked
2503 ** when there is lock contention. ^If SQLite determines that invoking the busy
2504 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2505 ** to the application instead of invoking the
2506 ** busy handler.
2507 ** Consider a scenario where one process is holding a read lock that
2508 ** it is trying to promote to a reserved lock and
2509 ** a second process is holding a reserved lock that it is trying
2510 ** to promote to an exclusive lock. The first process cannot proceed
2511 ** because it is blocked by the second and the second process cannot
2512 ** proceed because it is blocked by the first. If both processes
2513 ** invoke the busy handlers, neither will make any progress. Therefore,
2514 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2515 ** will induce the first process to release its read lock and allow
2516 ** the second process to proceed.
2517 **
2518 ** ^The default busy callback is NULL.
2519 **
2520 ** ^(There can only be a single busy handler defined for each
2521 ** [database connection]. Setting a new busy handler clears any
2522 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2523 ** or evaluating [PRAGMA busy_timeout=N] will change the
2524 ** busy handler and thus clear any previously set busy handler.
2525 **
2526 ** The busy callback should not take any actions which modify the
2527 ** database connection that invoked the busy handler. In other words,
2528 ** the busy handler is not reentrant. Any such actions
2529 ** result in undefined behavior.
2530 **
2531 ** A busy handler must not close the database connection
2532 ** or [prepared statement] that invoked the busy handler.
2533 */
2534 SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
2535 
2536 /*
2537 ** CAPI3REF: Set A Busy Timeout
2538 ** METHOD: sqlite3
2539 **
2540 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2541 ** for a specified amount of time when a table is locked. ^The handler
2542 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2543 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2544 ** the handler returns 0 which causes [sqlite3_step()] to return
2545 ** [SQLITE_BUSY].
2546 **
2547 ** ^Calling this routine with an argument less than or equal to zero
2548 ** turns off all busy handlers.
2549 **
2550 ** ^(There can only be a single busy handler for a particular
2551 ** [database connection] at any given moment. If another busy handler
2552 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2553 ** this routine, that other busy handler is cleared.)^
2554 **
2555 ** See also: [PRAGMA busy_timeout]
2556 */
2558 
2559 /*
2560 ** CAPI3REF: Convenience Routines For Running Queries
2561 ** METHOD: sqlite3
2562 **
2563 ** This is a legacy interface that is preserved for backwards compatibility.
2564 ** Use of this interface is not recommended.
2565 **
2566 ** Definition: A <b>result table</b> is memory data structure created by the
2567 ** [sqlite3_get_table()] interface. A result table records the
2568 ** complete query results from one or more queries.
2569 **
2570 ** The table conceptually has a number of rows and columns. But
2571 ** these numbers are not part of the result table itself. These
2572 ** numbers are obtained separately. Let N be the number of rows
2573 ** and M be the number of columns.
2574 **
2575 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2576 ** There are (N+1)*M elements in the array. The first M pointers point
2577 ** to zero-terminated strings that contain the names of the columns.
2578 ** The remaining entries all point to query results. NULL values result
2579 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2580 ** string representation as returned by [sqlite3_column_text()].
2581 **
2582 ** A result table might consist of one or more memory allocations.
2583 ** It is not safe to pass a result table directly to [sqlite3_free()].
2584 ** A result table should be deallocated using [sqlite3_free_table()].
2585 **
2586 ** ^(As an example of the result table format, suppose a query result
2587 ** is as follows:
2588 **
2589 ** <blockquote><pre>
2590 ** Name | Age
2591 ** -----------------------
2592 ** Alice | 43
2593 ** Bob | 28
2594 ** Cindy | 21
2595 ** </pre></blockquote>
2596 **
2597 ** There are two column (M==2) and three rows (N==3). Thus the
2598 ** result table has 8 entries. Suppose the result table is stored
2599 ** in an array names azResult. Then azResult holds this content:
2600 **
2601 ** <blockquote><pre>
2602 ** azResult&#91;0] = "Name";
2603 ** azResult&#91;1] = "Age";
2604 ** azResult&#91;2] = "Alice";
2605 ** azResult&#91;3] = "43";
2606 ** azResult&#91;4] = "Bob";
2607 ** azResult&#91;5] = "28";
2608 ** azResult&#91;6] = "Cindy";
2609 ** azResult&#91;7] = "21";
2610 ** </pre></blockquote>)^
2611 **
2612 ** ^The sqlite3_get_table() function evaluates one or more
2613 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2614 ** string of its 2nd parameter and returns a result table to the
2615 ** pointer given in its 3rd parameter.
2616 **
2617 ** After the application has finished with the result from sqlite3_get_table(),
2618 ** it must pass the result table pointer to sqlite3_free_table() in order to
2619 ** release the memory that was malloced. Because of the way the
2620 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2621 ** function must not try to call [sqlite3_free()] directly. Only
2622 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2623 **
2624 ** The sqlite3_get_table() interface is implemented as a wrapper around
2625 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2626 ** to any internal data structures of SQLite. It uses only the public
2627 ** interface defined here. As a consequence, errors that occur in the
2628 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2629 ** reflected in subsequent calls to [sqlite3_errcode()] or
2630 ** [sqlite3_errmsg()].
2631 */
2633  sqlite3 *db, /* An open database */
2634  const char *zSql, /* SQL to be evaluated */
2635  char ***pazResult, /* Results of the query */
2636  int *pnRow, /* Number of result rows written here */
2637  int *pnColumn, /* Number of result columns written here */
2638  char **pzErrmsg /* Error msg written here */
2639 );
2640 SQLITE_API void sqlite3_free_table(char **result);
2641 
2642 /*
2643 ** CAPI3REF: Formatted String Printing Functions
2644 **
2645 ** These routines are work-alikes of the "printf()" family of functions
2646 ** from the standard C library.
2647 ** These routines understand most of the common K&R formatting options,
2648 ** plus some additional non-standard formats, detailed below.
2649 ** Note that some of the more obscure formatting options from recent
2650 ** C-library standards are omitted from this implementation.
2651 **
2652 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2653 ** results into memory obtained from [sqlite3_malloc()].
2654 ** The strings returned by these two routines should be
2655 ** released by [sqlite3_free()]. ^Both routines return a
2656 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2657 ** memory to hold the resulting string.
2658 **
2659 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2660 ** the standard C library. The result is written into the
2661 ** buffer supplied as the second parameter whose size is given by
2662 ** the first parameter. Note that the order of the
2663 ** first two parameters is reversed from snprintf().)^ This is an
2664 ** historical accident that cannot be fixed without breaking
2665 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2666 ** returns a pointer to its buffer instead of the number of
2667 ** characters actually written into the buffer.)^ We admit that
2668 ** the number of characters written would be a more useful return
2669 ** value but we cannot change the implementation of sqlite3_snprintf()
2670 ** now without breaking compatibility.
2671 **
2672 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2673 ** guarantees that the buffer is always zero-terminated. ^The first
2674 ** parameter "n" is the total size of the buffer, including space for
2675 ** the zero terminator. So the longest string that can be completely
2676 ** written will be n-1 characters.
2677 **
2678 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2679 **
2680 ** These routines all implement some additional formatting
2681 ** options that are useful for constructing SQL statements.
2682 ** All of the usual printf() formatting options apply. In addition, there
2683 ** is are "%q", "%Q", "%w" and "%z" options.
2684 **
2685 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2686 ** string from the argument list. But %q also doubles every '\'' character.
2687 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2688 ** character it escapes that character and allows it to be inserted into
2689 ** the string.
2690 **
2691 ** For example, assume the string variable zText contains text as follows:
2692 **
2693 ** <blockquote><pre>
2694 ** char *zText = "It's a happy day!";
2695 ** </pre></blockquote>
2696 **
2697 ** One can use this text in an SQL statement as follows:
2698 **
2699 ** <blockquote><pre>
2700 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2701 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2702 ** sqlite3_free(zSQL);
2703 ** </pre></blockquote>
2704 **
2705 ** Because the %q format string is used, the '\'' character in zText
2706 ** is escaped and the SQL generated is as follows:
2707 **
2708 ** <blockquote><pre>
2709 ** INSERT INTO table1 VALUES('It''s a happy day!')
2710 ** </pre></blockquote>
2711 **
2712 ** This is correct. Had we used %s instead of %q, the generated SQL
2713 ** would have looked like this:
2714 **
2715 ** <blockquote><pre>
2716 ** INSERT INTO table1 VALUES('It's a happy day!');
2717 ** </pre></blockquote>
2718 **
2719 ** This second example is an SQL syntax error. As a general rule you should
2720 ** always use %q instead of %s when inserting text into a string literal.
2721 **
2722 ** ^(The %Q option works like %q except it also adds single quotes around
2723 ** the outside of the total string. Additionally, if the parameter in the
2724 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2725 ** single quotes).)^ So, for example, one could say:
2726 **
2727 ** <blockquote><pre>
2728 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2729 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2730 ** sqlite3_free(zSQL);
2731 ** </pre></blockquote>
2732 **
2733 ** The code above will render a correct SQL statement in the zSQL
2734 ** variable even if the zText variable is a NULL pointer.
2735 **
2736 ** ^(The "%w" formatting option is like "%q" except that it expects to
2737 ** be contained within double-quotes instead of single quotes, and it
2738 ** escapes the double-quote character instead of the single-quote
2739 ** character.)^ The "%w" formatting option is intended for safely inserting
2740 ** table and column names into a constructed SQL statement.
2741 **
2742 ** ^(The "%z" formatting option works like "%s" but with the
2743 ** addition that after the string has been read and copied into
2744 ** the result, [sqlite3_free()] is called on the input string.)^
2745 */
2746 SQLITE_API char *sqlite3_mprintf(const char*,...);
2747 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2748 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2749 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2750 
2751 /*
2752 ** CAPI3REF: Memory Allocation Subsystem
2753 **
2754 ** The SQLite core uses these three routines for all of its own
2755 ** internal memory allocation needs. "Core" in the previous sentence
2756 ** does not include operating-system specific VFS implementation. The
2757 ** Windows VFS uses native malloc() and free() for some operations.
2758 **
2759 ** ^The sqlite3_malloc() routine returns a pointer to a block
2760 ** of memory at least N bytes in length, where N is the parameter.
2761 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2762 ** memory, it returns a NULL pointer. ^If the parameter N to
2763 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2764 ** a NULL pointer.
2765 **
2766 ** ^The sqlite3_malloc64(N) routine works just like
2767 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2768 ** of a signed 32-bit integer.
2769 **
2770 ** ^Calling sqlite3_free() with a pointer previously returned
2771 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2772 ** that it might be reused. ^The sqlite3_free() routine is
2773 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2774 ** to sqlite3_free() is harmless. After being freed, memory
2775 ** should neither be read nor written. Even reading previously freed
2776 ** memory might result in a segmentation fault or other severe error.
2777 ** Memory corruption, a segmentation fault, or other severe error
2778 ** might result if sqlite3_free() is called with a non-NULL pointer that
2779 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2780 **
2781 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2782 ** prior memory allocation X to be at least N bytes.
2783 ** ^If the X parameter to sqlite3_realloc(X,N)
2784 ** is a NULL pointer then its behavior is identical to calling
2785 ** sqlite3_malloc(N).
2786 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2787 ** negative then the behavior is exactly the same as calling
2788 ** sqlite3_free(X).
2789 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2790 ** of at least N bytes in size or NULL if insufficient memory is available.
2791 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2792 ** of the prior allocation are copied into the beginning of buffer returned
2793 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2794 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2795 ** prior allocation is not freed.
2796 **
2797 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2798 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2799 ** of a 32-bit signed integer.
2800 **
2801 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2802 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2803 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2804 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2805 ** of bytes requested when X was allocated. ^If X is a NULL pointer then
2806 ** sqlite3_msize(X) returns zero. If X points to something that is not
2807 ** the beginning of memory allocation, or if it points to a formerly
2808 ** valid memory allocation that has now been freed, then the behavior
2809 ** of sqlite3_msize(X) is undefined and possibly harmful.
2810 **
2811 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2812 ** sqlite3_malloc64(), and sqlite3_realloc64()
2813 ** is always aligned to at least an 8 byte boundary, or to a
2814 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2815 ** option is used.
2816 **
2817 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2818 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2819 ** implementation of these routines to be omitted. That capability
2820 ** is no longer provided. Only built-in memory allocators can be used.
2821 **
2822 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2823 ** the system malloc() and free() directly when converting
2824 ** filenames between the UTF-8 encoding used by SQLite
2825 ** and whatever filename encoding is used by the particular Windows
2826 ** installation. Memory allocation errors were detected, but
2827 ** they were reported back as [SQLITE_CANTOPEN] or
2828 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2829 **
2830 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2831 ** must be either NULL or else pointers obtained from a prior
2832 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2833 ** not yet been released.
2834 **
2835 ** The application must not read or write any part of
2836 ** a block of memory after it has been released using
2837 ** [sqlite3_free()] or [sqlite3_realloc()].
2838 */
2839 SQLITE_API void *sqlite3_malloc(int);
2840 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
2841 SQLITE_API void *sqlite3_realloc(void*, int);
2842 SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
2843 SQLITE_API void sqlite3_free(void*);
2844 SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
2845 
2846 /*
2847 ** CAPI3REF: Memory Allocator Statistics
2848 **
2849 ** SQLite provides these two interfaces for reporting on the status
2850 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2851 ** routines, which form the built-in memory allocation subsystem.
2852 **
2853 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2854 ** of memory currently outstanding (malloced but not freed).
2855 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2856 ** value of [sqlite3_memory_used()] since the high-water mark
2857 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2858 ** [sqlite3_memory_highwater()] include any overhead
2859 ** added by SQLite in its implementation of [sqlite3_malloc()],
2860 ** but not overhead added by the any underlying system library
2861 ** routines that [sqlite3_malloc()] may call.
2862 **
2863 ** ^The memory high-water mark is reset to the current value of
2864 ** [sqlite3_memory_used()] if and only if the parameter to
2865 ** [sqlite3_memory_highwater()] is true. ^The value returned
2866 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2867 ** prior to the reset.
2868 */
2869 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2870 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2871 
2872 /*
2873 ** CAPI3REF: Pseudo-Random Number Generator
2874 **
2875 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2876 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2877 ** already uses the largest possible [ROWID]. The PRNG is also used for
2878 ** the build-in random() and randomblob() SQL functions. This interface allows
2879 ** applications to access the same PRNG for other purposes.
2880 **
2881 ** ^A call to this routine stores N bytes of randomness into buffer P.
2882 ** ^The P parameter can be a NULL pointer.
2883 **
2884 ** ^If this routine has not been previously called or if the previous
2885 ** call had N less than one or a NULL pointer for P, then the PRNG is
2886 ** seeded using randomness obtained from the xRandomness method of
2887 ** the default [sqlite3_vfs] object.
2888 ** ^If the previous call to this routine had an N of 1 or more and a
2889 ** non-NULL P then the pseudo-randomness is generated
2890 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2891 ** method.
2892 */
2893 SQLITE_API void sqlite3_randomness(int N, void *P);
2894 
2895 /*
2896 ** CAPI3REF: Compile-Time Authorization Callbacks
2897 ** METHOD: sqlite3
2898 **
2899 ** ^This routine registers an authorizer callback with a particular
2900 ** [database connection], supplied in the first argument.
2901 ** ^The authorizer callback is invoked as SQL statements are being compiled
2902 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2903 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2904 ** points during the compilation process, as logic is being created
2905 ** to perform various actions, the authorizer callback is invoked to
2906 ** see if those actions are allowed. ^The authorizer callback should
2907 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2908 ** specific action but allow the SQL statement to continue to be
2909 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2910 ** rejected with an error. ^If the authorizer callback returns
2911 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2912 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2913 ** the authorizer will fail with an error message.
2914 **
2915 ** When the callback returns [SQLITE_OK], that means the operation
2916 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2917 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2918 ** authorizer will fail with an error message explaining that
2919 ** access is denied.
2920 **
2921 ** ^The first parameter to the authorizer callback is a copy of the third
2922 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2923 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2924 ** the particular action to be authorized. ^The third through sixth parameters
2925 ** to the callback are zero-terminated strings that contain additional
2926 ** details about the action to be authorized.
2927 **
2928 ** ^If the action code is [SQLITE_READ]
2929 ** and the callback returns [SQLITE_IGNORE] then the
2930 ** [prepared statement] statement is constructed to substitute
2931 ** a NULL value in place of the table column that would have
2932 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2933 ** return can be used to deny an untrusted user access to individual
2934 ** columns of a table.
2935 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2936 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2937 ** [truncate optimization] is disabled and all rows are deleted individually.
2938 **
2939 ** An authorizer is used when [sqlite3_prepare | preparing]
2940 ** SQL statements from an untrusted source, to ensure that the SQL statements
2941 ** do not try to access data they are not allowed to see, or that they do not
2942 ** try to execute malicious statements that damage the database. For
2943 ** example, an application may allow a user to enter arbitrary
2944 ** SQL queries for evaluation by a database. But the application does
2945 ** not want the user to be able to make arbitrary changes to the
2946 ** database. An authorizer could then be put in place while the
2947 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2948 ** disallows everything except [SELECT] statements.
2949 **
2950 ** Applications that need to process SQL from untrusted sources
2951 ** might also consider lowering resource limits using [sqlite3_limit()]
2952 ** and limiting database size using the [max_page_count] [PRAGMA]
2953 ** in addition to using an authorizer.
2954 **
2955 ** ^(Only a single authorizer can be in place on a database connection
2956 ** at a time. Each call to sqlite3_set_authorizer overrides the
2957 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2958 ** The authorizer is disabled by default.
2959 **
2960 ** The authorizer callback must not do anything that will modify
2961 ** the database connection that invoked the authorizer callback.
2962 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2963 ** database connections for the meaning of "modify" in this paragraph.
2964 **
2965 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2966 ** statement might be re-prepared during [sqlite3_step()] due to a
2967 ** schema change. Hence, the application should ensure that the
2968 ** correct authorizer callback remains in place during the [sqlite3_step()].
2969 **
2970 ** ^Note that the authorizer callback is invoked only during
2971 ** [sqlite3_prepare()] or its variants. Authorization is not
2972 ** performed during statement evaluation in [sqlite3_step()], unless
2973 ** as stated in the previous paragraph, sqlite3_step() invokes
2974 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2975 */
2977  sqlite3*,
2978  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2979  void *pUserData
2980 );
2981 
2982 /*
2983 ** CAPI3REF: Authorizer Return Codes
2984 **
2985 ** The [sqlite3_set_authorizer | authorizer callback function] must
2986 ** return either [SQLITE_OK] or one of these two constants in order
2987 ** to signal SQLite whether or not the action is permitted. See the
2988 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2989 ** information.
2990 **
2991 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2992 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2993 */
2994 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2995 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2996 
2997 /*
2998 ** CAPI3REF: Authorizer Action Codes
2999 **
3000 ** The [sqlite3_set_authorizer()] interface registers a callback function
3001 ** that is invoked to authorize certain SQL statement actions. The
3002 ** second parameter to the callback is an integer code that specifies
3003 ** what action is being authorized. These are the integer action codes that
3004 ** the authorizer callback may be passed.
3005 **
3006 ** These action code values signify what kind of operation is to be
3007 ** authorized. The 3rd and 4th parameters to the authorization
3008 ** callback function will be parameters or NULL depending on which of these
3009 ** codes is used as the second parameter. ^(The 5th parameter to the
3010 ** authorizer callback is the name of the database ("main", "temp",
3011 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
3012 ** is the name of the inner-most trigger or view that is responsible for
3013 ** the access attempt or NULL if this access attempt is directly from
3014 ** top-level SQL code.
3015 */
3016 /******************************************* 3rd ************ 4th ***********/
3017 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
3018 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
3019 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
3020 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
3021 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
3022 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
3023 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
3024 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
3025 #define SQLITE_DELETE 9 /* Table Name NULL */
3026 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
3027 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
3028 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
3029 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
3030 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
3031 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
3032 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
3033 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
3034 #define SQLITE_INSERT 18 /* Table Name NULL */
3035 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
3036 #define SQLITE_READ 20 /* Table Name Column Name */
3037 #define SQLITE_SELECT 21 /* NULL NULL */
3038 #define SQLITE_TRANSACTION 22 /* Operation NULL */
3039 #define SQLITE_UPDATE 23 /* Table Name Column Name */
3040 #define SQLITE_ATTACH 24 /* Filename NULL */
3041 #define SQLITE_DETACH 25 /* Database Name NULL */
3042 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
3043 #define SQLITE_REINDEX 27 /* Index Name NULL */
3044 #define SQLITE_ANALYZE 28 /* Table Name NULL */
3045 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
3046 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3047 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3048 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3049 #define SQLITE_COPY 0 /* No longer used */
3050 #define SQLITE_RECURSIVE 33 /* NULL NULL */
3051 
3052 /*
3053 ** CAPI3REF: Tracing And Profiling Functions
3054 ** METHOD: sqlite3
3055 **
3056 ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
3057 ** instead of the routines described here.
3058 **
3059 ** These routines register callback functions that can be used for
3060 ** tracing and profiling the execution of SQL statements.
3061 **
3062 ** ^The callback function registered by sqlite3_trace() is invoked at
3063 ** various times when an SQL statement is being run by [sqlite3_step()].
3064 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3065 ** SQL statement text as the statement first begins executing.
3066 ** ^(Additional sqlite3_trace() callbacks might occur
3067 ** as each triggered subprogram is entered. The callbacks for triggers
3068 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3069 **
3070 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3071 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
3072 **
3073 ** ^The callback function registered by sqlite3_profile() is invoked
3074 ** as each SQL statement finishes. ^The profile callback contains
3075 ** the original statement text and an estimate of wall-clock time
3076 ** of how long that statement took to run. ^The profile callback
3077 ** time is in units of nanoseconds, however the current implementation
3078 ** is only capable of millisecond resolution so the six least significant
3079 ** digits in the time are meaningless. Future versions of SQLite
3080 ** might provide greater resolution on the profiler callback. The
3081 ** sqlite3_profile() function is considered experimental and is
3082 ** subject to change in future versions of SQLite.
3083 */
3085  void(*xTrace)(void*,const char*), void*);
3087  void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3088 
3089 /*
3090 ** CAPI3REF: SQL Trace Event Codes
3091 ** KEYWORDS: SQLITE_TRACE
3092 **
3093 ** These constants identify classes of events that can be monitored
3094 ** using the [sqlite3_trace_v2()] tracing logic. The third argument
3095 ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
3096 ** the following constants. ^The first argument to the trace callback
3097 ** is one of the following constants.
3098 **
3099 ** New tracing constants may be added in future releases.
3100 **
3101 ** ^A trace callback has four arguments: xCallback(T,C,P,X).
3102 ** ^The T argument is one of the integer type codes above.
3103 ** ^The C argument is a copy of the context pointer passed in as the
3104 ** fourth argument to [sqlite3_trace_v2()].
3105 ** The P and X arguments are pointers whose meanings depend on T.
3106 **
3107 ** <dl>
3108 ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
3109 ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3110 ** first begins running and possibly at other times during the
3111 ** execution of the prepared statement, such as at the start of each
3112 ** trigger subprogram. ^The P argument is a pointer to the
3113 ** [prepared statement]. ^The X argument is a pointer to a string which
3114 ** is the unexpanded SQL text of the prepared statement or an SQL comment
3115 ** that indicates the invocation of a trigger. ^The callback can compute
3116 ** the same text that would have been returned by the legacy [sqlite3_trace()]
3117 ** interface by using the X argument when X begins with "--" and invoking
3118 ** [sqlite3_expanded_sql(P)] otherwise.
3119 **
3120 ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
3121 ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3122 ** information as is provided by the [sqlite3_profile()] callback.
3123 ** ^The P argument is a pointer to the [prepared statement] and the
3124 ** X argument points to a 64-bit integer which is the estimated of
3125 ** the number of nanosecond that the prepared statement took to run.
3126 ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
3127 **
3128 ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
3129 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3130 ** statement generates a single row of result.
3131 ** ^The P argument is a pointer to the [prepared statement] and the
3132 ** X argument is unused.
3133 **
3134 ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
3135 ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3136 ** connection closes.
3137 ** ^The P argument is a pointer to the [database connection] object
3138 ** and the X argument is unused.
3139 ** </dl>
3140 */
3141 #define SQLITE_TRACE_STMT 0x01
3142 #define SQLITE_TRACE_PROFILE 0x02
3143 #define SQLITE_TRACE_ROW 0x04
3144 #define SQLITE_TRACE_CLOSE 0x08
3145 
3146 /*
3147 ** CAPI3REF: SQL Trace Hook
3148 ** METHOD: sqlite3
3149 **
3150 ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
3151 ** function X against [database connection] D, using property mask M
3152 ** and context pointer P. ^If the X callback is
3153 ** NULL or if the M mask is zero, then tracing is disabled. The
3154 ** M argument should be the bitwise OR-ed combination of
3155 ** zero or more [SQLITE_TRACE] constants.
3156 **
3157 ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
3158 ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
3159 **
3160 ** ^The X callback is invoked whenever any of the events identified by
3161 ** mask M occur. ^The integer return value from the callback is currently
3162 ** ignored, though this may change in future releases. Callback
3163 ** implementations should return zero to ensure future compatibility.
3164 **
3165 ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
3166 ** ^The T argument is one of the [SQLITE_TRACE]
3167 ** constants to indicate why the callback was invoked.
3168 ** ^The C argument is a copy of the context pointer.
3169 ** The P and X arguments are pointers whose meanings depend on T.
3170 **
3171 ** The sqlite3_trace_v2() interface is intended to replace the legacy
3172 ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
3173 ** are deprecated.
3174 */
3176  sqlite3*,
3177  unsigned uMask,
3178  int(*xCallback)(unsigned,void*,void*,void*),
3179  void *pCtx
3180 );
3181 
3182 /*
3183 ** CAPI3REF: Query Progress Callbacks
3184 ** METHOD: sqlite3
3185 **
3186 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3187 ** function X to be invoked periodically during long running calls to
3188 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3189 ** database connection D. An example use for this
3190 ** interface is to keep a GUI updated during a large query.
3191 **
3192 ** ^The parameter P is passed through as the only parameter to the
3193 ** callback function X. ^The parameter N is the approximate number of
3194 ** [virtual machine instructions] that are evaluated between successive
3195 ** invocations of the callback X. ^If N is less than one then the progress
3196 ** handler is disabled.
3197 **
3198 ** ^Only a single progress handler may be defined at one time per
3199 ** [database connection]; setting a new progress handler cancels the
3200 ** old one. ^Setting parameter X to NULL disables the progress handler.
3201 ** ^The progress handler is also disabled by setting N to a value less
3202 ** than 1.
3203 **
3204 ** ^If the progress callback returns non-zero, the operation is
3205 ** interrupted. This feature can be used to implement a
3206 ** "Cancel" button on a GUI progress dialog box.
3207 **
3208 ** The progress handler callback must not do anything that will modify
3209 ** the database connection that invoked the progress handler.
3210 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3211 ** database connections for the meaning of "modify" in this paragraph.
3212 **
3213 */
3214 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3215 
3216 /*
3217 ** CAPI3REF: Opening A New Database Connection
3218 ** CONSTRUCTOR: sqlite3
3219 **
3220 ** ^These routines open an SQLite database file as specified by the
3221 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3222 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3223 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3224 ** returned in *ppDb, even if an error occurs. The only exception is that
3225 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3226 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3227 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3228 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3229 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3230 ** an English language description of the error following a failure of any
3231 ** of the sqlite3_open() routines.
3232 **
3233 ** ^The default encoding will be UTF-8 for databases created using
3234 ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
3235 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
3236 **
3237 ** Whether or not an error occurs when it is opened, resources
3238 ** associated with the [database connection] handle should be released by
3239 ** passing it to [sqlite3_close()] when it is no longer required.
3240 **
3241 ** The sqlite3_open_v2() interface works like sqlite3_open()
3242 ** except that it accepts two additional parameters for additional control
3243 ** over the new database connection. ^(The flags parameter to
3244 ** sqlite3_open_v2() can take one of
3245 ** the following three values, optionally combined with the
3246 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3247 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3248 **
3249 ** <dl>
3250 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3251 ** <dd>The database is opened in read-only mode. If the database does not
3252 ** already exist, an error is returned.</dd>)^
3253 **
3254 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3255 ** <dd>The database is opened for reading and writing if possible, or reading
3256 ** only if the file is write protected by the operating system. In either
3257 ** case the database must already exist, otherwise an error is returned.</dd>)^
3258 **
3259 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3260 ** <dd>The database is opened for reading and writing, and is created if
3261 ** it does not already exist. This is the behavior that is always used for
3262 ** sqlite3_open() and sqlite3_open16().</dd>)^
3263 ** </dl>
3264 **
3265 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3266 ** combinations shown above optionally combined with other
3267 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3268 ** then the behavior is undefined.
3269 **
3270 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3271 ** opens in the multi-thread [threading mode] as long as the single-thread
3272 ** mode has not been set at compile-time or start-time. ^If the
3273 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3274 ** in the serialized [threading mode] unless single-thread was
3275 ** previously selected at compile-time or start-time.
3276 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3277 ** eligible to use [shared cache mode], regardless of whether or not shared
3278 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
3279 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3280 ** participate in [shared cache mode] even if it is enabled.
3281 **
3282 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3283 ** [sqlite3_vfs] object that defines the operating system interface that
3284 ** the new database connection should use. ^If the fourth parameter is
3285 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3286 **
3287 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3288 ** is created for the connection. ^This in-memory database will vanish when
3289 ** the database connection is closed. Future versions of SQLite might
3290 ** make use of additional special filenames that begin with the ":" character.
3291 ** It is recommended that when a database filename actually does begin with
3292 ** a ":" character you should prefix the filename with a pathname such as
3293 ** "./" to avoid ambiguity.
3294 **
3295 ** ^If the filename is an empty string, then a private, temporary
3296 ** on-disk database will be created. ^This private database will be
3297 ** automatically deleted as soon as the database connection is closed.
3298 **
3299 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3300 **
3301 ** ^If [URI filename] interpretation is enabled, and the filename argument
3302 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3303 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3304 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3305 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3306 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3307 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3308 ** by default, but future releases of SQLite might enable URI filename
3309 ** interpretation by default. See "[URI filenames]" for additional
3310 ** information.
3311 **
3312 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3313 ** authority, then it must be either an empty string or the string
3314 ** "localhost". ^If the authority is not an empty string or "localhost", an
3315 ** error is returned to the caller. ^The fragment component of a URI, if
3316 ** present, is ignored.
3317 **
3318 ** ^SQLite uses the path component of the URI as the name of the disk file
3319 ** which contains the database. ^If the path begins with a '/' character,
3320 ** then it is interpreted as an absolute path. ^If the path does not begin
3321 ** with a '/' (meaning that the authority section is omitted from the URI)
3322 ** then the path is interpreted as a relative path.
3323 ** ^(On windows, the first component of an absolute path
3324 ** is a drive specification (e.g. "C:").)^
3325 **
3326 ** [[core URI query parameters]]
3327 ** The query component of a URI may contain parameters that are interpreted
3328 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3329 ** SQLite and its built-in [VFSes] interpret the
3330 ** following query parameters:
3331 **
3332 ** <ul>
3333 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3334 ** a VFS object that provides the operating system interface that should
3335 ** be used to access the database file on disk. ^If this option is set to
3336 ** an empty string the default VFS object is used. ^Specifying an unknown
3337 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3338 ** present, then the VFS specified by the option takes precedence over
3339 ** the value passed as the fourth parameter to sqlite3_open_v2().
3340 **
3341 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3342 ** "rwc", or "memory". Attempting to set it to any other value is
3343 ** an error)^.
3344 ** ^If "ro" is specified, then the database is opened for read-only
3345 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3346 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
3347 ** "rw", then the database is opened for read-write (but not create)
3348 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3349 ** been set. ^Value "rwc" is equivalent to setting both
3350 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
3351 ** set to "memory" then a pure [in-memory database] that never reads
3352 ** or writes from disk is used. ^It is an error to specify a value for
3353 ** the mode parameter that is less restrictive than that specified by
3354 ** the flags passed in the third parameter to sqlite3_open_v2().
3355 **
3356 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3357 ** "private". ^Setting it to "shared" is equivalent to setting the
3358 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3359 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3360 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3361 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3362 ** a URI filename, its value overrides any behavior requested by setting
3363 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3364 **
3365 ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3366 ** [powersafe overwrite] property does or does not apply to the
3367 ** storage media on which the database file resides.
3368 **
3369 ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3370 ** which if set disables file locking in rollback journal modes. This
3371 ** is useful for accessing a database on a filesystem that does not
3372 ** support locking. Caution: Database corruption might result if two
3373 ** or more processes write to the same database and any one of those
3374 ** processes uses nolock=1.
3375 **
3376 ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3377 ** parameter that indicates that the database file is stored on
3378 ** read-only media. ^When immutable is set, SQLite assumes that the
3379 ** database file cannot be changed, even by a process with higher
3380 ** privilege, and so the database is opened read-only and all locking
3381 ** and change detection is disabled. Caution: Setting the immutable
3382 ** property on a database file that does in fact change can result
3383 ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
3384 ** See also: [SQLITE_IOCAP_IMMUTABLE].
3385 **
3386 ** </ul>
3387 **
3388 ** ^Specifying an unknown parameter in the query component of a URI is not an
3389 ** error. Future versions of SQLite might understand additional query
3390 ** parameters. See "[query parameters with special meaning to SQLite]" for
3391 ** additional information.
3392 **
3393 ** [[URI filename examples]] <h3>URI filename examples</h3>
3394 **
3395 ** <table border="1" align=center cellpadding=5>
3396 ** <tr><th> URI filenames <th> Results
3397 ** <tr><td> file:data.db <td>
3398 ** Open the file "data.db" in the current directory.
3399 ** <tr><td> file:/home/fred/data.db<br>
3400 ** file:///home/fred/data.db <br>
3401 ** file://localhost/home/fred/data.db <br> <td>
3402 ** Open the database file "/home/fred/data.db".
3403 ** <tr><td> file://darkstar/home/fred/data.db <td>
3404 ** An error. "darkstar" is not a recognized authority.
3405 ** <tr><td style="white-space:nowrap">
3406 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3407 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3408 ** C:. Note that the %20 escaping in this example is not strictly
3409 ** necessary - space characters can be used literally
3410 ** in URI filenames.
3411 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3412 ** Open file "data.db" in the current directory for read-only access.
3413 ** Regardless of whether or not shared-cache mode is enabled by
3414 ** default, use a private cache.
3415 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3416 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3417 ** that uses dot-files in place of posix advisory locking.
3418 ** <tr><td> file:data.db?mode=readonly <td>
3419 ** An error. "readonly" is not a valid option for the "mode" parameter.
3420 ** </table>
3421 **
3422 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3423 ** query components of a URI. A hexadecimal escape sequence consists of a
3424 ** percent sign - "%" - followed by exactly two hexadecimal digits
3425 ** specifying an octet value. ^Before the path or query components of a
3426 ** URI filename are interpreted, they are encoded using UTF-8 and all
3427 ** hexadecimal escape sequences replaced by a single byte containing the
3428 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3429 ** the results are undefined.
3430 **
3431 ** <b>Note to Windows users:</b> The encoding used for the filename argument
3432 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3433 ** codepage is currently defined. Filenames containing international
3434 ** characters must be converted to UTF-8 prior to passing them into
3435 ** sqlite3_open() or sqlite3_open_v2().
3436 **
3437 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3438 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3439 ** features that require the use of temporary files may fail.
3440 **
3441 ** See also: [sqlite3_temp_directory]
3442 */
3444  const char *filename, /* Database filename (UTF-8) */
3445  sqlite3 **ppDb /* OUT: SQLite db handle */
3446 );
3448  const void *filename, /* Database filename (UTF-16) */
3449  sqlite3 **ppDb /* OUT: SQLite db handle */
3450 );
3452  const char *filename, /* Database filename (UTF-8) */
3453  sqlite3 **ppDb, /* OUT: SQLite db handle */
3454  int flags, /* Flags */
3455  const char *zVfs /* Name of VFS module to use */
3456 );
3457 
3458 /*
3459 ** CAPI3REF: Obtain Values For URI Parameters
3460 **
3461 ** These are utility routines, useful to VFS implementations, that check
3462 ** to see if a database file was a URI that contained a specific query
3463 ** parameter, and if so obtains the value of that query parameter.
3464 **
3465 ** If F is the database filename pointer passed into the xOpen() method of
3466 ** a VFS implementation when the flags parameter to xOpen() has one or
3467 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3468 ** P is the name of the query parameter, then
3469 ** sqlite3_uri_parameter(F,P) returns the value of the P
3470 ** parameter if it exists or a NULL pointer if P does not appear as a
3471 ** query parameter on F. If P is a query parameter of F
3472 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3473 ** a pointer to an empty string.
3474 **
3475 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3476 ** parameter and returns true (1) or false (0) according to the value
3477 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3478 ** value of query parameter P is one of "yes", "true", or "on" in any
3479 ** case or if the value begins with a non-zero number. The
3480 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3481 ** query parameter P is one of "no", "false", or "off" in any case or
3482 ** if the value begins with a numeric zero. If P is not a query
3483 ** parameter on F or if the value of P is does not match any of the
3484 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3485 **
3486 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3487 ** 64-bit signed integer and returns that integer, or D if P does not
3488 ** exist. If the value of P is something other than an integer, then
3489 ** zero is returned.
3490 **
3491 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3492 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3493 ** is not a database file pathname pointer that SQLite passed into the xOpen
3494 ** VFS method, then the behavior of this routine is undefined and probably
3495 ** undesirable.
3496 */
3497 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3498 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3499 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3500 
3501 
3502 /*
3503 ** CAPI3REF: Error Codes And Messages
3504 ** METHOD: sqlite3
3505 **
3506 ** ^If the most recent sqlite3_* API call associated with
3507 ** [database connection] D failed, then the sqlite3_errcode(D) interface
3508 ** returns the numeric [result code] or [extended result code] for that
3509 ** API call.
3510 ** If the most recent API call was successful,
3511 ** then the return value from sqlite3_errcode() is undefined.
3512 ** ^The sqlite3_extended_errcode()
3513 ** interface is the same except that it always returns the
3514 ** [extended result code] even when extended result codes are
3515 ** disabled.
3516 **
3517 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3518 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3519 ** ^(Memory to hold the error message string is managed internally.
3520 ** The application does not need to worry about freeing the result.
3521 ** However, the error string might be overwritten or deallocated by
3522 ** subsequent calls to other SQLite interface functions.)^
3523 **
3524 ** ^The sqlite3_errstr() interface returns the English-language text
3525 ** that describes the [result code], as UTF-8.
3526 ** ^(Memory to hold the error message string is managed internally
3527 ** and must not be freed by the application)^.
3528 **
3529 ** When the serialized [threading mode] is in use, it might be the
3530 ** case that a second error occurs on a separate thread in between
3531 ** the time of the first error and the call to these interfaces.
3532 ** When that happens, the second error will be reported since these
3533 ** interfaces always report the most recent result. To avoid
3534 ** this, each thread can obtain exclusive use of the [database connection] D
3535 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3536 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3537 ** all calls to the interfaces listed here are completed.
3538 **
3539 ** If an interface fails with SQLITE_MISUSE, that means the interface
3540 ** was invoked incorrectly by the application. In that case, the
3541 ** error code and message may or may not be set.
3542 */
3545 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3546 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3547 SQLITE_API const char *sqlite3_errstr(int);
3548 
3549 /*
3550 ** CAPI3REF: Prepared Statement Object
3551 ** KEYWORDS: {prepared statement} {prepared statements}
3552 **
3553 ** An instance of this object represents a single SQL statement that
3554 ** has been compiled into binary form and is ready to be evaluated.
3555 **
3556 ** Think of each SQL statement as a separate computer program. The
3557 ** original SQL text is source code. A prepared statement object
3558 ** is the compiled object code. All SQL must be converted into a
3559 ** prepared statement before it can be run.
3560 **
3561 ** The life-cycle of a prepared statement object usually goes like this:
3562 **
3563 ** <ol>
3564 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3565 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
3566 ** interfaces.
3567 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3568 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3569 ** to step 2. Do this zero or more times.
3570 ** <li> Destroy the object using [sqlite3_finalize()].
3571 ** </ol>
3572 */
3574 
3575 /*
3576 ** CAPI3REF: Run-time Limits
3577 ** METHOD: sqlite3
3578 **
3579 ** ^(This interface allows the size of various constructs to be limited
3580 ** on a connection by connection basis. The first parameter is the
3581 ** [database connection] whose limit is to be set or queried. The
3582 ** second parameter is one of the [limit categories] that define a
3583 ** class of constructs to be size limited. The third parameter is the
3584 ** new limit for that construct.)^
3585 **
3586 ** ^If the new limit is a negative number, the limit is unchanged.
3587 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3588 ** [limits | hard upper bound]
3589 ** set at compile-time by a C preprocessor macro called
3590 ** [limits | SQLITE_MAX_<i>NAME</i>].
3591 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3592 ** ^Attempts to increase a limit above its hard upper bound are
3593 ** silently truncated to the hard upper bound.
3594 **
3595 ** ^Regardless of whether or not the limit was changed, the
3596 ** [sqlite3_limit()] interface returns the prior value of the limit.
3597 ** ^Hence, to find the current value of a limit without changing it,
3598 ** simply invoke this interface with the third parameter set to -1.
3599 **
3600 ** Run-time limits are intended for use in applications that manage
3601 ** both their own internal database and also databases that are controlled
3602 ** by untrusted external sources. An example application might be a
3603 ** web browser that has its own databases for storing history and
3604 ** separate databases controlled by JavaScript applications downloaded
3605 ** off the Internet. The internal databases can be given the
3606 ** large, default limits. Databases managed by external sources can
3607 ** be given much smaller limits designed to prevent a denial of service
3608 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3609 ** interface to further control untrusted SQL. The size of the database
3610 ** created by an untrusted script can be contained using the
3611 ** [max_page_count] [PRAGMA].
3612 **
3613 ** New run-time limit categories may be added in future releases.
3614 */
3615 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3616 
3617 /*
3618 ** CAPI3REF: Run-Time Limit Categories
3619 ** KEYWORDS: {limit category} {*limit categories}
3620 **
3621 ** These constants define various performance limits
3622 ** that can be lowered at run-time using [sqlite3_limit()].
3623 ** The synopsis of the meanings of the various limits is shown below.
3624 ** Additional information is available at [limits | Limits in SQLite].
3625 **
3626 ** <dl>
3627 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3628 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3629 **
3630 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3631 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3632 **
3633 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3634 ** <dd>The maximum number of columns in a table definition or in the
3635 ** result set of a [SELECT] or the maximum number of columns in an index
3636 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3637 **
3638 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3639 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3640 **
3641 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3642 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3643 **
3644 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3645 ** <dd>The maximum number of instructions in a virtual machine program
3646 ** used to implement an SQL statement. This limit is not currently
3647 ** enforced, though that might be added in some future release of
3648 ** SQLite.</dd>)^
3649 **
3650 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3651 ** <dd>The maximum number of arguments on a function.</dd>)^
3652 **
3653 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3654 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3655 **
3656 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3657 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3658 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3659 ** [GLOB] operators.</dd>)^
3660 **
3661 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3662 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3663 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3664 **
3665 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3666 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3667 **
3668 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3669 ** <dd>The maximum number of auxiliary worker threads that a single
3670 ** [prepared statement] may start.</dd>)^
3671 ** </dl>
3672 */
3673 #define SQLITE_LIMIT_LENGTH 0
3674 #define SQLITE_LIMIT_SQL_LENGTH 1
3675 #define SQLITE_LIMIT_COLUMN 2
3676 #define SQLITE_LIMIT_EXPR_DEPTH 3
3677 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3678 #define SQLITE_LIMIT_VDBE_OP 5
3679 #define SQLITE_LIMIT_FUNCTION_ARG 6
3680 #define SQLITE_LIMIT_ATTACHED 7
3681 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3682 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3683 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3684 #define SQLITE_LIMIT_WORKER_THREADS 11
3685 
3686 /*
3687 ** CAPI3REF: Compiling An SQL Statement
3688 ** KEYWORDS: {SQL statement compiler}
3689 ** METHOD: sqlite3
3690 ** CONSTRUCTOR: sqlite3_stmt
3691 **
3692 ** To execute an SQL query, it must first be compiled into a byte-code
3693 ** program using one of these routines.
3694 **
3695 ** The first argument, "db", is a [database connection] obtained from a
3696 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3697 ** [sqlite3_open16()]. The database connection must not have been closed.
3698 **
3699 ** The second argument, "zSql", is the statement to be compiled, encoded
3700 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3701 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3702 ** use UTF-16.
3703 **
3704 ** ^If the nByte argument is negative, then zSql is read up to the
3705 ** first zero terminator. ^If nByte is positive, then it is the
3706 ** number of bytes read from zSql. ^If nByte is zero, then no prepared
3707 ** statement is generated.
3708 ** If the caller knows that the supplied string is nul-terminated, then
3709 ** there is a small performance advantage to passing an nByte parameter that
3710 ** is the number of bytes in the input string <i>including</i>
3711 ** the nul-terminator.
3712 **
3713 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3714 ** past the end of the first SQL statement in zSql. These routines only
3715 ** compile the first statement in zSql, so *pzTail is left pointing to
3716 ** what remains uncompiled.
3717 **
3718 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3719 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3720 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3721 ** string or a comment) then *ppStmt is set to NULL.
3722 ** The calling procedure is responsible for deleting the compiled
3723 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3724 ** ppStmt may not be NULL.
3725 **
3726 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3727 ** otherwise an [error code] is returned.
3728 **
3729 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3730 ** recommended for all new programs. The two older interfaces are retained
3731 ** for backwards compatibility, but their use is discouraged.
3732 ** ^In the "v2" interfaces, the prepared statement
3733 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3734 ** original SQL text. This causes the [sqlite3_step()] interface to
3735 ** behave differently in three ways:
3736 **
3737 ** <ol>
3738 ** <li>
3739 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3740 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3741 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3742 ** retries will occur before sqlite3_step() gives up and returns an error.
3743 ** </li>
3744 **
3745 ** <li>
3746 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3747 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3748 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3749 ** and the application would have to make a second call to [sqlite3_reset()]
3750 ** in order to find the underlying cause of the problem. With the "v2" prepare
3751 ** interfaces, the underlying reason for the error is returned immediately.
3752 ** </li>
3753 **
3754 ** <li>
3755 ** ^If the specific value bound to [parameter | host parameter] in the
3756 ** WHERE clause might influence the choice of query plan for a statement,
3757 ** then the statement will be automatically recompiled, as if there had been
3758 ** a schema change, on the first [sqlite3_step()] call following any change
3759 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3760 ** ^The specific value of WHERE-clause [parameter] might influence the
3761 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3762 ** or [GLOB] operator or if the parameter is compared to an indexed column
3763 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3764 ** </li>
3765 ** </ol>
3766 */
3768  sqlite3 *db, /* Database handle */
3769  const char *zSql, /* SQL statement, UTF-8 encoded */
3770  int nByte, /* Maximum length of zSql in bytes. */
3771  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3772  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3773 );
3775  sqlite3 *db, /* Database handle */
3776  const char *zSql, /* SQL statement, UTF-8 encoded */
3777  int nByte, /* Maximum length of zSql in bytes. */
3778  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3779  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3780 );
3782  sqlite3 *db, /* Database handle */
3783  const void *zSql, /* SQL statement, UTF-16 encoded */
3784  int nByte, /* Maximum length of zSql in bytes. */
3785  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3786  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3787 );
3789  sqlite3 *db, /* Database handle */
3790  const void *zSql, /* SQL statement, UTF-16 encoded */
3791  int nByte, /* Maximum length of zSql in bytes. */
3792  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3793  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3794 );
3795 
3796 /*
3797 ** CAPI3REF: Retrieving Statement SQL
3798 ** METHOD: sqlite3_stmt
3799 **
3800 ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
3801 ** SQL text used to create [prepared statement] P if P was
3802 ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3803 ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
3804 ** string containing the SQL text of prepared statement P with
3805 ** [bound parameters] expanded.
3806 **
3807 ** ^(For example, if a prepared statement is created using the SQL
3808 ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
3809 ** and parameter :xyz is unbound, then sqlite3_sql() will return
3810 ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
3811 ** will return "SELECT 2345,NULL".)^
3812 **
3813 ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
3814 ** is available to hold the result, or if the result would exceed the
3815 ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
3816 **
3817 ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
3818 ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
3819 ** option causes sqlite3_expanded_sql() to always return NULL.
3820 **
3821 ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
3822 ** automatically freed when the prepared statement is finalized.
3823 ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
3824 ** is obtained from [sqlite3_malloc()] and must be free by the application
3825 ** by passing it to [sqlite3_free()].
3826 */
3827 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3829 
3830 /*
3831 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3832 ** METHOD: sqlite3_stmt
3833 **
3834 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3835 ** and only if the [prepared statement] X makes no direct changes to
3836 ** the content of the database file.
3837 **
3838 ** Note that [application-defined SQL functions] or
3839 ** [virtual tables] might change the database indirectly as a side effect.
3840 ** ^(For example, if an application defines a function "eval()" that
3841 ** calls [sqlite3_exec()], then the following SQL statement would
3842 ** change the database file through side-effects:
3843 **
3844 ** <blockquote><pre>
3845 ** SELECT eval('DELETE FROM t1') FROM t2;
3846 ** </pre></blockquote>
3847 **
3848 ** But because the [SELECT] statement does not change the database file
3849 ** directly, sqlite3_stmt_readonly() would still return true.)^
3850 **
3851 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3852 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3853 ** since the statements themselves do not actually modify the database but
3854 ** rather they control the timing of when other statements modify the
3855 ** database. ^The [ATTACH] and [DETACH] statements also cause
3856 ** sqlite3_stmt_readonly() to return true since, while those statements
3857 ** change the configuration of a database connection, they do not make
3858 ** changes to the content of the database files on disk.
3859 */
3861 
3862 /*
3863 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3864 ** METHOD: sqlite3_stmt
3865 **
3866 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3867 ** [prepared statement] S has been stepped at least once using
3868 ** [sqlite3_step(S)] but has neither run to completion (returned
3869 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3870 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3871 ** interface returns false if S is a NULL pointer. If S is not a
3872 ** NULL pointer and is not a pointer to a valid [prepared statement]
3873 ** object, then the behavior is undefined and probably undesirable.
3874 **
3875 ** This interface can be used in combination [sqlite3_next_stmt()]
3876 ** to locate all prepared statements associated with a database
3877 ** connection that are in need of being reset. This can be used,
3878 ** for example, in diagnostic routines to search for prepared
3879 ** statements that are holding a transaction open.
3880 */
3882 
3883 /*
3884 ** CAPI3REF: Dynamically Typed Value Object
3885 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3886 **
3887 ** SQLite uses the sqlite3_value object to represent all values
3888 ** that can be stored in a database table. SQLite uses dynamic typing
3889 ** for the values it stores. ^Values stored in sqlite3_value objects
3890 ** can be integers, floating point values, strings, BLOBs, or NULL.
3891 **
3892 ** An sqlite3_value object may be either "protected" or "unprotected".
3893 ** Some interfaces require a protected sqlite3_value. Other interfaces
3894 ** will accept either a protected or an unprotected sqlite3_value.
3895 ** Every interface that accepts sqlite3_value arguments specifies
3896 ** whether or not it requires a protected sqlite3_value. The
3897 ** [sqlite3_value_dup()] interface can be used to construct a new
3898 ** protected sqlite3_value from an unprotected sqlite3_value.
3899 **
3900 ** The terms "protected" and "unprotected" refer to whether or not
3901 ** a mutex is held. An internal mutex is held for a protected
3902 ** sqlite3_value object but no mutex is held for an unprotected
3903 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3904 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3905 ** or if SQLite is run in one of reduced mutex modes
3906 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3907 ** then there is no distinction between protected and unprotected
3908 ** sqlite3_value objects and they can be used interchangeably. However,
3909 ** for maximum code portability it is recommended that applications
3910 ** still make the distinction between protected and unprotected
3911 ** sqlite3_value objects even when not strictly required.
3912 **
3913 ** ^The sqlite3_value objects that are passed as parameters into the
3914 ** implementation of [application-defined SQL functions] are protected.
3915 ** ^The sqlite3_value object returned by
3916 ** [sqlite3_column_value()] is unprotected.
3917 ** Unprotected sqlite3_value objects may only be used with
3918 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3919 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3920 ** interfaces require protected sqlite3_value objects.
3921 */
3922 typedef struct Mem sqlite3_value;
3923 
3924 /*
3925 ** CAPI3REF: SQL Function Context Object
3926 **
3927 ** The context in which an SQL function executes is stored in an
3928 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3929 ** is always first parameter to [application-defined SQL functions].
3930 ** The application-defined SQL function implementation will pass this
3931 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3932 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3933 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3934 ** and/or [sqlite3_set_auxdata()].
3935 */
3937 
3938 /*
3939 ** CAPI3REF: Binding Values To Prepared Statements
3940 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3941 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3942 ** METHOD: sqlite3_stmt
3943 **
3944 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3945 ** literals may be replaced by a [parameter] that matches one of following
3946 ** templates:
3947 **
3948 ** <ul>
3949 ** <li> ?
3950 ** <li> ?NNN
3951 ** <li> :VVV
3952 ** <li> @VVV
3953 ** <li> $VVV
3954 ** </ul>
3955 **
3956 ** In the templates above, NNN represents an integer literal,
3957 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3958 ** parameters (also called "host parameter names" or "SQL parameters")
3959 ** can be set using the sqlite3_bind_*() routines defined here.
3960 **
3961 ** ^The first argument to the sqlite3_bind_*() routines is always
3962 ** a pointer to the [sqlite3_stmt] object returned from
3963 ** [sqlite3_prepare_v2()] or its variants.
3964 **
3965 ** ^The second argument is the index of the SQL parameter to be set.
3966 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3967 ** SQL parameter is used more than once, second and subsequent
3968 ** occurrences have the same index as the first occurrence.
3969 ** ^The index for named parameters can be looked up using the
3970 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3971 ** for "?NNN" parameters is the value of NNN.
3972 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3973 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3974 **
3975 ** ^The third argument is the value to bind to the parameter.
3976 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3977 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3978 ** is ignored and the end result is the same as sqlite3_bind_null().
3979 **
3980 ** ^(In those routines that have a fourth argument, its value is the
3981 ** number of bytes in the parameter. To be clear: the value is the
3982 ** number of <u>bytes</u> in the value, not the number of characters.)^
3983 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3984 ** is negative, then the length of the string is
3985 ** the number of bytes up to the first zero terminator.
3986 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3987 ** the behavior is undefined.
3988 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3989 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3990 ** that parameter must be the byte offset
3991 ** where the NUL terminator would occur assuming the string were NUL
3992 ** terminated. If any NUL characters occur at byte offsets less than
3993 ** the value of the fourth parameter then the resulting string value will
3994 ** contain embedded NULs. The result of expressions involving strings
3995 ** with embedded NULs is undefined.
3996 **
3997 ** ^The fifth argument to the BLOB and string binding interfaces
3998 ** is a destructor used to dispose of the BLOB or
3999 ** string after SQLite has finished with it. ^The destructor is called
4000 ** to dispose of the BLOB or string even if the call to bind API fails.
4001 ** ^If the fifth argument is
4002 ** the special value [SQLITE_STATIC], then SQLite assumes that the
4003 ** information is in static, unmanaged space and does not need to be freed.
4004 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
4005 ** SQLite makes its own private copy of the data immediately, before
4006 ** the sqlite3_bind_*() routine returns.
4007 **
4008 ** ^The sixth argument to sqlite3_bind_text64() must be one of
4009 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
4010 ** to specify the encoding of the text in the third parameter. If
4011 ** the sixth argument to sqlite3_bind_text64() is not one of the
4012 ** allowed values shown above, or if the text encoding is different
4013 ** from the encoding specified by the sixth parameter, then the behavior
4014 ** is undefined.
4015 **
4016 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
4017 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
4018 ** (just an integer to hold its size) while it is being processed.
4019 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
4020 ** content is later written using
4021 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
4022 ** ^A negative value for the zeroblob results in a zero-length BLOB.
4023 **
4024 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
4025 ** for the [prepared statement] or with a prepared statement for which
4026 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
4027 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
4028 ** routine is passed a [prepared statement] that has been finalized, the
4029 ** result is undefined and probably harmful.
4030 **
4031 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
4032 ** ^Unbound parameters are interpreted as NULL.
4033 **
4034 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
4035 ** [error code] if anything goes wrong.
4036 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
4037 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
4038 ** [SQLITE_MAX_LENGTH].
4039 ** ^[SQLITE_RANGE] is returned if the parameter
4040 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
4041 **
4042 ** See also: [sqlite3_bind_parameter_count()],
4043 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
4044 */
4045 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
4046 SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
4047  void(*)(void*));
4048 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
4049 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
4050 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
4052 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
4053 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
4054 SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
4055  void(*)(void*), unsigned char encoding);
4058 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
4059 
4060 /*
4061 ** CAPI3REF: Number Of SQL Parameters
4062 ** METHOD: sqlite3_stmt
4063 **
4064 ** ^This routine can be used to find the number of [SQL parameters]
4065 ** in a [prepared statement]. SQL parameters are tokens of the
4066 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
4067 ** placeholders for values that are [sqlite3_bind_blob | bound]
4068 ** to the parameters at a later time.
4069 **
4070 ** ^(This routine actually returns the index of the largest (rightmost)
4071 ** parameter. For all forms except ?NNN, this will correspond to the
4072 ** number of unique parameters. If parameters of the ?NNN form are used,
4073 ** there may be gaps in the list.)^
4074 **
4075 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4076 ** [sqlite3_bind_parameter_name()], and
4077 ** [sqlite3_bind_parameter_index()].
4078 */
4080 
4081 /*
4082 ** CAPI3REF: Name Of A Host Parameter
4083 ** METHOD: sqlite3_stmt
4084 **
4085 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
4086 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
4087 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
4088 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
4089 ** respectively.
4090 ** In other words, the initial ":" or "$" or "@" or "?"
4091 ** is included as part of the name.)^
4092 ** ^Parameters of the form "?" without a following integer have no name
4093 ** and are referred to as "nameless" or "anonymous parameters".
4094 **
4095 ** ^The first host parameter has an index of 1, not 0.
4096 **
4097 ** ^If the value N is out of range or if the N-th parameter is
4098 ** nameless, then NULL is returned. ^The returned string is
4099 ** always in UTF-8 encoding even if the named parameter was
4100 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
4101 ** [sqlite3_prepare16_v2()].
4102 **
4103 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4104 ** [sqlite3_bind_parameter_count()], and
4105 ** [sqlite3_bind_parameter_index()].
4106 */
4108 
4109 /*
4110 ** CAPI3REF: Index Of A Parameter With A Given Name
4111 ** METHOD: sqlite3_stmt
4112 **
4113 ** ^Return the index of an SQL parameter given its name. ^The
4114 ** index value returned is suitable for use as the second
4115 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
4116 ** is returned if no matching parameter is found. ^The parameter
4117 ** name must be given in UTF-8 even if the original statement
4118 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
4119 **
4120 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
4121 ** [sqlite3_bind_parameter_count()], and
4122 ** [sqlite3_bind_parameter_name()].
4123 */
4124 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
4125 
4126 /*
4127 ** CAPI3REF: Reset All Bindings On A Prepared Statement
4128 ** METHOD: sqlite3_stmt
4129 **
4130 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
4131 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
4132 ** ^Use this routine to reset all host parameters to NULL.
4133 */
4135 
4136 /*
4137 ** CAPI3REF: Number Of Columns In A Result Set
4138 ** METHOD: sqlite3_stmt
4139 **
4140 ** ^Return the number of columns in the result set returned by the
4141 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
4142 ** statement that does not return data (for example an [UPDATE]).
4143 **
4144 ** See also: [sqlite3_data_count()]
4145 */
4147 
4148 /*
4149 ** CAPI3REF: Column Names In A Result Set
4150 ** METHOD: sqlite3_stmt
4151 **
4152 ** ^These routines return the name assigned to a particular column
4153 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
4154 ** interface returns a pointer to a zero-terminated UTF-8 string
4155 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
4156 ** UTF-16 string. ^The first parameter is the [prepared statement]
4157 ** that implements the [SELECT] statement. ^The second parameter is the
4158 ** column number. ^The leftmost column is number 0.
4159 **
4160 ** ^The returned string pointer is valid until either the [prepared statement]
4161 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4162 ** reprepared by the first call to [sqlite3_step()] for a particular run
4163 ** or until the next call to
4164 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4165 **
4166 ** ^If sqlite3_malloc() fails during the processing of either routine
4167 ** (for example during a conversion from UTF-8 to UTF-16) then a
4168 ** NULL pointer is returned.
4169 **
4170 ** ^The name of a result column is the value of the "AS" clause for
4171 ** that column, if there is an AS clause. If there is no AS clause
4172 ** then the name of the column is unspecified and may change from
4173 ** one release of SQLite to the next.
4174 */
4175 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
4176 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
4177 
4178 /*
4179 ** CAPI3REF: Source Of Data In A Query Result
4180 ** METHOD: sqlite3_stmt
4181 **
4182 ** ^These routines provide a means to determine the database, table, and
4183 ** table column that is the origin of a particular result column in
4184 ** [SELECT] statement.
4185 ** ^The name of the database or table or column can be returned as
4186 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
4187 ** the database name, the _table_ routines return the table name, and
4188 ** the origin_ routines return the column name.
4189 ** ^The returned string is valid until the [prepared statement] is destroyed
4190 ** using [sqlite3_finalize()] or until the statement is automatically
4191 ** reprepared by the first call to [sqlite3_step()] for a particular run
4192 ** or until the same information is requested
4193 ** again in a different encoding.
4194 **
4195 ** ^The names returned are the original un-aliased names of the
4196 ** database, table, and column.
4197 **
4198 ** ^The first argument to these interfaces is a [prepared statement].
4199 ** ^These functions return information about the Nth result column returned by
4200 ** the statement, where N is the second function argument.
4201 ** ^The left-most column is column 0 for these routines.
4202 **
4203 ** ^If the Nth column returned by the statement is an expression or
4204 ** subquery and is not a column value, then all of these functions return
4205 ** NULL. ^These routine might also return NULL if a memory allocation error
4206 ** occurs. ^Otherwise, they return the name of the attached database, table,
4207 ** or column that query result column was extracted from.
4208 **
4209 ** ^As with all other SQLite APIs, those whose names end with "16" return
4210 ** UTF-16 encoded strings and the other functions return UTF-8.
4211 **
4212 ** ^These APIs are only available if the library was compiled with the
4213 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4214 **
4215 ** If two or more threads call one or more of these routines against the same
4216 ** prepared statement and column at the same time then the results are
4217 ** undefined.
4218 **
4219 ** If two or more threads call one or more
4220 ** [sqlite3_column_database_name | column metadata interfaces]
4221 ** for the same [prepared statement] and result column
4222 ** at the same time then the results are undefined.
4223 */
4230 
4231 /*
4232 ** CAPI3REF: Declared Datatype Of A Query Result
4233 ** METHOD: sqlite3_stmt
4234 **
4235 ** ^(The first parameter is a [prepared statement].
4236 ** If this statement is a [SELECT] statement and the Nth column of the
4237 ** returned result set of that [SELECT] is a table column (not an
4238 ** expression or subquery) then the declared type of the table
4239 ** column is returned.)^ ^If the Nth column of the result set is an
4240 ** expression or subquery, then a NULL pointer is returned.
4241 ** ^The returned string is always UTF-8 encoded.
4242 **
4243 ** ^(For example, given the database schema:
4244 **
4245 ** CREATE TABLE t1(c1 VARIANT);
4246 **
4247 ** and the following statement to be compiled:
4248 **
4249 ** SELECT c1 + 1, c1 FROM t1;
4250 **
4251 ** this routine would return the string "VARIANT" for the second result
4252 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4253 **
4254 ** ^SQLite uses dynamic run-time typing. ^So just because a column
4255 ** is declared to contain a particular type does not mean that the
4256 ** data stored in that column is of the declared type. SQLite is
4257 ** strongly typed, but the typing is dynamic not static. ^Type
4258 ** is associated with individual values, not with the containers
4259 ** used to hold those values.
4260 */
4263 
4264 /*
4265 ** CAPI3REF: Evaluate An SQL Statement
4266 ** METHOD: sqlite3_stmt
4267 **
4268 ** After a [prepared statement] has been prepared using either
4269 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4270 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4271 ** must be called one or more times to evaluate the statement.
4272 **
4273 ** The details of the behavior of the sqlite3_step() interface depend
4274 ** on whether the statement was prepared using the newer "v2" interface
4275 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4276 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
4277 ** new "v2" interface is recommended for new applications but the legacy
4278 ** interface will continue to be supported.
4279 **
4280 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4281 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4282 ** ^With the "v2" interface, any of the other [result codes] or
4283 ** [extended result codes] might be returned as well.
4284 **
4285 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4286 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
4287 ** or occurs outside of an explicit transaction, then you can retry the
4288 ** statement. If the statement is not a [COMMIT] and occurs within an
4289 ** explicit transaction then you should rollback the transaction before
4290 ** continuing.
4291 **
4292 ** ^[SQLITE_DONE] means that the statement has finished executing
4293 ** successfully. sqlite3_step() should not be called again on this virtual
4294 ** machine without first calling [sqlite3_reset()] to reset the virtual
4295 ** machine back to its initial state.
4296 **
4297 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4298 ** is returned each time a new row of data is ready for processing by the
4299 ** caller. The values may be accessed using the [column access functions].
4300 ** sqlite3_step() is called again to retrieve the next row of data.
4301 **
4302 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4303 ** violation) has occurred. sqlite3_step() should not be called again on
4304 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4305 ** ^With the legacy interface, a more specific error code (for example,
4306 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4307 ** can be obtained by calling [sqlite3_reset()] on the
4308 ** [prepared statement]. ^In the "v2" interface,
4309 ** the more specific error code is returned directly by sqlite3_step().
4310 **
4311 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4312 ** Perhaps it was called on a [prepared statement] that has
4313 ** already been [sqlite3_finalize | finalized] or on one that had
4314 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
4315 ** be the case that the same database connection is being used by two or
4316 ** more threads at the same moment in time.
4317 **
4318 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4319 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4320 ** other than [SQLITE_ROW] before any subsequent invocation of
4321 ** sqlite3_step(). Failure to reset the prepared statement using
4322 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4323 ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
4324 ** sqlite3_step() began
4325 ** calling [sqlite3_reset()] automatically in this circumstance rather
4326 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
4327 ** break because any application that ever receives an SQLITE_MISUSE error
4328 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
4329 ** can be used to restore the legacy behavior.
4330 **
4331 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4332 ** API always returns a generic error code, [SQLITE_ERROR], following any
4333 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
4334 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4335 ** specific [error codes] that better describes the error.
4336 ** We admit that this is a goofy design. The problem has been fixed
4337 ** with the "v2" interface. If you prepare all of your SQL statements
4338 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4339 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4340 ** then the more specific [error codes] are returned directly
4341 ** by sqlite3_step(). The use of the "v2" interface is recommended.
4342 */
4344 
4345 /*
4346 ** CAPI3REF: Number of columns in a result set
4347 ** METHOD: sqlite3_stmt
4348 **
4349 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4350 ** current row of the result set of [prepared statement] P.
4351 ** ^If prepared statement P does not have results ready to return
4352 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4353 ** interfaces) then sqlite3_data_count(P) returns 0.
4354 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4355 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4356 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
4357 ** will return non-zero if previous call to [sqlite3_step](P) returned
4358 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4359 ** where it always returns zero since each step of that multi-step
4360 ** pragma returns 0 columns of data.
4361 **
4362 ** See also: [sqlite3_column_count()]
4363 */
4365 
4366 /*
4367 ** CAPI3REF: Fundamental Datatypes
4368 ** KEYWORDS: SQLITE_TEXT
4369 **
4370 ** ^(Every value in SQLite has one of five fundamental datatypes:
4371 **
4372 ** <ul>
4373 ** <li> 64-bit signed integer
4374 ** <li> 64-bit IEEE floating point number
4375 ** <li> string
4376 ** <li> BLOB
4377 ** <li> NULL
4378 ** </ul>)^
4379 **
4380 ** These constants are codes for each of those types.
4381 **
4382 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4383 ** for a completely different meaning. Software that links against both
4384 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4385 ** SQLITE_TEXT.
4386 */
4387 #define SQLITE_INTEGER 1
4388 #define SQLITE_FLOAT 2
4389 #define SQLITE_BLOB 4
4390 #define SQLITE_NULL 5
4391 #ifdef SQLITE_TEXT
4392 # undef SQLITE_TEXT
4393 #else
4394 # define SQLITE_TEXT 3
4395 #endif
4396 #define SQLITE3_TEXT 3
4397 
4398 /*
4399 ** CAPI3REF: Result Values From A Query
4400 ** KEYWORDS: {column access functions}
4401 ** METHOD: sqlite3_stmt
4402 **
4403 ** ^These routines return information about a single column of the current
4404 ** result row of a query. ^In every case the first argument is a pointer
4405 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4406 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4407 ** and the second argument is the index of the column for which information
4408 ** should be returned. ^The leftmost column of the result set has the index 0.
4409 ** ^The number of columns in the result can be determined using
4410 ** [sqlite3_column_count()].
4411 **
4412 ** If the SQL statement does not currently point to a valid row, or if the
4413 ** column index is out of range, the result is undefined.
4414 ** These routines may only be called when the most recent call to
4415 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4416 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4417 ** If any of these routines are called after [sqlite3_reset()] or
4418 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4419 ** something other than [SQLITE_ROW], the results are undefined.
4420 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4421 ** are called from a different thread while any of these routines
4422 ** are pending, then the results are undefined.
4423 **
4424 ** ^The sqlite3_column_type() routine returns the
4425 ** [SQLITE_INTEGER | datatype code] for the initial data type
4426 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
4427 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
4428 ** returned by sqlite3_column_type() is only meaningful if no type
4429 ** conversions have occurred as described below. After a type conversion,
4430 ** the value returned by sqlite3_column_type() is undefined. Future
4431 ** versions of SQLite may change the behavior of sqlite3_column_type()
4432 ** following a type conversion.
4433 **
4434 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4435 ** routine returns the number of bytes in that BLOB or string.
4436 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4437 ** the string to UTF-8 and then returns the number of bytes.
4438 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4439 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4440 ** the number of bytes in that string.
4441 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4442 **
4443 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4444 ** routine returns the number of bytes in that BLOB or string.
4445 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4446 ** the string to UTF-16 and then returns the number of bytes.
4447 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4448 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4449 ** the number of bytes in that string.
4450 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4451 **
4452 ** ^The values returned by [sqlite3_column_bytes()] and
4453 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4454 ** of the string. ^For clarity: the values returned by
4455 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4456 ** bytes in the string, not the number of characters.
4457 **
4458 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4459 ** even empty strings, are always zero-terminated. ^The return
4460 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4461 **
4462 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4463 ** [unprotected sqlite3_value] object. In a multithreaded environment,
4464 ** an unprotected sqlite3_value object may only be used safely with
4465 ** [sqlite3_bind_value()] and [sqlite3_result_value()].
4466 ** If the [unprotected sqlite3_value] object returned by
4467 ** [sqlite3_column_value()] is used in any other way, including calls
4468 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4469 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4470 **
4471 ** These routines attempt to convert the value where appropriate. ^For
4472 ** example, if the internal representation is FLOAT and a text result
4473 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4474 ** conversion automatically. ^(The following table details the conversions
4475 ** that are applied:
4476 **
4477 ** <blockquote>
4478 ** <table border="1">
4479 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
4480 **
4481 ** <tr><td> NULL <td> INTEGER <td> Result is 0
4482 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
4483 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
4484 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
4485 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4486 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4487 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4488 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
4489 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4490 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
4491 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
4492 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
4493 ** <tr><td> TEXT <td> BLOB <td> No change
4494 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
4495 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
4496 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4497 ** </table>
4498 ** </blockquote>)^
4499 **
4500 ** Note that when type conversions occur, pointers returned by prior
4501 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4502 ** sqlite3_column_text16() may be invalidated.
4503 ** Type conversions and pointer invalidations might occur
4504 ** in the following cases:
4505 **
4506 ** <ul>
4507 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4508 ** sqlite3_column_text16() is called. A zero-terminator might
4509 ** need to be added to the string.</li>
4510 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4511 ** sqlite3_column_text16() is called. The content must be converted
4512 ** to UTF-16.</li>
4513 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4514 ** sqlite3_column_text() is called. The content must be converted
4515 ** to UTF-8.</li>
4516 ** </ul>
4517 **
4518 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4519 ** not invalidate a prior pointer, though of course the content of the buffer
4520 ** that the prior pointer references will have been modified. Other kinds
4521 ** of conversion are done in place when it is possible, but sometimes they
4522 ** are not possible and in those cases prior pointers are invalidated.
4523 **
4524 ** The safest policy is to invoke these routines
4525 ** in one of the following ways:
4526 **
4527 ** <ul>
4528 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4529 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4530 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4531 ** </ul>
4532 **
4533 ** In other words, you should call sqlite3_column_text(),
4534 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4535 ** into the desired format, then invoke sqlite3_column_bytes() or
4536 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4537 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4538 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4539 ** with calls to sqlite3_column_bytes().
4540 **
4541 ** ^The pointers returned are valid until a type conversion occurs as
4542 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4543 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4544 ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
4545 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4546 ** [sqlite3_free()].
4547 **
4548 ** ^(If a memory allocation error occurs during the evaluation of any
4549 ** of these routines, a default value is returned. The default value
4550 ** is either the integer 0, the floating point number 0.0, or a NULL
4551 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4552 ** [SQLITE_NOMEM].)^
4553 */
4554 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4557 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4559 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4560 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4561 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4564 
4565 /*
4566 ** CAPI3REF: Destroy A Prepared Statement Object
4567 ** DESTRUCTOR: sqlite3_stmt
4568 **
4569 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4570 ** ^If the most recent evaluation of the statement encountered no errors
4571 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4572 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4573 ** sqlite3_finalize(S) returns the appropriate [error code] or
4574 ** [extended error code].
4575 **
4576 ** ^The sqlite3_finalize(S) routine can be called at any point during
4577 ** the life cycle of [prepared statement] S:
4578 ** before statement S is ever evaluated, after
4579 ** one or more calls to [sqlite3_reset()], or after any call
4580 ** to [sqlite3_step()] regardless of whether or not the statement has
4581 ** completed execution.
4582 **
4583 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4584 **
4585 ** The application must finalize every [prepared statement] in order to avoid
4586 ** resource leaks. It is a grievous error for the application to try to use
4587 ** a prepared statement after it has been finalized. Any use of a prepared
4588 ** statement after it has been finalized can result in undefined and
4589 ** undesirable behavior such as segfaults and heap corruption.
4590 */
4592 
4593 /*
4594 ** CAPI3REF: Reset A Prepared Statement Object
4595 ** METHOD: sqlite3_stmt
4596 **
4597 ** The sqlite3_reset() function is called to reset a [prepared statement]
4598 ** object back to its initial state, ready to be re-executed.
4599 ** ^Any SQL statement variables that had values bound to them using
4600 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4601 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4602 **
4603 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4604 ** back to the beginning of its program.
4605 **
4606 ** ^If the most recent call to [sqlite3_step(S)] for the
4607 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4608 ** or if [sqlite3_step(S)] has never before been called on S,
4609 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4610 **
4611 ** ^If the most recent call to [sqlite3_step(S)] for the
4612 ** [prepared statement] S indicated an error, then
4613 ** [sqlite3_reset(S)] returns an appropriate [error code].
4614 **
4615 ** ^The [sqlite3_reset(S)] interface does not change the values
4616 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4617 */
4619 
4620 /*
4621 ** CAPI3REF: Create Or Redefine SQL Functions
4622 ** KEYWORDS: {function creation routines}
4623 ** KEYWORDS: {application-defined SQL function}
4624 ** KEYWORDS: {application-defined SQL functions}
4625 ** METHOD: sqlite3
4626 **
4627 ** ^These functions (collectively known as "function creation routines")
4628 ** are used to add SQL functions or aggregates or to redefine the behavior
4629 ** of existing SQL functions or aggregates. The only differences between
4630 ** these routines are the text encoding expected for
4631 ** the second parameter (the name of the function being created)
4632 ** and the presence or absence of a destructor callback for
4633 ** the application data pointer.
4634 **
4635 ** ^The first parameter is the [database connection] to which the SQL
4636 ** function is to be added. ^If an application uses more than one database
4637 ** connection then application-defined SQL functions must be added
4638 ** to each database connection separately.
4639 **
4640 ** ^The second parameter is the name of the SQL function to be created or
4641 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4642 ** representation, exclusive of the zero-terminator. ^Note that the name
4643 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4644 ** ^Any attempt to create a function with a longer name
4645 ** will result in [SQLITE_MISUSE] being returned.
4646 **
4647 ** ^The third parameter (nArg)
4648 ** is the number of arguments that the SQL function or
4649 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4650 ** aggregate may take any number of arguments between 0 and the limit
4651 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4652 ** parameter is less than -1 or greater than 127 then the behavior is
4653 ** undefined.
4654 **
4655 ** ^The fourth parameter, eTextRep, specifies what
4656 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4657 ** its parameters. The application should set this parameter to
4658 ** [SQLITE_UTF16LE] if the function implementation invokes
4659 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4660 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4661 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4662 ** otherwise. ^The same SQL function may be registered multiple times using
4663 ** different preferred text encodings, with different implementations for
4664 ** each encoding.
4665 ** ^When multiple implementations of the same function are available, SQLite
4666 ** will pick the one that involves the least amount of data conversion.
4667 **
4668 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4669 ** to signal that the function will always return the same result given
4670 ** the same inputs within a single SQL statement. Most SQL functions are
4671 ** deterministic. The built-in [random()] SQL function is an example of a
4672 ** function that is not deterministic. The SQLite query planner is able to
4673 ** perform additional optimizations on deterministic functions, so use
4674 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4675 **
4676 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4677 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4678 **
4679 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4680 ** pointers to C-language functions that implement the SQL function or
4681 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4682 ** callback only; NULL pointers must be passed as the xStep and xFinal
4683 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4684 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4685 ** SQL function or aggregate, pass NULL pointers for all three function
4686 ** callbacks.
4687 **
4688 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4689 ** then it is destructor for the application data pointer.
4690 ** The destructor is invoked when the function is deleted, either by being
4691 ** overloaded or when the database connection closes.)^
4692 ** ^The destructor is also invoked if the call to
4693 ** sqlite3_create_function_v2() fails.
4694 ** ^When the destructor callback of the tenth parameter is invoked, it
4695 ** is passed a single argument which is a copy of the application data
4696 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4697 **
4698 ** ^It is permitted to register multiple implementations of the same
4699 ** functions with the same name but with either differing numbers of
4700 ** arguments or differing preferred text encodings. ^SQLite will use
4701 ** the implementation that most closely matches the way in which the
4702 ** SQL function is used. ^A function implementation with a non-negative
4703 ** nArg parameter is a better match than a function implementation with
4704 ** a negative nArg. ^A function where the preferred text encoding
4705 ** matches the database encoding is a better
4706 ** match than a function where the encoding is different.
4707 ** ^A function where the encoding difference is between UTF16le and UTF16be
4708 ** is a closer match than a function where the encoding difference is
4709 ** between UTF8 and UTF16.
4710 **
4711 ** ^Built-in functions may be overloaded by new application-defined functions.
4712 **
4713 ** ^An application-defined function is permitted to call other
4714 ** SQLite interfaces. However, such calls must not
4715 ** close the database connection nor finalize or reset the prepared
4716 ** statement in which the function is running.
4717 */
4719  sqlite3 *db,
4720  const char *zFunctionName,
4721  int nArg,
4722  int eTextRep,
4723  void *pApp,
4724  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4725  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4726  void (*xFinal)(sqlite3_context*)
4727 );
4729  sqlite3 *db,
4730  const void *zFunctionName,
4731  int nArg,
4732  int eTextRep,
4733  void *pApp,
4734  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4735  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4736  void (*xFinal)(sqlite3_context*)
4737 );
4739  sqlite3 *db,
4740  const char *zFunctionName,
4741  int nArg,
4742  int eTextRep,
4743  void *pApp,
4744  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4745  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4746  void (*xFinal)(sqlite3_context*),
4747  void(*xDestroy)(void*)
4748 );
4749 
4750 /*
4751 ** CAPI3REF: Text Encodings
4752 **
4753 ** These constant define integer codes that represent the various
4754 ** text encodings supported by SQLite.
4755 */
4756 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
4757 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
4758 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
4759 #define SQLITE_UTF16 4 /* Use native byte order */
4760 #define SQLITE_ANY 5 /* Deprecated */
4761 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4762 
4763 /*
4764 ** CAPI3REF: Function Flags
4765 **
4766 ** These constants may be ORed together with the
4767 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4768 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4769 ** [sqlite3_create_function_v2()].
4770 */
4771 #define SQLITE_DETERMINISTIC 0x800
4772 
4773 /*
4774 ** CAPI3REF: Deprecated Functions
4775 ** DEPRECATED
4776 **
4777 ** These functions are [deprecated]. In order to maintain
4778 ** backwards compatibility with older code, these functions continue
4779 ** to be supported. However, new applications should avoid
4780 ** the use of these functions. To encourage programmers to avoid
4781 ** these functions, we will not explain what they do.
4782 */
4783 #ifndef SQLITE_OMIT_DEPRECATED
4789 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4790  void*,sqlite3_int64);
4791 #endif
4792 
4793 /*
4794 ** CAPI3REF: Obtaining SQL Values
4795 ** METHOD: sqlite3_value
4796 **
4797 ** The C-language implementation of SQL functions and aggregates uses
4798 ** this set of interface routines to access the parameter values on
4799 ** the function or aggregate.
4800 **
4801 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4802 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4803 ** define callbacks that implement the SQL functions and aggregates.
4804 ** The 3rd parameter to these callbacks is an array of pointers to
4805 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4806 ** each parameter to the SQL function. These routines are used to
4807 ** extract values from the [sqlite3_value] objects.
4808 **
4809 ** These routines work only with [protected sqlite3_value] objects.
4810 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4811 ** object results in undefined behavior.
4812 **
4813 ** ^These routines work just like the corresponding [column access functions]
4814 ** except that these routines take a single [protected sqlite3_value] object
4815 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4816 **
4817 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4818 ** in the native byte-order of the host machine. ^The
4819 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4820 ** extract UTF-16 strings as big-endian and little-endian respectively.
4821 **
4822 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4823 ** numeric affinity to the value. This means that an attempt is
4824 ** made to convert the value to an integer or floating point. If
4825 ** such a conversion is possible without loss of information (in other
4826 ** words, if the value is a string that looks like a number)
4827 ** then the conversion is performed. Otherwise no conversion occurs.
4828 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4829 **
4830 ** Please pay particular attention to the fact that the pointer returned
4831 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4832 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4833 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4834 ** or [sqlite3_value_text16()].
4835 **
4836 ** These routines must be called from the same thread as
4837 ** the SQL function that supplied the [sqlite3_value*] parameters.
4838 */
4845 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4851 
4852 /*
4853 ** CAPI3REF: Finding The Subtype Of SQL Values
4854 ** METHOD: sqlite3_value
4855 **
4856 ** The sqlite3_value_subtype(V) function returns the subtype for
4857 ** an [application-defined SQL function] argument V. The subtype
4858 ** information can be used to pass a limited amount of context from
4859 ** one SQL function to another. Use the [sqlite3_result_subtype()]
4860 ** routine to set the subtype for the return value of an SQL function.
4861 **
4862 ** SQLite makes no use of subtype itself. It merely passes the subtype
4863 ** from the result of one [application-defined SQL function] into the
4864 ** input of another.
4865 */
4867 
4868 /*
4869 ** CAPI3REF: Copy And Free SQL Values
4870 ** METHOD: sqlite3_value
4871 **
4872 ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4873 ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
4874 ** is a [protected sqlite3_value] object even if the input is not.
4875 ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4876 ** memory allocation fails.
4877 **
4878 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4879 ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
4880 ** then sqlite3_value_free(V) is a harmless no-op.
4881 */
4884 
4885 /*
4886 ** CAPI3REF: Obtain Aggregate Function Context
4887 ** METHOD: sqlite3_context
4888 **
4889 ** Implementations of aggregate SQL functions use this
4890 ** routine to allocate memory for storing their state.
4891 **
4892 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4893 ** for a particular aggregate function, SQLite
4894 ** allocates N of memory, zeroes out that memory, and returns a pointer
4895 ** to the new memory. ^On second and subsequent calls to
4896 ** sqlite3_aggregate_context() for the same aggregate function instance,
4897 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4898 ** called once for each invocation of the xStep callback and then one
4899 ** last time when the xFinal callback is invoked. ^(When no rows match
4900 ** an aggregate query, the xStep() callback of the aggregate function
4901 ** implementation is never called and xFinal() is called exactly once.
4902 ** In those cases, sqlite3_aggregate_context() might be called for the
4903 ** first time from within xFinal().)^
4904 **
4905 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4906 ** when first called if N is less than or equal to zero or if a memory
4907 ** allocate error occurs.
4908 **
4909 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4910 ** determined by the N parameter on first successful call. Changing the
4911 ** value of N in subsequent call to sqlite3_aggregate_context() within
4912 ** the same aggregate function instance will not resize the memory
4913 ** allocation.)^ Within the xFinal callback, it is customary to set
4914 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4915 ** pointless memory allocations occur.
4916 **
4917 ** ^SQLite automatically frees the memory allocated by
4918 ** sqlite3_aggregate_context() when the aggregate query concludes.
4919 **
4920 ** The first parameter must be a copy of the
4921 ** [sqlite3_context | SQL function context] that is the first parameter
4922 ** to the xStep or xFinal callback routine that implements the aggregate
4923 ** function.
4924 **
4925 ** This routine must be called from the same thread in which
4926 ** the aggregate SQL function is running.
4927 */
4929 
4930 /*
4931 ** CAPI3REF: User Data For Functions
4932 ** METHOD: sqlite3_context
4933 **
4934 ** ^The sqlite3_user_data() interface returns a copy of
4935 ** the pointer that was the pUserData parameter (the 5th parameter)
4936 ** of the [sqlite3_create_function()]
4937 ** and [sqlite3_create_function16()] routines that originally
4938 ** registered the application defined function.
4939 **
4940 ** This routine must be called from the same thread in which
4941 ** the application-defined function is running.
4942 */
4944 
4945 /*
4946 ** CAPI3REF: Database Connection For Functions
4947 ** METHOD: sqlite3_context
4948 **
4949 ** ^The sqlite3_context_db_handle() interface returns a copy of
4950 ** the pointer to the [database connection] (the 1st parameter)
4951 ** of the [sqlite3_create_function()]
4952 ** and [sqlite3_create_function16()] routines that originally
4953 ** registered the application defined function.
4954 */
4956 
4957 /*
4958 ** CAPI3REF: Function Auxiliary Data
4959 ** METHOD: sqlite3_context
4960 **
4961 ** These functions may be used by (non-aggregate) SQL functions to
4962 ** associate metadata with argument values. If the same value is passed to
4963 ** multiple invocations of the same SQL function during query execution, under
4964 ** some circumstances the associated metadata may be preserved. An example
4965 ** of where this might be useful is in a regular-expression matching
4966 ** function. The compiled version of the regular expression can be stored as
4967 ** metadata associated with the pattern string.
4968 ** Then as long as the pattern string remains the same,
4969 ** the compiled regular expression can be reused on multiple
4970 ** invocations of the same function.
4971 **
4972 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4973 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4974 ** value to the application-defined function. ^If there is no metadata
4975 ** associated with the function argument, this sqlite3_get_auxdata() interface
4976 ** returns a NULL pointer.
4977 **
4978 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4979 ** argument of the application-defined function. ^Subsequent
4980 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4981 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4982 ** NULL if the metadata has been discarded.
4983 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4984 ** SQLite will invoke the destructor function X with parameter P exactly
4985 ** once, when the metadata is discarded.
4986 ** SQLite is free to discard the metadata at any time, including: <ul>
4987 ** <li> ^(when the corresponding function parameter changes)^, or
4988 ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4989 ** SQL statement)^, or
4990 ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
4991 ** parameter)^, or
4992 ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
4993 ** allocation error occurs.)^ </ul>
4994 **
4995 ** Note the last bullet in particular. The destructor X in
4996 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4997 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
4998 ** should be called near the end of the function implementation and the
4999 ** function implementation should not make any use of P after
5000 ** sqlite3_set_auxdata() has been called.
5001 **
5002 ** ^(In practice, metadata is preserved between function calls for
5003 ** function parameters that are compile-time constants, including literal
5004 ** values and [parameters] and expressions composed from the same.)^
5005 **
5006 ** These routines must be called from the same thread in which
5007 ** the SQL function is running.
5008 */
5010 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
5011 
5012 
5013 /*
5014 ** CAPI3REF: Constants Defining Special Destructor Behavior
5015 **
5016 ** These are special values for the destructor that is passed in as the
5017 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
5018 ** argument is SQLITE_STATIC, it means that the content pointer is constant
5019 ** and will never change. It does not need to be destroyed. ^The
5020 ** SQLITE_TRANSIENT value means that the content will likely change in
5021 ** the near future and that SQLite should make its own private copy of
5022 ** the content before returning.
5023 **
5024 ** The typedef is necessary to work around problems in certain
5025 ** C++ compilers.
5026 */
5027 typedef void (*sqlite3_destructor_type)(void*);
5028 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
5029 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
5030 
5031 /*
5032 ** CAPI3REF: Setting The Result Of An SQL Function
5033 ** METHOD: sqlite3_context
5034 **
5035 ** These routines are used by the xFunc or xFinal callbacks that
5036 ** implement SQL functions and aggregates. See
5037 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
5038 ** for additional information.
5039 **
5040 ** These functions work very much like the [parameter binding] family of
5041 ** functions used to bind values to host parameters in prepared statements.
5042 ** Refer to the [SQL parameter] documentation for additional information.
5043 **
5044 ** ^The sqlite3_result_blob() interface sets the result from
5045 ** an application-defined function to be the BLOB whose content is pointed
5046 ** to by the second parameter and which is N bytes long where N is the
5047 ** third parameter.
5048 **
5049 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
5050 ** interfaces set the result of the application-defined function to be
5051 ** a BLOB containing all zero bytes and N bytes in size.
5052 **
5053 ** ^The sqlite3_result_double() interface sets the result from
5054 ** an application-defined function to be a floating point value specified
5055 ** by its 2nd argument.
5056 **
5057 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
5058 ** cause the implemented SQL function to throw an exception.
5059 ** ^SQLite uses the string pointed to by the
5060 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
5061 ** as the text of an error message. ^SQLite interprets the error
5062 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
5063 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
5064 ** byte order. ^If the third parameter to sqlite3_result_error()
5065 ** or sqlite3_result_error16() is negative then SQLite takes as the error
5066 ** message all text up through the first zero character.
5067 ** ^If the third parameter to sqlite3_result_error() or
5068 ** sqlite3_result_error16() is non-negative then SQLite takes that many
5069 ** bytes (not characters) from the 2nd parameter as the error message.
5070 ** ^The sqlite3_result_error() and sqlite3_result_error16()
5071 ** routines make a private copy of the error message text before
5072 ** they return. Hence, the calling function can deallocate or
5073 ** modify the text after they return without harm.
5074 ** ^The sqlite3_result_error_code() function changes the error code
5075 ** returned by SQLite as a result of an error in a function. ^By default,
5076 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
5077 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
5078 **
5079 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
5080 ** error indicating that a string or BLOB is too long to represent.
5081 **
5082 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
5083 ** error indicating that a memory allocation failed.
5084 **
5085 ** ^The sqlite3_result_int() interface sets the return value
5086 ** of the application-defined function to be the 32-bit signed integer
5087 ** value given in the 2nd argument.
5088 ** ^The sqlite3_result_int64() interface sets the return value
5089 ** of the application-defined function to be the 64-bit signed integer
5090 ** value given in the 2nd argument.
5091 **
5092 ** ^The sqlite3_result_null() interface sets the return value
5093 ** of the application-defined function to be NULL.
5094 **
5095 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
5096 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
5097 ** set the return value of the application-defined function to be
5098 ** a text string which is represented as UTF-8, UTF-16 native byte order,
5099 ** UTF-16 little endian, or UTF-16 big endian, respectively.
5100 ** ^The sqlite3_result_text64() interface sets the return value of an
5101 ** application-defined function to be a text string in an encoding
5102 ** specified by the fifth (and last) parameter, which must be one
5103 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
5104 ** ^SQLite takes the text result from the application from
5105 ** the 2nd parameter of the sqlite3_result_text* interfaces.
5106 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5107 ** is negative, then SQLite takes result text from the 2nd parameter
5108 ** through the first zero character.
5109 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
5110 ** is non-negative, then as many bytes (not characters) of the text
5111 ** pointed to by the 2nd parameter are taken as the application-defined
5112 ** function result. If the 3rd parameter is non-negative, then it
5113 ** must be the byte offset into the string where the NUL terminator would
5114 ** appear if the string where NUL terminated. If any NUL characters occur
5115 ** in the string at a byte offset that is less than the value of the 3rd
5116 ** parameter, then the resulting string will contain embedded NULs and the
5117 ** result of expressions operating on strings with embedded NULs is undefined.
5118 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
5119 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
5120 ** function as the destructor on the text or BLOB result when it has
5121 ** finished using that result.
5122 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
5123 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
5124 ** assumes that the text or BLOB result is in constant space and does not
5125 ** copy the content of the parameter nor call a destructor on the content
5126 ** when it has finished using that result.
5127 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
5128 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
5129 ** then SQLite makes a copy of the result into space obtained from
5130 ** from [sqlite3_malloc()] before it returns.
5131 **
5132 ** ^The sqlite3_result_value() interface sets the result of
5133 ** the application-defined function to be a copy of the
5134 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
5135 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
5136 ** so that the [sqlite3_value] specified in the parameter may change or
5137 ** be deallocated after sqlite3_result_value() returns without harm.
5138 ** ^A [protected sqlite3_value] object may always be used where an
5139 ** [unprotected sqlite3_value] object is required, so either
5140 ** kind of [sqlite3_value] object can be used with this interface.
5141 **
5142 ** If these routines are called from within the different thread
5143 ** than the one containing the application-defined function that received
5144 ** the [sqlite3_context] pointer, the results are undefined.
5145 */
5146 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
5148  sqlite3_uint64,void(*)(void*));
5150 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
5151 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
5156 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
5158 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
5159 SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
5160  void(*)(void*), unsigned char encoding);
5161 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
5162 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
5163 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
5166 SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
5167 
5168 
5169 /*
5170 ** CAPI3REF: Setting The Subtype Of An SQL Function
5171 ** METHOD: sqlite3_context
5172 **
5173 ** The sqlite3_result_subtype(C,T) function causes the subtype of
5174 ** the result from the [application-defined SQL function] with
5175 ** [sqlite3_context] C to be the value T. Only the lower 8 bits
5176 ** of the subtype T are preserved in current versions of SQLite;
5177 ** higher order bits are discarded.
5178 ** The number of subtype bytes preserved by SQLite might increase
5179 ** in future releases of SQLite.
5180 */
5182 
5183 /*
5184 ** CAPI3REF: Define New Collating Sequences
5185 ** METHOD: sqlite3
5186 **
5187 ** ^These functions add, remove, or modify a [collation] associated
5188 ** with the [database connection] specified as the first argument.
5189 **
5190 ** ^The name of the collation is a UTF-8 string
5191 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5192 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
5193 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
5194 ** considered to be the same name.
5195 **
5196 ** ^(The third argument (eTextRep) must be one of the constants:
5197 ** <ul>
5198 ** <li> [SQLITE_UTF8],
5199 ** <li> [SQLITE_UTF16LE],
5200 ** <li> [SQLITE_UTF16BE],
5201 ** <li> [SQLITE_UTF16], or
5202 ** <li> [SQLITE_UTF16_ALIGNED].
5203 ** </ul>)^
5204 ** ^The eTextRep argument determines the encoding of strings passed
5205 ** to the collating function callback, xCallback.
5206 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
5207 ** force strings to be UTF16 with native byte order.
5208 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
5209 ** on an even byte address.
5210 **
5211 ** ^The fourth argument, pArg, is an application data pointer that is passed
5212 ** through as the first argument to the collating function callback.
5213 **
5214 ** ^The fifth argument, xCallback, is a pointer to the collating function.
5215 ** ^Multiple collating functions can be registered using the same name but
5216 ** with different eTextRep parameters and SQLite will use whichever
5217 ** function requires the least amount of data transformation.
5218 ** ^If the xCallback argument is NULL then the collating function is
5219 ** deleted. ^When all collating functions having the same name are deleted,
5220 ** that collation is no longer usable.
5221 **
5222 ** ^The collating function callback is invoked with a copy of the pArg
5223 ** application data pointer and with two strings in the encoding specified
5224 ** by the eTextRep argument. The collating function must return an
5225 ** integer that is negative, zero, or positive
5226 ** if the first string is less than, equal to, or greater than the second,
5227 ** respectively. A collating function must always return the same answer
5228 ** given the same inputs. If two or more collating functions are registered
5229 ** to the same collation name (using different eTextRep values) then all
5230 ** must give an equivalent answer when invoked with equivalent strings.
5231 ** The collating function must obey the following properties for all
5232 ** strings A, B, and C:
5233 **
5234 ** <ol>
5235 ** <li> If A==B then B==A.
5236 ** <li> If A==B and B==C then A==C.
5237 ** <li> If A&lt;B THEN B&gt;A.
5238 ** <li> If A&lt;B and B&lt;C then A&lt;C.
5239 ** </ol>
5240 **
5241 ** If a collating function fails any of the above constraints and that
5242 ** collating function is registered and used, then the behavior of SQLite
5243 ** is undefined.
5244 **
5245 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5246 ** with the addition that the xDestroy callback is invoked on pArg when
5247 ** the collating function is deleted.
5248 ** ^Collating functions are deleted when they are overridden by later
5249 ** calls to the collation creation functions or when the
5250 ** [database connection] is closed using [sqlite3_close()].
5251 **
5252 ** ^The xDestroy callback is <u>not</u> called if the
5253 ** sqlite3_create_collation_v2() function fails. Applications that invoke
5254 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5255 ** check the return code and dispose of the application data pointer
5256 ** themselves rather than expecting SQLite to deal with it for them.
5257 ** This is different from every other SQLite interface. The inconsistency
5258 ** is unfortunate but cannot be changed without breaking backwards
5259 ** compatibility.
5260 **
5261 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5262 */
5264  sqlite3*,
5265  const char *zName,
5266  int eTextRep,
5267  void *pArg,
5268  int(*xCompare)(void*,int,const void*,int,const void*)
5269 );
5271  sqlite3*,
5272  const char *zName,
5273  int eTextRep,
5274  void *pArg,
5275  int(*xCompare)(void*,int,const void*,int,const void*),
5276  void(*xDestroy)(void*)
5277 );
5279  sqlite3*,
5280  const void *zName,
5281  int eTextRep,
5282  void *pArg,
5283  int(*xCompare)(void*,int,const void*,int,const void*)
5284 );
5285 
5286 /*
5287 ** CAPI3REF: Collation Needed Callbacks
5288 ** METHOD: sqlite3
5289 **
5290 ** ^To avoid having to register all collation sequences before a database
5291 ** can be used, a single callback function may be registered with the
5292 ** [database connection] to be invoked whenever an undefined collation
5293 ** sequence is required.
5294 **
5295 ** ^If the function is registered using the sqlite3_collation_needed() API,
5296 ** then it is passed the names of undefined collation sequences as strings
5297 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5298 ** the names are passed as UTF-16 in machine native byte order.
5299 ** ^A call to either function replaces the existing collation-needed callback.
5300 **
5301 ** ^(When the callback is invoked, the first argument passed is a copy
5302 ** of the second argument to sqlite3_collation_needed() or
5303 ** sqlite3_collation_needed16(). The second argument is the database
5304 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5305 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5306 ** sequence function required. The fourth parameter is the name of the
5307 ** required collation sequence.)^
5308 **
5309 ** The callback function should register the desired collation using
5310 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5311 ** [sqlite3_create_collation_v2()].
5312 */
5314  sqlite3*,
5315  void*,
5316  void(*)(void*,sqlite3*,int eTextRep,const char*)
5317 );
5319  sqlite3*,
5320  void*,
5321  void(*)(void*,sqlite3*,int eTextRep,const void*)
5322 );
5323 
5324 #ifdef SQLITE_HAS_CODEC
5325 /*
5326 ** Specify the key for an encrypted database. This routine should be
5327 ** called right after sqlite3_open().
5328 **
5329 ** The code to implement this API is not available in the public release
5330 ** of SQLite.
5331 */
5332 SQLITE_API int sqlite3_key(
5333  sqlite3 *db, /* Database to be rekeyed */
5334  const void *pKey, int nKey /* The key */
5335 );
5336 SQLITE_API int sqlite3_key_v2(
5337  sqlite3 *db, /* Database to be rekeyed */
5338  const char *zDbName, /* Name of the database */
5339  const void *pKey, int nKey /* The key */
5340 );
5341 
5342 /*
5343 ** Change the key on an open database. If the current database is not
5344 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5345 ** database is decrypted.
5346 **
5347 ** The code to implement this API is not available in the public release
5348 ** of SQLite.
5349 */
5350 SQLITE_API int sqlite3_rekey(
5351  sqlite3 *db, /* Database to be rekeyed */
5352  const void *pKey, int nKey /* The new key */
5353 );
5354 SQLITE_API int sqlite3_rekey_v2(
5355  sqlite3 *db, /* Database to be rekeyed */
5356  const char *zDbName, /* Name of the database */
5357  const void *pKey, int nKey /* The new key */
5358 );
5359 
5360 /*
5361 ** Specify the activation key for a SEE database. Unless
5362 ** activated, none of the SEE routines will work.
5363 */
5364 SQLITE_API void sqlite3_activate_see(
5365  const char *zPassPhrase /* Activation phrase */
5366 );
5367 #endif
5368 
5369 #ifdef SQLITE_ENABLE_CEROD
5370 /*
5371 ** Specify the activation key for a CEROD database. Unless
5372 ** activated, none of the CEROD routines will work.
5373 */
5374 SQLITE_API void sqlite3_activate_cerod(
5375  const char *zPassPhrase /* Activation phrase */
5376 );
5377 #endif
5378 
5379 /*
5380 ** CAPI3REF: Suspend Execution For A Short Time
5381 **
5382 ** The sqlite3_sleep() function causes the current thread to suspend execution
5383 ** for at least a number of milliseconds specified in its parameter.
5384 **
5385 ** If the operating system does not support sleep requests with
5386 ** millisecond time resolution, then the time will be rounded up to
5387 ** the nearest second. The number of milliseconds of sleep actually
5388 ** requested from the operating system is returned.
5389 **
5390 ** ^SQLite implements this interface by calling the xSleep()
5391 ** method of the default [sqlite3_vfs] object. If the xSleep() method
5392 ** of the default VFS is not implemented correctly, or not implemented at
5393 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5394 ** in the previous paragraphs.
5395 */
5396 SQLITE_API int sqlite3_sleep(int);
5397 
5398 /*
5399 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5400 **
5401 ** ^(If this global variable is made to point to a string which is
5402 ** the name of a folder (a.k.a. directory), then all temporary files
5403 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5404 ** will be placed in that directory.)^ ^If this variable
5405 ** is a NULL pointer, then SQLite performs a search for an appropriate
5406 ** temporary file directory.
5407 **
5408 ** Applications are strongly discouraged from using this global variable.
5409 ** It is required to set a temporary folder on Windows Runtime (WinRT).
5410 ** But for all other platforms, it is highly recommended that applications
5411 ** neither read nor write this variable. This global variable is a relic
5412 ** that exists for backwards compatibility of legacy applications and should
5413 ** be avoided in new projects.
5414 **
5415 ** It is not safe to read or modify this variable in more than one
5416 ** thread at a time. It is not safe to read or modify this variable
5417 ** if a [database connection] is being used at the same time in a separate
5418 ** thread.
5419 ** It is intended that this variable be set once
5420 ** as part of process initialization and before any SQLite interface
5421 ** routines have been called and that this variable remain unchanged
5422 ** thereafter.
5423 **
5424 ** ^The [temp_store_directory pragma] may modify this variable and cause
5425 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5426 ** the [temp_store_directory pragma] always assumes that any string
5427 ** that this variable points to is held in memory obtained from
5428 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5429 ** using [sqlite3_free].
5430 ** Hence, if this variable is modified directly, either it should be
5431 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5432 ** or else the use of the [temp_store_directory pragma] should be avoided.
5433 ** Except when requested by the [temp_store_directory pragma], SQLite
5434 ** does not free the memory that sqlite3_temp_directory points to. If
5435 ** the application wants that memory to be freed, it must do
5436 ** so itself, taking care to only do so after all [database connection]
5437 ** objects have been destroyed.
5438 **
5439 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
5440 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
5441 ** features that require the use of temporary files may fail. Here is an
5442 ** example of how to do this using C++ with the Windows Runtime:
5443 **
5444 ** <blockquote><pre>
5445 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5446 ** &nbsp; TemporaryFolder->Path->Data();
5447 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5448 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5449 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5450 ** &nbsp; NULL, NULL);
5451 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5452 ** </pre></blockquote>
5453 */
5455 
5456 /*
5457 ** CAPI3REF: Name Of The Folder Holding Database Files
5458 **
5459 ** ^(If this global variable is made to point to a string which is
5460 ** the name of a folder (a.k.a. directory), then all database files
5461 ** specified with a relative pathname and created or accessed by
5462 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5463 ** to be relative to that directory.)^ ^If this variable is a NULL
5464 ** pointer, then SQLite assumes that all database files specified
5465 ** with a relative pathname are relative to the current directory
5466 ** for the process. Only the windows VFS makes use of this global
5467 ** variable; it is ignored by the unix VFS.
5468 **
5469 ** Changing the value of this variable while a database connection is
5470 ** open can result in a corrupt database.
5471 **
5472 ** It is not safe to read or modify this variable in more than one
5473 ** thread at a time. It is not safe to read or modify this variable
5474 ** if a [database connection] is being used at the same time in a separate
5475 ** thread.
5476 ** It is intended that this variable be set once
5477 ** as part of process initialization and before any SQLite interface
5478 ** routines have been called and that this variable remain unchanged
5479 ** thereafter.
5480 **
5481 ** ^The [data_store_directory pragma] may modify this variable and cause
5482 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5483 ** the [data_store_directory pragma] always assumes that any string
5484 ** that this variable points to is held in memory obtained from
5485 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5486 ** using [sqlite3_free].
5487 ** Hence, if this variable is modified directly, either it should be
5488 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5489 ** or else the use of the [data_store_directory pragma] should be avoided.
5490 */
5492 
5493 /*
5494 ** CAPI3REF: Test For Auto-Commit Mode
5495 ** KEYWORDS: {autocommit mode}
5496 ** METHOD: sqlite3
5497 **
5498 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5499 ** zero if the given database connection is or is not in autocommit mode,
5500 ** respectively. ^Autocommit mode is on by default.
5501 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5502 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5503 **
5504 ** If certain kinds of errors occur on a statement within a multi-statement
5505 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5506 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5507 ** transaction might be rolled back automatically. The only way to
5508 ** find out whether SQLite automatically rolled back the transaction after
5509 ** an error is to use this function.
5510 **
5511 ** If another thread changes the autocommit status of the database
5512 ** connection while this routine is running, then the return value
5513 ** is undefined.
5514 */
5516 
5517 /*
5518 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5519 ** METHOD: sqlite3_stmt
5520 **
5521 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5522 ** to which a [prepared statement] belongs. ^The [database connection]
5523 ** returned by sqlite3_db_handle is the same [database connection]
5524 ** that was the first argument
5525 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5526 ** create the statement in the first place.
5527 */
5529 
5530 /*
5531 ** CAPI3REF: Return The Filename For A Database Connection
5532 ** METHOD: sqlite3
5533 **
5534 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5535 ** associated with database N of connection D. ^The main database file
5536 ** has the name "main". If there is no attached database N on the database
5537 ** connection D, or if database N is a temporary or in-memory database, then
5538 ** a NULL pointer is returned.
5539 **
5540 ** ^The filename returned by this function is the output of the
5541 ** xFullPathname method of the [VFS]. ^In other words, the filename
5542 ** will be an absolute pathname, even if the filename used
5543 ** to open the database originally was a URI or relative pathname.
5544 */
5545 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5546 
5547 /*
5548 ** CAPI3REF: Determine if a database is read-only
5549 ** METHOD: sqlite3
5550 **
5551 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5552 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5553 ** the name of a database on connection D.
5554 */
5555 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5556 
5557 /*
5558 ** CAPI3REF: Find the next prepared statement
5559 ** METHOD: sqlite3
5560 **
5561 ** ^This interface returns a pointer to the next [prepared statement] after
5562 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
5563 ** then this interface returns a pointer to the first prepared statement
5564 ** associated with the database connection pDb. ^If no prepared statement
5565 ** satisfies the conditions of this routine, it returns NULL.
5566 **
5567 ** The [database connection] pointer D in a call to
5568 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5569 ** connection and in particular must not be a NULL pointer.
5570 */
5572 
5573 /*
5574 ** CAPI3REF: Commit And Rollback Notification Callbacks
5575 ** METHOD: sqlite3
5576 **
5577 ** ^The sqlite3_commit_hook() interface registers a callback
5578 ** function to be invoked whenever a transaction is [COMMIT | committed].
5579 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5580 ** for the same database connection is overridden.
5581 ** ^The sqlite3_rollback_hook() interface registers a callback
5582 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5583 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5584 ** for the same database connection is overridden.
5585 ** ^The pArg argument is passed through to the callback.
5586 ** ^If the callback on a commit hook function returns non-zero,
5587 ** then the commit is converted into a rollback.
5588 **
5589 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5590 ** return the P argument from the previous call of the same function
5591 ** on the same [database connection] D, or NULL for
5592 ** the first call for each function on D.
5593 **
5594 ** The commit and rollback hook callbacks are not reentrant.
5595 ** The callback implementation must not do anything that will modify
5596 ** the database connection that invoked the callback. Any actions
5597 ** to modify the database connection must be deferred until after the
5598 ** completion of the [sqlite3_step()] call that triggered the commit
5599 ** or rollback hook in the first place.
5600 ** Note that running any other SQL statements, including SELECT statements,
5601 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5602 ** the database connections for the meaning of "modify" in this paragraph.
5603 **
5604 ** ^Registering a NULL function disables the callback.
5605 **
5606 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5607 ** operation is allowed to continue normally. ^If the commit hook
5608 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5609 ** ^The rollback hook is invoked on a rollback that results from a commit
5610 ** hook returning non-zero, just as it would be with any other rollback.
5611 **
5612 ** ^For the purposes of this API, a transaction is said to have been
5613 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5614 ** an error or constraint causes an implicit rollback to occur.
5615 ** ^The rollback callback is not invoked if a transaction is
5616 ** automatically rolled back because the database connection is closed.
5617 **
5618 ** See also the [sqlite3_update_hook()] interface.
5619 */
5620 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5621 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5622 
5623 /*
5624 ** CAPI3REF: Data Change Notification Callbacks
5625 ** METHOD: sqlite3
5626 **
5627 ** ^The sqlite3_update_hook() interface registers a callback function
5628 ** with the [database connection] identified by the first argument
5629 ** to be invoked whenever a row is updated, inserted or deleted in
5630 ** a [rowid table].
5631 ** ^Any callback set by a previous call to this function
5632 ** for the same database connection is overridden.
5633 **
5634 ** ^The second argument is a pointer to the function to invoke when a
5635 ** row is updated, inserted or deleted in a rowid table.
5636 ** ^The first argument to the callback is a copy of the third argument
5637 ** to sqlite3_update_hook().
5638 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5639 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5640 ** to be invoked.
5641 ** ^The third and fourth arguments to the callback contain pointers to the
5642 ** database and table name containing the affected row.
5643 ** ^The final callback parameter is the [rowid] of the row.
5644 ** ^In the case of an update, this is the [rowid] after the update takes place.
5645 **
5646 ** ^(The update hook is not invoked when internal system tables are
5647 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5648 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5649 **
5650 ** ^In the current implementation, the update hook
5651 ** is not invoked when duplication rows are deleted because of an
5652 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5653 ** invoked when rows are deleted using the [truncate optimization].
5654 ** The exceptions defined in this paragraph might change in a future
5655 ** release of SQLite.
5656 **
5657 ** The update hook implementation must not do anything that will modify
5658 ** the database connection that invoked the update hook. Any actions
5659 ** to modify the database connection must be deferred until after the
5660 ** completion of the [sqlite3_step()] call that triggered the update hook.
5661 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5662 ** database connections for the meaning of "modify" in this paragraph.
5663 **
5664 ** ^The sqlite3_update_hook(D,C,P) function
5665 ** returns the P argument from the previous call
5666 ** on the same [database connection] D, or NULL for
5667 ** the first call on D.
5668 **
5669 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5670 ** and [sqlite3_preupdate_hook()] interfaces.
5671 */
5673  sqlite3*,
5674  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5675  void*
5676 );
5677 
5678 /*
5679 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5680 **
5681 ** ^(This routine enables or disables the sharing of the database cache
5682 ** and schema data structures between [database connection | connections]
5683 ** to the same database. Sharing is enabled if the argument is true
5684 ** and disabled if the argument is false.)^
5685 **
5686 ** ^Cache sharing is enabled and disabled for an entire process.
5687 ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
5688 ** In prior versions of SQLite,
5689 ** sharing was enabled or disabled for each thread separately.
5690 **
5691 ** ^(The cache sharing mode set by this interface effects all subsequent
5692 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5693 ** Existing database connections continue use the sharing mode
5694 ** that was in effect at the time they were opened.)^
5695 **
5696 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5697 ** successfully. An [error code] is returned otherwise.)^
5698 **
5699 ** ^Shared cache is disabled by default. But this might change in
5700 ** future releases of SQLite. Applications that care about shared
5701 ** cache setting should set it explicitly.
5702 **
5703 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5704 ** and will always return SQLITE_MISUSE. On those systems,
5705 ** shared cache mode should be enabled per-database connection via
5706 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5707 **
5708 ** This interface is threadsafe on processors where writing a
5709 ** 32-bit integer is atomic.
5710 **
5711 ** See Also: [SQLite Shared-Cache Mode]
5712 */
5714 
5715 /*
5716 ** CAPI3REF: Attempt To Free Heap Memory
5717 **
5718 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5719 ** of heap memory by deallocating non-essential memory allocations
5720 ** held by the database library. Memory used to cache database
5721 ** pages to improve performance is an example of non-essential memory.
5722 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5723 ** which might be more or less than the amount requested.
5724 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5725 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5726 **
5727 ** See also: [sqlite3_db_release_memory()]
5728 */
5730 
5731 /*
5732 ** CAPI3REF: Free Memory Used By A Database Connection
5733 ** METHOD: sqlite3
5734 **
5735 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5736 ** memory as possible from database connection D. Unlike the
5737 ** [sqlite3_release_memory()] interface, this interface is in effect even
5738 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5739 ** omitted.
5740 **
5741 ** See also: [sqlite3_release_memory()]
5742 */
5744 
5745 /*
5746 ** CAPI3REF: Impose A Limit On Heap Size
5747 **
5748 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5749 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5750 ** ^SQLite strives to keep heap memory utilization below the soft heap
5751 ** limit by reducing the number of pages held in the page cache
5752 ** as heap memory usages approaches the limit.
5753 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5754 ** below the limit, it will exceed the limit rather than generate
5755 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5756 ** is advisory only.
5757 **
5758 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5759 ** the soft heap limit prior to the call, or negative in the case of an
5760 ** error. ^If the argument N is negative
5761 ** then no change is made to the soft heap limit. Hence, the current
5762 ** size of the soft heap limit can be determined by invoking
5763 ** sqlite3_soft_heap_limit64() with a negative argument.
5764 **
5765 ** ^If the argument N is zero then the soft heap limit is disabled.
5766 **
5767 ** ^(The soft heap limit is not enforced in the current implementation
5768 ** if one or more of following conditions are true:
5769 **
5770 ** <ul>
5771 ** <li> The soft heap limit is set to zero.
5772 ** <li> Memory accounting is disabled using a combination of the
5773 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5774 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5775 ** <li> An alternative page cache implementation is specified using
5776 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5777 ** <li> The page cache allocates from its own memory pool supplied
5778 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5779 ** from the heap.
5780 ** </ul>)^
5781 **
5782 ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
5783 ** the soft heap limit is enforced
5784 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5785 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5786 ** the soft heap limit is enforced on every memory allocation. Without
5787 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5788 ** when memory is allocated by the page cache. Testing suggests that because
5789 ** the page cache is the predominate memory user in SQLite, most
5790 ** applications will achieve adequate soft heap limit enforcement without
5791 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5792 **
5793 ** The circumstances under which SQLite will enforce the soft heap limit may
5794 ** changes in future releases of SQLite.
5795 */
5796 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5797 
5798 /*
5799 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5800 ** DEPRECATED
5801 **
5802 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5803 ** interface. This routine is provided for historical compatibility
5804 ** only. All new applications should use the
5805 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5806 */
5808 
5809 
5810 /*
5811 ** CAPI3REF: Extract Metadata About A Column Of A Table
5812 ** METHOD: sqlite3
5813 **
5814 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5815 ** information about column C of table T in database D
5816 ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
5817 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
5818 ** the final five arguments with appropriate values if the specified
5819 ** column exists. ^The sqlite3_table_column_metadata() interface returns
5820 ** SQLITE_ERROR and if the specified column does not exist.
5821 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5822 ** NULL pointer, then this routine simply checks for the existence of the
5823 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5824 ** does not.
5825 **
5826 ** ^The column is identified by the second, third and fourth parameters to
5827 ** this function. ^(The second parameter is either the name of the database
5828 ** (i.e. "main", "temp", or an attached database) containing the specified
5829 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5830 ** for the table using the same algorithm used by the database engine to
5831 ** resolve unqualified table references.
5832 **
5833 ** ^The third and fourth parameters to this function are the table and column
5834 ** name of the desired column, respectively.
5835 **
5836 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5837 ** and subsequent parameters to this function. ^Any of these arguments may be
5838 ** NULL, in which case the corresponding element of metadata is omitted.
5839 **
5840 ** ^(<blockquote>
5841 ** <table border="1">
5842 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5843 **
5844 ** <tr><td> 5th <td> const char* <td> Data type
5845 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5846 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5847 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5848 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5849 ** </table>
5850 ** </blockquote>)^
5851 **
5852 ** ^The memory pointed to by the character pointers returned for the
5853 ** declaration type and collation sequence is valid until the next
5854 ** call to any SQLite API function.
5855 **
5856 ** ^If the specified table is actually a view, an [error code] is returned.
5857 **
5858 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5859 ** is not a [WITHOUT ROWID] table and an
5860 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5861 ** parameters are set for the explicitly declared column. ^(If there is no
5862 ** [INTEGER PRIMARY KEY] column, then the outputs
5863 ** for the [rowid] are set as follows:
5864 **
5865 ** <pre>
5866 ** data type: "INTEGER"
5867 ** collation sequence: "BINARY"
5868 ** not null: 0
5869 ** primary key: 1
5870 ** auto increment: 0
5871 ** </pre>)^
5872 **
5873 ** ^This function causes all database schemas to be read from disk and
5874 ** parsed, if that has not already been done, and returns an error if
5875 ** any errors are encountered while loading the schema.
5876 */
5878  sqlite3 *db, /* Connection handle */
5879  const char *zDbName, /* Database name or NULL */
5880  const char *zTableName, /* Table name */
5881  const char *zColumnName, /* Column name */
5882  char const **pzDataType, /* OUTPUT: Declared data type */
5883  char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5884  int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5885  int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5886  int *pAutoinc /* OUTPUT: True if column is auto-increment */
5887 );
5888 
5889 /*
5890 ** CAPI3REF: Load An Extension
5891 ** METHOD: sqlite3
5892 **
5893 ** ^This interface loads an SQLite extension library from the named file.
5894 **
5895 ** ^The sqlite3_load_extension() interface attempts to load an
5896 ** [SQLite extension] library contained in the file zFile. If
5897 ** the file cannot be loaded directly, attempts are made to load
5898 ** with various operating-system specific extensions added.
5899 ** So for example, if "samplelib" cannot be loaded, then names like
5900 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5901 ** be tried also.
5902 **
5903 ** ^The entry point is zProc.
5904 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5905 ** entry point name on its own. It first tries "sqlite3_extension_init".
5906 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5907 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5908 ** characters in the filename from the last "/" to the first following
5909 ** "." and omitting any initial "lib".)^
5910 ** ^The sqlite3_load_extension() interface returns
5911 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5912 ** ^If an error occurs and pzErrMsg is not 0, then the
5913 ** [sqlite3_load_extension()] interface shall attempt to
5914 ** fill *pzErrMsg with error message text stored in memory
5915 ** obtained from [sqlite3_malloc()]. The calling function
5916 ** should free this memory by calling [sqlite3_free()].
5917 **
5918 ** ^Extension loading must be enabled using
5919 ** [sqlite3_enable_load_extension()] or
5920 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5921 ** prior to calling this API,
5922 ** otherwise an error will be returned.
5923 **
5924 ** <b>Security warning:</b> It is recommended that the
5925 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5926 ** interface. The use of the [sqlite3_enable_load_extension()] interface
5927 ** should be avoided. This will keep the SQL function [load_extension()]
5928 ** disabled and prevent SQL injections from giving attackers
5929 ** access to extension loading capabilities.
5930 **
5931 ** See also the [load_extension() SQL function].
5932 */
5934  sqlite3 *db, /* Load the extension into this database connection */
5935  const char *zFile, /* Name of the shared library containing extension */
5936  const char *zProc, /* Entry point. Derived from zFile if 0 */
5937  char **pzErrMsg /* Put error message here if not 0 */
5938 );
5939 
5940 /*
5941 ** CAPI3REF: Enable Or Disable Extension Loading
5942 ** METHOD: sqlite3
5943 **
5944 ** ^So as not to open security holes in older applications that are
5945 ** unprepared to deal with [extension loading], and as a means of disabling
5946 ** [extension loading] while evaluating user-entered SQL, the following API
5947 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5948 **
5949 ** ^Extension loading is off by default.
5950 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5951 ** to turn extension loading on and call it with onoff==0 to turn
5952 ** it back off again.
5953 **
5954 ** ^This interface enables or disables both the C-API
5955 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
5956 ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5957 ** to enable or disable only the C-API.)^
5958 **
5959 ** <b>Security warning:</b> It is recommended that extension loading
5960 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5961 ** rather than this interface, so the [load_extension()] SQL function
5962 ** remains disabled. This will prevent SQL injections from giving attackers
5963 ** access to extension loading capabilities.
5964 */
5966 
5967 /*
5968 ** CAPI3REF: Automatically Load Statically Linked Extensions
5969 **
5970 ** ^This interface causes the xEntryPoint() function to be invoked for
5971 ** each new [database connection] that is created. The idea here is that
5972 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5973 ** that is to be automatically loaded into all new database connections.
5974 **
5975 ** ^(Even though the function prototype shows that xEntryPoint() takes
5976 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5977 ** arguments and expects an integer result as if the signature of the
5978 ** entry point where as follows:
5979 **
5980 ** <blockquote><pre>
5981 ** &nbsp; int xEntryPoint(
5982 ** &nbsp; sqlite3 *db,
5983 ** &nbsp; const char **pzErrMsg,
5984 ** &nbsp; const struct sqlite3_api_routines *pThunk
5985 ** &nbsp; );
5986 ** </pre></blockquote>)^
5987 **
5988 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5989 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5990 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5991 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5992 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5993 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5994 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5995 **
5996 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5997 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5998 ** will be called more than once for each database connection that is opened.
5999 **
6000 ** See also: [sqlite3_reset_auto_extension()]
6001 ** and [sqlite3_cancel_auto_extension()]
6002 */
6003 SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
6004 
6005 /*
6006 ** CAPI3REF: Cancel Automatic Extension Loading
6007 **
6008 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
6009 ** initialization routine X that was registered using a prior call to
6010 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
6011 ** routine returns 1 if initialization routine X was successfully
6012 ** unregistered and it returns 0 if X was not on the list of initialization
6013 ** routines.
6014 */
6015 SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
6016 
6017 /*
6018 ** CAPI3REF: Reset Automatic Extension Loading
6019 **
6020 ** ^This interface disables all automatic extensions previously
6021 ** registered using [sqlite3_auto_extension()].
6022 */
6024 
6025 /*
6026 ** The interface to the virtual-table mechanism is currently considered
6027 ** to be experimental. The interface might change in incompatible ways.
6028 ** If this is a problem for you, do not use the interface at this time.
6029 **
6030 ** When the virtual-table mechanism stabilizes, we will declare the
6031 ** interface fixed, support it indefinitely, and remove this comment.
6032 */
6033 
6034 /*
6035 ** Structures used by the virtual table interface
6036 */
6041 
6042 /*
6043 ** CAPI3REF: Virtual Table Object
6044 ** KEYWORDS: sqlite3_module {virtual table module}
6045 **
6046 ** This structure, sometimes called a "virtual table module",
6047 ** defines the implementation of a [virtual tables].
6048 ** This structure consists mostly of methods for the module.
6049 **
6050 ** ^A virtual table module is created by filling in a persistent
6051 ** instance of this structure and passing a pointer to that instance
6052 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
6053 ** ^The registration remains valid until it is replaced by a different
6054 ** module or until the [database connection] closes. The content
6055 ** of this structure must not change while it is registered with
6056 ** any database connection.
6057 */
6060  int (*xCreate)(sqlite3*, void *pAux,
6061  int argc, const char *const*argv,
6062  sqlite3_vtab **ppVTab, char**);
6063  int (*xConnect)(sqlite3*, void *pAux,
6064  int argc, const char *const*argv,
6065  sqlite3_vtab **ppVTab, char**);
6066  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
6067  int (*xDisconnect)(sqlite3_vtab *pVTab);
6068  int (*xDestroy)(sqlite3_vtab *pVTab);
6069  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
6070  int (*xClose)(sqlite3_vtab_cursor*);
6071  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
6072  int argc, sqlite3_value **argv);
6073  int (*xNext)(sqlite3_vtab_cursor*);
6074  int (*xEof)(sqlite3_vtab_cursor*);
6075  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
6076  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
6077  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
6078  int (*xBegin)(sqlite3_vtab *pVTab);
6079  int (*xSync)(sqlite3_vtab *pVTab);
6080  int (*xCommit)(sqlite3_vtab *pVTab);
6081  int (*xRollback)(sqlite3_vtab *pVTab);
6082  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
6083  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
6084  void **ppArg);
6085  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
6086  /* The methods above are in version 1 of the sqlite_module object. Those
6087  ** below are for version 2 and greater. */
6088  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
6089  int (*xRelease)(sqlite3_vtab *pVTab, int);
6090  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
6091 };
6092 
6093 /*
6094 ** CAPI3REF: Virtual Table Indexing Information
6095 ** KEYWORDS: sqlite3_index_info
6096 **
6097 ** The sqlite3_index_info structure and its substructures is used as part
6098 ** of the [virtual table] interface to
6099 ** pass information into and receive the reply from the [xBestIndex]
6100 ** method of a [virtual table module]. The fields under **Inputs** are the
6101 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
6102 ** results into the **Outputs** fields.
6103 **
6104 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
6105 **
6106 ** <blockquote>column OP expr</blockquote>
6107 **
6108 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
6109 ** stored in aConstraint[].op using one of the
6110 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
6111 ** ^(The index of the column is stored in
6112 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
6113 ** expr on the right-hand side can be evaluated (and thus the constraint
6114 ** is usable) and false if it cannot.)^
6115 **
6116 ** ^The optimizer automatically inverts terms of the form "expr OP column"
6117 ** and makes other simplifications to the WHERE clause in an attempt to
6118 ** get as many WHERE clause terms into the form shown above as possible.
6119 ** ^The aConstraint[] array only reports WHERE clause terms that are
6120 ** relevant to the particular virtual table being queried.
6121 **
6122 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
6123 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
6124 **
6125 ** The colUsed field indicates which columns of the virtual table may be
6126 ** required by the current scan. Virtual table columns are numbered from
6127 ** zero in the order in which they appear within the CREATE TABLE statement
6128 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
6129 ** the corresponding bit is set within the colUsed mask if the column may be
6130 ** required by SQLite. If the table has at least 64 columns and any column
6131 ** to the right of the first 63 is required, then bit 63 of colUsed is also
6132 ** set. In other words, column iCol may be required if the expression
6133 ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
6134 ** non-zero.
6135 **
6136 ** The [xBestIndex] method must fill aConstraintUsage[] with information
6137 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
6138 ** the right-hand side of the corresponding aConstraint[] is evaluated
6139 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
6140 ** is true, then the constraint is assumed to be fully handled by the
6141 ** virtual table and is not checked again by SQLite.)^
6142 **
6143 ** ^The idxNum and idxPtr values are recorded and passed into the
6144 ** [xFilter] method.
6145 ** ^[sqlite3_free()] is used to free idxPtr if and only if
6146 ** needToFreeIdxPtr is true.
6147 **
6148 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
6149 ** the correct order to satisfy the ORDER BY clause so that no separate
6150 ** sorting step is required.
6151 **
6152 ** ^The estimatedCost value is an estimate of the cost of a particular
6153 ** strategy. A cost of N indicates that the cost of the strategy is similar
6154 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
6155 ** indicates that the expense of the operation is similar to that of a
6156 ** binary search on a unique indexed field of an SQLite table with N rows.
6157 **
6158 ** ^The estimatedRows value is an estimate of the number of rows that
6159 ** will be returned by the strategy.
6160 **
6161 ** The xBestIndex method may optionally populate the idxFlags field with a
6162 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
6163 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
6164 ** assumes that the strategy may visit at most one row.
6165 **
6166 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
6167 ** SQLite also assumes that if a call to the xUpdate() method is made as
6168 ** part of the same statement to delete or update a virtual table row and the
6169 ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
6170 ** any database changes. In other words, if the xUpdate() returns
6171 ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
6172 ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
6173 ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
6174 ** the xUpdate method are automatically rolled back by SQLite.
6175 **
6176 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
6177 ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
6178 ** If a virtual table extension is
6179 ** used with an SQLite version earlier than 3.8.2, the results of attempting
6180 ** to read or write the estimatedRows field are undefined (but are likely
6181 ** to included crashing the application). The estimatedRows field should
6182 ** therefore only be used if [sqlite3_libversion_number()] returns a
6183 ** value greater than or equal to 3008002. Similarly, the idxFlags field
6184 ** was added for [version 3.9.0] ([dateof:3.9.0]).
6185 ** It may therefore only be used if
6186 ** sqlite3_libversion_number() returns a value greater than or equal to
6187 ** 3009000.
6188 */
6190  /* Inputs */
6191  int nConstraint; /* Number of entries in aConstraint */
6193  int iColumn; /* Column constrained. -1 for ROWID */
6194  unsigned char op; /* Constraint operator */
6195  unsigned char usable; /* True if this constraint is usable */
6196  int iTermOffset; /* Used internally - xBestIndex should ignore */
6197  } *aConstraint; /* Table of WHERE clause constraints */
6198  int nOrderBy; /* Number of terms in the ORDER BY clause */
6200  int iColumn; /* Column number */
6201  unsigned char desc; /* True for DESC. False for ASC. */
6202  } *aOrderBy; /* The ORDER BY clause */
6203  /* Outputs */
6205  int argvIndex; /* if >0, constraint is part of argv to xFilter */
6206  unsigned char omit; /* Do not code a test for this constraint */
6207  } *aConstraintUsage;
6208  int idxNum; /* Number used to identify the index */
6209  char *idxStr; /* String, possibly obtained from sqlite3_malloc */
6210  int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
6211  int orderByConsumed; /* True if output is already ordered */
6212  double estimatedCost; /* Estimated cost of using this index */
6213  /* Fields below are only available in SQLite 3.8.2 and later */
6214  sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
6215  /* Fields below are only available in SQLite 3.9.0 and later */
6216  int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
6217  /* Fields below are only available in SQLite 3.10.0 and later */
6218  sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
6219 };
6220 
6221 /*
6222 ** CAPI3REF: Virtual Table Scan Flags
6223 */
6224 #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
6225 
6226 /*
6227 ** CAPI3REF: Virtual Table Constraint Operator Codes
6228 **
6229 ** These macros defined the allowed values for the
6230 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
6231 ** an operator that is part of a constraint term in the wHERE clause of
6232 ** a query that uses a [virtual table].
6233 */
6234 #define SQLITE_INDEX_CONSTRAINT_EQ 2
6235 #define SQLITE_INDEX_CONSTRAINT_GT 4
6236 #define SQLITE_INDEX_CONSTRAINT_LE 8
6237 #define SQLITE_INDEX_CONSTRAINT_LT 16
6238 #define SQLITE_INDEX_CONSTRAINT_GE 32
6239 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
6240 #define SQLITE_INDEX_CONSTRAINT_LIKE 65
6241 #define SQLITE_INDEX_CONSTRAINT_GLOB 66
6242 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
6243 
6244 /*
6245 ** CAPI3REF: Register A Virtual Table Implementation
6246 ** METHOD: sqlite3
6247 **
6248 ** ^These routines are used to register a new [virtual table module] name.
6249 ** ^Module names must be registered before
6250 ** creating a new [virtual table] using the module and before using a
6251 ** preexisting [virtual table] for the module.
6252 **
6253 ** ^The module name is registered on the [database connection] specified
6254 ** by the first parameter. ^The name of the module is given by the
6255 ** second parameter. ^The third parameter is a pointer to
6256 ** the implementation of the [virtual table module]. ^The fourth
6257 ** parameter is an arbitrary client data pointer that is passed through
6258 ** into the [xCreate] and [xConnect] methods of the virtual table module
6259 ** when a new virtual table is be being created or reinitialized.
6260 **
6261 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
6262 ** is a pointer to a destructor for the pClientData. ^SQLite will
6263 ** invoke the destructor function (if it is not NULL) when SQLite
6264 ** no longer needs the pClientData pointer. ^The destructor will also
6265 ** be invoked if the call to sqlite3_create_module_v2() fails.
6266 ** ^The sqlite3_create_module()
6267 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
6268 ** destructor.
6269 */
6271  sqlite3 *db, /* SQLite connection to register module with */
6272  const char *zName, /* Name of the module */
6273  const sqlite3_module *p, /* Methods for the module */
6274  void *pClientData /* Client data for xCreate/xConnect */
6275 );
6277  sqlite3 *db, /* SQLite connection to register module with */
6278  const char *zName, /* Name of the module */
6279  const sqlite3_module *p, /* Methods for the module */
6280  void *pClientData, /* Client data for xCreate/xConnect */
6281  void(*xDestroy)(void*) /* Module destructor function */
6282 );
6283 
6284 /*
6285 ** CAPI3REF: Virtual Table Instance Object
6286 ** KEYWORDS: sqlite3_vtab
6287 **
6288 ** Every [virtual table module] implementation uses a subclass
6289 ** of this object to describe a particular instance
6290 ** of the [virtual table]. Each subclass will
6291 ** be tailored to the specific needs of the module implementation.
6292 ** The purpose of this superclass is to define certain fields that are
6293 ** common to all module implementations.
6294 **
6295 ** ^Virtual tables methods can set an error message by assigning a
6296 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
6297 ** take care that any prior string is freed by a call to [sqlite3_free()]
6298 ** prior to assigning a new string to zErrMsg. ^After the error message
6299 ** is delivered up to the client application, the string will be automatically
6300 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
6301 */
6303  const sqlite3_module *pModule; /* The module for this virtual table */
6304  int nRef; /* Number of open cursors */
6305  char *zErrMsg; /* Error message from sqlite3_mprintf() */
6306  /* Virtual table implementations will typically add additional fields */
6307 };
6308 
6309 /*
6310 ** CAPI3REF: Virtual Table Cursor Object
6311 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
6312 **
6313 ** Every [virtual table module] implementation uses a subclass of the
6314 ** following structure to describe cursors that point into the
6315 ** [virtual table] and are used
6316 ** to loop through the virtual table. Cursors are created using the
6317 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6318 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
6319 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6320 ** of the module. Each module implementation will define
6321 ** the content of a cursor structure to suit its own needs.
6322 **
6323 ** This superclass exists in order to define fields of the cursor that
6324 ** are common to all implementations.
6325 */
6327  sqlite3_vtab *pVtab; /* Virtual table of this cursor */
6328  /* Virtual table implementations will typically add additional fields */
6329 };
6330 
6331 /*
6332 ** CAPI3REF: Declare The Schema Of A Virtual Table
6333 **
6334 ** ^The [xCreate] and [xConnect] methods of a
6335 ** [virtual table module] call this interface
6336 ** to declare the format (the names and datatypes of the columns) of
6337 ** the virtual tables they implement.
6338 */
6339 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6340 
6341 /*
6342 ** CAPI3REF: Overload A Function For A Virtual Table
6343 ** METHOD: sqlite3
6344 **
6345 ** ^(Virtual tables can provide alternative implementations of functions
6346 ** using the [xFindFunction] method of the [virtual table module].
6347 ** But global versions of those functions
6348 ** must exist in order to be overloaded.)^
6349 **
6350 ** ^(This API makes sure a global version of a function with a particular
6351 ** name and number of parameters exists. If no such function exists
6352 ** before this API is called, a new function is created.)^ ^The implementation
6353 ** of the new function always causes an exception to be thrown. So
6354 ** the new function is not good for anything by itself. Its only
6355 ** purpose is to be a placeholder function that can be overloaded
6356 ** by a [virtual table].
6357 */
6358 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6359 
6360 /*
6361 ** The interface to the virtual-table mechanism defined above (back up
6362 ** to a comment remarkably similar to this one) is currently considered
6363 ** to be experimental. The interface might change in incompatible ways.
6364 ** If this is a problem for you, do not use the interface at this time.
6365 **
6366 ** When the virtual-table mechanism stabilizes, we will declare the
6367 ** interface fixed, support it indefinitely, and remove this comment.
6368 */
6369 
6370 /*
6371 ** CAPI3REF: A Handle To An Open BLOB
6372 ** KEYWORDS: {BLOB handle} {BLOB handles}
6373 **
6374 ** An instance of this object represents an open BLOB on which
6375 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6376 ** ^Objects of this type are created by [sqlite3_blob_open()]
6377 ** and destroyed by [sqlite3_blob_close()].
6378 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6379 ** can be used to read or write small subsections of the BLOB.
6380 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6381 */
6383 
6384 /*
6385 ** CAPI3REF: Open A BLOB For Incremental I/O
6386 ** METHOD: sqlite3
6387 ** CONSTRUCTOR: sqlite3_blob
6388 **
6389 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6390 ** in row iRow, column zColumn, table zTable in database zDb;
6391 ** in other words, the same BLOB that would be selected by:
6392 **
6393 ** <pre>
6394 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6395 ** </pre>)^
6396 **
6397 ** ^(Parameter zDb is not the filename that contains the database, but
6398 ** rather the symbolic name of the database. For attached databases, this is
6399 ** the name that appears after the AS keyword in the [ATTACH] statement.
6400 ** For the main database file, the database name is "main". For TEMP
6401 ** tables, the database name is "temp".)^
6402 **
6403 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
6404 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
6405 ** read-only access.
6406 **
6407 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6408 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6409 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6410 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6411 ** on *ppBlob after this function it returns.
6412 **
6413 ** This function fails with SQLITE_ERROR if any of the following are true:
6414 ** <ul>
6415 ** <li> ^(Database zDb does not exist)^,
6416 ** <li> ^(Table zTable does not exist within database zDb)^,
6417 ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
6418 ** <li> ^(Column zColumn does not exist)^,
6419 ** <li> ^(Row iRow is not present in the table)^,
6420 ** <li> ^(The specified column of row iRow contains a value that is not
6421 ** a TEXT or BLOB value)^,
6422 ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6423 ** constraint and the blob is being opened for read/write access)^,
6424 ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6425 ** column zColumn is part of a [child key] definition and the blob is
6426 ** being opened for read/write access)^.
6427 ** </ul>
6428 **
6429 ** ^Unless it returns SQLITE_MISUSE, this function sets the
6430 ** [database connection] error code and message accessible via
6431 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6432 **
6433 **
6434 ** ^(If the row that a BLOB handle points to is modified by an
6435 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6436 ** then the BLOB handle is marked as "expired".
6437 ** This is true if any column of the row is changed, even a column
6438 ** other than the one the BLOB handle is open on.)^
6439 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6440 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6441 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6442 ** rolled back by the expiration of the BLOB. Such changes will eventually
6443 ** commit if the transaction continues to completion.)^
6444 **
6445 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6446 ** the opened blob. ^The size of a blob may not be changed by this
6447 ** interface. Use the [UPDATE] SQL command to change the size of a
6448 ** blob.
6449 **
6450 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6451 ** and the built-in [zeroblob] SQL function may be used to create a
6452 ** zero-filled blob to read or write using the incremental-blob interface.
6453 **
6454 ** To avoid a resource leak, every open [BLOB handle] should eventually
6455 ** be released by a call to [sqlite3_blob_close()].
6456 */
6458  sqlite3*,
6459  const char *zDb,
6460  const char *zTable,
6461  const char *zColumn,
6462  sqlite3_int64 iRow,
6463  int flags,
6464  sqlite3_blob **ppBlob
6465 );
6466 
6467 /*
6468 ** CAPI3REF: Move a BLOB Handle to a New Row
6469 ** METHOD: sqlite3_blob
6470 **
6471 ** ^This function is used to move an existing blob handle so that it points
6472 ** to a different row of the same database table. ^The new row is identified
6473 ** by the rowid value passed as the second argument. Only the row can be
6474 ** changed. ^The database, table and column on which the blob handle is open
6475 ** remain the same. Moving an existing blob handle to a new row can be
6476 ** faster than closing the existing handle and opening a new one.
6477 **
6478 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6479 ** it must exist and there must be either a blob or text value stored in
6480 ** the nominated column.)^ ^If the new row is not present in the table, or if
6481 ** it does not contain a blob or text value, or if another error occurs, an
6482 ** SQLite error code is returned and the blob handle is considered aborted.
6483 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6484 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6485 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6486 ** always returns zero.
6487 **
6488 ** ^This function sets the database handle error code and message.
6489 */
6490 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6491 
6492 /*
6493 ** CAPI3REF: Close A BLOB Handle
6494 ** DESTRUCTOR: sqlite3_blob
6495 **
6496 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6497 ** unconditionally. Even if this routine returns an error code, the
6498 ** handle is still closed.)^
6499 **
6500 ** ^If the blob handle being closed was opened for read-write access, and if
6501 ** the database is in auto-commit mode and there are no other open read-write
6502 ** blob handles or active write statements, the current transaction is
6503 ** committed. ^If an error occurs while committing the transaction, an error
6504 ** code is returned and the transaction rolled back.
6505 **
6506 ** Calling this function with an argument that is not a NULL pointer or an
6507 ** open blob handle results in undefined behaviour. ^Calling this routine
6508 ** with a null pointer (such as would be returned by a failed call to
6509 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6510 ** is passed a valid open blob handle, the values returned by the
6511 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6512 */
6514 
6515 /*
6516 ** CAPI3REF: Return The Size Of An Open BLOB
6517 ** METHOD: sqlite3_blob
6518 **
6519 ** ^Returns the size in bytes of the BLOB accessible via the
6520 ** successfully opened [BLOB handle] in its only argument. ^The
6521 ** incremental blob I/O routines can only read or overwriting existing
6522 ** blob content; they cannot change the size of a blob.
6523 **
6524 ** This routine only works on a [BLOB handle] which has been created
6525 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6526 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6527 ** to this routine results in undefined and probably undesirable behavior.
6528 */
6530 
6531 /*
6532 ** CAPI3REF: Read Data From A BLOB Incrementally
6533 ** METHOD: sqlite3_blob
6534 **
6535 ** ^(This function is used to read data from an open [BLOB handle] into a
6536 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6537 ** from the open BLOB, starting at offset iOffset.)^
6538 **
6539 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6540 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
6541 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6542 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6543 ** can be determined using the [sqlite3_blob_bytes()] interface.
6544 **
6545 ** ^An attempt to read from an expired [BLOB handle] fails with an
6546 ** error code of [SQLITE_ABORT].
6547 **
6548 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6549 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6550 **
6551 ** This routine only works on a [BLOB handle] which has been created
6552 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6553 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6554 ** to this routine results in undefined and probably undesirable behavior.
6555 **
6556 ** See also: [sqlite3_blob_write()].
6557 */
6558 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6559 
6560 /*
6561 ** CAPI3REF: Write Data Into A BLOB Incrementally
6562 ** METHOD: sqlite3_blob
6563 **
6564 ** ^(This function is used to write data into an open [BLOB handle] from a
6565 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6566 ** into the open BLOB, starting at offset iOffset.)^
6567 **
6568 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6569 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6570 ** ^Unless SQLITE_MISUSE is returned, this function sets the
6571 ** [database connection] error code and message accessible via
6572 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6573 **
6574 ** ^If the [BLOB handle] passed as the first argument was not opened for
6575 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6576 ** this function returns [SQLITE_READONLY].
6577 **
6578 ** This function may only modify the contents of the BLOB; it is
6579 ** not possible to increase the size of a BLOB using this API.
6580 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6581 ** [SQLITE_ERROR] is returned and no data is written. The size of the
6582 ** BLOB (and hence the maximum value of N+iOffset) can be determined
6583 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6584 ** than zero [SQLITE_ERROR] is returned and no data is written.
6585 **
6586 ** ^An attempt to write to an expired [BLOB handle] fails with an
6587 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
6588 ** before the [BLOB handle] expired are not rolled back by the
6589 ** expiration of the handle, though of course those changes might
6590 ** have been overwritten by the statement that expired the BLOB handle
6591 ** or by other independent statements.
6592 **
6593 ** This routine only works on a [BLOB handle] which has been created
6594 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6595 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6596 ** to this routine results in undefined and probably undesirable behavior.
6597 **
6598 ** See also: [sqlite3_blob_read()].
6599 */
6600 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6601 
6602 /*
6603 ** CAPI3REF: Virtual File System Objects
6604 **
6605 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6606 ** that SQLite uses to interact
6607 ** with the underlying operating system. Most SQLite builds come with a
6608 ** single default VFS that is appropriate for the host computer.
6609 ** New VFSes can be registered and existing VFSes can be unregistered.
6610 ** The following interfaces are provided.
6611 **
6612 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6613 ** ^Names are case sensitive.
6614 ** ^Names are zero-terminated UTF-8 strings.
6615 ** ^If there is no match, a NULL pointer is returned.
6616 ** ^If zVfsName is NULL then the default VFS is returned.
6617 **
6618 ** ^New VFSes are registered with sqlite3_vfs_register().
6619 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6620 ** ^The same VFS can be registered multiple times without injury.
6621 ** ^To make an existing VFS into the default VFS, register it again
6622 ** with the makeDflt flag set. If two different VFSes with the
6623 ** same name are registered, the behavior is undefined. If a
6624 ** VFS is registered with a name that is NULL or an empty string,
6625 ** then the behavior is undefined.
6626 **
6627 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6628 ** ^(If the default VFS is unregistered, another VFS is chosen as
6629 ** the default. The choice for the new VFS is arbitrary.)^
6630 */
6631 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6632 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6633 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6634 
6635 /*
6636 ** CAPI3REF: Mutexes
6637 **
6638 ** The SQLite core uses these routines for thread
6639 ** synchronization. Though they are intended for internal
6640 ** use by SQLite, code that links against SQLite is
6641 ** permitted to use any of these routines.
6642 **
6643 ** The SQLite source code contains multiple implementations
6644 ** of these mutex routines. An appropriate implementation
6645 ** is selected automatically at compile-time. The following
6646 ** implementations are available in the SQLite core:
6647 **
6648 ** <ul>
6649 ** <li> SQLITE_MUTEX_PTHREADS
6650 ** <li> SQLITE_MUTEX_W32
6651 ** <li> SQLITE_MUTEX_NOOP
6652 ** </ul>
6653 **
6654 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6655 ** that does no real locking and is appropriate for use in
6656 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
6657 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6658 ** and Windows.
6659 **
6660 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6661 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6662 ** implementation is included with the library. In this case the
6663 ** application must supply a custom mutex implementation using the
6664 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6665 ** before calling sqlite3_initialize() or any other public sqlite3_
6666 ** function that calls sqlite3_initialize().
6667 **
6668 ** ^The sqlite3_mutex_alloc() routine allocates a new
6669 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6670 ** routine returns NULL if it is unable to allocate the requested
6671 ** mutex. The argument to sqlite3_mutex_alloc() must one of these
6672 ** integer constants:
6673 **
6674 ** <ul>
6675 ** <li> SQLITE_MUTEX_FAST
6676 ** <li> SQLITE_MUTEX_RECURSIVE
6677 ** <li> SQLITE_MUTEX_STATIC_MASTER
6678 ** <li> SQLITE_MUTEX_STATIC_MEM
6679 ** <li> SQLITE_MUTEX_STATIC_OPEN
6680 ** <li> SQLITE_MUTEX_STATIC_PRNG
6681 ** <li> SQLITE_MUTEX_STATIC_LRU
6682 ** <li> SQLITE_MUTEX_STATIC_PMEM
6683 ** <li> SQLITE_MUTEX_STATIC_APP1
6684 ** <li> SQLITE_MUTEX_STATIC_APP2
6685 ** <li> SQLITE_MUTEX_STATIC_APP3
6686 ** <li> SQLITE_MUTEX_STATIC_VFS1
6687 ** <li> SQLITE_MUTEX_STATIC_VFS2
6688 ** <li> SQLITE_MUTEX_STATIC_VFS3
6689 ** </ul>
6690 **
6691 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6692 ** cause sqlite3_mutex_alloc() to create
6693 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6694 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6695 ** The mutex implementation does not need to make a distinction
6696 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6697 ** not want to. SQLite will only request a recursive mutex in
6698 ** cases where it really needs one. If a faster non-recursive mutex
6699 ** implementation is available on the host platform, the mutex subsystem
6700 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6701 **
6702 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6703 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6704 ** a pointer to a static preexisting mutex. ^Nine static mutexes are
6705 ** used by the current version of SQLite. Future versions of SQLite
6706 ** may add additional static mutexes. Static mutexes are for internal
6707 ** use by SQLite only. Applications that use SQLite mutexes should
6708 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6709 ** SQLITE_MUTEX_RECURSIVE.
6710 **
6711 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6712 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6713 ** returns a different mutex on every call. ^For the static
6714 ** mutex types, the same mutex is returned on every call that has
6715 ** the same type number.
6716 **
6717 ** ^The sqlite3_mutex_free() routine deallocates a previously
6718 ** allocated dynamic mutex. Attempting to deallocate a static
6719 ** mutex results in undefined behavior.
6720 **
6721 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6722 ** to enter a mutex. ^If another thread is already within the mutex,
6723 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6724 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6725 ** upon successful entry. ^(Mutexes created using
6726 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6727 ** In such cases, the
6728 ** mutex must be exited an equal number of times before another thread
6729 ** can enter.)^ If the same thread tries to enter any mutex other
6730 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6731 **
6732 ** ^(Some systems (for example, Windows 95) do not support the operation
6733 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
6734 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6735 ** sqlite3_mutex_try() as an optimization so this is acceptable
6736 ** behavior.)^
6737 **
6738 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6739 ** previously entered by the same thread. The behavior
6740 ** is undefined if the mutex is not currently entered by the
6741 ** calling thread or is not currently allocated.
6742 **
6743 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6744 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6745 ** behave as no-ops.
6746 **
6747 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6748 */
6754 
6755 /*
6756 ** CAPI3REF: Mutex Methods Object
6757 **
6758 ** An instance of this structure defines the low-level routines
6759 ** used to allocate and use mutexes.
6760 **
6761 ** Usually, the default mutex implementations provided by SQLite are
6762 ** sufficient, however the application has the option of substituting a custom
6763 ** implementation for specialized deployments or systems for which SQLite
6764 ** does not provide a suitable implementation. In this case, the application
6765 ** creates and populates an instance of this structure to pass
6766 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6767 ** Additionally, an instance of this structure can be used as an
6768 ** output variable when querying the system for the current mutex
6769 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6770 **
6771 ** ^The xMutexInit method defined by this structure is invoked as
6772 ** part of system initialization by the sqlite3_initialize() function.
6773 ** ^The xMutexInit routine is called by SQLite exactly once for each
6774 ** effective call to [sqlite3_initialize()].
6775 **
6776 ** ^The xMutexEnd method defined by this structure is invoked as
6777 ** part of system shutdown by the sqlite3_shutdown() function. The
6778 ** implementation of this method is expected to release all outstanding
6779 ** resources obtained by the mutex methods implementation, especially
6780 ** those obtained by the xMutexInit method. ^The xMutexEnd()
6781 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6782 **
6783 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6784 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6785 ** xMutexNotheld) implement the following interfaces (respectively):
6786 **
6787 ** <ul>
6788 ** <li> [sqlite3_mutex_alloc()] </li>
6789 ** <li> [sqlite3_mutex_free()] </li>
6790 ** <li> [sqlite3_mutex_enter()] </li>
6791 ** <li> [sqlite3_mutex_try()] </li>
6792 ** <li> [sqlite3_mutex_leave()] </li>
6793 ** <li> [sqlite3_mutex_held()] </li>
6794 ** <li> [sqlite3_mutex_notheld()] </li>
6795 ** </ul>)^
6796 **
6797 ** The only difference is that the public sqlite3_XXX functions enumerated
6798 ** above silently ignore any invocations that pass a NULL pointer instead
6799 ** of a valid mutex handle. The implementations of the methods defined
6800 ** by this structure are not required to handle this case, the results
6801 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6802 ** (i.e. it is acceptable to provide an implementation that segfaults if
6803 ** it is passed a NULL pointer).
6804 **
6805 ** The xMutexInit() method must be threadsafe. It must be harmless to
6806 ** invoke xMutexInit() multiple times within the same process and without
6807 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6808 ** xMutexInit() must be no-ops.
6809 **
6810 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6811 ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
6812 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6813 ** memory allocation for a fast or recursive mutex.
6814 **
6815 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6816 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6817 ** If xMutexInit fails in any way, it is expected to clean up after itself
6818 ** prior to returning.
6819 */
6822  int (*xMutexInit)(void);
6823  int (*xMutexEnd)(void);
6824  sqlite3_mutex *(*xMutexAlloc)(int);
6825  void (*xMutexFree)(sqlite3_mutex *);
6826  void (*xMutexEnter)(sqlite3_mutex *);
6827  int (*xMutexTry)(sqlite3_mutex *);
6828  void (*xMutexLeave)(sqlite3_mutex *);
6829  int (*xMutexHeld)(sqlite3_mutex *);
6830  int (*xMutexNotheld)(sqlite3_mutex *);
6831 };
6832 
6833 /*
6834 ** CAPI3REF: Mutex Verification Routines
6835 **
6836 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6837 ** are intended for use inside assert() statements. The SQLite core
6838 ** never uses these routines except inside an assert() and applications
6839 ** are advised to follow the lead of the core. The SQLite core only
6840 ** provides implementations for these routines when it is compiled
6841 ** with the SQLITE_DEBUG flag. External mutex implementations
6842 ** are only required to provide these routines if SQLITE_DEBUG is
6843 ** defined and if NDEBUG is not defined.
6844 **
6845 ** These routines should return true if the mutex in their argument
6846 ** is held or not held, respectively, by the calling thread.
6847 **
6848 ** The implementation is not required to provide versions of these
6849 ** routines that actually work. If the implementation does not provide working
6850 ** versions of these routines, it should at least provide stubs that always
6851 ** return true so that one does not get spurious assertion failures.
6852 **
6853 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
6854 ** the routine should return 1. This seems counter-intuitive since
6855 ** clearly the mutex cannot be held if it does not exist. But
6856 ** the reason the mutex does not exist is because the build is not
6857 ** using mutexes. And we do not want the assert() containing the
6858 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6859 ** the appropriate thing to do. The sqlite3_mutex_notheld()
6860 ** interface should also return 1 when given a NULL pointer.
6861 */
6862 #ifndef NDEBUG
6865 #endif
6866 
6867 /*
6868 ** CAPI3REF: Mutex Types
6869 **
6870 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6871 ** which is one of these integer constants.
6872 **
6873 ** The set of static mutexes may change from one SQLite release to the
6874 ** next. Applications that override the built-in mutex logic must be
6875 ** prepared to accommodate additional static mutexes.
6876 */
6877 #define SQLITE_MUTEX_FAST 0
6878 #define SQLITE_MUTEX_RECURSIVE 1
6879 #define SQLITE_MUTEX_STATIC_MASTER 2
6880 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6881 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6882 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6883 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
6884 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6885 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6886 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6887 #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
6888 #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
6889 #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
6890 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
6891 #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
6892 #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
6893 
6894 /*
6895 ** CAPI3REF: Retrieve the mutex for a database connection
6896 ** METHOD: sqlite3
6897 **
6898 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6899 ** serializes access to the [database connection] given in the argument
6900 ** when the [threading mode] is Serialized.
6901 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6902 ** routine returns a NULL pointer.
6903 */
6905 
6906 /*
6907 ** CAPI3REF: Low-Level Control Of Database Files
6908 ** METHOD: sqlite3
6909 **
6910 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6911 ** xFileControl method for the [sqlite3_io_methods] object associated
6912 ** with a particular database identified by the second argument. ^The
6913 ** name of the database is "main" for the main database or "temp" for the
6914 ** TEMP database, or the name that appears after the AS keyword for
6915 ** databases that are added using the [ATTACH] SQL command.
6916 ** ^A NULL pointer can be used in place of "main" to refer to the
6917 ** main database file.
6918 ** ^The third and fourth parameters to this routine
6919 ** are passed directly through to the second and third parameters of
6920 ** the xFileControl method. ^The return value of the xFileControl
6921 ** method becomes the return value of this routine.
6922 **
6923 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6924 ** a pointer to the underlying [sqlite3_file] object to be written into
6925 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6926 ** case is a short-circuit path which does not actually invoke the
6927 ** underlying sqlite3_io_methods.xFileControl method.
6928 **
6929 ** ^If the second parameter (zDbName) does not match the name of any
6930 ** open database file, then SQLITE_ERROR is returned. ^This error
6931 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6932 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6933 ** also return SQLITE_ERROR. There is no way to distinguish between
6934 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6935 ** xFileControl method.
6936 **
6937 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6938 */
6939 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6940 
6941 /*
6942 ** CAPI3REF: Testing Interface
6943 **
6944 ** ^The sqlite3_test_control() interface is used to read out internal
6945 ** state of SQLite and to inject faults into SQLite for testing
6946 ** purposes. ^The first parameter is an operation code that determines
6947 ** the number, meaning, and operation of all subsequent parameters.
6948 **
6949 ** This interface is not for use by applications. It exists solely
6950 ** for verifying the correct operation of the SQLite library. Depending
6951 ** on how the SQLite library is compiled, this interface might not exist.
6952 **
6953 ** The details of the operation codes, their meanings, the parameters
6954 ** they take, and what they do are all subject to change without notice.
6955 ** Unlike most of the SQLite API, this function is not guaranteed to
6956 ** operate consistently from one release to the next.
6957 */
6958 SQLITE_API int sqlite3_test_control(int op, ...);
6959 
6960 /*
6961 ** CAPI3REF: Testing Interface Operation Codes
6962 **
6963 ** These constants are the valid operation code parameters used
6964 ** as the first argument to [sqlite3_test_control()].
6965 **
6966 ** These parameters and their meanings are subject to change
6967 ** without notice. These values are for testing purposes only.
6968 ** Applications should not use any of these parameters or the
6969 ** [sqlite3_test_control()] interface.
6970 */
6971 #define SQLITE_TESTCTRL_FIRST 5
6972 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6973 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6974 #define SQLITE_TESTCTRL_PRNG_RESET 7
6975 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6976 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6977 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6978 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6979 #define SQLITE_TESTCTRL_ASSERT 12
6980 #define SQLITE_TESTCTRL_ALWAYS 13
6981 #define SQLITE_TESTCTRL_RESERVE 14
6982 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6983 #define SQLITE_TESTCTRL_ISKEYWORD 16
6984 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
6985 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
6986 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
6987 #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
6988 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
6989 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
6990 #define SQLITE_TESTCTRL_BYTEORDER 22
6991 #define SQLITE_TESTCTRL_ISINIT 23
6992 #define SQLITE_TESTCTRL_SORTER_MMAP 24
6993 #define SQLITE_TESTCTRL_IMPOSTER 25
6994 #define SQLITE_TESTCTRL_LAST 25
6995 
6996 /*
6997 ** CAPI3REF: SQLite Runtime Status
6998 **
6999 ** ^These interfaces are used to retrieve runtime status information
7000 ** about the performance of SQLite, and optionally to reset various
7001 ** highwater marks. ^The first argument is an integer code for
7002 ** the specific parameter to measure. ^(Recognized integer codes
7003 ** are of the form [status parameters | SQLITE_STATUS_...].)^
7004 ** ^The current value of the parameter is returned into *pCurrent.
7005 ** ^The highest recorded value is returned in *pHighwater. ^If the
7006 ** resetFlag is true, then the highest record value is reset after
7007 ** *pHighwater is written. ^(Some parameters do not record the highest
7008 ** value. For those parameters
7009 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
7010 ** ^(Other parameters record only the highwater mark and not the current
7011 ** value. For these latter parameters nothing is written into *pCurrent.)^
7012 **
7013 ** ^The sqlite3_status() and sqlite3_status64() routines return
7014 ** SQLITE_OK on success and a non-zero [error code] on failure.
7015 **
7016 ** If either the current value or the highwater mark is too large to
7017 ** be represented by a 32-bit integer, then the values returned by
7018 ** sqlite3_status() are undefined.
7019 **
7020 ** See also: [sqlite3_db_status()]
7021 */
7022 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
7024  int op,
7025  sqlite3_int64 *pCurrent,
7026  sqlite3_int64 *pHighwater,
7027  int resetFlag
7028 );
7029 
7030 
7031 /*
7032 ** CAPI3REF: Status Parameters
7033 ** KEYWORDS: {status parameters}
7034 **
7035 ** These integer constants designate various run-time status parameters
7036 ** that can be returned by [sqlite3_status()].
7037 **
7038 ** <dl>
7039 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
7040 ** <dd>This parameter is the current amount of memory checked out
7041 ** using [sqlite3_malloc()], either directly or indirectly. The
7042 ** figure includes calls made to [sqlite3_malloc()] by the application
7043 ** and internal memory usage by the SQLite library. Scratch memory
7044 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
7045 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
7046 ** this parameter. The amount returned is the sum of the allocation
7047 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
7048 **
7049 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
7050 ** <dd>This parameter records the largest memory allocation request
7051 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
7052 ** internal equivalents). Only the value returned in the
7053 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7054 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7055 **
7056 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
7057 ** <dd>This parameter records the number of separate memory allocations
7058 ** currently checked out.</dd>)^
7059 **
7060 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
7061 ** <dd>This parameter returns the number of pages used out of the
7062 ** [pagecache memory allocator] that was configured using
7063 ** [SQLITE_CONFIG_PAGECACHE]. The
7064 ** value returned is in pages, not in bytes.</dd>)^
7065 **
7066 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
7067 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
7068 ** <dd>This parameter returns the number of bytes of page cache
7069 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
7070 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
7071 ** returned value includes allocations that overflowed because they
7072 ** where too large (they were larger than the "sz" parameter to
7073 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
7074 ** no space was left in the page cache.</dd>)^
7075 **
7076 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
7077 ** <dd>This parameter records the largest memory allocation request
7078 ** handed to [pagecache memory allocator]. Only the value returned in the
7079 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7080 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7081 **
7082 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
7083 ** <dd>This parameter returns the number of allocations used out of the
7084 ** [scratch memory allocator] configured using
7085 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
7086 ** in bytes. Since a single thread may only have one scratch allocation
7087 ** outstanding at time, this parameter also reports the number of threads
7088 ** using scratch memory at the same time.</dd>)^
7089 **
7090 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
7091 ** <dd>This parameter returns the number of bytes of scratch memory
7092 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
7093 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
7094 ** returned include overflows because the requested allocation was too
7095 ** larger (that is, because the requested allocation was larger than the
7096 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
7097 ** slots were available.
7098 ** </dd>)^
7099 **
7100 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
7101 ** <dd>This parameter records the largest memory allocation request
7102 ** handed to [scratch memory allocator]. Only the value returned in the
7103 ** *pHighwater parameter to [sqlite3_status()] is of interest.
7104 ** The value written into the *pCurrent parameter is undefined.</dd>)^
7105 **
7106 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
7107 ** <dd>The *pHighwater parameter records the deepest parser stack.
7108 ** The *pCurrent value is undefined. The *pHighwater value is only
7109 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
7110 ** </dl>
7111 **
7112 ** New status parameters may be added from time to time.
7113 */
7114 #define SQLITE_STATUS_MEMORY_USED 0
7115 #define SQLITE_STATUS_PAGECACHE_USED 1
7116 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
7117 #define SQLITE_STATUS_SCRATCH_USED 3
7118 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
7119 #define SQLITE_STATUS_MALLOC_SIZE 5
7120 #define SQLITE_STATUS_PARSER_STACK 6
7121 #define SQLITE_STATUS_PAGECACHE_SIZE 7
7122 #define SQLITE_STATUS_SCRATCH_SIZE 8
7123 #define SQLITE_STATUS_MALLOC_COUNT 9
7124 
7125 /*
7126 ** CAPI3REF: Database Connection Status
7127 ** METHOD: sqlite3
7128 **
7129 ** ^This interface is used to retrieve runtime status information
7130 ** about a single [database connection]. ^The first argument is the
7131 ** database connection object to be interrogated. ^The second argument
7132 ** is an integer constant, taken from the set of
7133 ** [SQLITE_DBSTATUS options], that
7134 ** determines the parameter to interrogate. The set of
7135 ** [SQLITE_DBSTATUS options] is likely
7136 ** to grow in future releases of SQLite.
7137 **
7138 ** ^The current value of the requested parameter is written into *pCur
7139 ** and the highest instantaneous value is written into *pHiwtr. ^If
7140 ** the resetFlg is true, then the highest instantaneous value is
7141 ** reset back down to the current value.
7142 **
7143 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
7144 ** non-zero [error code] on failure.
7145 **
7146 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
7147 */
7148 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
7149 
7150 /*
7151 ** CAPI3REF: Status Parameters for database connections
7152 ** KEYWORDS: {SQLITE_DBSTATUS options}
7153 **
7154 ** These constants are the available integer "verbs" that can be passed as
7155 ** the second argument to the [sqlite3_db_status()] interface.
7156 **
7157 ** New verbs may be added in future releases of SQLite. Existing verbs
7158 ** might be discontinued. Applications should check the return code from
7159 ** [sqlite3_db_status()] to make sure that the call worked.
7160 ** The [sqlite3_db_status()] interface will return a non-zero error code
7161 ** if a discontinued or unsupported verb is invoked.
7162 **
7163 ** <dl>
7164 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
7165 ** <dd>This parameter returns the number of lookaside memory slots currently
7166 ** checked out.</dd>)^
7167 **
7168 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
7169 ** <dd>This parameter returns the number malloc attempts that were
7170 ** satisfied using lookaside memory. Only the high-water value is meaningful;
7171 ** the current value is always zero.)^
7172 **
7173 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
7174 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
7175 ** <dd>This parameter returns the number malloc attempts that might have
7176 ** been satisfied using lookaside memory but failed due to the amount of
7177 ** memory requested being larger than the lookaside slot size.
7178 ** Only the high-water value is meaningful;
7179 ** the current value is always zero.)^
7180 **
7181 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
7182 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
7183 ** <dd>This parameter returns the number malloc attempts that might have
7184 ** been satisfied using lookaside memory but failed due to all lookaside
7185 ** memory already being in use.
7186 ** Only the high-water value is meaningful;
7187 ** the current value is always zero.)^
7188 **
7189 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
7190 ** <dd>This parameter returns the approximate number of bytes of heap
7191 ** memory used by all pager caches associated with the database connection.)^
7192 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
7193 **
7194 ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
7195 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
7196 ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
7197 ** pager cache is shared between two or more connections the bytes of heap
7198 ** memory used by that pager cache is divided evenly between the attached
7199 ** connections.)^ In other words, if none of the pager caches associated
7200 ** with the database connection are shared, this request returns the same
7201 ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
7202 ** shared, the value returned by this call will be smaller than that returned
7203 ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
7204 ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
7205 **
7206 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
7207 ** <dd>This parameter returns the approximate number of bytes of heap
7208 ** memory used to store the schema for all databases associated
7209 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
7210 ** ^The full amount of memory used by the schemas is reported, even if the
7211 ** schema memory is shared with other database connections due to
7212 ** [shared cache mode] being enabled.
7213 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
7214 **
7215 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
7216 ** <dd>This parameter returns the approximate number of bytes of heap
7217 ** and lookaside memory used by all prepared statements associated with
7218 ** the database connection.)^
7219 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
7220 ** </dd>
7221 **
7222 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
7223 ** <dd>This parameter returns the number of pager cache hits that have
7224 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
7225 ** is always 0.
7226 ** </dd>
7227 **
7228 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
7229 ** <dd>This parameter returns the number of pager cache misses that have
7230 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
7231 ** is always 0.
7232 ** </dd>
7233 **
7234 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
7235 ** <dd>This parameter returns the number of dirty cache entries that have
7236 ** been written to disk. Specifically, the number of pages written to the
7237 ** wal file in wal mode databases, or the number of pages written to the
7238 ** database file in rollback mode databases. Any pages written as part of
7239 ** transaction rollback or database recovery operations are not included.
7240 ** If an IO or other error occurs while writing a page to disk, the effect
7241 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
7242 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
7243 ** </dd>
7244 **
7245 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
7246 ** <dd>This parameter returns zero for the current value if and only if
7247 ** all foreign key constraints (deferred or immediate) have been
7248 ** resolved.)^ ^The highwater mark is always 0.
7249 ** </dd>
7250 ** </dl>
7251 */
7252 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
7253 #define SQLITE_DBSTATUS_CACHE_USED 1
7254 #define SQLITE_DBSTATUS_SCHEMA_USED 2
7255 #define SQLITE_DBSTATUS_STMT_USED 3
7256 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
7257 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
7258 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
7259 #define SQLITE_DBSTATUS_CACHE_HIT 7
7260 #define SQLITE_DBSTATUS_CACHE_MISS 8
7261 #define SQLITE_DBSTATUS_CACHE_WRITE 9
7262 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
7263 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
7264 #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */
7265 
7266 
7267 /*
7268 ** CAPI3REF: Prepared Statement Status
7269 ** METHOD: sqlite3_stmt
7270 **
7271 ** ^(Each prepared statement maintains various
7272 ** [SQLITE_STMTSTATUS counters] that measure the number
7273 ** of times it has performed specific operations.)^ These counters can
7274 ** be used to monitor the performance characteristics of the prepared
7275 ** statements. For example, if the number of table steps greatly exceeds
7276 ** the number of table searches or result rows, that would tend to indicate
7277 ** that the prepared statement is using a full table scan rather than
7278 ** an index.
7279 **
7280 ** ^(This interface is used to retrieve and reset counter values from
7281 ** a [prepared statement]. The first argument is the prepared statement
7282 ** object to be interrogated. The second argument
7283 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
7284 ** to be interrogated.)^
7285 ** ^The current value of the requested counter is returned.
7286 ** ^If the resetFlg is true, then the counter is reset to zero after this
7287 ** interface call returns.
7288 **
7289 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
7290 */
7291 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7292 
7293 /*
7294 ** CAPI3REF: Status Parameters for prepared statements
7295 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
7296 **
7297 ** These preprocessor macros define integer codes that name counter
7298 ** values associated with the [sqlite3_stmt_status()] interface.
7299 ** The meanings of the various counters are as follows:
7300 **
7301 ** <dl>
7302 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7303 ** <dd>^This is the number of times that SQLite has stepped forward in
7304 ** a table as part of a full table scan. Large numbers for this counter
7305 ** may indicate opportunities for performance improvement through
7306 ** careful use of indices.</dd>
7307 **
7308 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
7309 ** <dd>^This is the number of sort operations that have occurred.
7310 ** A non-zero value in this counter may indicate an opportunity to
7311 ** improvement performance through careful use of indices.</dd>
7312 **
7313 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
7314 ** <dd>^This is the number of rows inserted into transient indices that
7315 ** were created automatically in order to help joins run faster.
7316 ** A non-zero value in this counter may indicate an opportunity to
7317 ** improvement performance by adding permanent indices that do not
7318 ** need to be reinitialized each time the statement is run.</dd>
7319 **
7320 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
7321 ** <dd>^This is the number of virtual machine operations executed
7322 ** by the prepared statement if that number is less than or equal
7323 ** to 2147483647. The number of virtual machine operations can be
7324 ** used as a proxy for the total work done by the prepared statement.
7325 ** If the number of virtual machine operations exceeds 2147483647
7326 ** then the value returned by this statement status code is undefined.
7327 ** </dd>
7328 ** </dl>
7329 */
7330 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
7331 #define SQLITE_STMTSTATUS_SORT 2
7332 #define SQLITE_STMTSTATUS_AUTOINDEX 3
7333 #define SQLITE_STMTSTATUS_VM_STEP 4
7334 
7335 /*
7336 ** CAPI3REF: Custom Page Cache Object
7337 **
7338 ** The sqlite3_pcache type is opaque. It is implemented by
7339 ** the pluggable module. The SQLite core has no knowledge of
7340 ** its size or internal structure and never deals with the
7341 ** sqlite3_pcache object except by holding and passing pointers
7342 ** to the object.
7343 **
7344 ** See [sqlite3_pcache_methods2] for additional information.
7345 */
7347 
7348 /*
7349 ** CAPI3REF: Custom Page Cache Object
7350 **
7351 ** The sqlite3_pcache_page object represents a single page in the
7352 ** page cache. The page cache will allocate instances of this
7353 ** object. Various methods of the page cache use pointers to instances
7354 ** of this object as parameters or as their return value.
7355 **
7356 ** See [sqlite3_pcache_methods2] for additional information.
7357 */
7360  void *pBuf; /* The content of the page */
7361  void *pExtra; /* Extra information associated with the page */
7362 };
7363 
7364 /*
7365 ** CAPI3REF: Application Defined Page Cache.
7366 ** KEYWORDS: {page cache}
7367 **
7368 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7369 ** register an alternative page cache implementation by passing in an
7370 ** instance of the sqlite3_pcache_methods2 structure.)^
7371 ** In many applications, most of the heap memory allocated by
7372 ** SQLite is used for the page cache.
7373 ** By implementing a
7374 ** custom page cache using this API, an application can better control
7375 ** the amount of memory consumed by SQLite, the way in which
7376 ** that memory is allocated and released, and the policies used to
7377 ** determine exactly which parts of a database file are cached and for
7378 ** how long.
7379 **
7380 ** The alternative page cache mechanism is an
7381 ** extreme measure that is only needed by the most demanding applications.
7382 ** The built-in page cache is recommended for most uses.
7383 **
7384 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7385 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
7386 ** the application may discard the parameter after the call to
7387 ** [sqlite3_config()] returns.)^
7388 **
7389 ** [[the xInit() page cache method]]
7390 ** ^(The xInit() method is called once for each effective
7391 ** call to [sqlite3_initialize()])^
7392 ** (usually only once during the lifetime of the process). ^(The xInit()
7393 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7394 ** The intent of the xInit() method is to set up global data structures
7395 ** required by the custom page cache implementation.
7396 ** ^(If the xInit() method is NULL, then the
7397 ** built-in default page cache is used instead of the application defined
7398 ** page cache.)^
7399 **
7400 ** [[the xShutdown() page cache method]]
7401 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
7402 ** It can be used to clean up
7403 ** any outstanding resources before process shutdown, if required.
7404 ** ^The xShutdown() method may be NULL.
7405 **
7406 ** ^SQLite automatically serializes calls to the xInit method,
7407 ** so the xInit method need not be threadsafe. ^The
7408 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
7409 ** not need to be threadsafe either. All other methods must be threadsafe
7410 ** in multithreaded applications.
7411 **
7412 ** ^SQLite will never invoke xInit() more than once without an intervening
7413 ** call to xShutdown().
7414 **
7415 ** [[the xCreate() page cache methods]]
7416 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
7417 ** SQLite will typically create one cache instance for each open database file,
7418 ** though this is not guaranteed. ^The
7419 ** first parameter, szPage, is the size in bytes of the pages that must
7420 ** be allocated by the cache. ^szPage will always a power of two. ^The
7421 ** second parameter szExtra is a number of bytes of extra storage
7422 ** associated with each page cache entry. ^The szExtra parameter will
7423 ** a number less than 250. SQLite will use the
7424 ** extra szExtra bytes on each page to store metadata about the underlying
7425 ** database page on disk. The value passed into szExtra depends
7426 ** on the SQLite version, the target platform, and how SQLite was compiled.
7427 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7428 ** created will be used to cache database pages of a file stored on disk, or
7429 ** false if it is used for an in-memory database. The cache implementation
7430 ** does not have to do anything special based with the value of bPurgeable;
7431 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
7432 ** never invoke xUnpin() except to deliberately delete a page.
7433 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7434 ** false will always have the "discard" flag set to true.
7435 ** ^Hence, a cache created with bPurgeable false will
7436 ** never contain any unpinned pages.
7437 **
7438 ** [[the xCachesize() page cache method]]
7439 ** ^(The xCachesize() method may be called at any time by SQLite to set the
7440 ** suggested maximum cache-size (number of pages stored by) the cache
7441 ** instance passed as the first argument. This is the value configured using
7442 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
7443 ** parameter, the implementation is not required to do anything with this
7444 ** value; it is advisory only.
7445 **
7446 ** [[the xPagecount() page cache methods]]
7447 ** The xPagecount() method must return the number of pages currently
7448 ** stored in the cache, both pinned and unpinned.
7449 **
7450 ** [[the xFetch() page cache methods]]
7451 ** The xFetch() method locates a page in the cache and returns a pointer to
7452 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7453 ** The pBuf element of the returned sqlite3_pcache_page object will be a
7454 ** pointer to a buffer of szPage bytes used to store the content of a
7455 ** single database page. The pExtra element of sqlite3_pcache_page will be
7456 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7457 ** for each entry in the page cache.
7458 **
7459 ** The page to be fetched is determined by the key. ^The minimum key value
7460 ** is 1. After it has been retrieved using xFetch, the page is considered
7461 ** to be "pinned".
7462 **
7463 ** If the requested page is already in the page cache, then the page cache
7464 ** implementation must return a pointer to the page buffer with its content
7465 ** intact. If the requested page is not already in the cache, then the
7466 ** cache implementation should use the value of the createFlag
7467 ** parameter to help it determined what action to take:
7468 **
7469 ** <table border=1 width=85% align=center>
7470 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7471 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
7472 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7473 ** Otherwise return NULL.
7474 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
7475 ** NULL if allocating a new page is effectively impossible.
7476 ** </table>
7477 **
7478 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
7479 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7480 ** failed.)^ In between the to xFetch() calls, SQLite may
7481 ** attempt to unpin one or more cache pages by spilling the content of
7482 ** pinned pages to disk and synching the operating system disk cache.
7483 **
7484 ** [[the xUnpin() page cache method]]
7485 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7486 ** as its second argument. If the third parameter, discard, is non-zero,
7487 ** then the page must be evicted from the cache.
7488 ** ^If the discard parameter is
7489 ** zero, then the page may be discarded or retained at the discretion of
7490 ** page cache implementation. ^The page cache implementation
7491 ** may choose to evict unpinned pages at any time.
7492 **
7493 ** The cache must not perform any reference counting. A single
7494 ** call to xUnpin() unpins the page regardless of the number of prior calls
7495 ** to xFetch().
7496 **
7497 ** [[the xRekey() page cache methods]]
7498 ** The xRekey() method is used to change the key value associated with the
7499 ** page passed as the second argument. If the cache
7500 ** previously contains an entry associated with newKey, it must be
7501 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7502 ** to be pinned.
7503 **
7504 ** When SQLite calls the xTruncate() method, the cache must discard all
7505 ** existing cache entries with page numbers (keys) greater than or equal
7506 ** to the value of the iLimit parameter passed to xTruncate(). If any
7507 ** of these pages are pinned, they are implicitly unpinned, meaning that
7508 ** they can be safely discarded.
7509 **
7510 ** [[the xDestroy() page cache method]]
7511 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7512 ** All resources associated with the specified cache should be freed. ^After
7513 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7514 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7515 ** functions.
7516 **
7517 ** [[the xShrink() page cache method]]
7518 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7519 ** free up as much of heap memory as possible. The page cache implementation
7520 ** is not obligated to free any memory, but well-behaved implementations should
7521 ** do their best.
7522 */
7526  void *pArg;
7527  int (*xInit)(void*);
7528  void (*xShutdown)(void*);
7529  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7530  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7531  int (*xPagecount)(sqlite3_pcache*);
7532  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7533  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7534  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7535  unsigned oldKey, unsigned newKey);
7536  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7537  void (*xDestroy)(sqlite3_pcache*);
7538  void (*xShrink)(sqlite3_pcache*);
7539 };
7540 
7541 /*
7542 ** This is the obsolete pcache_methods object that has now been replaced
7543 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
7544 ** retained in the header file for backwards compatibility only.
7545 */
7548  void *pArg;
7549  int (*xInit)(void*);
7550  void (*xShutdown)(void*);
7551  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7552  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7553  int (*xPagecount)(sqlite3_pcache*);
7554  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7555  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7556  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7557  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7558  void (*xDestroy)(sqlite3_pcache*);
7559 };
7560 
7561 
7562 /*
7563 ** CAPI3REF: Online Backup Object
7564 **
7565 ** The sqlite3_backup object records state information about an ongoing
7566 ** online backup operation. ^The sqlite3_backup object is created by
7567 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7568 ** [sqlite3_backup_finish()].
7569 **
7570 ** See Also: [Using the SQLite Online Backup API]
7571 */
7573 
7574 /*
7575 ** CAPI3REF: Online Backup API.
7576 **
7577 ** The backup API copies the content of one database into another.
7578 ** It is useful either for creating backups of databases or
7579 ** for copying in-memory databases to or from persistent files.
7580 **
7581 ** See Also: [Using the SQLite Online Backup API]
7582 **
7583 ** ^SQLite holds a write transaction open on the destination database file
7584 ** for the duration of the backup operation.
7585 ** ^The source database is read-locked only while it is being read;
7586 ** it is not locked continuously for the entire backup operation.
7587 ** ^Thus, the backup may be performed on a live source database without
7588 ** preventing other database connections from
7589 ** reading or writing to the source database while the backup is underway.
7590 **
7591 ** ^(To perform a backup operation:
7592 ** <ol>
7593 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
7594 ** backup,
7595 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7596 ** the data between the two databases, and finally
7597 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
7598 ** associated with the backup operation.
7599 ** </ol>)^
7600 ** There should be exactly one call to sqlite3_backup_finish() for each
7601 ** successful call to sqlite3_backup_init().
7602 **
7603 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7604 **
7605 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7606 ** [database connection] associated with the destination database
7607 ** and the database name, respectively.
7608 ** ^The database name is "main" for the main database, "temp" for the
7609 ** temporary database, or the name specified after the AS keyword in
7610 ** an [ATTACH] statement for an attached database.
7611 ** ^The S and M arguments passed to
7612 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7613 ** and database name of the source database, respectively.
7614 ** ^The source and destination [database connections] (parameters S and D)
7615 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7616 ** an error.
7617 **
7618 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7619 ** there is already a read or read-write transaction open on the
7620 ** destination database.
7621 **
7622 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7623 ** returned and an error code and error message are stored in the
7624 ** destination [database connection] D.
7625 ** ^The error code and message for the failed call to sqlite3_backup_init()
7626 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7627 ** [sqlite3_errmsg16()] functions.
7628 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7629 ** [sqlite3_backup] object.
7630 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7631 ** sqlite3_backup_finish() functions to perform the specified backup
7632 ** operation.
7633 **
7634 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7635 **
7636 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7637 ** the source and destination databases specified by [sqlite3_backup] object B.
7638 ** ^If N is negative, all remaining source pages are copied.
7639 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7640 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7641 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7642 ** from source to destination, then it returns [SQLITE_DONE].
7643 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7644 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7645 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7646 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7647 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7648 **
7649 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7650 ** <ol>
7651 ** <li> the destination database was opened read-only, or
7652 ** <li> the destination database is using write-ahead-log journaling
7653 ** and the destination and source page sizes differ, or
7654 ** <li> the destination database is an in-memory database and the
7655 ** destination and source page sizes differ.
7656 ** </ol>)^
7657 **
7658 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7659 ** the [sqlite3_busy_handler | busy-handler function]
7660 ** is invoked (if one is specified). ^If the
7661 ** busy-handler returns non-zero before the lock is available, then
7662 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7663 ** sqlite3_backup_step() can be retried later. ^If the source
7664 ** [database connection]
7665 ** is being used to write to the source database when sqlite3_backup_step()
7666 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7667 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7668 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7669 ** [SQLITE_READONLY] is returned, then
7670 ** there is no point in retrying the call to sqlite3_backup_step(). These
7671 ** errors are considered fatal.)^ The application must accept
7672 ** that the backup operation has failed and pass the backup operation handle
7673 ** to the sqlite3_backup_finish() to release associated resources.
7674 **
7675 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7676 ** on the destination file. ^The exclusive lock is not released until either
7677 ** sqlite3_backup_finish() is called or the backup operation is complete
7678 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
7679 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7680 ** lasts for the duration of the sqlite3_backup_step() call.
7681 ** ^Because the source database is not locked between calls to
7682 ** sqlite3_backup_step(), the source database may be modified mid-way
7683 ** through the backup process. ^If the source database is modified by an
7684 ** external process or via a database connection other than the one being
7685 ** used by the backup operation, then the backup will be automatically
7686 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7687 ** database is modified by the using the same database connection as is used
7688 ** by the backup operation, then the backup database is automatically
7689 ** updated at the same time.
7690 **
7691 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7692 **
7693 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7694 ** application wishes to abandon the backup operation, the application
7695 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7696 ** ^The sqlite3_backup_finish() interfaces releases all
7697 ** resources associated with the [sqlite3_backup] object.
7698 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7699 ** active write-transaction on the destination database is rolled back.
7700 ** The [sqlite3_backup] object is invalid
7701 ** and may not be used following a call to sqlite3_backup_finish().
7702 **
7703 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7704 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7705 ** sqlite3_backup_step() completed.
7706 ** ^If an out-of-memory condition or IO error occurred during any prior
7707 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7708 ** sqlite3_backup_finish() returns the corresponding [error code].
7709 **
7710 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7711 ** is not a permanent error and does not affect the return value of
7712 ** sqlite3_backup_finish().
7713 **
7714 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7715 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7716 **
7717 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
7718 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7719 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7720 ** in the source database at the conclusion of the most recent
7721 ** sqlite3_backup_step().
7722 ** ^(The values returned by these functions are only updated by
7723 ** sqlite3_backup_step(). If the source database is modified in a way that
7724 ** changes the size of the source database or the number of pages remaining,
7725 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
7726 ** and sqlite3_backup_remaining() until after the next
7727 ** sqlite3_backup_step().)^
7728 **
7729 ** <b>Concurrent Usage of Database Handles</b>
7730 **
7731 ** ^The source [database connection] may be used by the application for other
7732 ** purposes while a backup operation is underway or being initialized.
7733 ** ^If SQLite is compiled and configured to support threadsafe database
7734 ** connections, then the source database connection may be used concurrently
7735 ** from within other threads.
7736 **
7737 ** However, the application must guarantee that the destination
7738 ** [database connection] is not passed to any other API (by any thread) after
7739 ** sqlite3_backup_init() is called and before the corresponding call to
7740 ** sqlite3_backup_finish(). SQLite does not currently check to see
7741 ** if the application incorrectly accesses the destination [database connection]
7742 ** and so no error code is reported, but the operations may malfunction
7743 ** nevertheless. Use of the destination database connection while a
7744 ** backup is in progress might also also cause a mutex deadlock.
7745 **
7746 ** If running in [shared cache mode], the application must
7747 ** guarantee that the shared cache used by the destination database
7748 ** is not accessed while the backup is running. In practice this means
7749 ** that the application must guarantee that the disk file being
7750 ** backed up to is not accessed by any connection within the process,
7751 ** not just the specific connection that was passed to sqlite3_backup_init().
7752 **
7753 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7754 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7755 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7756 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7757 ** same time as another thread is invoking sqlite3_backup_step() it is
7758 ** possible that they return invalid values.
7759 */
7761  sqlite3 *pDest, /* Destination database handle */
7762  const char *zDestName, /* Destination database name */
7763  sqlite3 *pSource, /* Source database handle */
7764  const char *zSourceName /* Source database name */
7765 );
7766 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7770 
7771 /*
7772 ** CAPI3REF: Unlock Notification
7773 ** METHOD: sqlite3
7774 **
7775 ** ^When running in shared-cache mode, a database operation may fail with
7776 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7777 ** individual tables within the shared-cache cannot be obtained. See
7778 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7779 ** ^This API may be used to register a callback that SQLite will invoke
7780 ** when the connection currently holding the required lock relinquishes it.
7781 ** ^This API is only available if the library was compiled with the
7782 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7783 **
7784 ** See Also: [Using the SQLite Unlock Notification Feature].
7785 **
7786 ** ^Shared-cache locks are released when a database connection concludes
7787 ** its current transaction, either by committing it or rolling it back.
7788 **
7789 ** ^When a connection (known as the blocked connection) fails to obtain a
7790 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7791 ** identity of the database connection (the blocking connection) that
7792 ** has locked the required resource is stored internally. ^After an
7793 ** application receives an SQLITE_LOCKED error, it may call the
7794 ** sqlite3_unlock_notify() method with the blocked connection handle as
7795 ** the first argument to register for a callback that will be invoked
7796 ** when the blocking connections current transaction is concluded. ^The
7797 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7798 ** call that concludes the blocking connections transaction.
7799 **
7800 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7801 ** there is a chance that the blocking connection will have already
7802 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7803 ** If this happens, then the specified callback is invoked immediately,
7804 ** from within the call to sqlite3_unlock_notify().)^
7805 **
7806 ** ^If the blocked connection is attempting to obtain a write-lock on a
7807 ** shared-cache table, and more than one other connection currently holds
7808 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7809 ** the other connections to use as the blocking connection.
7810 **
7811 ** ^(There may be at most one unlock-notify callback registered by a
7812 ** blocked connection. If sqlite3_unlock_notify() is called when the
7813 ** blocked connection already has a registered unlock-notify callback,
7814 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7815 ** called with a NULL pointer as its second argument, then any existing
7816 ** unlock-notify callback is canceled. ^The blocked connections
7817 ** unlock-notify callback may also be canceled by closing the blocked
7818 ** connection using [sqlite3_close()].
7819 **
7820 ** The unlock-notify callback is not reentrant. If an application invokes
7821 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7822 ** crash or deadlock may be the result.
7823 **
7824 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7825 ** returns SQLITE_OK.
7826 **
7827 ** <b>Callback Invocation Details</b>
7828 **
7829 ** When an unlock-notify callback is registered, the application provides a
7830 ** single void* pointer that is passed to the callback when it is invoked.
7831 ** However, the signature of the callback function allows SQLite to pass
7832 ** it an array of void* context pointers. The first argument passed to
7833 ** an unlock-notify callback is a pointer to an array of void* pointers,
7834 ** and the second is the number of entries in the array.
7835 **
7836 ** When a blocking connections transaction is concluded, there may be
7837 ** more than one blocked connection that has registered for an unlock-notify
7838 ** callback. ^If two or more such blocked connections have specified the
7839 ** same callback function, then instead of invoking the callback function
7840 ** multiple times, it is invoked once with the set of void* context pointers
7841 ** specified by the blocked connections bundled together into an array.
7842 ** This gives the application an opportunity to prioritize any actions
7843 ** related to the set of unblocked database connections.
7844 **
7845 ** <b>Deadlock Detection</b>
7846 **
7847 ** Assuming that after registering for an unlock-notify callback a
7848 ** database waits for the callback to be issued before taking any further
7849 ** action (a reasonable assumption), then using this API may cause the
7850 ** application to deadlock. For example, if connection X is waiting for
7851 ** connection Y's transaction to be concluded, and similarly connection
7852 ** Y is waiting on connection X's transaction, then neither connection
7853 ** will proceed and the system may remain deadlocked indefinitely.
7854 **
7855 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7856 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7857 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7858 ** unlock-notify callback is registered. The system is said to be in
7859 ** a deadlocked state if connection A has registered for an unlock-notify
7860 ** callback on the conclusion of connection B's transaction, and connection
7861 ** B has itself registered for an unlock-notify callback when connection
7862 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7863 ** the system is also considered to be deadlocked if connection B has
7864 ** registered for an unlock-notify callback on the conclusion of connection
7865 ** C's transaction, where connection C is waiting on connection A. ^Any
7866 ** number of levels of indirection are allowed.
7867 **
7868 ** <b>The "DROP TABLE" Exception</b>
7869 **
7870 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7871 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7872 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7873 ** SQLite checks if there are any currently executing SELECT statements
7874 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7875 ** returned. In this case there is no "blocking connection", so invoking
7876 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7877 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7878 ** or "DROP INDEX" query, an infinite loop might be the result.
7879 **
7880 ** One way around this problem is to check the extended error code returned
7881 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7882 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7883 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7884 ** SQLITE_LOCKED.)^
7885 */
7887  sqlite3 *pBlocked, /* Waiting connection */
7888  void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7889  void *pNotifyArg /* Argument to pass to xNotify */
7890 );
7891 
7892 
7893 /*
7894 ** CAPI3REF: String Comparison
7895 **
7896 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7897 ** and extensions to compare the contents of two buffers containing UTF-8
7898 ** strings in a case-independent fashion, using the same definition of "case
7899 ** independence" that SQLite uses internally when comparing identifiers.
7900 */
7901 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7902 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7903 
7904 /*
7905 ** CAPI3REF: String Globbing
7906 *
7907 ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
7908 ** string X matches the [GLOB] pattern P.
7909 ** ^The definition of [GLOB] pattern matching used in
7910 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7911 ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
7912 ** is case sensitive.
7913 **
7914 ** Note that this routine returns zero on a match and non-zero if the strings
7915 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7916 **
7917 ** See also: [sqlite3_strlike()].
7918 */
7919 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7920 
7921 /*
7922 ** CAPI3REF: String LIKE Matching
7923 *
7924 ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
7925 ** string X matches the [LIKE] pattern P with escape character E.
7926 ** ^The definition of [LIKE] pattern matching used in
7927 ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
7928 ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
7929 ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
7930 ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
7931 ** insensitive - equivalent upper and lower case ASCII characters match
7932 ** one another.
7933 **
7934 ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
7935 ** only ASCII characters are case folded.
7936 **
7937 ** Note that this routine returns zero on a match and non-zero if the strings
7938 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7939 **
7940 ** See also: [sqlite3_strglob()].
7941 */
7942 SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
7943 
7944 /*
7945 ** CAPI3REF: Error Logging Interface
7946 **
7947 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7948 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7949 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7950 ** used with [sqlite3_snprintf()] to generate the final output string.
7951 **
7952 ** The sqlite3_log() interface is intended for use by extensions such as
7953 ** virtual tables, collating functions, and SQL functions. While there is
7954 ** nothing to prevent an application from calling sqlite3_log(), doing so
7955 ** is considered bad form.
7956 **
7957 ** The zFormat string must not be NULL.
7958 **
7959 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7960 ** will not use dynamically allocated memory. The log message is stored in
7961 ** a fixed-length buffer on the stack. If the log message is longer than
7962 ** a few hundred characters, it will be truncated to the length of the
7963 ** buffer.
7964 */
7965 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7966 
7967 /*
7968 ** CAPI3REF: Write-Ahead Log Commit Hook
7969 ** METHOD: sqlite3
7970 **
7971 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7972 ** is invoked each time data is committed to a database in wal mode.
7973 **
7974 ** ^(The callback is invoked by SQLite after the commit has taken place and
7975 ** the associated write-lock on the database released)^, so the implementation
7976 ** may read, write or [checkpoint] the database as required.
7977 **
7978 ** ^The first parameter passed to the callback function when it is invoked
7979 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7980 ** registering the callback. ^The second is a copy of the database handle.
7981 ** ^The third parameter is the name of the database that was written to -
7982 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7983 ** is the number of pages currently in the write-ahead log file,
7984 ** including those that were just committed.
7985 **
7986 ** The callback function should normally return [SQLITE_OK]. ^If an error
7987 ** code is returned, that error will propagate back up through the
7988 ** SQLite code base to cause the statement that provoked the callback
7989 ** to report an error, though the commit will have still occurred. If the
7990 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7991 ** that does not correspond to any valid SQLite error code, the results
7992 ** are undefined.
7993 **
7994 ** A single database handle may have at most a single write-ahead log callback
7995 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7996 ** previously registered write-ahead log callback. ^Note that the
7997 ** [sqlite3_wal_autocheckpoint()] interface and the
7998 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7999 ** overwrite any prior [sqlite3_wal_hook()] settings.
8000 */
8002  sqlite3*,
8003  int(*)(void *,sqlite3*,const char*,int),
8004  void*
8005 );
8006 
8007 /*
8008 ** CAPI3REF: Configure an auto-checkpoint
8009 ** METHOD: sqlite3
8010 **
8011 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
8012 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
8013 ** to automatically [checkpoint]
8014 ** after committing a transaction if there are N or
8015 ** more frames in the [write-ahead log] file. ^Passing zero or
8016 ** a negative value as the nFrame parameter disables automatic
8017 ** checkpoints entirely.
8018 **
8019 ** ^The callback registered by this function replaces any existing callback
8020 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
8021 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
8022 ** configured by this function.
8023 **
8024 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
8025 ** from SQL.
8026 **
8027 ** ^Checkpoints initiated by this mechanism are
8028 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
8029 **
8030 ** ^Every new [database connection] defaults to having the auto-checkpoint
8031 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
8032 ** pages. The use of this interface
8033 ** is only necessary if the default setting is found to be suboptimal
8034 ** for a particular application.
8035 */
8037 
8038 /*
8039 ** CAPI3REF: Checkpoint a database
8040 ** METHOD: sqlite3
8041 **
8042 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
8043 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
8044 **
8045 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
8046 ** [write-ahead log] for database X on [database connection] D to be
8047 ** transferred into the database file and for the write-ahead log to
8048 ** be reset. See the [checkpointing] documentation for addition
8049 ** information.
8050 **
8051 ** This interface used to be the only way to cause a checkpoint to
8052 ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
8053 ** interface was added. This interface is retained for backwards
8054 ** compatibility and as a convenience for applications that need to manually
8055 ** start a callback but which do not need the full power (and corresponding
8056 ** complication) of [sqlite3_wal_checkpoint_v2()].
8057 */
8058 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
8059 
8060 /*
8061 ** CAPI3REF: Checkpoint a database
8062 ** METHOD: sqlite3
8063 **
8064 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
8065 ** operation on database X of [database connection] D in mode M. Status
8066 ** information is written back into integers pointed to by L and C.)^
8067 ** ^(The M parameter must be a valid [checkpoint mode]:)^
8068 **
8069 ** <dl>
8070 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
8071 ** ^Checkpoint as many frames as possible without waiting for any database
8072 ** readers or writers to finish, then sync the database file if all frames
8073 ** in the log were checkpointed. ^The [busy-handler callback]
8074 ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
8075 ** ^On the other hand, passive mode might leave the checkpoint unfinished
8076 ** if there are concurrent readers or writers.
8077 **
8078 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
8079 ** ^This mode blocks (it invokes the
8080 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
8081 ** database writer and all readers are reading from the most recent database
8082 ** snapshot. ^It then checkpoints all frames in the log file and syncs the
8083 ** database file. ^This mode blocks new database writers while it is pending,
8084 ** but new database readers are allowed to continue unimpeded.
8085 **
8086 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
8087 ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
8088 ** that after checkpointing the log file it blocks (calls the
8089 ** [busy-handler callback])
8090 ** until all readers are reading from the database file only. ^This ensures
8091 ** that the next writer will restart the log file from the beginning.
8092 ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
8093 ** database writer attempts while it is pending, but does not impede readers.
8094 **
8095 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
8096 ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
8097 ** addition that it also truncates the log file to zero bytes just prior
8098 ** to a successful return.
8099 ** </dl>
8100 **
8101 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
8102 ** the log file or to -1 if the checkpoint could not run because
8103 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
8104 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
8105 ** log file (including any that were already checkpointed before the function
8106 ** was called) or to -1 if the checkpoint could not run due to an error or
8107 ** because the database is not in WAL mode. ^Note that upon successful
8108 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
8109 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
8110 **
8111 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
8112 ** any other process is running a checkpoint operation at the same time, the
8113 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
8114 ** busy-handler configured, it will not be invoked in this case.
8115 **
8116 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
8117 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
8118 ** obtained immediately, and a busy-handler is configured, it is invoked and
8119 ** the writer lock retried until either the busy-handler returns 0 or the lock
8120 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
8121 ** database readers as described above. ^If the busy-handler returns 0 before
8122 ** the writer lock is obtained or while waiting for database readers, the
8123 ** checkpoint operation proceeds from that point in the same way as
8124 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
8125 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
8126 **
8127 ** ^If parameter zDb is NULL or points to a zero length string, then the
8128 ** specified operation is attempted on all WAL databases [attached] to
8129 ** [database connection] db. In this case the
8130 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
8131 ** an SQLITE_BUSY error is encountered when processing one or more of the
8132 ** attached WAL databases, the operation is still attempted on any remaining
8133 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
8134 ** error occurs while processing an attached database, processing is abandoned
8135 ** and the error code is returned to the caller immediately. ^If no error
8136 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
8137 ** databases, SQLITE_OK is returned.
8138 **
8139 ** ^If database zDb is the name of an attached database that is not in WAL
8140 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
8141 ** zDb is not NULL (or a zero length string) and is not the name of any
8142 ** attached database, SQLITE_ERROR is returned to the caller.
8143 **
8144 ** ^Unless it returns SQLITE_MISUSE,
8145 ** the sqlite3_wal_checkpoint_v2() interface
8146 ** sets the error information that is queried by
8147 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
8148 **
8149 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
8150 ** from SQL.
8151 */
8153  sqlite3 *db, /* Database handle */
8154  const char *zDb, /* Name of attached database (or NULL) */
8155  int eMode, /* SQLITE_CHECKPOINT_* value */
8156  int *pnLog, /* OUT: Size of WAL log in frames */
8157  int *pnCkpt /* OUT: Total number of frames checkpointed */
8158 );
8159 
8160 /*
8161 ** CAPI3REF: Checkpoint Mode Values
8162 ** KEYWORDS: {checkpoint mode}
8163 **
8164 ** These constants define all valid values for the "checkpoint mode" passed
8165 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
8166 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
8167 ** meaning of each of these checkpoint modes.
8168 */
8169 #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
8170 #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
8171 #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
8172 #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
8173 
8174 /*
8175 ** CAPI3REF: Virtual Table Interface Configuration
8176 **
8177 ** This function may be called by either the [xConnect] or [xCreate] method
8178 ** of a [virtual table] implementation to configure
8179 ** various facets of the virtual table interface.
8180 **
8181 ** If this interface is invoked outside the context of an xConnect or
8182 ** xCreate virtual table method then the behavior is undefined.
8183 **
8184 ** At present, there is only one option that may be configured using
8185 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
8186 ** may be added in the future.
8187 */
8188 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
8189 
8190 /*
8191 ** CAPI3REF: Virtual Table Configuration Options
8192 **
8193 ** These macros define the various options to the
8194 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
8195 ** can use to customize and optimize their behavior.
8196 **
8197 ** <dl>
8198 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
8199 ** <dd>Calls of the form
8200 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
8201 ** where X is an integer. If X is zero, then the [virtual table] whose
8202 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
8203 ** support constraints. In this configuration (which is the default) if
8204 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
8205 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
8206 ** specified as part of the users SQL statement, regardless of the actual
8207 ** ON CONFLICT mode specified.
8208 **
8209 ** If X is non-zero, then the virtual table implementation guarantees
8210 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
8211 ** any modifications to internal or persistent data structures have been made.
8212 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
8213 ** is able to roll back a statement or database transaction, and abandon
8214 ** or continue processing the current SQL statement as appropriate.
8215 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
8216 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
8217 ** had been ABORT.
8218 **
8219 ** Virtual table implementations that are required to handle OR REPLACE
8220 ** must do so within the [xUpdate] method. If a call to the
8221 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
8222 ** CONFLICT policy is REPLACE, the virtual table implementation should
8223 ** silently replace the appropriate rows within the xUpdate callback and
8224 ** return SQLITE_OK. Or, if this is not possible, it may return
8225 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
8226 ** constraint handling.
8227 ** </dl>
8228 */
8229 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
8230 
8231 /*
8232 ** CAPI3REF: Determine The Virtual Table Conflict Policy
8233 **
8234 ** This function may only be called from within a call to the [xUpdate] method
8235 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
8236 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
8237 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
8238 ** of the SQL statement that triggered the call to the [xUpdate] method of the
8239 ** [virtual table].
8240 */
8242 
8243 /*
8244 ** CAPI3REF: Conflict resolution modes
8245 ** KEYWORDS: {conflict resolution mode}
8246 **
8247 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
8248 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
8249 ** is for the SQL statement being evaluated.
8250 **
8251 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
8252 ** return value from the [sqlite3_set_authorizer()] callback and that
8253 ** [SQLITE_ABORT] is also a [result code].
8254 */
8255 #define SQLITE_ROLLBACK 1
8256 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
8257 #define SQLITE_FAIL 3
8258 /* #define SQLITE_ABORT 4 // Also an error code */
8259 #define SQLITE_REPLACE 5
8260 
8261 /*
8262 ** CAPI3REF: Prepared Statement Scan Status Opcodes
8263 ** KEYWORDS: {scanstatus options}
8264 **
8265 ** The following constants can be used for the T parameter to the
8266 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
8267 ** different metric for sqlite3_stmt_scanstatus() to return.
8268 **
8269 ** When the value returned to V is a string, space to hold that string is
8270 ** managed by the prepared statement S and will be automatically freed when
8271 ** S is finalized.
8272 **
8273 ** <dl>
8274 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
8275 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
8276 ** set to the total number of times that the X-th loop has run.</dd>
8277 **
8278 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
8279 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
8280 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
8281 **
8282 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
8283 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
8284 ** query planner's estimate for the average number of rows output from each
8285 ** iteration of the X-th loop. If the query planner's estimates was accurate,
8286 ** then this value will approximate the quotient NVISIT/NLOOP and the
8287 ** product of this value for all prior loops with the same SELECTID will
8288 ** be the NLOOP value for the current loop.
8289 **
8290 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
8291 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8292 ** to a zero-terminated UTF-8 string containing the name of the index or table
8293 ** used for the X-th loop.
8294 **
8295 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
8296 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8297 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
8298 ** description for the X-th loop.
8299 **
8300 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
8301 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
8302 ** "select-id" for the X-th loop. The select-id identifies which query or
8303 ** subquery the loop is part of. The main query has a select-id of zero.
8304 ** The select-id is the same value as is output in the first column
8305 ** of an [EXPLAIN QUERY PLAN] query.
8306 ** </dl>
8307 */
8308 #define SQLITE_SCANSTAT_NLOOP 0
8309 #define SQLITE_SCANSTAT_NVISIT 1
8310 #define SQLITE_SCANSTAT_EST 2
8311 #define SQLITE_SCANSTAT_NAME 3
8312 #define SQLITE_SCANSTAT_EXPLAIN 4
8313 #define SQLITE_SCANSTAT_SELECTID 5
8314 
8315 /*
8316 ** CAPI3REF: Prepared Statement Scan Status
8317 ** METHOD: sqlite3_stmt
8318 **
8319 ** This interface returns information about the predicted and measured
8320 ** performance for pStmt. Advanced applications can use this
8321 ** interface to compare the predicted and the measured performance and
8322 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
8323 **
8324 ** Since this interface is expected to be rarely used, it is only
8325 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
8326 ** compile-time option.
8327 **
8328 ** The "iScanStatusOp" parameter determines which status information to return.
8329 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
8330 ** of this interface is undefined.
8331 ** ^The requested measurement is written into a variable pointed to by
8332 ** the "pOut" parameter.
8333 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
8334 ** Loops are numbered starting from zero. ^If idx is out of range - less than
8335 ** zero or greater than or equal to the total number of loops used to implement
8336 ** the statement - a non-zero value is returned and the variable that pOut
8337 ** points to is unchanged.
8338 **
8339 ** ^Statistics might not be available for all loops in all statements. ^In cases
8340 ** where there exist loops with no available statistics, this function behaves
8341 ** as if the loop did not exist - it returns non-zero and leave the variable
8342 ** that pOut points to unchanged.
8343 **
8344 ** See also: [sqlite3_stmt_scanstatus_reset()]
8345 */
8347  sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
8348  int idx, /* Index of loop to report on */
8349  int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
8350  void *pOut /* Result written here */
8351 );
8352 
8353 /*
8354 ** CAPI3REF: Zero Scan-Status Counters
8355 ** METHOD: sqlite3_stmt
8356 **
8357 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8358 **
8359 ** This API is only available if the library is built with pre-processor
8360 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8361 */
8363 
8364 /*
8365 ** CAPI3REF: Flush caches to disk mid-transaction
8366 **
8367 ** ^If a write-transaction is open on [database connection] D when the
8368 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
8369 ** pages in the pager-cache that are not currently in use are written out
8370 ** to disk. A dirty page may be in use if a database cursor created by an
8371 ** active SQL statement is reading from it, or if it is page 1 of a database
8372 ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
8373 ** interface flushes caches for all schemas - "main", "temp", and
8374 ** any [attached] databases.
8375 **
8376 ** ^If this function needs to obtain extra database locks before dirty pages
8377 ** can be flushed to disk, it does so. ^If those locks cannot be obtained
8378 ** immediately and there is a busy-handler callback configured, it is invoked
8379 ** in the usual manner. ^If the required lock still cannot be obtained, then
8380 ** the database is skipped and an attempt made to flush any dirty pages
8381 ** belonging to the next (if any) database. ^If any databases are skipped
8382 ** because locks cannot be obtained, but no other error occurs, this
8383 ** function returns SQLITE_BUSY.
8384 **
8385 ** ^If any other error occurs while flushing dirty pages to disk (for
8386 ** example an IO error or out-of-memory condition), then processing is
8387 ** abandoned and an SQLite [error code] is returned to the caller immediately.
8388 **
8389 ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
8390 **
8391 ** ^This function does not set the database handle error code or message
8392 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8393 */
8395 
8396 /*
8397 ** CAPI3REF: The pre-update hook.
8398 **
8399 ** ^These interfaces are only available if SQLite is compiled using the
8400 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8401 **
8402 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8403 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8404 ** on a [rowid table].
8405 ** ^At most one preupdate hook may be registered at a time on a single
8406 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8407 ** the previous setting.
8408 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8409 ** with a NULL pointer as the second parameter.
8410 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8411 ** the first parameter to callbacks.
8412 **
8413 ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
8414 ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
8415 ** tables.
8416 **
8417 ** ^The second parameter to the preupdate callback is a pointer to
8418 ** the [database connection] that registered the preupdate hook.
8419 ** ^The third parameter to the preupdate callback is one of the constants
8420 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
8421 ** kind of update operation that is about to occur.
8422 ** ^(The fourth parameter to the preupdate callback is the name of the
8423 ** database within the database connection that is being modified. This
8424 ** will be "main" for the main database or "temp" for TEMP tables or
8425 ** the name given after the AS keyword in the [ATTACH] statement for attached
8426 ** databases.)^
8427 ** ^The fifth parameter to the preupdate callback is the name of the
8428 ** table that is being modified.
8429 ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
8430 ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
8431 ** undefined for SQLITE_INSERT changes.
8432 ** ^The seventh parameter to the preupdate callback is the final [rowid] of
8433 ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
8434 ** undefined for SQLITE_DELETE changes.
8435 **
8436 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8437 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8438 ** provide additional information about a preupdate event. These routines
8439 ** may only be called from within a preupdate callback. Invoking any of
8440 ** these routines from outside of a preupdate callback or with a
8441 ** [database connection] pointer that is different from the one supplied
8442 ** to the preupdate callback results in undefined and probably undesirable
8443 ** behavior.
8444 **
8445 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8446 ** in the row that is being inserted, updated, or deleted.
8447 **
8448 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8449 ** a [protected sqlite3_value] that contains the value of the Nth column of
8450 ** the table row before it is updated. The N parameter must be between 0
8451 ** and one less than the number of columns or the behavior will be
8452 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8453 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8454 ** behavior is undefined. The [sqlite3_value] that P points to
8455 ** will be destroyed when the preupdate callback returns.
8456 **
8457 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8458 ** a [protected sqlite3_value] that contains the value of the Nth column of
8459 ** the table row after it is updated. The N parameter must be between 0
8460 ** and one less than the number of columns or the behavior will be
8461 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8462 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8463 ** behavior is undefined. The [sqlite3_value] that P points to
8464 ** will be destroyed when the preupdate callback returns.
8465 **
8466 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8467 ** callback was invoked as a result of a direct insert, update, or delete
8468 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
8469 ** triggers; or 2 for changes resulting from triggers called by top-level
8470 ** triggers; and so forth.
8471 **
8472 ** See also: [sqlite3_update_hook()]
8473 */
8475  sqlite3 *db,
8476  void(*xPreUpdate)(
8477  void *pCtx, /* Copy of third arg to preupdate_hook() */
8478  sqlite3 *db, /* Database handle */
8479  int op, /* SQLITE_UPDATE, DELETE or INSERT */
8480  char const *zDb, /* Database name */
8481  char const *zName, /* Table name */
8482  sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8483  sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8484  ),
8485  void*
8486 );
8491 
8492 /*
8493 ** CAPI3REF: Low-level system error code
8494 **
8495 ** ^Attempt to return the underlying operating system error code or error
8496 ** number that caused the most recent I/O error or failure to open a file.
8497 ** The return value is OS-dependent. For example, on unix systems, after
8498 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8499 ** called to get back the underlying "errno" that caused the problem, such
8500 ** as ENOSPC, EAUTH, EISDIR, and so forth.
8501 */
8503 
8504 /*
8505 ** CAPI3REF: Database Snapshot
8506 ** KEYWORDS: {snapshot}
8507 ** EXPERIMENTAL
8508 **
8509 ** An instance of the snapshot object records the state of a [WAL mode]
8510 ** database for some specific point in history.
8511 **
8512 ** In [WAL mode], multiple [database connections] that are open on the
8513 ** same database file can each be reading a different historical version
8514 ** of the database file. When a [database connection] begins a read
8515 ** transaction, that connection sees an unchanging copy of the database
8516 ** as it existed for the point in time when the transaction first started.
8517 ** Subsequent changes to the database from other connections are not seen
8518 ** by the reader until a new read transaction is started.
8519 **
8520 ** The sqlite3_snapshot object records state information about an historical
8521 ** version of the database file so that it is possible to later open a new read
8522 ** transaction that sees that historical version of the database rather than
8523 ** the most recent version.
8524 **
8525 ** The constructor for this object is [sqlite3_snapshot_get()]. The
8526 ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
8527 ** to an historical snapshot (if possible). The destructor for
8528 ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
8529 */
8531 
8532 /*
8533 ** CAPI3REF: Record A Database Snapshot
8534 ** EXPERIMENTAL
8535 **
8536 ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
8537 ** new [sqlite3_snapshot] object that records the current state of
8538 ** schema S in database connection D. ^On success, the
8539 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
8540 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
8541 ** ^If schema S of [database connection] D is not a [WAL mode] database
8542 ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
8543 ** leaves the *P value unchanged and returns an appropriate [error code].
8544 **
8545 ** The [sqlite3_snapshot] object returned from a successful call to
8546 ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
8547 ** to avoid a memory leak.
8548 **
8549 ** The [sqlite3_snapshot_get()] interface is only available when the
8550 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8551 */
8553  sqlite3 *db,
8554  const char *zSchema,
8555  sqlite3_snapshot **ppSnapshot
8556 );
8557 
8558 /*
8559 ** CAPI3REF: Start a read transaction on an historical snapshot
8560 ** EXPERIMENTAL
8561 **
8562 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8563 ** read transaction for schema S of
8564 ** [database connection] D such that the read transaction
8565 ** refers to historical [snapshot] P, rather than the most
8566 ** recent change to the database.
8567 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8568 ** or an appropriate [error code] if it fails.
8569 **
8570 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8571 ** the first operation following the [BEGIN] that takes the schema S
8572 ** out of [autocommit mode].
8573 ** ^In other words, schema S must not currently be in
8574 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8575 ** database connection D must be out of [autocommit mode].
8576 ** ^A [snapshot] will fail to open if it has been overwritten by a
8577 ** [checkpoint].
8578 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8579 ** database connection D does not know that the database file for
8580 ** schema S is in [WAL mode]. A database connection might not know
8581 ** that the database file is in [WAL mode] if there has been no prior
8582 ** I/O on that database connection, or if the database entered [WAL mode]
8583 ** after the most recent I/O on the database connection.)^
8584 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
8585 ** database connection in order to make it ready to use snapshots.)
8586 **
8587 ** The [sqlite3_snapshot_open()] interface is only available when the
8588 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8589 */
8591  sqlite3 *db,
8592  const char *zSchema,
8593  sqlite3_snapshot *pSnapshot
8594 );
8595 
8596 /*
8597 ** CAPI3REF: Destroy a snapshot
8598 ** EXPERIMENTAL
8599 **
8600 ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
8601 ** The application must eventually free every [sqlite3_snapshot] object
8602 ** using this routine to avoid a memory leak.
8603 **
8604 ** The [sqlite3_snapshot_free()] interface is only available when the
8605 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8606 */
8608 
8609 /*
8610 ** CAPI3REF: Compare the ages of two snapshot handles.
8611 ** EXPERIMENTAL
8612 **
8613 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8614 ** of two valid snapshot handles.
8615 **
8616 ** If the two snapshot handles are not associated with the same database
8617 ** file, the result of the comparison is undefined.
8618 **
8619 ** Additionally, the result of the comparison is only valid if both of the
8620 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8621 ** last time the wal file was deleted. The wal file is deleted when the
8622 ** database is changed back to rollback mode or when the number of database
8623 ** clients drops to zero. If either snapshot handle was obtained before the
8624 ** wal file was last deleted, the value returned by this function
8625 ** is undefined.
8626 **
8627 ** Otherwise, this API returns a negative value if P1 refers to an older
8628 ** snapshot than P2, zero if the two handles refer to the same database
8629 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
8630 */
8632  sqlite3_snapshot *p1,
8633  sqlite3_snapshot *p2
8634 );
8635 
8636 /*
8637 ** Undo the hack that converts floating point types to integer for
8638 ** builds on processors without floating point support.
8639 */
8640 #ifdef SQLITE_OMIT_FLOATING_POINT
8641 # undef double
8642 #endif
8643 
8644 #if 0
8645 } /* End of the 'extern "C"' block */
8646 #endif
8647 #endif /* SQLITE3_H */
8648 
8649 /******** Begin file sqlite3rtree.h *********/
8650 /*
8651 ** 2010 August 30
8652 **
8653 ** The author disclaims copyright to this source code. In place of
8654 ** a legal notice, here is a blessing:
8655 **
8656 ** May you do good and not evil.
8657 ** May you find forgiveness for yourself and forgive others.
8658 ** May you share freely, never taking more than you give.
8659 **
8660 *************************************************************************
8661 */
8662 
8663 #ifndef _SQLITE3RTREE_H_
8664 #define _SQLITE3RTREE_H_
8665 
8666 
8667 #if 0
8668 extern "C" {
8669 #endif
8670 
8673 
8674 /* The double-precision datatype used by RTree depends on the
8675 ** SQLITE_RTREE_INT_ONLY compile-time option.
8676 */
8677 #ifdef SQLITE_RTREE_INT_ONLY
8678  typedef sqlite3_int64 sqlite3_rtree_dbl;
8679 #else
8680  typedef double sqlite3_rtree_dbl;
8681 #endif
8682 
8683 /*
8684 ** Register a geometry callback named zGeom that can be used as part of an
8685 ** R-Tree geometry query as follows:
8686 **
8687 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8688 */
8690  sqlite3 *db,
8691  const char *zGeom,
8692  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8693  void *pContext
8694 );
8695 
8696 
8697 /*
8698 ** A pointer to a structure of the following type is passed as the first
8699 ** argument to callbacks registered using rtree_geometry_callback().
8700 */
8702  void *pContext; /* Copy of pContext passed to s_r_g_c() */
8703  int nParam; /* Size of array aParam[] */
8704  sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
8705  void *pUser; /* Callback implementation user data */
8706  void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
8707 };
8708 
8709 /*
8710 ** Register a 2nd-generation geometry callback named zScore that can be
8711 ** used as part of an R-Tree geometry query as follows:
8712 **
8713 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8714 */
8716  sqlite3 *db,
8717  const char *zQueryFunc,
8718  int (*xQueryFunc)(sqlite3_rtree_query_info*),
8719  void *pContext,
8720  void (*xDestructor)(void*)
8721 );
8722 
8723 
8724 /*
8725 ** A pointer to a structure of the following type is passed as the
8726 ** argument to scored geometry callback registered using
8727 ** sqlite3_rtree_query_callback().
8728 **
8729 ** Note that the first 5 fields of this structure are identical to
8730 ** sqlite3_rtree_geometry. This structure is a subclass of
8731 ** sqlite3_rtree_geometry.
8732 */
8734  void *pContext; /* pContext from when function registered */
8735  int nParam; /* Number of function parameters */
8736  sqlite3_rtree_dbl *aParam; /* value of function parameters */
8737  void *pUser; /* callback can use this, if desired */
8738  void (*xDelUser)(void*); /* function to free pUser */
8739  sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
8740  unsigned int *anQueue; /* Number of pending entries in the queue */
8741  int nCoord; /* Number of coordinates */
8742  int iLevel; /* Level of current node or entry */
8743  int mxLevel; /* The largest iLevel value in the tree */
8744  sqlite3_int64 iRowid; /* Rowid for current entry */
8745  sqlite3_rtree_dbl rParentScore; /* Score of parent node */
8746  int eParentWithin; /* Visibility of parent node */
8747  int eWithin; /* OUT: Visiblity */
8748  sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
8749  /* The following fields are only available in 3.8.11 and later */
8750  sqlite3_value **apSqlParam; /* Original SQL values of parameters */
8751 };
8752 
8753 /*
8754 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8755 */
8756 #define NOT_WITHIN 0 /* Object completely outside of query region */
8757 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
8758 #define FULLY_WITHIN 2 /* Object fully contained within query region */
8759 
8760 
8761 #if 0
8762 } /* end of the 'extern "C"' block */
8763 #endif
8764 
8765 #endif /* ifndef _SQLITE3RTREE_H_ */
8766 
8767 /******** End of sqlite3rtree.h *********/
8768 /******** Begin file sqlite3session.h *********/
8769 
8770 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8771 #define __SQLITESESSION_H_ 1
8772 
8773 /*
8774 ** Make sure we can call this stuff from C++.
8775 */
8776 #if 0
8777 extern "C" {
8778 #endif
8779 
8780 
8781 /*
8782 ** CAPI3REF: Session Object Handle
8783 */
8784 typedef struct sqlite3_session sqlite3_session;
8785 
8786 /*
8787 ** CAPI3REF: Changeset Iterator Handle
8788 */
8789 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8790 
8791 /*
8792 ** CAPI3REF: Create A New Session Object
8793 **
8794 ** Create a new session object attached to database handle db. If successful,
8795 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
8796 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8797 ** error code (e.g. SQLITE_NOMEM) is returned.
8798 **
8799 ** It is possible to create multiple session objects attached to a single
8800 ** database handle.
8801 **
8802 ** Session objects created using this function should be deleted using the
8803 ** [sqlite3session_delete()] function before the database handle that they
8804 ** are attached to is itself closed. If the database handle is closed before
8805 ** the session object is deleted, then the results of calling any session
8806 ** module function, including [sqlite3session_delete()] on the session object
8807 ** are undefined.
8808 **
8809 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8810 ** is not possible for an application to register a pre-update hook on a
8811 ** database handle that has one or more session objects attached. Nor is
8812 ** it possible to create a session object attached to a database handle for
8813 ** which a pre-update hook is already defined. The results of attempting
8814 ** either of these things are undefined.
8815 **
8816 ** The session object will be used to create changesets for tables in
8817 ** database zDb, where zDb is either "main", or "temp", or the name of an
8818 ** attached database. It is not an error if database zDb is not attached
8819 ** to the database when the session object is created.
8820 */
8821 int sqlite3session_create(
8822  sqlite3 *db, /* Database handle */
8823  const char *zDb, /* Name of db (e.g. "main") */
8824  sqlite3_session **ppSession /* OUT: New session object */
8825 );
8826 
8827 /*
8828 ** CAPI3REF: Delete A Session Object
8829 **
8830 ** Delete a session object previously allocated using
8831 ** [sqlite3session_create()]. Once a session object has been deleted, the
8832 ** results of attempting to use pSession with any other session module
8833 ** function are undefined.
8834 **
8835 ** Session objects must be deleted before the database handle to which they
8836 ** are attached is closed. Refer to the documentation for
8837 ** [sqlite3session_create()] for details.
8838 */
8839 void sqlite3session_delete(sqlite3_session *pSession);
8840 
8841 
8842 /*
8843 ** CAPI3REF: Enable Or Disable A Session Object
8844 **
8845 ** Enable or disable the recording of changes by a session object. When
8846 ** enabled, a session object records changes made to the database. When
8847 ** disabled - it does not. A newly created session object is enabled.
8848 ** Refer to the documentation for [sqlite3session_changeset()] for further
8849 ** details regarding how enabling and disabling a session object affects
8850 ** the eventual changesets.
8851 **
8852 ** Passing zero to this function disables the session. Passing a value
8853 ** greater than zero enables it. Passing a value less than zero is a
8854 ** no-op, and may be used to query the current state of the session.
8855 **
8856 ** The return value indicates the final state of the session object: 0 if
8857 ** the session is disabled, or 1 if it is enabled.
8858 */
8859 int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8860 
8861 /*
8862 ** CAPI3REF: Set Or Clear the Indirect Change Flag
8863 **
8864 ** Each change recorded by a session object is marked as either direct or
8865 ** indirect. A change is marked as indirect if either:
8866 **
8867 ** <ul>
8868 ** <li> The session object "indirect" flag is set when the change is
8869 ** made, or
8870 ** <li> The change is made by an SQL trigger or foreign key action
8871 ** instead of directly as a result of a users SQL statement.
8872 ** </ul>
8873 **
8874 ** If a single row is affected by more than one operation within a session,
8875 ** then the change is considered indirect if all operations meet the criteria
8876 ** for an indirect change above, or direct otherwise.
8877 **
8878 ** This function is used to set, clear or query the session object indirect
8879 ** flag. If the second argument passed to this function is zero, then the
8880 ** indirect flag is cleared. If it is greater than zero, the indirect flag
8881 ** is set. Passing a value less than zero does not modify the current value
8882 ** of the indirect flag, and may be used to query the current state of the
8883 ** indirect flag for the specified session object.
8884 **
8885 ** The return value indicates the final state of the indirect flag: 0 if
8886 ** it is clear, or 1 if it is set.
8887 */
8888 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8889 
8890 /*
8891 ** CAPI3REF: Attach A Table To A Session Object
8892 **
8893 ** If argument zTab is not NULL, then it is the name of a table to attach
8894 ** to the session object passed as the first argument. All subsequent changes
8895 ** made to the table while the session object is enabled will be recorded. See
8896 ** documentation for [sqlite3session_changeset()] for further details.
8897 **
8898 ** Or, if argument zTab is NULL, then changes are recorded for all tables
8899 ** in the database. If additional tables are added to the database (by
8900 ** executing "CREATE TABLE" statements) after this call is made, changes for
8901 ** the new tables are also recorded.
8902 **
8903 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8904 ** defined as part of their CREATE TABLE statement. It does not matter if the
8905 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8906 ** KEY may consist of a single column, or may be a composite key.
8907 **
8908 ** It is not an error if the named table does not exist in the database. Nor
8909 ** is it an error if the named table does not have a PRIMARY KEY. However,
8910 ** no changes will be recorded in either of these scenarios.
8911 **
8912 ** Changes are not recorded for individual rows that have NULL values stored
8913 ** in one or more of their PRIMARY KEY columns.
8914 **
8915 ** SQLITE_OK is returned if the call completes without error. Or, if an error
8916 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8917 */
8918 int sqlite3session_attach(
8919  sqlite3_session *pSession, /* Session object */
8920  const char *zTab /* Table name */
8921 );
8922 
8923 /*
8924 ** CAPI3REF: Set a table filter on a Session Object.
8925 **
8926 ** The second argument (xFilter) is the "filter callback". For changes to rows
8927 ** in tables that are not attached to the Session object, the filter is called
8928 ** to determine whether changes to the table's rows should be tracked or not.
8929 ** If xFilter returns 0, changes is not tracked. Note that once a table is
8930 ** attached, xFilter will not be called again.
8931 */
8932 void sqlite3session_table_filter(
8933  sqlite3_session *pSession, /* Session object */
8934  int(*xFilter)(
8935  void *pCtx, /* Copy of third arg to _filter_table() */
8936  const char *zTab /* Table name */
8937  ),
8938  void *pCtx /* First argument passed to xFilter */
8939 );
8940 
8941 /*
8942 ** CAPI3REF: Generate A Changeset From A Session Object
8943 **
8944 ** Obtain a changeset containing changes to the tables attached to the
8945 ** session object passed as the first argument. If successful,
8946 ** set *ppChangeset to point to a buffer containing the changeset
8947 ** and *pnChangeset to the size of the changeset in bytes before returning
8948 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8949 ** zero and return an SQLite error code.
8950 **
8951 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8952 ** each representing a change to a single row of an attached table. An INSERT
8953 ** change contains the values of each field of a new database row. A DELETE
8954 ** contains the original values of each field of a deleted database row. An
8955 ** UPDATE change contains the original values of each field of an updated
8956 ** database row along with the updated values for each updated non-primary-key
8957 ** column. It is not possible for an UPDATE change to represent a change that
8958 ** modifies the values of primary key columns. If such a change is made, it
8959 ** is represented in a changeset as a DELETE followed by an INSERT.
8960 **
8961 ** Changes are not recorded for rows that have NULL values stored in one or
8962 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8963 ** no corresponding change is present in the changesets returned by this
8964 ** function. If an existing row with one or more NULL values stored in
8965 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8966 ** only an INSERT is appears in the changeset. Similarly, if an existing row
8967 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
8968 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8969 ** DELETE change only.
8970 **
8971 ** The contents of a changeset may be traversed using an iterator created
8972 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
8973 ** a database with a compatible schema using the [sqlite3changeset_apply()]
8974 ** API.
8975 **
8976 ** Within a changeset generated by this function, all changes related to a
8977 ** single table are grouped together. In other words, when iterating through
8978 ** a changeset or when applying a changeset to a database, all changes related
8979 ** to a single table are processed before moving on to the next table. Tables
8980 ** are sorted in the same order in which they were attached (or auto-attached)
8981 ** to the sqlite3_session object. The order in which the changes related to
8982 ** a single table are stored is undefined.
8983 **
8984 ** Following a successful call to this function, it is the responsibility of
8985 ** the caller to eventually free the buffer that *ppChangeset points to using
8986 ** [sqlite3_free()].
8987 **
8988 ** <h3>Changeset Generation</h3>
8989 **
8990 ** Once a table has been attached to a session object, the session object
8991 ** records the primary key values of all new rows inserted into the table.
8992 ** It also records the original primary key and other column values of any
8993 ** deleted or updated rows. For each unique primary key value, data is only
8994 ** recorded once - the first time a row with said primary key is inserted,
8995 ** updated or deleted in the lifetime of the session.
8996 **
8997 ** There is one exception to the previous paragraph: when a row is inserted,
8998 ** updated or deleted, if one or more of its primary key columns contain a
8999 ** NULL value, no record of the change is made.
9000 **
9001 ** The session object therefore accumulates two types of records - those
9002 ** that consist of primary key values only (created when the user inserts
9003 ** a new record) and those that consist of the primary key values and the
9004 ** original values of other table columns (created when the users deletes
9005 ** or updates a record).
9006 **
9007 ** When this function is called, the requested changeset is created using
9008 ** both the accumulated records and the current contents of the database
9009 ** file. Specifically:
9010 **
9011 ** <ul>
9012 ** <li> For each record generated by an insert, the database is queried
9013 ** for a row with a matching primary key. If one is found, an INSERT
9014 ** change is added to the changeset. If no such row is found, no change
9015 ** is added to the changeset.
9016 **
9017 ** <li> For each record generated by an update or delete, the database is
9018 ** queried for a row with a matching primary key. If such a row is
9019 ** found and one or more of the non-primary key fields have been
9020 ** modified from their original values, an UPDATE change is added to
9021 ** the changeset. Or, if no such row is found in the table, a DELETE
9022 ** change is added to the changeset. If there is a row with a matching
9023 ** primary key in the database, but all fields contain their original
9024 ** values, no change is added to the changeset.
9025 ** </ul>
9026 **
9027 ** This means, amongst other things, that if a row is inserted and then later
9028 ** deleted while a session object is active, neither the insert nor the delete
9029 ** will be present in the changeset. Or if a row is deleted and then later a
9030 ** row with the same primary key values inserted while a session object is
9031 ** active, the resulting changeset will contain an UPDATE change instead of
9032 ** a DELETE and an INSERT.
9033 **
9034 ** When a session object is disabled (see the [sqlite3session_enable()] API),
9035 ** it does not accumulate records when rows are inserted, updated or deleted.
9036 ** This may appear to have some counter-intuitive effects if a single row
9037 ** is written to more than once during a session. For example, if a row
9038 ** is inserted while a session object is enabled, then later deleted while
9039 ** the same session object is disabled, no INSERT record will appear in the
9040 ** changeset, even though the delete took place while the session was disabled.
9041 ** Or, if one field of a row is updated while a session is disabled, and
9042 ** another field of the same row is updated while the session is enabled, the
9043 ** resulting changeset will contain an UPDATE change that updates both fields.
9044 */
9045 int sqlite3session_changeset(
9046  sqlite3_session *pSession, /* Session object */
9047  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
9048  void **ppChangeset /* OUT: Buffer containing changeset */
9049 );
9050 
9051 /*
9052 ** CAPI3REF: Load The Difference Between Tables Into A Session
9053 **
9054 ** If it is not already attached to the session object passed as the first
9055 ** argument, this function attaches table zTbl in the same manner as the
9056 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
9057 ** does not have a primary key, this function is a no-op (but does not return
9058 ** an error).
9059 **
9060 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
9061 ** attached to the same database handle as the session object that contains
9062 ** a table compatible with the table attached to the session by this function.
9063 ** A table is considered compatible if it:
9064 **
9065 ** <ul>
9066 ** <li> Has the same name,
9067 ** <li> Has the same set of columns declared in the same order, and
9068 ** <li> Has the same PRIMARY KEY definition.
9069 ** </ul>
9070 **
9071 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
9072 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
9073 ** but no changes are added to the session object. As with other session
9074 ** APIs, tables without PRIMARY KEYs are simply ignored.
9075 **
9076 ** This function adds a set of changes to the session object that could be
9077 ** used to update the table in database zFrom (call this the "from-table")
9078 ** so that its content is the same as the table attached to the session
9079 ** object (call this the "to-table"). Specifically:
9080 **
9081 ** <ul>
9082 ** <li> For each row (primary key) that exists in the to-table but not in
9083 ** the from-table, an INSERT record is added to the session object.
9084 **
9085 ** <li> For each row (primary key) that exists in the to-table but not in
9086 ** the from-table, a DELETE record is added to the session object.
9087 **
9088 ** <li> For each row (primary key) that exists in both tables, but features
9089 ** different in each, an UPDATE record is added to the session.
9090 ** </ul>
9091 **
9092 ** To clarify, if this function is called and then a changeset constructed
9093 ** using [sqlite3session_changeset()], then after applying that changeset to
9094 ** database zFrom the contents of the two compatible tables would be
9095 ** identical.
9096 **
9097 ** It an error if database zFrom does not exist or does not contain the
9098 ** required compatible table.
9099 **
9100 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
9101 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
9102 ** may be set to point to a buffer containing an English language error
9103 ** message. It is the responsibility of the caller to free this buffer using
9104 ** sqlite3_free().
9105 */
9106 int sqlite3session_diff(
9107  sqlite3_session *pSession,
9108  const char *zFromDb,
9109  const char *zTbl,
9110  char **pzErrMsg
9111 );
9112 
9113 
9114 /*
9115 ** CAPI3REF: Generate A Patchset From A Session Object
9116 **
9117 ** The differences between a patchset and a changeset are that:
9118 **
9119 ** <ul>
9120 ** <li> DELETE records consist of the primary key fields only. The
9121 ** original values of other fields are omitted.
9122 ** <li> The original values of any modified fields are omitted from
9123 ** UPDATE records.
9124 ** </ul>
9125 **
9126 ** A patchset blob may be used with up to date versions of all
9127 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
9128 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
9129 ** attempting to use a patchset blob with old versions of the
9130 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
9131 **
9132 ** Because the non-primary key "old.*" fields are omitted, no
9133 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
9134 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
9135 ** in the same way as for changesets.
9136 **
9137 ** Changes within a patchset are ordered in the same way as for changesets
9138 ** generated by the sqlite3session_changeset() function (i.e. all changes for
9139 ** a single table are grouped together, tables appear in the order in which
9140 ** they were attached to the session object).
9141 */
9142 int sqlite3session_patchset(
9143  sqlite3_session *pSession, /* Session object */
9144  int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
9145  void **ppPatchset /* OUT: Buffer containing changeset */
9146 );
9147 
9148 /*
9149 ** CAPI3REF: Test if a changeset has recorded any changes.
9150 **
9151 ** Return non-zero if no changes to attached tables have been recorded by
9152 ** the session object passed as the first argument. Otherwise, if one or
9153 ** more changes have been recorded, return zero.
9154 **
9155 ** Even if this function returns zero, it is possible that calling
9156 ** [sqlite3session_changeset()] on the session handle may still return a
9157 ** changeset that contains no changes. This can happen when a row in
9158 ** an attached table is modified and then later on the original values
9159 ** are restored. However, if this function returns non-zero, then it is
9160 ** guaranteed that a call to sqlite3session_changeset() will return a
9161 ** changeset containing zero changes.
9162 */
9163 int sqlite3session_isempty(sqlite3_session *pSession);
9164 
9165 /*
9166 ** CAPI3REF: Create An Iterator To Traverse A Changeset
9167 **
9168 ** Create an iterator used to iterate through the contents of a changeset.
9169 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
9170 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
9171 ** SQLite error code is returned.
9172 **
9173 ** The following functions can be used to advance and query a changeset
9174 ** iterator created by this function:
9175 **
9176 ** <ul>
9177 ** <li> [sqlite3changeset_next()]
9178 ** <li> [sqlite3changeset_op()]
9179 ** <li> [sqlite3changeset_new()]
9180 ** <li> [sqlite3changeset_old()]
9181 ** </ul>
9182 **
9183 ** It is the responsibility of the caller to eventually destroy the iterator
9184 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
9185 ** changeset (pChangeset) must remain valid until after the iterator is
9186 ** destroyed.
9187 **
9188 ** Assuming the changeset blob was created by one of the
9189 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9190 ** [sqlite3changeset_invert()] functions, all changes within the changeset
9191 ** that apply to a single table are grouped together. This means that when
9192 ** an application iterates through a changeset using an iterator created by
9193 ** this function, all changes that relate to a single table are visited
9194 ** consecutively. There is no chance that the iterator will visit a change
9195 ** the applies to table X, then one for table Y, and then later on visit
9196 ** another change for table X.
9197 */
9198 int sqlite3changeset_start(
9199  sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
9200  int nChangeset, /* Size of changeset blob in bytes */
9201  void *pChangeset /* Pointer to blob containing changeset */
9202 );
9203 
9204 
9205 /*
9206 ** CAPI3REF: Advance A Changeset Iterator
9207 **
9208 ** This function may only be used with iterators created by function
9209 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
9210 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9211 ** is returned and the call has no effect.
9212 **
9213 ** Immediately after an iterator is created by sqlite3changeset_start(), it
9214 ** does not point to any change in the changeset. Assuming the changeset
9215 ** is not empty, the first call to this function advances the iterator to
9216 ** point to the first change in the changeset. Each subsequent call advances
9217 ** the iterator to point to the next change in the changeset (if any). If
9218 ** no error occurs and the iterator points to a valid change after a call
9219 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9220 ** Otherwise, if all changes in the changeset have already been visited,
9221 ** SQLITE_DONE is returned.
9222 **
9223 ** If an error occurs, an SQLite error code is returned. Possible error
9224 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9225 ** SQLITE_NOMEM.
9226 */
9227 int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9228 
9229 /*
9230 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9231 **
9232 ** The pIter argument passed to this function may either be an iterator
9233 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9234 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9235 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9236 ** is not the case, this function returns [SQLITE_MISUSE].
9237 **
9238 ** If argument pzTab is not NULL, then *pzTab is set to point to a
9239 ** nul-terminated utf-8 encoded string containing the name of the table
9240 ** affected by the current change. The buffer remains valid until either
9241 ** sqlite3changeset_next() is called on the iterator or until the
9242 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9243 ** set to the number of columns in the table affected by the change. If
9244 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9245 ** is an indirect change, or false (0) otherwise. See the documentation for
9246 ** [sqlite3session_indirect()] for a description of direct and indirect
9247 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9248 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9249 ** type of change that the iterator currently points to.
9250 **
9251 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9252 ** SQLite error code is returned. The values of the output variables may not
9253 ** be trusted in this case.
9254 */
9255 int sqlite3changeset_op(
9256  sqlite3_changeset_iter *pIter, /* Iterator object */
9257  const char **pzTab, /* OUT: Pointer to table name */
9258  int *pnCol, /* OUT: Number of columns in table */
9259  int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9260  int *pbIndirect /* OUT: True for an 'indirect' change */
9261 );
9262 
9263 /*
9264 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
9265 **
9266 ** For each modified table, a changeset includes the following:
9267 **
9268 ** <ul>
9269 ** <li> The number of columns in the table, and
9270 ** <li> Which of those columns make up the tables PRIMARY KEY.
9271 ** </ul>
9272 **
9273 ** This function is used to find which columns comprise the PRIMARY KEY of
9274 ** the table modified by the change that iterator pIter currently points to.
9275 ** If successful, *pabPK is set to point to an array of nCol entries, where
9276 ** nCol is the number of columns in the table. Elements of *pabPK are set to
9277 ** 0x01 if the corresponding column is part of the tables primary key, or
9278 ** 0x00 if it is not.
9279 **
9280 ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
9281 ** in the table.
9282 **
9283 ** If this function is called when the iterator does not point to a valid
9284 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9285 ** SQLITE_OK is returned and the output variables populated as described
9286 ** above.
9287 */
9288 int sqlite3changeset_pk(
9289  sqlite3_changeset_iter *pIter, /* Iterator object */
9290  unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
9291  int *pnCol /* OUT: Number of entries in output array */
9292 );
9293 
9294 /*
9295 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9296 **
9297 ** The pIter argument passed to this function may either be an iterator
9298 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9299 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9300 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9301 ** Furthermore, it may only be called if the type of change that the iterator
9302 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9303 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9304 **
9305 ** Argument iVal must be greater than or equal to 0, and less than the number
9306 ** of columns in the table affected by the current change. Otherwise,
9307 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9308 **
9309 ** If successful, this function sets *ppValue to point to a protected
9310 ** sqlite3_value object containing the iVal'th value from the vector of
9311 ** original row values stored as part of the UPDATE or DELETE change and
9312 ** returns SQLITE_OK. The name of the function comes from the fact that this
9313 ** is similar to the "old.*" columns available to update or delete triggers.
9314 **
9315 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9316 ** is returned and *ppValue is set to NULL.
9317 */
9318 int sqlite3changeset_old(
9319  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9320  int iVal, /* Column number */
9321  sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
9322 );
9323 
9324 /*
9325 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9326 **
9327 ** The pIter argument passed to this function may either be an iterator
9328 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9329 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9330 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9331 ** Furthermore, it may only be called if the type of change that the iterator
9332 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9333 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9334 **
9335 ** Argument iVal must be greater than or equal to 0, and less than the number
9336 ** of columns in the table affected by the current change. Otherwise,
9337 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9338 **
9339 ** If successful, this function sets *ppValue to point to a protected
9340 ** sqlite3_value object containing the iVal'th value from the vector of
9341 ** new row values stored as part of the UPDATE or INSERT change and
9342 ** returns SQLITE_OK. If the change is an UPDATE and does not include
9343 ** a new value for the requested column, *ppValue is set to NULL and
9344 ** SQLITE_OK returned. The name of the function comes from the fact that
9345 ** this is similar to the "new.*" columns available to update or delete
9346 ** triggers.
9347 **
9348 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9349 ** is returned and *ppValue is set to NULL.
9350 */
9351 int sqlite3changeset_new(
9352  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9353  int iVal, /* Column number */
9354  sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
9355 );
9356 
9357 /*
9358 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9359 **
9360 ** This function should only be used with iterator objects passed to a
9361 ** conflict-handler callback by [sqlite3changeset_apply()] with either
9362 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9363 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9364 ** is set to NULL.
9365 **
9366 ** Argument iVal must be greater than or equal to 0, and less than the number
9367 ** of columns in the table affected by the current change. Otherwise,
9368 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9369 **
9370 ** If successful, this function sets *ppValue to point to a protected
9371 ** sqlite3_value object containing the iVal'th value from the
9372 ** "conflicting row" associated with the current conflict-handler callback
9373 ** and returns SQLITE_OK.
9374 **
9375 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9376 ** is returned and *ppValue is set to NULL.
9377 */
9378 int sqlite3changeset_conflict(
9379  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9380  int iVal, /* Column number */
9381  sqlite3_value **ppValue /* OUT: Value from conflicting row */
9382 );
9383 
9384 /*
9385 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9386 **
9387 ** This function may only be called with an iterator passed to an
9388 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9389 ** it sets the output variable to the total number of known foreign key
9390 ** violations in the destination database and returns SQLITE_OK.
9391 **
9392 ** In all other cases this function returns SQLITE_MISUSE.
9393 */
9394 int sqlite3changeset_fk_conflicts(
9395  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9396  int *pnOut /* OUT: Number of FK violations */
9397 );
9398 
9399 
9400 /*
9401 ** CAPI3REF: Finalize A Changeset Iterator
9402 **
9403 ** This function is used to finalize an iterator allocated with
9404 ** [sqlite3changeset_start()].
9405 **
9406 ** This function should only be called on iterators created using the
9407 ** [sqlite3changeset_start()] function. If an application calls this
9408 ** function with an iterator passed to a conflict-handler by
9409 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9410 ** call has no effect.
9411 **
9412 ** If an error was encountered within a call to an sqlite3changeset_xxx()
9413 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9414 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9415 ** to that error is returned by this function. Otherwise, SQLITE_OK is
9416 ** returned. This is to allow the following pattern (pseudo-code):
9417 **
9418 ** sqlite3changeset_start();
9419 ** while( SQLITE_ROW==sqlite3changeset_next() ){
9420 ** // Do something with change.
9421 ** }
9422 ** rc = sqlite3changeset_finalize();
9423 ** if( rc!=SQLITE_OK ){
9424 ** // An error has occurred
9425 ** }
9426 */
9427 int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9428 
9429 /*
9430 ** CAPI3REF: Invert A Changeset
9431 **
9432 ** This function is used to "invert" a changeset object. Applying an inverted
9433 ** changeset to a database reverses the effects of applying the uninverted
9434 ** changeset. Specifically:
9435 **
9436 ** <ul>
9437 ** <li> Each DELETE change is changed to an INSERT, and
9438 ** <li> Each INSERT change is changed to a DELETE, and
9439 ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9440 ** </ul>
9441 **
9442 ** This function does not change the order in which changes appear within
9443 ** the changeset. It merely reverses the sense of each individual change.
9444 **
9445 ** If successful, a pointer to a buffer containing the inverted changeset
9446 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9447 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9448 ** zeroed and an SQLite error code returned.
9449 **
9450 ** It is the responsibility of the caller to eventually call sqlite3_free()
9451 ** on the *ppOut pointer to free the buffer allocation following a successful
9452 ** call to this function.
9453 **
9454 ** WARNING/TODO: This function currently assumes that the input is a valid
9455 ** changeset. If it is not, the results are undefined.
9456 */
9457 int sqlite3changeset_invert(
9458  int nIn, const void *pIn, /* Input changeset */
9459  int *pnOut, void **ppOut /* OUT: Inverse of input */
9460 );
9461 
9462 /*
9463 ** CAPI3REF: Concatenate Two Changeset Objects
9464 **
9465 ** This function is used to concatenate two changesets, A and B, into a
9466 ** single changeset. The result is a changeset equivalent to applying
9467 ** changeset A followed by changeset B.
9468 **
9469 ** This function combines the two input changesets using an
9470 ** sqlite3_changegroup object. Calling it produces similar results as the
9471 ** following code fragment:
9472 **
9473 ** sqlite3_changegroup *pGrp;
9474 ** rc = sqlite3_changegroup_new(&pGrp);
9475 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9476 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9477 ** if( rc==SQLITE_OK ){
9478 ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9479 ** }else{
9480 ** *ppOut = 0;
9481 ** *pnOut = 0;
9482 ** }
9483 **
9484 ** Refer to the sqlite3_changegroup documentation below for details.
9485 */
9486 int sqlite3changeset_concat(
9487  int nA, /* Number of bytes in buffer pA */
9488  void *pA, /* Pointer to buffer containing changeset A */
9489  int nB, /* Number of bytes in buffer pB */
9490  void *pB, /* Pointer to buffer containing changeset B */
9491  int *pnOut, /* OUT: Number of bytes in output changeset */
9492  void **ppOut /* OUT: Buffer containing output changeset */
9493 );
9494 
9495 
9496 /*
9497 ** CAPI3REF: Changegroup Handle
9498 */
9499 typedef struct sqlite3_changegroup sqlite3_changegroup;
9500 
9501 /*
9502 ** CAPI3REF: Create A New Changegroup Object
9503 **
9504 ** An sqlite3_changegroup object is used to combine two or more changesets
9505 ** (or patchsets) into a single changeset (or patchset). A single changegroup
9506 ** object may combine changesets or patchsets, but not both. The output is
9507 ** always in the same format as the input.
9508 **
9509 ** If successful, this function returns SQLITE_OK and populates (*pp) with
9510 ** a pointer to a new sqlite3_changegroup object before returning. The caller
9511 ** should eventually free the returned object using a call to
9512 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9513 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9514 **
9515 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
9516 **
9517 ** <ul>
9518 ** <li> It is created using a call to sqlite3changegroup_new().
9519 **
9520 ** <li> Zero or more changesets (or patchsets) are added to the object
9521 ** by calling sqlite3changegroup_add().
9522 **
9523 ** <li> The result of combining all input changesets together is obtained
9524 ** by the application via a call to sqlite3changegroup_output().
9525 **
9526 ** <li> The object is deleted using a call to sqlite3changegroup_delete().
9527 ** </ul>
9528 **
9529 ** Any number of calls to add() and output() may be made between the calls to
9530 ** new() and delete(), and in any order.
9531 **
9532 ** As well as the regular sqlite3changegroup_add() and
9533 ** sqlite3changegroup_output() functions, also available are the streaming
9534 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9535 */
9536 int sqlite3changegroup_new(sqlite3_changegroup **pp);
9537 
9538 /*
9539 ** CAPI3REF: Add A Changeset To A Changegroup
9540 **
9541 ** Add all changes within the changeset (or patchset) in buffer pData (size
9542 ** nData bytes) to the changegroup.
9543 **
9544 ** If the buffer contains a patchset, then all prior calls to this function
9545 ** on the same changegroup object must also have specified patchsets. Or, if
9546 ** the buffer contains a changeset, so must have the earlier calls to this
9547 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9548 ** to the changegroup.
9549 **
9550 ** Rows within the changeset and changegroup are identified by the values in
9551 ** their PRIMARY KEY columns. A change in the changeset is considered to
9552 ** apply to the same row as a change already present in the changegroup if
9553 ** the two rows have the same primary key.
9554 **
9555 ** Changes to rows that do not already appear in the changegroup are
9556 ** simply copied into it. Or, if both the new changeset and the changegroup
9557 ** contain changes that apply to a single row, the final contents of the
9558 ** changegroup depends on the type of each change, as follows:
9559 **
9560 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9561 ** <tr><th style="white-space:pre">Existing Change </th>
9562 ** <th style="white-space:pre">New Change </th>
9563 ** <th>Output Change
9564 ** <tr><td>INSERT <td>INSERT <td>
9565 ** The new change is ignored. This case does not occur if the new
9566 ** changeset was recorded immediately after the changesets already
9567 ** added to the changegroup.
9568 ** <tr><td>INSERT <td>UPDATE <td>
9569 ** The INSERT change remains in the changegroup. The values in the
9570 ** INSERT change are modified as if the row was inserted by the
9571 ** existing change and then updated according to the new change.
9572 ** <tr><td>INSERT <td>DELETE <td>
9573 ** The existing INSERT is removed from the changegroup. The DELETE is
9574 ** not added.
9575 ** <tr><td>UPDATE <td>INSERT <td>
9576 ** The new change is ignored. This case does not occur if the new
9577 ** changeset was recorded immediately after the changesets already
9578 ** added to the changegroup.
9579 ** <tr><td>UPDATE <td>UPDATE <td>
9580 ** The existing UPDATE remains within the changegroup. It is amended
9581 ** so that the accompanying values are as if the row was updated once
9582 ** by the existing change and then again by the new change.
9583 ** <tr><td>UPDATE <td>DELETE <td>
9584 ** The existing UPDATE is replaced by the new DELETE within the
9585 ** changegroup.
9586 ** <tr><td>DELETE <td>INSERT <td>
9587 ** If one or more of the column values in the row inserted by the
9588 ** new change differ from those in the row deleted by the existing
9589 ** change, the existing DELETE is replaced by an UPDATE within the
9590 ** changegroup. Otherwise, if the inserted row is exactly the same
9591 ** as the deleted row, the existing DELETE is simply discarded.
9592 ** <tr><td>DELETE <td>UPDATE <td>
9593 ** The new change is ignored. This case does not occur if the new
9594 ** changeset was recorded immediately after the changesets already
9595 ** added to the changegroup.
9596 ** <tr><td>DELETE <td>DELETE <td>
9597 ** The new change is ignored. This case does not occur if the new
9598 ** changeset was recorded immediately after the changesets already
9599 ** added to the changegroup.
9600 ** </table>
9601 **
9602 ** If the new changeset contains changes to a table that is already present
9603 ** in the changegroup, then the number of columns and the position of the
9604 ** primary key columns for the table must be consistent. If this is not the
9605 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
9606 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9607 ** returned. Or, if an out-of-memory condition occurs during processing, this
9608 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9609 ** final contents of the changegroup is undefined.
9610 **
9611 ** If no error occurs, SQLITE_OK is returned.
9612 */
9613 int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9614 
9615 /*
9616 ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
9617 **
9618 ** Obtain a buffer containing a changeset (or patchset) representing the
9619 ** current contents of the changegroup. If the inputs to the changegroup
9620 ** were themselves changesets, the output is a changeset. Or, if the
9621 ** inputs were patchsets, the output is also a patchset.
9622 **
9623 ** As with the output of the sqlite3session_changeset() and
9624 ** sqlite3session_patchset() functions, all changes related to a single
9625 ** table are grouped together in the output of this function. Tables appear
9626 ** in the same order as for the very first changeset added to the changegroup.
9627 ** If the second or subsequent changesets added to the changegroup contain
9628 ** changes for tables that do not appear in the first changeset, they are
9629 ** appended onto the end of the output changeset, again in the order in
9630 ** which they are first encountered.
9631 **
9632 ** If an error occurs, an SQLite error code is returned and the output
9633 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9634 ** is returned and the output variables are set to the size of and a
9635 ** pointer to the output buffer, respectively. In this case it is the
9636 ** responsibility of the caller to eventually free the buffer using a
9637 ** call to sqlite3_free().
9638 */
9639 int sqlite3changegroup_output(
9640  sqlite3_changegroup*,
9641  int *pnData, /* OUT: Size of output buffer in bytes */
9642  void **ppData /* OUT: Pointer to output buffer */
9643 );
9644 
9645 /*
9646 ** CAPI3REF: Delete A Changegroup Object
9647 */
9648 void sqlite3changegroup_delete(sqlite3_changegroup*);
9649 
9650 /*
9651 ** CAPI3REF: Apply A Changeset To A Database
9652 **
9653 ** Apply a changeset to a database. This function attempts to update the
9654 ** "main" database attached to handle db with the changes found in the
9655 ** changeset passed via the second and third arguments.
9656 **
9657 ** The fourth argument (xFilter) passed to this function is the "filter
9658 ** callback". If it is not NULL, then for each table affected by at least one
9659 ** change in the changeset, the filter callback is invoked with
9660 ** the table name as the second argument, and a copy of the context pointer
9661 ** passed as the sixth argument to this function as the first. If the "filter
9662 ** callback" returns zero, then no attempt is made to apply any changes to
9663 ** the table. Otherwise, if the return value is non-zero or the xFilter
9664 ** argument to this function is NULL, all changes related to the table are
9665 ** attempted.
9666 **
9667 ** For each table that is not excluded by the filter callback, this function
9668 ** tests that the target database contains a compatible table. A table is
9669 ** considered compatible if all of the following are true:
9670 **
9671 ** <ul>
9672 ** <li> The table has the same name as the name recorded in the
9673 ** changeset, and
9674 ** <li> The table has the same number of columns as recorded in the
9675 ** changeset, and
9676 ** <li> The table has primary key columns in the same position as
9677 ** recorded in the changeset.
9678 ** </ul>
9679 **
9680 ** If there is no compatible table, it is not an error, but none of the
9681 ** changes associated with the table are applied. A warning message is issued
9682 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9683 ** one such warning is issued for each table in the changeset.
9684 **
9685 ** For each change for which there is a compatible table, an attempt is made
9686 ** to modify the table contents according to the UPDATE, INSERT or DELETE
9687 ** change. If a change cannot be applied cleanly, the conflict handler
9688 ** function passed as the fifth argument to sqlite3changeset_apply() may be
9689 ** invoked. A description of exactly when the conflict handler is invoked for
9690 ** each type of change is below.
9691 **
9692 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9693 ** of passing anything other than a valid function pointer as the xConflict
9694 ** argument are undefined.
9695 **
9696 ** Each time the conflict handler function is invoked, it must return one
9697 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9698 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9699 ** if the second argument passed to the conflict handler is either
9700 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9701 ** returns an illegal value, any changes already made are rolled back and
9702 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9703 ** actions are taken by sqlite3changeset_apply() depending on the value
9704 ** returned by each invocation of the conflict-handler function. Refer to
9705 ** the documentation for the three
9706 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
9707 **
9708 ** <dl>
9709 ** <dt>DELETE Changes<dd>
9710 ** For each DELETE change, this function checks if the target database
9711 ** contains a row with the same primary key value (or values) as the
9712 ** original row values stored in the changeset. If it does, and the values
9713 ** stored in all non-primary key columns also match the values stored in
9714 ** the changeset the row is deleted from the target database.
9715 **
9716 ** If a row with matching primary key values is found, but one or more of
9717 ** the non-primary key fields contains a value different from the original
9718 ** row value stored in the changeset, the conflict-handler function is
9719 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9720 **
9721 ** If no row with matching primary key values is found in the database,
9722 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9723 ** passed as the second argument.
9724 **
9725 ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9726 ** (which can only happen if a foreign key constraint is violated), the
9727 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9728 ** passed as the second argument. This includes the case where the DELETE
9729 ** operation is attempted because an earlier call to the conflict handler
9730 ** function returned [SQLITE_CHANGESET_REPLACE].
9731 **
9732 ** <dt>INSERT Changes<dd>
9733 ** For each INSERT change, an attempt is made to insert the new row into
9734 ** the database.
9735 **
9736 ** If the attempt to insert the row fails because the database already
9737 ** contains a row with the same primary key values, the conflict handler
9738 ** function is invoked with the second argument set to
9739 ** [SQLITE_CHANGESET_CONFLICT].
9740 **
9741 ** If the attempt to insert the row fails because of some other constraint
9742 ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9743 ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9744 ** This includes the case where the INSERT operation is re-attempted because
9745 ** an earlier call to the conflict handler function returned
9746 ** [SQLITE_CHANGESET_REPLACE].
9747 **
9748 ** <dt>UPDATE Changes<dd>
9749 ** For each UPDATE change, this function checks if the target database
9750 ** contains a row with the same primary key value (or values) as the
9751 ** original row values stored in the changeset. If it does, and the values
9752 ** stored in all non-primary key columns also match the values stored in
9753 ** the changeset the row is updated within the target database.
9754 **
9755 ** If a row with matching primary key values is found, but one or more of
9756 ** the non-primary key fields contains a value different from an original
9757 ** row value stored in the changeset, the conflict-handler function is
9758 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9759 ** UPDATE changes only contain values for non-primary key fields that are
9760 ** to be modified, only those fields need to match the original values to
9761 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9762 **
9763 ** If no row with matching primary key values is found in the database,
9764 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9765 ** passed as the second argument.
9766 **
9767 ** If the UPDATE operation is attempted, but SQLite returns
9768 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9769 ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9770 ** This includes the case where the UPDATE operation is attempted after
9771 ** an earlier call to the conflict handler function returned
9772 ** [SQLITE_CHANGESET_REPLACE].
9773 ** </dl>
9774 **
9775 ** It is safe to execute SQL statements, including those that write to the
9776 ** table that the callback related to, from within the xConflict callback.
9777 ** This can be used to further customize the applications conflict
9778 ** resolution strategy.
9779 **
9780 ** All changes made by this function are enclosed in a savepoint transaction.
9781 ** If any other error (aside from a constraint failure when attempting to
9782 ** write to the target database) occurs, then the savepoint transaction is
9783 ** rolled back, restoring the target database to its original state, and an
9784 ** SQLite error code returned.
9785 */
9786 int sqlite3changeset_apply(
9787  sqlite3 *db, /* Apply change to "main" db of this handle */
9788  int nChangeset, /* Size of changeset in bytes */
9789  void *pChangeset, /* Changeset blob */
9790  int(*xFilter)(
9791  void *pCtx, /* Copy of sixth arg to _apply() */
9792  const char *zTab /* Table name */
9793  ),
9794  int(*xConflict)(
9795  void *pCtx, /* Copy of sixth arg to _apply() */
9796  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9797  sqlite3_changeset_iter *p /* Handle describing change and conflict */
9798  ),
9799  void *pCtx /* First argument passed to xConflict */
9800 );
9801 
9802 /*
9803 ** CAPI3REF: Constants Passed To The Conflict Handler
9804 **
9805 ** Values that may be passed as the second argument to a conflict-handler.
9806 **
9807 ** <dl>
9808 ** <dt>SQLITE_CHANGESET_DATA<dd>
9809 ** The conflict handler is invoked with CHANGESET_DATA as the second argument
9810 ** when processing a DELETE or UPDATE change if a row with the required
9811 ** PRIMARY KEY fields is present in the database, but one or more other
9812 ** (non primary-key) fields modified by the update do not contain the
9813 ** expected "before" values.
9814 **
9815 ** The conflicting row, in this case, is the database row with the matching
9816 ** primary key.
9817 **
9818 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9819 ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9820 ** argument when processing a DELETE or UPDATE change if a row with the
9821 ** required PRIMARY KEY fields is not present in the database.
9822 **
9823 ** There is no conflicting row in this case. The results of invoking the
9824 ** sqlite3changeset_conflict() API are undefined.
9825 **
9826 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9827 ** CHANGESET_CONFLICT is passed as the second argument to the conflict
9828 ** handler while processing an INSERT change if the operation would result
9829 ** in duplicate primary key values.
9830 **
9831 ** The conflicting row in this case is the database row with the matching
9832 ** primary key.
9833 **
9834 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9835 ** If foreign key handling is enabled, and applying a changeset leaves the
9836 ** database in a state containing foreign key violations, the conflict
9837 ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9838 ** exactly once before the changeset is committed. If the conflict handler
9839 ** returns CHANGESET_OMIT, the changes, including those that caused the
9840 ** foreign key constraint violation, are committed. Or, if it returns
9841 ** CHANGESET_ABORT, the changeset is rolled back.
9842 **
9843 ** No current or conflicting row information is provided. The only function
9844 ** it is possible to call on the supplied sqlite3_changeset_iter handle
9845 ** is sqlite3changeset_fk_conflicts().
9846 **
9847 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9848 ** If any other constraint violation occurs while applying a change (i.e.
9849 ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9850 ** invoked with CHANGESET_CONSTRAINT as the second argument.
9851 **
9852 ** There is no conflicting row in this case. The results of invoking the
9853 ** sqlite3changeset_conflict() API are undefined.
9854 **
9855 ** </dl>
9856 */
9857 #define SQLITE_CHANGESET_DATA 1
9858 #define SQLITE_CHANGESET_NOTFOUND 2
9859 #define SQLITE_CHANGESET_CONFLICT 3
9860 #define SQLITE_CHANGESET_CONSTRAINT 4
9861 #define SQLITE_CHANGESET_FOREIGN_KEY 5
9862 
9863 /*
9864 ** CAPI3REF: Constants Returned By The Conflict Handler
9865 **
9866 ** A conflict handler callback must return one of the following three values.
9867 **
9868 ** <dl>
9869 ** <dt>SQLITE_CHANGESET_OMIT<dd>
9870 ** If a conflict handler returns this value no special action is taken. The
9871 ** change that caused the conflict is not applied. The session module
9872 ** continues to the next change in the changeset.
9873 **
9874 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
9875 ** This value may only be returned if the second argument to the conflict
9876 ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9877 ** is not the case, any changes applied so far are rolled back and the
9878 ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9879 **
9880 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9881 ** handler, then the conflicting row is either updated or deleted, depending
9882 ** on the type of change.
9883 **
9884 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9885 ** handler, then the conflicting row is removed from the database and a
9886 ** second attempt to apply the change is made. If this second attempt fails,
9887 ** the original row is restored to the database before continuing.
9888 **
9889 ** <dt>SQLITE_CHANGESET_ABORT<dd>
9890 ** If this value is returned, any changes applied so far are rolled back
9891 ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9892 ** </dl>
9893 */
9894 #define SQLITE_CHANGESET_OMIT 0
9895 #define SQLITE_CHANGESET_REPLACE 1
9896 #define SQLITE_CHANGESET_ABORT 2
9897 
9898 /*
9899 ** CAPI3REF: Streaming Versions of API functions.
9900 **
9901 ** The six streaming API xxx_strm() functions serve similar purposes to the
9902 ** corresponding non-streaming API functions:
9903 **
9904 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9905 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9906 ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9907 ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9908 ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9909 ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9910 ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9911 ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9912 ** </table>
9913 **
9914 ** Non-streaming functions that accept changesets (or patchsets) as input
9915 ** require that the entire changeset be stored in a single buffer in memory.
9916 ** Similarly, those that return a changeset or patchset do so by returning
9917 ** a pointer to a single large buffer allocated using sqlite3_malloc().
9918 ** Normally this is convenient. However, if an application running in a
9919 ** low-memory environment is required to handle very large changesets, the
9920 ** large contiguous memory allocations required can become onerous.
9921 **
9922 ** In order to avoid this problem, instead of a single large buffer, input
9923 ** is passed to a streaming API functions by way of a callback function that
9924 ** the sessions module invokes to incrementally request input data as it is
9925 ** required. In all cases, a pair of API function parameters such as
9926 **
9927 ** <pre>
9928 ** &nbsp; int nChangeset,
9929 ** &nbsp; void *pChangeset,
9930 ** </pre>
9931 **
9932 ** Is replaced by:
9933 **
9934 ** <pre>
9935 ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9936 ** &nbsp; void *pIn,
9937 ** </pre>
9938 **
9939 ** Each time the xInput callback is invoked by the sessions module, the first
9940 ** argument passed is a copy of the supplied pIn context pointer. The second
9941 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9942 ** error occurs the xInput method should copy up to (*pnData) bytes of data
9943 ** into the buffer and set (*pnData) to the actual number of bytes copied
9944 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9945 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9946 ** error code should be returned. In all cases, if an xInput callback returns
9947 ** an error, all processing is abandoned and the streaming API function
9948 ** returns a copy of the error code to the caller.
9949 **
9950 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9951 ** invoked by the sessions module at any point during the lifetime of the
9952 ** iterator. If such an xInput callback returns an error, the iterator enters
9953 ** an error state, whereby all subsequent calls to iterator functions
9954 ** immediately fail with the same error code as returned by xInput.
9955 **
9956 ** Similarly, streaming API functions that return changesets (or patchsets)
9957 ** return them in chunks by way of a callback function instead of via a
9958 ** pointer to a single large buffer. In this case, a pair of parameters such
9959 ** as:
9960 **
9961 ** <pre>
9962 ** &nbsp; int *pnChangeset,
9963 ** &nbsp; void **ppChangeset,
9964 ** </pre>
9965 **
9966 ** Is replaced by:
9967 **
9968 ** <pre>
9969 ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9970 ** &nbsp; void *pOut
9971 ** </pre>
9972 **
9973 ** The xOutput callback is invoked zero or more times to return data to
9974 ** the application. The first parameter passed to each call is a copy of the
9975 ** pOut pointer supplied by the application. The second parameter, pData,
9976 ** points to a buffer nData bytes in size containing the chunk of output
9977 ** data being returned. If the xOutput callback successfully processes the
9978 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9979 ** it should return some other SQLite error code. In this case processing
9980 ** is immediately abandoned and the streaming API function returns a copy
9981 ** of the xOutput error code to the application.
9982 **
9983 ** The sessions module never invokes an xOutput callback with the third
9984 ** parameter set to a value less than or equal to zero. Other than this,
9985 ** no guarantees are made as to the size of the chunks of data returned.
9986 */
9987 int sqlite3changeset_apply_strm(
9988  sqlite3 *db, /* Apply change to "main" db of this handle */
9989  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9990  void *pIn, /* First arg for xInput */
9991  int(*xFilter)(
9992  void *pCtx, /* Copy of sixth arg to _apply() */
9993  const char *zTab /* Table name */
9994  ),
9995  int(*xConflict)(
9996  void *pCtx, /* Copy of sixth arg to _apply() */
9997  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9998  sqlite3_changeset_iter *p /* Handle describing change and conflict */
9999  ),
10000  void *pCtx /* First argument passed to xConflict */
10001 );
10002 int sqlite3changeset_concat_strm(
10003  int (*xInputA)(void *pIn, void *pData, int *pnData),
10004  void *pInA,
10005  int (*xInputB)(void *pIn, void *pData, int *pnData),
10006  void *pInB,
10007  int (*xOutput)(void *pOut, const void *pData, int nData),
10008  void *pOut
10009 );
10010 int sqlite3changeset_invert_strm(
10011  int (*xInput)(void *pIn, void *pData, int *pnData),
10012  void *pIn,
10013  int (*xOutput)(void *pOut, const void *pData, int nData),
10014  void *pOut
10015 );
10016 int sqlite3changeset_start_strm(
10017  sqlite3_changeset_iter **pp,
10018  int (*xInput)(void *pIn, void *pData, int *pnData),
10019  void *pIn
10020 );
10021 int sqlite3session_changeset_strm(
10022  sqlite3_session *pSession,
10023  int (*xOutput)(void *pOut, const void *pData, int nData),
10024  void *pOut
10025 );
10026 int sqlite3session_patchset_strm(
10027  sqlite3_session *pSession,
10028  int (*xOutput)(void *pOut, const void *pData, int nData),
10029  void *pOut
10030 );
10031 int sqlite3changegroup_add_strm(sqlite3_changegroup*,
10032  int (*xInput)(void *pIn, void *pData, int *pnData),
10033  void *pIn
10034 );
10035 int sqlite3changegroup_output_strm(sqlite3_changegroup*,
10036  int (*xOutput)(void *pOut, const void *pData, int nData),
10037  void *pOut
10038 );
10039 
10040 
10041 /*
10042 ** Make sure we can call this stuff from C++.
10043 */
10044 #if 0
10045 }
10046 #endif
10047 
10048 #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
10049 
10050 /******** End of sqlite3session.h *********/
10051 /******** Begin file fts5.h *********/
10052 /*
10053 ** 2014 May 31
10054 **
10055 ** The author disclaims copyright to this source code. In place of
10056 ** a legal notice, here is a blessing:
10057 **
10058 ** May you do good and not evil.
10059 ** May you find forgiveness for yourself and forgive others.
10060 ** May you share freely, never taking more than you give.
10061 **
10062 ******************************************************************************
10063 **
10064 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
10065 ** FTS5 may be extended with:
10066 **
10067 ** * custom tokenizers, and
10068 ** * custom auxiliary functions.
10069 */
10070 
10071 
10072 #ifndef _FTS5_H
10073 #define _FTS5_H
10074 
10075 
10076 #if 0
10077 extern "C" {
10078 #endif
10079 
10080 /*************************************************************************
10081 ** CUSTOM AUXILIARY FUNCTIONS
10082 **
10083 ** Virtual table implementations may overload SQL functions by implementing
10084 ** the sqlite3_module.xFindFunction() method.
10085 */
10086 
10088 typedef struct Fts5Context Fts5Context;
10090 
10091 typedef void (*fts5_extension_function)(
10092  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
10093  Fts5Context *pFts, /* First arg to pass to pApi functions */
10094  sqlite3_context *pCtx, /* Context for returning result/error */
10095  int nVal, /* Number of values in apVal[] array */
10096  sqlite3_value **apVal /* Array of trailing arguments */
10097 );
10098 
10100  const unsigned char *a;
10101  const unsigned char *b;
10102 };
10103 
10104 /*
10105 ** EXTENSION API FUNCTIONS
10106 **
10107 ** xUserData(pFts):
10108 ** Return a copy of the context pointer the extension function was
10109 ** registered with.
10110 **
10111 ** xColumnTotalSize(pFts, iCol, pnToken):
10112 ** If parameter iCol is less than zero, set output variable *pnToken
10113 ** to the total number of tokens in the FTS5 table. Or, if iCol is
10114 ** non-negative but less than the number of columns in the table, return
10115 ** the total number of tokens in column iCol, considering all rows in
10116 ** the FTS5 table.
10117 **
10118 ** If parameter iCol is greater than or equal to the number of columns
10119 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10120 ** an OOM condition or IO error), an appropriate SQLite error code is
10121 ** returned.
10122 **
10123 ** xColumnCount(pFts):
10124 ** Return the number of columns in the table.
10125 **
10126 ** xColumnSize(pFts, iCol, pnToken):
10127 ** If parameter iCol is less than zero, set output variable *pnToken
10128 ** to the total number of tokens in the current row. Or, if iCol is
10129 ** non-negative but less than the number of columns in the table, set
10130 ** *pnToken to the number of tokens in column iCol of the current row.
10131 **
10132 ** If parameter iCol is greater than or equal to the number of columns
10133 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10134 ** an OOM condition or IO error), an appropriate SQLite error code is
10135 ** returned.
10136 **
10137 ** This function may be quite inefficient if used with an FTS5 table
10138 ** created with the "columnsize=0" option.
10139 **
10140 ** xColumnText:
10141 ** This function attempts to retrieve the text of column iCol of the
10142 ** current document. If successful, (*pz) is set to point to a buffer
10143 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
10144 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
10145 ** if an error occurs, an SQLite error code is returned and the final values
10146 ** of (*pz) and (*pn) are undefined.
10147 **
10148 ** xPhraseCount:
10149 ** Returns the number of phrases in the current query expression.
10150 **
10151 ** xPhraseSize:
10152 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
10153 ** are numbered starting from zero.
10154 **
10155 ** xInstCount:
10156 ** Set *pnInst to the total number of occurrences of all phrases within
10157 ** the query within the current row. Return SQLITE_OK if successful, or
10158 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
10159 **
10160 ** This API can be quite slow if used with an FTS5 table created with the
10161 ** "detail=none" or "detail=column" option. If the FTS5 table is created
10162 ** with either "detail=none" or "detail=column" and "content=" option
10163 ** (i.e. if it is a contentless table), then this API always returns 0.
10164 **
10165 ** xInst:
10166 ** Query for the details of phrase match iIdx within the current row.
10167 ** Phrase matches are numbered starting from zero, so the iIdx argument
10168 ** should be greater than or equal to zero and smaller than the value
10169 ** output by xInstCount().
10170 **
10171 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
10172 ** to the column in which it occurs and *piOff the token offset of the
10173 ** first token of the phrase. The exception is if the table was created
10174 ** with the offsets=0 option specified. In this case *piOff is always
10175 ** set to -1.
10176 **
10177 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
10178 ** if an error occurs.
10179 **
10180 ** This API can be quite slow if used with an FTS5 table created with the
10181 ** "detail=none" or "detail=column" option.
10182 **
10183 ** xRowid:
10184 ** Returns the rowid of the current row.
10185 **
10186 ** xTokenize:
10187 ** Tokenize text using the tokenizer belonging to the FTS5 table.
10188 **
10189 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
10190 ** This API function is used to query the FTS table for phrase iPhrase
10191 ** of the current query. Specifically, a query equivalent to:
10192 **
10193 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10194 **
10195 ** with $p set to a phrase equivalent to the phrase iPhrase of the
10196 ** current query is executed. Any column filter that applies to
10197 ** phrase iPhrase of the current query is included in $p. For each
10198 ** row visited, the callback function passed as the fourth argument
10199 ** is invoked. The context and API objects passed to the callback
10200 ** function may be used to access the properties of each matched row.
10201 ** Invoking Api.xUserData() returns a copy of the pointer passed as
10202 ** the third argument to pUserData.
10203 **
10204 ** If the callback function returns any value other than SQLITE_OK, the
10205 ** query is abandoned and the xQueryPhrase function returns immediately.
10206 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10207 ** Otherwise, the error code is propagated upwards.
10208 **
10209 ** If the query runs to completion without incident, SQLITE_OK is returned.
10210 ** Or, if some error occurs before the query completes or is aborted by
10211 ** the callback, an SQLite error code is returned.
10212 **
10213 **
10214 ** xSetAuxdata(pFts5, pAux, xDelete)
10215 **
10216 ** Save the pointer passed as the second argument as the extension functions
10217 ** "auxiliary data". The pointer may then be retrieved by the current or any
10218 ** future invocation of the same fts5 extension function made as part of
10219 ** of the same MATCH query using the xGetAuxdata() API.
10220 **
10221 ** Each extension function is allocated a single auxiliary data slot for
10222 ** each FTS query (MATCH expression). If the extension function is invoked
10223 ** more than once for a single FTS query, then all invocations share a
10224 ** single auxiliary data context.
10225 **
10226 ** If there is already an auxiliary data pointer when this function is
10227 ** invoked, then it is replaced by the new pointer. If an xDelete callback
10228 ** was specified along with the original pointer, it is invoked at this
10229 ** point.
10230 **
10231 ** The xDelete callback, if one is specified, is also invoked on the
10232 ** auxiliary data pointer after the FTS5 query has finished.
10233 **
10234 ** If an error (e.g. an OOM condition) occurs within this function, an
10235 ** the auxiliary data is set to NULL and an error code returned. If the
10236 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
10237 ** pointer before returning.
10238 **
10239 **
10240 ** xGetAuxdata(pFts5, bClear)
10241 **
10242 ** Returns the current auxiliary data pointer for the fts5 extension
10243 ** function. See the xSetAuxdata() method for details.
10244 **
10245 ** If the bClear argument is non-zero, then the auxiliary data is cleared
10246 ** (set to NULL) before this function returns. In this case the xDelete,
10247 ** if any, is not invoked.
10248 **
10249 **
10250 ** xRowCount(pFts5, pnRow)
10251 **
10252 ** This function is used to retrieve the total number of rows in the table.
10253 ** In other words, the same value that would be returned by:
10254 **
10255 ** SELECT count(*) FROM ftstable;
10256 **
10257 ** xPhraseFirst()
10258 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
10259 ** method, to iterate through all instances of a single query phrase within
10260 ** the current row. This is the same information as is accessible via the
10261 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
10262 ** to use, this API may be faster under some circumstances. To iterate
10263 ** through instances of phrase iPhrase, use the following code:
10264 **
10265 ** Fts5PhraseIter iter;
10266 ** int iCol, iOff;
10267 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
10268 ** iCol>=0;
10269 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
10270 ** ){
10271 ** // An instance of phrase iPhrase at offset iOff of column iCol
10272 ** }
10273 **
10274 ** The Fts5PhraseIter structure is defined above. Applications should not
10275 ** modify this structure directly - it should only be used as shown above
10276 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
10277 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
10278 **
10279 ** This API can be quite slow if used with an FTS5 table created with the
10280 ** "detail=none" or "detail=column" option. If the FTS5 table is created
10281 ** with either "detail=none" or "detail=column" and "content=" option
10282 ** (i.e. if it is a contentless table), then this API always iterates
10283 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
10284 **
10285 ** xPhraseNext()
10286 ** See xPhraseFirst above.
10287 **
10288 ** xPhraseFirstColumn()
10289 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
10290 ** and xPhraseNext() APIs described above. The difference is that instead
10291 ** of iterating through all instances of a phrase in the current row, these
10292 ** APIs are used to iterate through the set of columns in the current row
10293 ** that contain one or more instances of a specified phrase. For example:
10294 **
10295 ** Fts5PhraseIter iter;
10296 ** int iCol;
10297 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
10298 ** iCol>=0;
10299 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
10300 ** ){
10301 ** // Column iCol contains at least one instance of phrase iPhrase
10302 ** }
10303 **
10304 ** This API can be quite slow if used with an FTS5 table created with the
10305 ** "detail=none" option. If the FTS5 table is created with either
10306 ** "detail=none" "content=" option (i.e. if it is a contentless table),
10307 ** then this API always iterates through an empty set (all calls to
10308 ** xPhraseFirstColumn() set iCol to -1).
10309 **
10310 ** The information accessed using this API and its companion
10311 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
10312 ** (or xInst/xInstCount). The chief advantage of this API is that it is
10313 ** significantly more efficient than those alternatives when used with
10314 ** "detail=column" tables.
10315 **
10316 ** xPhraseNextColumn()
10317 ** See xPhraseFirstColumn above.
10318 */
10320  int iVersion; /* Currently always set to 3 */
10321 
10322  void *(*xUserData)(Fts5Context*);
10323 
10324  int (*xColumnCount)(Fts5Context*);
10325  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
10326  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
10327 
10328  int (*xTokenize)(Fts5Context*,
10329  const char *pText, int nText, /* Text to tokenize */
10330  void *pCtx, /* Context passed to xToken() */
10331  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
10332  );
10333 
10334  int (*xPhraseCount)(Fts5Context*);
10335  int (*xPhraseSize)(Fts5Context*, int iPhrase);
10336 
10337  int (*xInstCount)(Fts5Context*, int *pnInst);
10338  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
10339 
10341  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
10342  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
10343 
10344  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
10345  int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
10346  );
10347  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
10348  void *(*xGetAuxdata)(Fts5Context*, int bClear);
10349 
10350  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
10351  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
10352 
10353  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
10354  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
10355 };
10356 
10357 /*
10358 ** CUSTOM AUXILIARY FUNCTIONS
10359 *************************************************************************/
10360 
10361 /*************************************************************************
10362 ** CUSTOM TOKENIZERS
10363 **
10364 ** Applications may also register custom tokenizer types. A tokenizer
10365 ** is registered by providing fts5 with a populated instance of the
10366 ** following structure. All structure methods must be defined, setting
10367 ** any member of the fts5_tokenizer struct to NULL leads to undefined
10368 ** behaviour. The structure methods are expected to function as follows:
10369 **
10370 ** xCreate:
10371 ** This function is used to allocate and initialize a tokenizer instance.
10372 ** A tokenizer instance is required to actually tokenize text.
10373 **
10374 ** The first argument passed to this function is a copy of the (void*)
10375 ** pointer provided by the application when the fts5_tokenizer object
10376 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
10377 ** The second and third arguments are an array of nul-terminated strings
10378 ** containing the tokenizer arguments, if any, specified following the
10379 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
10380 ** to create the FTS5 table.
10381 **
10382 ** The final argument is an output variable. If successful, (*ppOut)
10383 ** should be set to point to the new tokenizer handle and SQLITE_OK
10384 ** returned. If an error occurs, some value other than SQLITE_OK should
10385 ** be returned. In this case, fts5 assumes that the final value of *ppOut
10386 ** is undefined.
10387 **
10388 ** xDelete:
10389 ** This function is invoked to delete a tokenizer handle previously
10390 ** allocated using xCreate(). Fts5 guarantees that this function will
10391 ** be invoked exactly once for each successful call to xCreate().
10392 **
10393 ** xTokenize:
10394 ** This function is expected to tokenize the nText byte string indicated
10395 ** by argument pText. pText may or may not be nul-terminated. The first
10396 ** argument passed to this function is a pointer to an Fts5Tokenizer object
10397 ** returned by an earlier call to xCreate().
10398 **
10399 ** The second argument indicates the reason that FTS5 is requesting
10400 ** tokenization of the supplied text. This is always one of the following
10401 ** four values:
10402 **
10403 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
10404 ** or removed from the FTS table. The tokenizer is being invoked to
10405 ** determine the set of tokens to add to (or delete from) the
10406 ** FTS index.
10407 **
10408 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
10409 ** against the FTS index. The tokenizer is being called to tokenize
10410 ** a bareword or quoted string specified as part of the query.
10411 **
10412 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
10413 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
10414 ** followed by a "*" character, indicating that the last token
10415 ** returned by the tokenizer will be treated as a token prefix.
10416 **
10417 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
10418 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
10419 ** function. Or an fts5_api.xColumnSize() request made by the same
10420 ** on a columnsize=0 database.
10421 ** </ul>
10422 **
10423 ** For each token in the input string, the supplied callback xToken() must
10424 ** be invoked. The first argument to it should be a copy of the pointer
10425 ** passed as the second argument to xTokenize(). The third and fourth
10426 ** arguments are a pointer to a buffer containing the token text, and the
10427 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
10428 ** of the first byte of and first byte immediately following the text from
10429 ** which the token is derived within the input.
10430 **
10431 ** The second argument passed to the xToken() callback ("tflags") should
10432 ** normally be set to 0. The exception is if the tokenizer supports
10433 ** synonyms. In this case see the discussion below for details.
10434 **
10435 ** FTS5 assumes the xToken() callback is invoked for each token in the
10436 ** order that they occur within the input text.
10437 **
10438 ** If an xToken() callback returns any value other than SQLITE_OK, then
10439 ** the tokenization should be abandoned and the xTokenize() method should
10440 ** immediately return a copy of the xToken() return value. Or, if the
10441 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
10442 ** if an error occurs with the xTokenize() implementation itself, it
10443 ** may abandon the tokenization and return any error code other than
10444 ** SQLITE_OK or SQLITE_DONE.
10445 **
10446 ** SYNONYM SUPPORT
10447 **
10448 ** Custom tokenizers may also support synonyms. Consider a case in which a
10449 ** user wishes to query for a phrase such as "first place". Using the
10450 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
10451 ** of "first place" within the document set, but not alternative forms
10452 ** such as "1st place". In some applications, it would be better to match
10453 ** all instances of "first place" or "1st place" regardless of which form
10454 ** the user specified in the MATCH query text.
10455 **
10456 ** There are several ways to approach this in FTS5:
10457 **
10458 ** <ol><li> By mapping all synonyms to a single token. In this case, the
10459 ** In the above example, this means that the tokenizer returns the
10460 ** same token for inputs "first" and "1st". Say that token is in
10461 ** fact "first", so that when the user inserts the document "I won
10462 ** 1st place" entries are added to the index for tokens "i", "won",
10463 ** "first" and "place". If the user then queries for '1st + place',
10464 ** the tokenizer substitutes "first" for "1st" and the query works
10465 ** as expected.
10466 **
10467 ** <li> By adding multiple synonyms for a single term to the FTS index.
10468 ** In this case, when tokenizing query text, the tokenizer may
10469 ** provide multiple synonyms for a single term within the document.
10470 ** FTS5 then queries the index for each synonym individually. For
10471 ** example, faced with the query:
10472 **
10473 ** <codeblock>
10474 ** ... MATCH 'first place'</codeblock>
10475 **
10476 ** the tokenizer offers both "1st" and "first" as synonyms for the
10477 ** first token in the MATCH query and FTS5 effectively runs a query
10478 ** similar to:
10479 **
10480 ** <codeblock>
10481 ** ... MATCH '(first OR 1st) place'</codeblock>
10482 **
10483 ** except that, for the purposes of auxiliary functions, the query
10484 ** still appears to contain just two phrases - "(first OR 1st)"
10485 ** being treated as a single phrase.
10486 **
10487 ** <li> By adding multiple synonyms for a single term to the FTS index.
10488 ** Using this method, when tokenizing document text, the tokenizer
10489 ** provides multiple synonyms for each token. So that when a
10490 ** document such as "I won first place" is tokenized, entries are
10491 ** added to the FTS index for "i", "won", "first", "1st" and
10492 ** "place".
10493 **
10494 ** This way, even if the tokenizer does not provide synonyms
10495 ** when tokenizing query text (it should not - to do would be
10496 ** inefficient), it doesn't matter if the user queries for
10497 ** 'first + place' or '1st + place', as there are entires in the
10498 ** FTS index corresponding to both forms of the first token.
10499 ** </ol>
10500 **
10501 ** Whether it is parsing document or query text, any call to xToken that
10502 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
10503 ** is considered to supply a synonym for the previous token. For example,
10504 ** when parsing the document "I won first place", a tokenizer that supports
10505 ** synonyms would call xToken() 5 times, as follows:
10506 **
10507 ** <codeblock>
10508 ** xToken(pCtx, 0, "i", 1, 0, 1);
10509 ** xToken(pCtx, 0, "won", 3, 2, 5);
10510 ** xToken(pCtx, 0, "first", 5, 6, 11);
10511 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
10512 ** xToken(pCtx, 0, "place", 5, 12, 17);
10513 **</codeblock>
10514 **
10515 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
10516 ** xToken() is called. Multiple synonyms may be specified for a single token
10517 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
10518 ** There is no limit to the number of synonyms that may be provided for a
10519 ** single token.
10520 **
10521 ** In many cases, method (1) above is the best approach. It does not add
10522 ** extra data to the FTS index or require FTS5 to query for multiple terms,
10523 ** so it is efficient in terms of disk space and query speed. However, it
10524 ** does not support prefix queries very well. If, as suggested above, the
10525 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
10526 **
10527 ** <codeblock>
10528 ** ... MATCH '1s*'</codeblock>
10529 **
10530 ** will not match documents that contain the token "1st" (as the tokenizer
10531 ** will probably not map "1s" to any prefix of "first").
10532 **
10533 ** For full prefix support, method (3) may be preferred. In this case,
10534 ** because the index contains entries for both "first" and "1st", prefix
10535 ** queries such as 'fi*' or '1s*' will match correctly. However, because
10536 ** extra entries are added to the FTS index, this method uses more space
10537 ** within the database.
10538 **
10539 ** Method (2) offers a midpoint between (1) and (3). Using this method,
10540 ** a query such as '1s*' will match documents that contain the literal
10541 ** token "1st", but not "first" (assuming the tokenizer is not able to
10542 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
10543 ** will match against "1st" and "first". This method does not require
10544 ** extra disk space, as no extra entries are added to the FTS index.
10545 ** On the other hand, it may require more CPU cycles to run MATCH queries,
10546 ** as separate queries of the FTS index are required for each synonym.
10547 **
10548 ** When using methods (2) or (3), it is important that the tokenizer only
10549 ** provide synonyms when tokenizing document text (method (2)) or query
10550 ** text (method (3)), not both. Doing so will not cause any errors, but is
10551 ** inefficient.
10552 */
10556  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
10557  void (*xDelete)(Fts5Tokenizer*);
10558  int (*xTokenize)(Fts5Tokenizer*,
10559  void *pCtx,
10560  int flags, /* Mask of FTS5_TOKENIZE_* flags */
10561  const char *pText, int nText,
10562  int (*xToken)(
10563  void *pCtx, /* Copy of 2nd argument to xTokenize() */
10564  int tflags, /* Mask of FTS5_TOKEN_* flags */
10565  const char *pToken, /* Pointer to buffer containing token */
10566  int nToken, /* Size of token in bytes */
10567  int iStart, /* Byte offset of token within input text */
10568  int iEnd /* Byte offset of end of token within input text */
10569  )
10570  );
10571 };
10572 
10573 /* Flags that may be passed as the third argument to xTokenize() */
10574 #define FTS5_TOKENIZE_QUERY 0x0001
10575 #define FTS5_TOKENIZE_PREFIX 0x0002
10576 #define FTS5_TOKENIZE_DOCUMENT 0x0004
10577 #define FTS5_TOKENIZE_AUX 0x0008
10578 
10579 /* Flags that may be passed by the tokenizer implementation back to FTS5
10580 ** as the third argument to the supplied xToken callback. */
10581 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
10582 
10583 /*
10584 ** END OF CUSTOM TOKENIZERS
10585 *************************************************************************/
10586 
10587 /*************************************************************************
10588 ** FTS5 EXTENSION REGISTRATION API
10589 */
10590 typedef struct fts5_api fts5_api;
10591 struct fts5_api {
10592  int iVersion; /* Currently always set to 2 */
10593 
10594  /* Create a new tokenizer */
10595  int (*xCreateTokenizer)(
10596  fts5_api *pApi,
10597  const char *zName,
10598  void *pContext,
10599  fts5_tokenizer *pTokenizer,
10600  void (*xDestroy)(void*)
10601  );
10602 
10603  /* Find an existing tokenizer */
10604  int (*xFindTokenizer)(
10605  fts5_api *pApi,
10606  const char *zName,
10607  void **ppContext,
10608  fts5_tokenizer *pTokenizer
10609  );
10610 
10611  /* Create a new auxiliary function */
10612  int (*xCreateFunction)(
10613  fts5_api *pApi,
10614  const char *zName,
10615  void *pContext,
10616  fts5_extension_function xFunction,
10617  void (*xDestroy)(void*)
10618  );
10619 };
10620 
10621 /*
10622 ** END OF REGISTRATION API
10623 *************************************************************************/
10624 
10625 #if 0
10626 } /* end of the 'extern "C"' block */
10627 #endif
10628 
10629 #endif /* _FTS5_H */
10630 
10631 /******** End of fts5.h *********/
10632 
10633 /************** End of sqlite3.h *********************************************/
10634 /************** Continuing where we left off in sqliteInt.h ******************/
10635 
10636 /*
10637 ** Include the configuration header output by 'configure' if we're using the
10638 ** autoconf-based build
10639 */
10640 #ifdef _HAVE_SQLITE_CONFIG_H
10641 #include "config.h"
10642 #endif
10643 
10644 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
10645 /************** Begin file sqliteLimit.h *************************************/
10646 /*
10647 ** 2007 May 7
10648 **
10649 ** The author disclaims copyright to this source code. In place of
10650 ** a legal notice, here is a blessing:
10651 **
10652 ** May you do good and not evil.
10653 ** May you find forgiveness for yourself and forgive others.
10654 ** May you share freely, never taking more than you give.
10655 **
10656 *************************************************************************
10657 **
10658 ** This file defines various limits of what SQLite can process.
10659 */
10660 
10661 /*
10662 ** The maximum length of a TEXT or BLOB in bytes. This also
10663 ** limits the size of a row in a table or index.
10664 **
10665 ** The hard limit is the ability of a 32-bit signed integer
10666 ** to count the size: 2^31-1 or 2147483647.
10667 */
10668 #ifndef SQLITE_MAX_LENGTH
10669 # define SQLITE_MAX_LENGTH 1000000000
10670 #endif
10671 
10672 /*
10673 ** This is the maximum number of
10674 **
10675 ** * Columns in a table
10676 ** * Columns in an index
10677 ** * Columns in a view
10678 ** * Terms in the SET clause of an UPDATE statement
10679 ** * Terms in the result set of a SELECT statement
10680 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
10681 ** * Terms in the VALUES clause of an INSERT statement
10682 **
10683 ** The hard upper limit here is 32676. Most database people will
10684 ** tell you that in a well-normalized database, you usually should
10685 ** not have more than a dozen or so columns in any table. And if
10686 ** that is the case, there is no point in having more than a few
10687 ** dozen values in any of the other situations described above.
10688 */
10689 #ifndef SQLITE_MAX_COLUMN
10690 # define SQLITE_MAX_COLUMN 2000
10691 #endif
10692 
10693 /*
10694 ** The maximum length of a single SQL statement in bytes.
10695 **
10696 ** It used to be the case that setting this value to zero would
10697 ** turn the limit off. That is no longer true. It is not possible
10698 ** to turn this limit off.
10699 */
10700 #ifndef SQLITE_MAX_SQL_LENGTH
10701 # define SQLITE_MAX_SQL_LENGTH 1000000000
10702 #endif
10703 
10704 /*
10705 ** The maximum depth of an expression tree. This is limited to
10706 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
10707 ** want to place more severe limits on the complexity of an
10708 ** expression.
10709 **
10710 ** A value of 0 used to mean that the limit was not enforced.
10711 ** But that is no longer true. The limit is now strictly enforced
10712 ** at all times.
10713 */
10714 #ifndef SQLITE_MAX_EXPR_DEPTH
10715 # define SQLITE_MAX_EXPR_DEPTH 1000
10716 #endif
10717 
10718 /*
10719 ** The maximum number of terms in a compound SELECT statement.
10720 ** The code generator for compound SELECT statements does one
10721 ** level of recursion for each term. A stack overflow can result
10722 ** if the number of terms is too large. In practice, most SQL
10723 ** never has more than 3 or 4 terms. Use a value of 0 to disable
10724 ** any limit on the number of terms in a compount SELECT.
10725 */
10726 #ifndef SQLITE_MAX_COMPOUND_SELECT
10727 # define SQLITE_MAX_COMPOUND_SELECT 500
10728 #endif
10729 
10730 /*
10731 ** The maximum number of opcodes in a VDBE program.
10732 ** Not currently enforced.
10733 */
10734 #ifndef SQLITE_MAX_VDBE_OP
10735 # define SQLITE_MAX_VDBE_OP 25000
10736 #endif
10737 
10738 /*
10739 ** The maximum number of arguments to an SQL function.
10740 */
10741 #ifndef SQLITE_MAX_FUNCTION_ARG
10742 # define SQLITE_MAX_FUNCTION_ARG 127
10743 #endif
10744 
10745 /*
10746 ** The suggested maximum number of in-memory pages to use for
10747 ** the main database table and for temporary tables.
10748 **
10749 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
10750 ** which means the cache size is limited to 2048000 bytes of memory.
10751 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
10752 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
10753 */
10754 #ifndef SQLITE_DEFAULT_CACHE_SIZE
10755 # define SQLITE_DEFAULT_CACHE_SIZE -2000
10756 #endif
10757 
10758 /*
10759 ** The default number of frames to accumulate in the log file before
10760 ** checkpointing the database in WAL mode.
10761 */
10762 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
10763 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
10764 #endif
10765 
10766 /*
10767 ** The maximum number of attached databases. This must be between 0
10768 ** and 125. The upper bound of 125 is because the attached databases are
10769 ** counted using a signed 8-bit integer which has a maximum value of 127
10770 ** and we have to allow 2 extra counts for the "main" and "temp" databases.
10771 */
10772 #ifndef SQLITE_MAX_ATTACHED
10773 # define SQLITE_MAX_ATTACHED 10
10774 #endif
10775 
10776 
10777 /*
10778 ** The maximum value of a ?nnn wildcard that the parser will accept.
10779 */
10780 #ifndef SQLITE_MAX_VARIABLE_NUMBER
10781 # define SQLITE_MAX_VARIABLE_NUMBER 999
10782 #endif
10783 
10784 /* Maximum page size. The upper bound on this value is 65536. This a limit
10785 ** imposed by the use of 16-bit offsets within each page.
10786 **
10787 ** Earlier versions of SQLite allowed the user to change this value at
10788 ** compile time. This is no longer permitted, on the grounds that it creates
10789 ** a library that is technically incompatible with an SQLite library
10790 ** compiled with a different limit. If a process operating on a database
10791 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
10792 ** compiled with the default page-size limit will not be able to rollback
10793 ** the aborted transaction. This could lead to database corruption.
10794 */
10795 #ifdef SQLITE_MAX_PAGE_SIZE
10796 # undef SQLITE_MAX_PAGE_SIZE
10797 #endif
10798 #define SQLITE_MAX_PAGE_SIZE 65536
10799 
10800 
10801 /*
10802 ** The default size of a database page.
10803 */
10804 #ifndef SQLITE_DEFAULT_PAGE_SIZE
10805 # define SQLITE_DEFAULT_PAGE_SIZE 4096
10806 #endif
10807 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10808 # undef SQLITE_DEFAULT_PAGE_SIZE
10809 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10810 #endif
10811 
10812 /*
10813 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
10814 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
10815 ** device characteristics (sector-size and atomic write() support),
10816 ** SQLite may choose a larger value. This constant is the maximum value
10817 ** SQLite will choose on its own.
10818 */
10819 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
10820 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
10821 #endif
10822 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10823 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
10824 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10825 #endif
10826 
10827 
10828 /*
10829 ** Maximum number of pages in one database file.
10830 **
10831 ** This is really just the default value for the max_page_count pragma.
10832 ** This value can be lowered (or raised) at run-time using that the
10833 ** max_page_count macro.
10834 */
10835 #ifndef SQLITE_MAX_PAGE_COUNT
10836 # define SQLITE_MAX_PAGE_COUNT 1073741823
10837 #endif
10838 
10839 /*
10840 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
10841 ** operator.
10842 */
10843 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
10844 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
10845 #endif
10846 
10847 /*
10848 ** Maximum depth of recursion for triggers.
10849 **
10850 ** A value of 1 means that a trigger program will not be able to itself
10851 ** fire any triggers. A value of 0 means that no trigger programs at all
10852 ** may be executed.
10853 */
10854 #ifndef SQLITE_MAX_TRIGGER_DEPTH
10855 # define SQLITE_MAX_TRIGGER_DEPTH 1000
10856 #endif
10857 
10858 /************** End of sqliteLimit.h *****************************************/
10859 /************** Continuing where we left off in sqliteInt.h ******************/
10860 
10861 /* Disable nuisance warnings on Borland compilers */
10862 #if defined(__BORLANDC__)
10863 #pragma warn -rch /* unreachable code */
10864 #pragma warn -ccc /* Condition is always true or false */
10865 #pragma warn -aus /* Assigned value is never used */
10866 #pragma warn -csu /* Comparing signed and unsigned */
10867 #pragma warn -spa /* Suspicious pointer arithmetic */
10868 #endif
10869 
10870 /*
10871 ** Include standard header files as necessary
10872 */
10873 #ifdef HAVE_STDINT_H
10874 #include <stdint.h>
10875 #endif
10876 #ifdef HAVE_INTTYPES_H
10877 #include <inttypes.h>
10878 #endif
10879 
10880 /*
10881 ** The following macros are used to cast pointers to integers and
10882 ** integers to pointers. The way you do this varies from one compiler
10883 ** to the next, so we have developed the following set of #if statements
10884 ** to generate appropriate macros for a wide range of compilers.
10885 **
10886 ** The correct "ANSI" way to do this is to use the intptr_t type.
10887 ** Unfortunately, that typedef is not available on all compilers, or
10888 ** if it is available, it requires an #include of specific headers
10889 ** that vary from one machine to the next.
10890 **
10891 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
10892 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
10893 ** So we have to define the macros in different ways depending on the
10894 ** compiler.
10895 */
10896 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
10897 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
10898 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
10899 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
10900 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
10901 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
10902 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
10903 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
10904 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
10905 #else /* Generates a warning - but it always works */
10906 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
10907 # define SQLITE_PTR_TO_INT(X) ((int)(X))
10908 #endif
10909 
10910 /*
10911 ** A macro to hint to the compiler that a function should not be
10912 ** inlined.
10913 */
10914 #if defined(__GNUC__)
10915 # define SQLITE_NOINLINE __attribute__((noinline))
10916 #elif defined(_MSC_VER) && _MSC_VER>=1310
10917 # define SQLITE_NOINLINE __declspec(noinline)
10918 #else
10919 # define SQLITE_NOINLINE
10920 #endif
10921 
10922 /*
10923 ** Make sure that the compiler intrinsics we desire are enabled when
10924 ** compiling with an appropriate version of MSVC unless prevented by
10925 ** the SQLITE_DISABLE_INTRINSIC define.
10926 */
10927 #if !defined(SQLITE_DISABLE_INTRINSIC)
10928 # if defined(_MSC_VER) && _MSC_VER>=1400
10929 # if !defined(_WIN32_WCE)
10930 # include <intrin.h>
10931 # pragma intrinsic(_byteswap_ushort)
10932 # pragma intrinsic(_byteswap_ulong)
10933 # pragma intrinsic(_ReadWriteBarrier)
10934 # else
10935 # include <cmnintrin.h>
10936 # endif
10937 # endif
10938 #endif
10939 
10940 /*
10941 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
10942 ** 0 means mutexes are permanently disable and the library is never
10943 ** threadsafe. 1 means the library is serialized which is the highest
10944 ** level of threadsafety. 2 means the library is multithreaded - multiple
10945 ** threads can use SQLite as long as no two threads try to use the same
10946 ** database connection at the same time.
10947 **
10948 ** Older versions of SQLite used an optional THREADSAFE macro.
10949 ** We support that for legacy.
10950 */
10951 #if !defined(SQLITE_THREADSAFE)
10952 # if defined(THREADSAFE)
10953 # define SQLITE_THREADSAFE THREADSAFE
10954 # else
10955 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
10956 # endif
10957 #endif
10958 
10959 /*
10960 ** Powersafe overwrite is on by default. But can be turned off using
10961 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
10962 */
10963 #ifndef SQLITE_POWERSAFE_OVERWRITE
10964 # define SQLITE_POWERSAFE_OVERWRITE 1
10965 #endif
10966 
10967 /*
10968 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
10969 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
10970 ** which case memory allocation statistics are disabled by default.
10971 */
10972 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
10973 # define SQLITE_DEFAULT_MEMSTATUS 1
10974 #endif
10975 
10976 /*
10977 ** Exactly one of the following macros must be defined in order to
10978 ** specify which memory allocation subsystem to use.
10979 **
10980 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
10981 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
10982 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
10983 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
10984 **
10985 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
10986 ** assert() macro is enabled, each call into the Win32 native heap subsystem
10987 ** will cause HeapValidate to be called. If heap validation should fail, an
10988 ** assertion will be triggered.
10989 **
10990 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
10991 ** the default.
10992 */
10993 #if defined(SQLITE_SYSTEM_MALLOC) \
10994  + defined(SQLITE_WIN32_MALLOC) \
10995  + defined(SQLITE_ZERO_MALLOC) \
10996  + defined(SQLITE_MEMDEBUG)>1
10997 # error "Two or more of the following compile-time configuration options\
10998  are defined but at most one is allowed:\
10999  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
11000  SQLITE_ZERO_MALLOC"
11001 #endif
11002 #if defined(SQLITE_SYSTEM_MALLOC) \
11003  + defined(SQLITE_WIN32_MALLOC) \
11004  + defined(SQLITE_ZERO_MALLOC) \
11005  + defined(SQLITE_MEMDEBUG)==0
11006 # define SQLITE_SYSTEM_MALLOC 1
11007 #endif
11008 
11009 /*
11010 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
11011 ** sizes of memory allocations below this value where possible.
11012 */
11013 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
11014 # define SQLITE_MALLOC_SOFT_LIMIT 1024
11015 #endif
11016 
11017 /*
11018 ** We need to define _XOPEN_SOURCE as follows in order to enable
11019 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
11020 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
11021 ** it.
11022 */
11023 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
11024 # define _XOPEN_SOURCE 600
11025 #endif
11026 
11027 /*
11028 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
11029 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
11030 ** make it true by defining or undefining NDEBUG.
11031 **
11032 ** Setting NDEBUG makes the code smaller and faster by disabling the
11033 ** assert() statements in the code. So we want the default action
11034 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
11035 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
11036 ** feature.
11037 */
11038 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
11039 # define NDEBUG 1
11040 #endif
11041 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
11042 # undef NDEBUG
11043 #endif
11044 
11045 /*
11046 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
11047 */
11048 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
11049 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
11050 #endif
11051 
11052 /*
11053 ** The testcase() macro is used to aid in coverage testing. When
11054 ** doing coverage testing, the condition inside the argument to
11055 ** testcase() must be evaluated both true and false in order to
11056 ** get full branch coverage. The testcase() macro is inserted
11057 ** to help ensure adequate test coverage in places where simple
11058 ** condition/decision coverage is inadequate. For example, testcase()
11059 ** can be used to make sure boundary values are tested. For
11060 ** bitmask tests, testcase() can be used to make sure each bit
11061 ** is significant and used at least once. On switch statements
11062 ** where multiple cases go to the same block of code, testcase()
11063 ** can insure that all cases are evaluated.
11064 **
11065 */
11066 #ifdef SQLITE_COVERAGE_TEST
11067 SQLITE_PRIVATE void sqlite3Coverage(int);
11068 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
11069 #else
11070 # define testcase(X)
11071 #endif
11072 
11073 /*
11074 ** The TESTONLY macro is used to enclose variable declarations or
11075 ** other bits of code that are needed to support the arguments
11076 ** within testcase() and assert() macros.
11077 */
11078 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
11079 # define TESTONLY(X) X
11080 #else
11081 # define TESTONLY(X)
11082 #endif
11083 
11084 /*
11085 ** Sometimes we need a small amount of code such as a variable initialization
11086 ** to setup for a later assert() statement. We do not want this code to
11087 ** appear when assert() is disabled. The following macro is therefore
11088 ** used to contain that setup code. The "VVA" acronym stands for
11089 ** "Verification, Validation, and Accreditation". In other words, the
11090 ** code within VVA_ONLY() will only run during verification processes.
11091 */
11092 #ifndef NDEBUG
11093 # define VVA_ONLY(X) X
11094 #else
11095 # define VVA_ONLY(X)
11096 #endif
11097 
11098 /*
11099 ** The ALWAYS and NEVER macros surround boolean expressions which
11100 ** are intended to always be true or false, respectively. Such
11101 ** expressions could be omitted from the code completely. But they
11102 ** are included in a few cases in order to enhance the resilience
11103 ** of SQLite to unexpected behavior - to make the code "self-healing"
11104 ** or "ductile" rather than being "brittle" and crashing at the first
11105 ** hint of unplanned behavior.
11106 **
11107 ** In other words, ALWAYS and NEVER are added for defensive code.
11108 **
11109 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
11110 ** be true and false so that the unreachable code they specify will
11111 ** not be counted as untested code.
11112 */
11113 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11114 # define ALWAYS(X) (1)
11115 # define NEVER(X) (0)
11116 #elif !defined(NDEBUG)
11117 # define ALWAYS(X) ((X)?1:(assert(0),0))
11118 # define NEVER(X) ((X)?(assert(0),1):0)
11119 #else
11120 # define ALWAYS(X) (X)
11121 # define NEVER(X) (X)
11122 #endif
11123 
11124 /*
11125 ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
11126 ** defined. We need to defend against those failures when testing with
11127 ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
11128 ** during a normal build. The following macro can be used to disable tests
11129 ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
11130 */
11131 #if defined(SQLITE_TEST_REALLOC_STRESS)
11132 # define ONLY_IF_REALLOC_STRESS(X) (X)
11133 #elif !defined(NDEBUG)
11134 # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
11135 #else
11136 # define ONLY_IF_REALLOC_STRESS(X) (0)
11137 #endif
11138 
11139 /*
11140 ** Declarations used for tracing the operating system interfaces.
11141 */
11142 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
11143  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11144  extern int sqlite3OSTrace;
11145 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
11146 # define SQLITE_HAVE_OS_TRACE
11147 #else
11148 # define OSTRACE(X)
11149 # undef SQLITE_HAVE_OS_TRACE
11150 #endif
11151 
11152 /*
11153 ** Is the sqlite3ErrName() function needed in the build? Currently,
11154 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
11155 ** OSTRACE is enabled), and by several "test*.c" files (which are
11156 ** compiled using SQLITE_TEST).
11157 */
11158 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
11159  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11160 # define SQLITE_NEED_ERR_NAME
11161 #else
11162 # undef SQLITE_NEED_ERR_NAME
11163 #endif
11164 
11165 /*
11166 ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
11167 */
11168 #ifdef SQLITE_OMIT_EXPLAIN
11169 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
11170 #endif
11171 
11172 /*
11173 ** Return true (non-zero) if the input is an integer that is too large
11174 ** to fit in 32-bits. This macro is used inside of various testcase()
11175 ** macros to verify that we have tested SQLite for large-file support.
11176 */
11177 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
11178 
11179 /*
11180 ** The macro unlikely() is a hint that surrounds a boolean
11181 ** expression that is usually false. Macro likely() surrounds
11182 ** a boolean expression that is usually true. These hints could,
11183 ** in theory, be used by the compiler to generate better code, but
11184 ** currently they are just comments for human readers.
11185 */
11186 #define likely(X) (X)
11187 #define unlikely(X) (X)
11188 
11189 /************** Include hash.h in the middle of sqliteInt.h ******************/
11190 /************** Begin file hash.h ********************************************/
11191 /*
11192 ** 2001 September 22
11193 **
11194 ** The author disclaims copyright to this source code. In place of
11195 ** a legal notice, here is a blessing:
11196 **
11197 ** May you do good and not evil.
11198 ** May you find forgiveness for yourself and forgive others.
11199 ** May you share freely, never taking more than you give.
11200 **
11201 *************************************************************************
11202 ** This is the header file for the generic hash-table implementation
11203 ** used in SQLite.
11204 */
11205 #ifndef SQLITE_HASH_H
11206 #define SQLITE_HASH_H
11207 
11208 /* Forward declarations of structures. */
11209 typedef struct Hash Hash;
11210 typedef struct HashElem HashElem;
11211 
11212 /* A complete hash table is an instance of the following structure.
11213 ** The internals of this structure are intended to be opaque -- client
11214 ** code should not attempt to access or modify the fields of this structure
11215 ** directly. Change this structure only by using the routines below.
11216 ** However, some of the "procedures" and "functions" for modifying and
11217 ** accessing this structure are really macros, so we can't really make
11218 ** this structure opaque.
11219 **
11220 ** All elements of the hash table are on a single doubly-linked list.
11221 ** Hash.first points to the head of this list.
11222 **
11223 ** There are Hash.htsize buckets. Each bucket points to a spot in
11224 ** the global doubly-linked list. The contents of the bucket are the
11225 ** element pointed to plus the next _ht.count-1 elements in the list.
11226 **
11227 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
11228 ** by a linear search of the global list. For small tables, the
11229 ** Hash.ht table is never allocated because if there are few elements
11230 ** in the table, it is faster to do a linear search than to manage
11231 ** the hash table.
11232 */
11233 struct Hash {
11234  unsigned int htsize; /* Number of buckets in the hash table */
11235  unsigned int count; /* Number of entries in this table */
11236  HashElem *first; /* The first element of the array */
11237  struct _ht { /* the hash table */
11238  int count; /* Number of entries with this hash */
11239  HashElem *chain; /* Pointer to first entry with this hash */
11240  } *ht;
11241 };
11242 
11243 /* Each element in the hash table is an instance of the following
11244 ** structure. All elements are stored on a single doubly-linked list.
11245 **
11246 ** Again, this structure is intended to be opaque, but it can't really
11247 ** be opaque because it is used by macros.
11248 */
11249 struct HashElem {
11250  HashElem *next, *prev; /* Next and previous elements in the table */
11251  void *data; /* Data associated with this element */
11252  const char *pKey; /* Key associated with this element */
11253 };
11254 
11255 /*
11256 ** Access routines. To delete, insert a NULL pointer.
11257 */
11259 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
11260 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
11262 
11263 /*
11264 ** Macros for looping over all elements of a hash table. The idiom is
11265 ** like this:
11266 **
11267 ** Hash h;
11268 ** HashElem *p;
11269 ** ...
11270 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
11271 ** SomeStructure *pData = sqliteHashData(p);
11272 ** // do something with pData
11273 ** }
11274 */
11275 #define sqliteHashFirst(H) ((H)->first)
11276 #define sqliteHashNext(E) ((E)->next)
11277 #define sqliteHashData(E) ((E)->data)
11278 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
11279 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
11280 
11281 /*
11282 ** Number of entries in a hash table
11283 */
11284 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
11285 
11286 #endif /* SQLITE_HASH_H */
11287 
11288 /************** End of hash.h ************************************************/
11289 /************** Continuing where we left off in sqliteInt.h ******************/
11290 /************** Include parse.h in the middle of sqliteInt.h *****************/
11291 /************** Begin file parse.h *******************************************/
11292 #define TK_SEMI 1
11293 #define TK_EXPLAIN 2
11294 #define TK_QUERY 3
11295 #define TK_PLAN 4
11296 #define TK_BEGIN 5
11297 #define TK_TRANSACTION 6
11298 #define TK_DEFERRED 7
11299 #define TK_IMMEDIATE 8
11300 #define TK_EXCLUSIVE 9
11301 #define TK_COMMIT 10
11302 #define TK_END 11
11303 #define TK_ROLLBACK 12
11304 #define TK_SAVEPOINT 13
11305 #define TK_RELEASE 14
11306 #define TK_TO 15
11307 #define TK_TABLE 16
11308 #define TK_CREATE 17
11309 #define TK_IF 18
11310 #define TK_NOT 19
11311 #define TK_EXISTS 20
11312 #define TK_TEMP 21
11313 #define TK_LP 22
11314 #define TK_RP 23
11315 #define TK_AS 24
11316 #define TK_WITHOUT 25
11317 #define TK_COMMA 26
11318 #define TK_OR 27
11319 #define TK_AND 28
11320 #define TK_IS 29
11321 #define TK_MATCH 30
11322 #define TK_LIKE_KW 31
11323 #define TK_BETWEEN 32
11324 #define TK_IN 33
11325 #define TK_ISNULL 34
11326 #define TK_NOTNULL 35
11327 #define TK_NE 36
11328 #define TK_EQ 37
11329 #define TK_GT 38
11330 #define TK_LE 39
11331 #define TK_LT 40
11332 #define TK_GE 41
11333 #define TK_ESCAPE 42
11334 #define TK_BITAND 43
11335 #define TK_BITOR 44
11336 #define TK_LSHIFT 45
11337 #define TK_RSHIFT 46
11338 #define TK_PLUS 47
11339 #define TK_MINUS 48
11340 #define TK_STAR 49
11341 #define TK_SLASH 50
11342 #define TK_REM 51
11343 #define TK_CONCAT 52
11344 #define TK_COLLATE 53
11345 #define TK_BITNOT 54
11346 #define TK_ID 55
11347 #define TK_INDEXED 56
11348 #define TK_ABORT 57
11349 #define TK_ACTION 58
11350 #define TK_AFTER 59
11351 #define TK_ANALYZE 60
11352 #define TK_ASC 61
11353 #define TK_ATTACH 62
11354 #define TK_BEFORE 63
11355 #define TK_BY 64
11356 #define TK_CASCADE 65
11357 #define TK_CAST 66
11358 #define TK_COLUMNKW 67
11359 #define TK_CONFLICT 68
11360 #define TK_DATABASE 69
11361 #define TK_DESC 70
11362 #define TK_DETACH 71
11363 #define TK_EACH 72
11364 #define TK_FAIL 73
11365 #define TK_FOR 74
11366 #define TK_IGNORE 75
11367 #define TK_INITIALLY 76
11368 #define TK_INSTEAD 77
11369 #define TK_NO 78
11370 #define TK_KEY 79
11371 #define TK_OF 80
11372 #define TK_OFFSET 81
11373 #define TK_PRAGMA 82
11374 #define TK_RAISE 83
11375 #define TK_RECURSIVE 84
11376 #define TK_REPLACE 85
11377 #define TK_RESTRICT 86
11378 #define TK_ROW 87
11379 #define TK_TRIGGER 88
11380 #define TK_VACUUM 89
11381 #define TK_VIEW 90
11382 #define TK_VIRTUAL 91
11383 #define TK_WITH 92
11384 #define TK_REINDEX 93
11385 #define TK_RENAME 94
11386 #define TK_CTIME_KW 95
11387 #define TK_ANY 96
11388 #define TK_STRING 97
11389 #define TK_JOIN_KW 98
11390 #define TK_CONSTRAINT 99
11391 #define TK_DEFAULT 100
11392 #define TK_NULL 101
11393 #define TK_PRIMARY 102
11394 #define TK_UNIQUE 103
11395 #define TK_CHECK 104
11396 #define TK_REFERENCES 105
11397 #define TK_AUTOINCR 106
11398 #define TK_ON 107
11399 #define TK_INSERT 108
11400 #define TK_DELETE 109
11401 #define TK_UPDATE 110
11402 #define TK_SET 111
11403 #define TK_DEFERRABLE 112
11404 #define TK_FOREIGN 113
11405 #define TK_DROP 114
11406 #define TK_UNION 115
11407 #define TK_ALL 116
11408 #define TK_EXCEPT 117
11409 #define TK_INTERSECT 118
11410 #define TK_SELECT 119
11411 #define TK_VALUES 120
11412 #define TK_DISTINCT 121
11413 #define TK_DOT 122
11414 #define TK_FROM 123
11415 #define TK_JOIN 124
11416 #define TK_USING 125
11417 #define TK_ORDER 126
11418 #define TK_GROUP 127
11419 #define TK_HAVING 128
11420 #define TK_LIMIT 129
11421 #define TK_WHERE 130
11422 #define TK_INTO 131
11423 #define TK_FLOAT 132
11424 #define TK_BLOB 133
11425 #define TK_INTEGER 134
11426 #define TK_VARIABLE 135
11427 #define TK_CASE 136
11428 #define TK_WHEN 137
11429 #define TK_THEN 138
11430 #define TK_ELSE 139
11431 #define TK_INDEX 140
11432 #define TK_ALTER 141
11433 #define TK_ADD 142
11434 #define TK_TO_TEXT 143
11435 #define TK_TO_BLOB 144
11436 #define TK_TO_NUMERIC 145
11437 #define TK_TO_INT 146
11438 #define TK_TO_REAL 147
11439 #define TK_ISNOT 148
11440 #define TK_END_OF_FILE 149
11441 #define TK_UNCLOSED_STRING 150
11442 #define TK_FUNCTION 151
11443 #define TK_COLUMN 152
11444 #define TK_AGG_FUNCTION 153
11445 #define TK_AGG_COLUMN 154
11446 #define TK_UMINUS 155
11447 #define TK_UPLUS 156
11448 #define TK_REGISTER 157
11449 #define TK_VECTOR 158
11450 #define TK_SELECT_COLUMN 159
11451 #define TK_ASTERISK 160
11452 #define TK_SPAN 161
11453 #define TK_SPACE 162
11454 #define TK_ILLEGAL 163
11455 
11456 /* The token codes above must all fit in 8 bits */
11457 #define TKFLG_MASK 0xff
11458 
11459 /* Flags that can be added to a token code when it is not
11460 ** being stored in a u8: */
11461 #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
11462 
11463 /************** End of parse.h ***********************************************/
11464 /************** Continuing where we left off in sqliteInt.h ******************/
11465 #include <stdio.h>
11466 #include <stdlib.h>
11467 #include <string.h>
11468 #include <assert.h>
11469 #include <stddef.h>
11470 
11471 /*
11472 ** If compiling for a processor that lacks floating point support,
11473 ** substitute integer for floating-point
11474 */
11475 #ifdef SQLITE_OMIT_FLOATING_POINT
11476 # define double sqlite_int64
11477 # define float sqlite_int64
11478 # define LONGDOUBLE_TYPE sqlite_int64
11479 # ifndef SQLITE_BIG_DBL
11480 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
11481 # endif
11482 # define SQLITE_OMIT_DATETIME_FUNCS 1
11483 # define SQLITE_OMIT_TRACE 1
11484 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11485 # undef SQLITE_HAVE_ISNAN
11486 #endif
11487 #ifndef SQLITE_BIG_DBL
11488 # define SQLITE_BIG_DBL (1e99)
11489 #endif
11490 
11491 /*
11492 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
11493 ** afterward. Having this macro allows us to cause the C compiler
11494 ** to omit code used by TEMP tables without messy #ifndef statements.
11495 */
11496 #ifdef SQLITE_OMIT_TEMPDB
11497 #define OMIT_TEMPDB 1
11498 #else
11499 #define OMIT_TEMPDB 0
11500 #endif
11501 
11502 /*
11503 ** The "file format" number is an integer that is incremented whenever
11504 ** the VDBE-level file format changes. The following macros define the
11505 ** the default file format for new databases and the maximum file format
11506 ** that the library can read.
11507 */
11508 #define SQLITE_MAX_FILE_FORMAT 4
11509 #ifndef SQLITE_DEFAULT_FILE_FORMAT
11510 # define SQLITE_DEFAULT_FILE_FORMAT 4
11511 #endif
11512 
11513 /*
11514 ** Determine whether triggers are recursive by default. This can be
11515 ** changed at run-time using a pragma.
11516 */
11517 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
11518 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
11519 #endif
11520 
11521 /*
11522 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
11523 ** on the command-line
11524 */
11525 #ifndef SQLITE_TEMP_STORE
11526 # define SQLITE_TEMP_STORE 1
11527 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
11528 #endif
11529 
11530 /*
11531 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
11532 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
11533 ** to zero.
11534 */
11535 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
11536 # undef SQLITE_MAX_WORKER_THREADS
11537 # define SQLITE_MAX_WORKER_THREADS 0
11538 #endif
11539 #ifndef SQLITE_MAX_WORKER_THREADS
11540 # define SQLITE_MAX_WORKER_THREADS 8
11541 #endif
11542 #ifndef SQLITE_DEFAULT_WORKER_THREADS
11543 # define SQLITE_DEFAULT_WORKER_THREADS 0
11544 #endif
11545 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
11546 # undef SQLITE_MAX_WORKER_THREADS
11547 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
11548 #endif
11549 
11550 /*
11551 ** The default initial allocation for the pagecache when using separate
11552 ** pagecaches for each database connection. A positive number is the
11553 ** number of pages. A negative number N translations means that a buffer
11554 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
11555 */
11556 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
11557 # define SQLITE_DEFAULT_PCACHE_INITSZ 100
11558 #endif
11559 
11560 /*
11561 ** GCC does not define the offsetof() macro so we'll have to do it
11562 ** ourselves.
11563 */
11564 #ifndef offsetof
11565 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
11566 #endif
11567 
11568 /*
11569 ** Macros to compute minimum and maximum of two numbers.
11570 */
11571 #ifndef MIN
11572 # define MIN(A,B) ((A)<(B)?(A):(B))
11573 #endif
11574 #ifndef MAX
11575 # define MAX(A,B) ((A)>(B)?(A):(B))
11576 #endif
11577 
11578 /*
11579 ** Swap two objects of type TYPE.
11580 */
11581 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
11582 
11583 /*
11584 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
11585 ** not, there are still machines out there that use EBCDIC.)
11586 */
11587 #if 'A' == '\301'
11588 # define SQLITE_EBCDIC 1
11589 #else
11590 # define SQLITE_ASCII 1
11591 #endif
11592 
11593 /*
11594 ** Integers of known sizes. These typedefs might change for architectures
11595 ** where the sizes very. Preprocessor macros are available so that the
11596 ** types can be conveniently redefined at compile-type. Like this:
11597 **
11598 ** cc '-DUINTPTR_TYPE=long long int' ...
11599 */
11600 #ifndef UINT32_TYPE
11601 # ifdef HAVE_UINT32_T
11602 # define UINT32_TYPE uint32_t
11603 # else
11604 # define UINT32_TYPE unsigned int
11605 # endif
11606 #endif
11607 #ifndef UINT16_TYPE
11608 # ifdef HAVE_UINT16_T
11609 # define UINT16_TYPE uint16_t
11610 # else
11611 # define UINT16_TYPE unsigned short int
11612 # endif
11613 #endif
11614 #ifndef INT16_TYPE
11615 # ifdef HAVE_INT16_T
11616 # define INT16_TYPE int16_t
11617 # else
11618 # define INT16_TYPE short int
11619 # endif
11620 #endif
11621 #ifndef UINT8_TYPE
11622 # ifdef HAVE_UINT8_T
11623 # define UINT8_TYPE uint8_t
11624 # else
11625 # define UINT8_TYPE unsigned char
11626 # endif
11627 #endif
11628 #ifndef INT8_TYPE
11629 # ifdef HAVE_INT8_T
11630 # define INT8_TYPE int8_t
11631 # else
11632 # define INT8_TYPE signed char
11633 # endif
11634 #endif
11635 #ifndef LONGDOUBLE_TYPE
11636 # define LONGDOUBLE_TYPE long double
11637 #endif
11638 typedef sqlite_int64 i64; /* 8-byte signed integer */
11639 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
11640 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
11641 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
11642 typedef INT16_TYPE i16; /* 2-byte signed integer */
11643 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
11644 typedef INT8_TYPE i8; /* 1-byte signed integer */
11645 
11646 /*
11647 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
11648 ** that can be stored in a u32 without loss of data. The value
11649 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
11650 ** have to specify the value in the less intuitive manner shown:
11651 */
11652 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
11653 
11654 /*
11655 ** The datatype used to store estimates of the number of rows in a
11656 ** table or index. This is an unsigned integer type. For 99.9% of
11657 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
11658 ** can be used at compile-time if desired.
11659 */
11660 #ifdef SQLITE_64BIT_STATS
11661  typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
11662 #else
11663  typedef u32 tRowcnt; /* 32-bit is the default */
11664 #endif
11665 
11666 /*
11667 ** Estimated quantities used for query planning are stored as 16-bit
11668 ** logarithms. For quantity X, the value stored is 10*log2(X). This
11669 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
11670 ** But the allowed values are "grainy". Not every value is representable.
11671 ** For example, quantities 16 and 17 are both represented by a LogEst
11672 ** of 40. However, since LogEst quantities are suppose to be estimates,
11673 ** not exact values, this imprecision is not a problem.
11674 **
11675 ** "LogEst" is short for "Logarithmic Estimate".
11676 **
11677 ** Examples:
11678 ** 1 -> 0 20 -> 43 10000 -> 132
11679 ** 2 -> 10 25 -> 46 25000 -> 146
11680 ** 3 -> 16 100 -> 66 1000000 -> 199
11681 ** 4 -> 20 1000 -> 99 1048576 -> 200
11682 ** 10 -> 33 1024 -> 100 4294967296 -> 320
11683 **
11684 ** The LogEst can be negative to indicate fractional values.
11685 ** Examples:
11686 **
11687 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
11688 */
11690 
11691 /*
11692 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
11693 */
11694 #ifndef SQLITE_PTRSIZE
11695 # if defined(__SIZEOF_POINTER__)
11696 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
11697 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11698  defined(_M_ARM) || defined(__arm__) || defined(__x86)
11699 # define SQLITE_PTRSIZE 4
11700 # else
11701 # define SQLITE_PTRSIZE 8
11702 # endif
11703 #endif
11704 
11705 /* The uptr type is an unsigned integer large enough to hold a pointer
11706 */
11707 #if defined(HAVE_STDINT_H)
11708  typedef uintptr_t uptr;
11709 #elif SQLITE_PTRSIZE==4
11710  typedef u32 uptr;
11711 #else
11712  typedef u64 uptr;
11713 #endif
11714 
11715 /*
11716 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
11717 ** something between S (inclusive) and E (exclusive).
11718 **
11719 ** In other words, S is a buffer and E is a pointer to the first byte after
11720 ** the end of buffer S. This macro returns true if P points to something
11721 ** contained within the buffer S.
11722 */
11723 #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
11724 
11725 
11726 /*
11727 ** Macros to determine whether the machine is big or little endian,
11728 ** and whether or not that determination is run-time or compile-time.
11729 **
11730 ** For best performance, an attempt is made to guess at the byte-order
11731 ** using C-preprocessor macros. If that is unsuccessful, or if
11732 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
11733 ** at run-time.
11734 */
11735 #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11736  defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
11737  defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
11738  defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
11739 # define SQLITE_BYTEORDER 1234
11740 # define SQLITE_BIGENDIAN 0
11741 # define SQLITE_LITTLEENDIAN 1
11742 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
11743 #endif
11744 #if (defined(sparc) || defined(__ppc__)) \
11745  && !defined(SQLITE_RUNTIME_BYTEORDER)
11746 # define SQLITE_BYTEORDER 4321
11747 # define SQLITE_BIGENDIAN 1
11748 # define SQLITE_LITTLEENDIAN 0
11749 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
11750 #endif
11751 #if !defined(SQLITE_BYTEORDER)
11752 # ifdef SQLITE_AMALGAMATION
11753  const int sqlite3one = 1;
11754 # else
11755  extern const int sqlite3one;
11756 # endif
11757 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
11758 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
11759 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
11760 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
11761 #endif
11762 
11763 /*
11764 ** Constants for the largest and smallest possible 64-bit signed integers.
11765 ** These macros are designed to work correctly on both 32-bit and 64-bit
11766 ** compilers.
11767 */
11768 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
11769 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
11770 
11771 /*
11772 ** Round up a number to the next larger multiple of 8. This is used
11773 ** to force 8-byte alignment on 64-bit architectures.
11774 */
11775 #define ROUND8(x) (((x)+7)&~7)
11776 
11777 /*
11778 ** Round down to the nearest multiple of 8
11779 */
11780 #define ROUNDDOWN8(x) ((x)&~7)
11781 
11782 /*
11783 ** Assert that the pointer X is aligned to an 8-byte boundary. This
11784 ** macro is used only within assert() to verify that the code gets
11785 ** all alignment restrictions correct.
11786 **
11787 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
11788 ** underlying malloc() implementation might return us 4-byte aligned
11789 ** pointers. In that case, only verify 4-byte alignment.
11790 */
11791 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11792 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
11793 #else
11794 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
11795 #endif
11796 
11797 /*
11798 ** Disable MMAP on platforms where it is known to not work
11799 */
11800 #if defined(__OpenBSD__) || defined(__QNXNTO__)
11801 # undef SQLITE_MAX_MMAP_SIZE
11802 # define SQLITE_MAX_MMAP_SIZE 0
11803 #endif
11804 
11805 /*
11806 ** Default maximum size of memory used by memory-mapped I/O in the VFS
11807 */
11808 #ifdef __APPLE__
11809 # include <TargetConditionals.h>
11810 #endif
11811 #ifndef SQLITE_MAX_MMAP_SIZE
11812 # if defined(__linux__) \
11813  || defined(_WIN32) \
11814  || (defined(__APPLE__) && defined(__MACH__)) \
11815  || defined(__sun) \
11816  || defined(__FreeBSD__) \
11817  || defined(__DragonFly__)
11818 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
11819 # else
11820 # define SQLITE_MAX_MMAP_SIZE 0
11821 # endif
11822 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
11823 #endif
11824 
11825 /*
11826 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
11827 ** default MMAP_SIZE is specified at compile-time, make sure that it does
11828 ** not exceed the maximum mmap size.
11829 */
11830 #ifndef SQLITE_DEFAULT_MMAP_SIZE
11831 # define SQLITE_DEFAULT_MMAP_SIZE 0
11832 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
11833 #endif
11834 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
11835 # undef SQLITE_DEFAULT_MMAP_SIZE
11836 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
11837 #endif
11838 
11839 /*
11840 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
11841 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
11842 ** define SQLITE_ENABLE_STAT3_OR_STAT4
11843 */
11844 #ifdef SQLITE_ENABLE_STAT4
11845 # undef SQLITE_ENABLE_STAT3
11846 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11847 #elif SQLITE_ENABLE_STAT3
11848 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11849 #elif SQLITE_ENABLE_STAT3_OR_STAT4
11850 # undef SQLITE_ENABLE_STAT3_OR_STAT4
11851 #endif
11852 
11853 /*
11854 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
11855 ** the Select query generator tracing logic is turned on.
11856 */
11857 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
11858 # define SELECTTRACE_ENABLED 1
11859 #else
11860 # define SELECTTRACE_ENABLED 0
11861 #endif
11862 
11863 /*
11864 ** An instance of the following structure is used to store the busy-handler
11865 ** callback for a given sqlite handle.
11866 **
11867 ** The sqlite.busyHandler member of the sqlite struct contains the busy
11868 ** callback for the database handle. Each pager opened via the sqlite
11869 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
11870 ** callback is currently invoked only from within pager.c.
11871 */
11872 typedef struct BusyHandler BusyHandler;
11873 struct BusyHandler {
11874  int (*xFunc)(void *,int); /* The busy callback */
11875  void *pArg; /* First arg to busy callback */
11876  int nBusy; /* Incremented with each busy call */
11877 };
11878 
11879 /*
11880 ** Name of the master database table. The master database table
11881 ** is a special table that holds the names and attributes of all
11882 ** user tables and indices.
11883 */
11884 #define MASTER_NAME "sqlite_master"
11885 #define TEMP_MASTER_NAME "sqlite_temp_master"
11886 
11887 /*
11888 ** The root-page of the master database table.
11889 */
11890 #define MASTER_ROOT 1
11891 
11892 /*
11893 ** The name of the schema table.
11894 */
11895 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
11896 
11897 /*
11898 ** A convenience macro that returns the number of elements in
11899 ** an array.
11900 */
11901 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
11902 
11903 /*
11904 ** Determine if the argument is a power of two
11905 */
11906 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
11907 
11908 /*
11909 ** The following value as a destructor means to use sqlite3DbFree().
11910 ** The sqlite3DbFree() routine requires two parameters instead of the
11911 ** one parameter that destructors normally want. So we have to introduce
11912 ** this magic value that the code knows to handle differently. Any
11913 ** pointer will work here as long as it is distinct from SQLITE_STATIC
11914 ** and SQLITE_TRANSIENT.
11915 */
11916 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
11917 
11918 /*
11919 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
11920 ** not support Writable Static Data (WSD) such as global and static variables.
11921 ** All variables must either be on the stack or dynamically allocated from
11922 ** the heap. When WSD is unsupported, the variable declarations scattered
11923 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
11924 ** macro is used for this purpose. And instead of referencing the variable
11925 ** directly, we use its constant as a key to lookup the run-time allocated
11926 ** buffer that holds real variable. The constant is also the initializer
11927 ** for the run-time allocated buffer.
11928 **
11929 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
11930 ** macros become no-ops and have zero performance impact.
11931 */
11932 #ifdef SQLITE_OMIT_WSD
11933  #define SQLITE_WSD const
11934  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
11935  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
11936 SQLITE_API int sqlite3_wsd_init(int N, int J);
11937 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
11938 #else
11939  #define SQLITE_WSD
11940  #define GLOBAL(t,v) v
11941  #define sqlite3GlobalConfig sqlite3Config
11942 #endif
11943 
11944 /*
11945 ** The following macros are used to suppress compiler warnings and to
11946 ** make it clear to human readers when a function parameter is deliberately
11947 ** left unused within the body of a function. This usually happens when
11948 ** a function is called via a function pointer. For example the
11949 ** implementation of an SQL aggregate step callback may not use the
11950 ** parameter indicating the number of arguments passed to the aggregate,
11951 ** if it knows that this is enforced elsewhere.
11952 **
11953 ** When a function parameter is not used at all within the body of a function,
11954 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
11955 ** However, these macros may also be used to suppress warnings related to
11956 ** parameters that may or may not be used depending on compilation options.
11957 ** For example those parameters only used in assert() statements. In these
11958 ** cases the parameters are named as per the usual conventions.
11959 */
11960 #define UNUSED_PARAMETER(x) (void)(x)
11961 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
11962 
11963 /*
11964 ** Forward references to structures
11965 */
11966 typedef struct AggInfo AggInfo;
11967 typedef struct AuthContext AuthContext;
11968 typedef struct AutoincInfo AutoincInfo;
11969 typedef struct Bitvec Bitvec;
11970 typedef struct CollSeq CollSeq;
11971 typedef struct Column Column;
11972 typedef struct Db Db;
11973 typedef struct Schema Schema;
11974 typedef struct Expr Expr;
11975 typedef struct ExprList ExprList;
11976 typedef struct ExprSpan ExprSpan;
11977 typedef struct FKey FKey;
11979 typedef struct FuncDef FuncDef;
11980 typedef struct FuncDefHash FuncDefHash;
11981 typedef struct IdList IdList;
11982 typedef struct Index Index;
11983 typedef struct IndexSample IndexSample;
11984 typedef struct KeyClass KeyClass;
11985 typedef struct KeyInfo KeyInfo;
11986 typedef struct Lookaside Lookaside;
11988 typedef struct Module Module;
11989 typedef struct NameContext NameContext;
11990 typedef struct Parse Parse;
11991 typedef struct PreUpdate PreUpdate;
11993 typedef struct RowSet RowSet;
11994 typedef struct Savepoint Savepoint;
11995 typedef struct Select Select;
11997 typedef struct SelectDest SelectDest;
11998 typedef struct SrcList SrcList;
11999 typedef struct StrAccum StrAccum;
12000 typedef struct Table Table;
12001 typedef struct TableLock TableLock;
12002 typedef struct Token Token;
12003 typedef struct TreeView TreeView;
12004 typedef struct Trigger Trigger;
12005 typedef struct TriggerPrg TriggerPrg;
12006 typedef struct TriggerStep TriggerStep;
12008 typedef struct VTable VTable;
12009 typedef struct VtabCtx VtabCtx;
12010 typedef struct Walker Walker;
12011 typedef struct WhereInfo WhereInfo;
12012 typedef struct With With;
12013 
12014 /*
12015 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
12016 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
12017 ** pointer types (i.e. FuncDef) defined above.
12018 */
12019 /************** Include btree.h in the middle of sqliteInt.h *****************/
12020 /************** Begin file btree.h *******************************************/
12021 /*
12022 ** 2001 September 15
12023 **
12024 ** The author disclaims copyright to this source code. In place of
12025 ** a legal notice, here is a blessing:
12026 **
12027 ** May you do good and not evil.
12028 ** May you find forgiveness for yourself and forgive others.
12029 ** May you share freely, never taking more than you give.
12030 **
12031 *************************************************************************
12032 ** This header file defines the interface that the sqlite B-Tree file
12033 ** subsystem. See comments in the source code for a detailed description
12034 ** of what each interface routine does.
12035 */
12036 #ifndef SQLITE_BTREE_H
12037 #define SQLITE_BTREE_H
12038 
12039 /* TODO: This definition is just included so other modules compile. It
12040 ** needs to be revisited.
12041 */
12042 #define SQLITE_N_BTREE_META 16
12043 
12044 /*
12045 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
12046 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
12047 */
12048 #ifndef SQLITE_DEFAULT_AUTOVACUUM
12049  #define SQLITE_DEFAULT_AUTOVACUUM 0
12050 #endif
12051 
12052 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
12053 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
12054 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
12055 
12056 /*
12057 ** Forward declarations of structure
12058 */
12059 typedef struct Btree Btree;
12060 typedef struct BtCursor BtCursor;
12061 typedef struct BtShared BtShared;
12063 
12064 
12066  sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
12067  const char *zFilename, /* Name of database file to open */
12068  sqlite3 *db, /* Associated database connection */
12069  Btree **ppBtree, /* Return open Btree* here */
12070  int flags, /* Flags */
12071  int vfsFlags /* Flags passed through to VFS open */
12072 );
12073 
12074 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
12075 ** following values.
12076 **
12077 ** NOTE: These values must match the corresponding PAGER_ values in
12078 ** pager.h.
12079 */
12080 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
12081 #define BTREE_MEMORY 2 /* This is an in-memory DB */
12082 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
12083 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
12084 
12088 #if SQLITE_MAX_MMAP_SIZE>0
12089 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
12090 #endif
12092 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
12102 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
12107 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
12111 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
12113 #ifndef SQLITE_OMIT_SHARED_CACHE
12114 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
12115 #endif
12116 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
12117 
12121 
12123 
12124 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
12125 ** of the flags shown below.
12126 **
12127 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
12128 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
12129 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
12130 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
12131 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
12132 ** indices.)
12133 */
12134 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
12135 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
12136 
12137 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
12141 
12142 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
12143 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
12144 
12146 
12147 /*
12148 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
12149 ** should be one of the following values. The integer values are assigned
12150 ** to constants so that the offset of the corresponding field in an
12151 ** SQLite database header may be found using the following formula:
12152 **
12153 ** offset = 36 + (idx * 4)
12154 **
12155 ** For example, the free-page-count field is located at byte offset 36 of
12156 ** the database file header. The incr-vacuum-flag field is located at
12157 ** byte offset 64 (== 36+4*7).
12158 **
12159 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
12160 ** It is a read-only number computed by the pager. But we merge it with
12161 ** the header value access routines since its access pattern is the same.
12162 ** Call it a "virtual meta value".
12163 */
12164 #define BTREE_FREE_PAGE_COUNT 0
12165 #define BTREE_SCHEMA_VERSION 1
12166 #define BTREE_FILE_FORMAT 2
12167 #define BTREE_DEFAULT_CACHE_SIZE 3
12168 #define BTREE_LARGEST_ROOT_PAGE 4
12169 #define BTREE_TEXT_ENCODING 5
12170 #define BTREE_USER_VERSION 6
12171 #define BTREE_INCR_VACUUM 7
12172 #define BTREE_APPLICATION_ID 8
12173 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
12174 
12175 /*
12176 ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
12177 ** interface.
12178 **
12179 ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
12180 **
12181 ** The first argument is an Expr* (which is guaranteed to be constant for
12182 ** the lifetime of the cursor) that defines constraints on which rows
12183 ** might be fetched with this cursor. The Expr* tree may contain
12184 ** TK_REGISTER nodes that refer to values stored in the array of registers
12185 ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
12186 ** then the value of the node is the value in Mem[pExpr.iTable]. Any
12187 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
12188 ** column of the b-tree of the cursor. The Expr tree will not contain
12189 ** any function calls nor subqueries nor references to b-trees other than
12190 ** the cursor being hinted.
12191 **
12192 ** The design of the _RANGE hint is aid b-tree implementations that try
12193 ** to prefetch content from remote machines - to provide those
12194 ** implementations with limits on what needs to be prefetched and thereby
12195 ** reduce network bandwidth.
12196 **
12197 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
12198 ** standard SQLite. The other hints are provided for extentions that use
12199 ** the SQLite parser and code generator but substitute their own storage
12200 ** engine.
12201 */
12202 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
12203 
12204 /*
12205 ** Values that may be OR'd together to form the argument to the
12206 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
12207 **
12208 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
12209 ** to be filled with content that is already in sorted order.
12210 **
12211 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
12212 ** OP_SeekLE opcodes for a range search, but where the range of entries
12213 ** selected will all have the same key. In other words, the cursor will
12214 ** be used only for equality key searches.
12215 **
12216 */
12217 #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
12218 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
12219 
12220 /*
12221 ** Flags passed as the third argument to sqlite3BtreeCursor().
12222 **
12223 ** For read-only cursors the wrFlag argument is always zero. For read-write
12224 ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
12225 ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
12226 ** only be used by SQLite for the following:
12227 **
12228 ** * to seek to and then delete specific entries, and/or
12229 **
12230 ** * to read values that will be used to create keys that other
12231 ** BTREE_FORDELETE cursors will seek to and delete.
12232 **
12233 ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
12234 ** by this, the native b-tree engine of SQLite, but it is available to
12235 ** alternative storage engines that might be substituted in place of this
12236 ** b-tree system. For alternative storage engines in which a delete of
12237 ** the main table row automatically deletes corresponding index rows,
12238 ** the FORDELETE flag hint allows those alternative storage engines to
12239 ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
12240 ** and DELETE operations as no-ops, and any READ operation against a
12241 ** FORDELETE cursor may return a null row: 0x01 0x00.
12242 */
12243 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
12244 #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
12245 
12247  Btree*, /* BTree containing table to open */
12248  int iTable, /* Index of root page */
12249  int wrFlag, /* 1 for writing. 0 for read-only */
12250  struct KeyInfo*, /* First argument to compare function */
12251  BtCursor *pCursor /* Space to write cursor structure */
12252 );
12256 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12257 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
12258 #endif
12259 
12262  BtCursor*,
12263  UnpackedRecord *pUnKey,
12264  i64 intKey,
12265  int bias,
12266  int *pRes
12267 );
12271 
12272 /* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */
12273 #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
12274 #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
12275 
12276 /* An instance of the BtreePayload object describes the content of a single
12277 ** entry in either an index or table btree.
12278 **
12279 ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
12280 ** an arbitrary key and no data. These btrees have pKey,nKey set to their
12281 ** key and pData,nData,nZero set to zero.
12282 **
12283 ** Table btrees (used for rowid tables) contain an integer rowid used as
12284 ** the key and passed in the nKey field. The pKey field is zero.
12285 ** pData,nData hold the content of the new entry. nZero extra zero bytes
12286 ** are appended to the end of the content when constructing the entry.
12287 **
12288 ** This object is used to pass information into sqlite3BtreeInsert(). The
12289 ** same information used to be passed as five separate parameters. But placing
12290 ** the information into this object helps to keep the interface more
12291 ** organized and understandable, and it also helps the resulting code to
12292 ** run a little faster by using fewer registers for parameter passing.
12293 */
12295  const void *pKey; /* Key content for indexes. NULL for tables */
12296  sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
12297  const void *pData; /* Data for tables. NULL for indexes */
12298  int nData; /* Size of pData. 0 if none. */
12299  int nZero; /* Extra zero data appended after pData,nData */
12300 };
12301 
12303  int bias, int seekResult);
12304 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
12305 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
12306 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
12310 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
12311 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
12313 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
12314 
12315 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
12317 
12318 #ifndef SQLITE_OMIT_INCRBLOB
12319 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
12321 #endif
12323 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
12324 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
12327 
12328 #ifndef NDEBUG
12329 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
12330 #endif
12331 
12332 #ifndef SQLITE_OMIT_BTREECOUNT
12334 #endif
12335 
12336 #ifdef SQLITE_TEST
12337 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
12338 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
12339 #endif
12340 
12341 #ifndef SQLITE_OMIT_WAL
12342 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
12343 #endif
12344 
12345 /*
12346 ** If we are not using shared cache, then there is no need to
12347 ** use mutexes to access the BtShared structures. So make the
12348 ** Enter and Leave procedures no-ops.
12349 */
12350 #ifndef SQLITE_OMIT_SHARED_CACHE
12356 #else
12357 # define sqlite3BtreeEnter(X)
12358 # define sqlite3BtreeEnterAll(X)
12359 # define sqlite3BtreeSharable(X) 0
12360 # define sqlite3BtreeEnterCursor(X)
12361 # define sqlite3BtreeConnectionCount(X) 1
12362 #endif
12363 
12364 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
12368 #ifndef NDEBUG
12369  /* These routines are used inside assert() statements only. */
12370 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
12371 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
12372 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
12373 #endif
12374 #else
12375 
12376 # define sqlite3BtreeLeave(X)
12377 # define sqlite3BtreeLeaveCursor(X)
12378 # define sqlite3BtreeLeaveAll(X)
12379 
12380 # define sqlite3BtreeHoldsMutex(X) 1
12381 # define sqlite3BtreeHoldsAllMutexes(X) 1
12382 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
12383 #endif
12384 
12385 
12386 #endif /* SQLITE_BTREE_H */
12387 
12388 /************** End of btree.h ***********************************************/
12389 /************** Continuing where we left off in sqliteInt.h ******************/
12390 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
12391 /************** Begin file vdbe.h ********************************************/
12392 /*
12393 ** 2001 September 15
12394 **
12395 ** The author disclaims copyright to this source code. In place of
12396 ** a legal notice, here is a blessing:
12397 **
12398 ** May you do good and not evil.
12399 ** May you find forgiveness for yourself and forgive others.
12400 ** May you share freely, never taking more than you give.
12401 **
12402 *************************************************************************
12403 ** Header file for the Virtual DataBase Engine (VDBE)
12404 **
12405 ** This header defines the interface to the virtual database engine
12406 ** or VDBE. The VDBE implements an abstract machine that runs a
12407 ** simple program to access and modify the underlying database.
12408 */
12409 #ifndef SQLITE_VDBE_H
12410 #define SQLITE_VDBE_H
12411 /* #include <stdio.h> */
12412 
12413 /*
12414 ** A single VDBE is an opaque structure named "Vdbe". Only routines
12415 ** in the source file sqliteVdbe.c are allowed to see the insides
12416 ** of this structure.
12417 */
12418 typedef struct Vdbe Vdbe;
12419 
12420 /*
12421 ** The names of the following types declared in vdbeInt.h are required
12422 ** for the VdbeOp definition.
12423 */
12424 typedef struct Mem Mem;
12425 typedef struct SubProgram SubProgram;
12426 
12427 /*
12428 ** A single instruction of the virtual machine has an opcode
12429 ** and as many as three operands. The instruction is recorded
12430 ** as an instance of the following structure:
12431 */
12432 struct VdbeOp {
12433  u8 opcode; /* What operation to perform */
12434  signed char p4type; /* One of the P4_xxx constants for p4 */
12436  u8 p5; /* Fifth parameter is an unsigned character */
12437  int p1; /* First operand */
12438  int p2; /* Second parameter (often the jump destination) */
12439  int p3; /* The third parameter */
12440  union p4union { /* fourth parameter */
12441  int i; /* Integer value if p4type==P4_INT32 */
12442  void *p; /* Generic pointer */
12443  char *z; /* Pointer to data for string (char array) types */
12444  i64 *pI64; /* Used when p4type is P4_INT64 */
12445  double *pReal; /* Used when p4type is P4_REAL */
12446  FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
12447  sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
12448  CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
12449  Mem *pMem; /* Used when p4type is P4_MEM */
12450  VTable *pVtab; /* Used when p4type is P4_VTAB */
12451  KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
12452  int *ai; /* Used when p4type is P4_INTARRAY */
12453  SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
12454  Table *pTab; /* Used when p4type is P4_TABLE */
12455 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12456  Expr *pExpr; /* Used when p4type is P4_EXPR */
12457 #endif
12458  int (*xAdvance)(BtCursor *, int *);
12459  } p4;
12460 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12461  char *zComment; /* Comment to improve readability */
12462 #endif
12463 #ifdef VDBE_PROFILE
12464  u32 cnt; /* Number of times this instruction was executed */
12465  u64 cycles; /* Total time spent executing this instruction */
12466 #endif
12467 #ifdef SQLITE_VDBE_COVERAGE
12468  int iSrcLine; /* Source-code line that generated this opcode */
12469 #endif
12470 };
12471 typedef struct VdbeOp VdbeOp;
12472 
12473 
12474 /*
12475 ** A sub-routine used to implement a trigger program.
12476 */
12477 struct SubProgram {
12478  VdbeOp *aOp; /* Array of opcodes for sub-program */
12479  int nOp; /* Elements in aOp[] */
12480  int nMem; /* Number of memory cells required */
12481  int nCsr; /* Number of cursors required */
12482  void *token; /* id that may be used to recursive triggers */
12483  SubProgram *pNext; /* Next sub-program already visited */
12484 };
12485 
12486 /*
12487 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
12488 ** it takes up less space.
12489 */
12490 struct VdbeOpList {
12491  u8 opcode; /* What operation to perform */
12492  signed char p1; /* First operand */
12493  signed char p2; /* Second parameter (often the jump destination) */
12494  signed char p3; /* Third parameter */
12495 };
12496 typedef struct VdbeOpList VdbeOpList;
12497 
12498 /*
12499 ** Allowed values of VdbeOp.p4type
12500 */
12501 #define P4_NOTUSED 0 /* The P4 parameter is not used */
12502 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
12503 #define P4_STATIC (-2) /* Pointer to a static string */
12504 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
12505 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
12506 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
12507 #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */
12508 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
12509 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
12510 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
12511 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
12512 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
12513 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
12514 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
12515 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
12516 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
12517 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12518 #define P4_TABLE (-20) /* P4 is a pointer to a Table structure */
12519 #define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */
12520 
12521 /* Error message codes for OP_Halt */
12522 #define P5_ConstraintNotNull 1
12523 #define P5_ConstraintUnique 2
12524 #define P5_ConstraintCheck 3
12525 #define P5_ConstraintFK 4
12526 
12527 /*
12528 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
12529 ** number of columns of data returned by the statement.
12530 */
12531 #define COLNAME_NAME 0
12532 #define COLNAME_DECLTYPE 1
12533 #define COLNAME_DATABASE 2
12534 #define COLNAME_TABLE 3
12535 #define COLNAME_COLUMN 4
12536 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12537 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
12538 #else
12539 # ifdef SQLITE_OMIT_DECLTYPE
12540 # define COLNAME_N 1 /* Store only the name */
12541 # else
12542 # define COLNAME_N 2 /* Store the name and decltype */
12543 # endif
12544 #endif
12545 
12546 /*
12547 ** The following macro converts a relative address in the p2 field
12548 ** of a VdbeOp structure into a negative number so that
12549 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
12550 ** the macro again restores the address.
12551 */
12552 #define ADDR(X) (-1-(X))
12553 
12554 /*
12555 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
12556 ** header file that defines a number for each opcode used by the VDBE.
12557 */
12558 /************** Include opcodes.h in the middle of vdbe.h ********************/
12559 /************** Begin file opcodes.h *****************************************/
12560 /* Automatically generated. Do not edit */
12561 /* See the tool/mkopcodeh.tcl script for details */
12562 #define OP_Savepoint 0
12563 #define OP_AutoCommit 1
12564 #define OP_Transaction 2
12565 #define OP_SorterNext 3
12566 #define OP_PrevIfOpen 4
12567 #define OP_NextIfOpen 5
12568 #define OP_Prev 6
12569 #define OP_Next 7
12570 #define OP_Checkpoint 8
12571 #define OP_JournalMode 9
12572 #define OP_Vacuum 10
12573 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
12574 #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
12575 #define OP_Goto 13
12576 #define OP_Gosub 14
12577 #define OP_InitCoroutine 15
12578 #define OP_Yield 16
12579 #define OP_MustBeInt 17
12580 #define OP_Jump 18
12581 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
12582 #define OP_Once 20
12583 #define OP_If 21
12584 #define OP_IfNot 22
12585 #define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */
12586 #define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */
12587 #define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */
12588 #define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */
12589 #define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12590 #define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12591 #define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */
12592 #define OP_NotFound 30 /* synopsis: key=r[P3@P4] */
12593 #define OP_Found 31 /* synopsis: key=r[P3@P4] */
12594 #define OP_SeekRowid 32 /* synopsis: intkey=r[P3] */
12595 #define OP_NotExists 33 /* synopsis: intkey=r[P3] */
12596 #define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12597 #define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12598 #define OP_Ne 36 /* same as TK_NE, synopsis: IF r[P3]!=r[P1] */
12599 #define OP_Eq 37 /* same as TK_EQ, synopsis: IF r[P3]==r[P1] */
12600 #define OP_Gt 38 /* same as TK_GT, synopsis: IF r[P3]>r[P1] */
12601 #define OP_Le 39 /* same as TK_LE, synopsis: IF r[P3]<=r[P1] */
12602 #define OP_Lt 40 /* same as TK_LT, synopsis: IF r[P3]<r[P1] */
12603 #define OP_Ge 41 /* same as TK_GE, synopsis: IF r[P3]>=r[P1] */
12604 #define OP_ElseNotEq 42 /* same as TK_ESCAPE */
12605 #define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12606 #define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12607 #define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12608 #define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12609 #define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12610 #define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12611 #define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12612 #define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12613 #define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12614 #define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12615 #define OP_Last 53
12616 #define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12617 #define OP_SorterSort 55
12618 #define OP_Sort 56
12619 #define OP_Rewind 57
12620 #define OP_IdxLE 58 /* synopsis: key=r[P3@P4] */
12621 #define OP_IdxGT 59 /* synopsis: key=r[P3@P4] */
12622 #define OP_IdxLT 60 /* synopsis: key=r[P3@P4] */
12623 #define OP_IdxGE 61 /* synopsis: key=r[P3@P4] */
12624 #define OP_RowSetRead 62 /* synopsis: r[P3]=rowset(P1) */
12625 #define OP_RowSetTest 63 /* synopsis: if r[P3] in rowset(P1) goto P2 */
12626 #define OP_Program 64
12627 #define OP_FkIfZero 65 /* synopsis: if fkctr[P1]==0 goto P2 */
12628 #define OP_IfPos 66 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12629 #define OP_IfNotZero 67 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12630 #define OP_DecrJumpZero 68 /* synopsis: if (--r[P1])==0 goto P2 */
12631 #define OP_IncrVacuum 69
12632 #define OP_VNext 70
12633 #define OP_Init 71 /* synopsis: Start at P2 */
12634 #define OP_Return 72
12635 #define OP_EndCoroutine 73
12636 #define OP_HaltIfNull 74 /* synopsis: if r[P3]=null halt */
12637 #define OP_Halt 75
12638 #define OP_Integer 76 /* synopsis: r[P2]=P1 */
12639 #define OP_Int64 77 /* synopsis: r[P2]=P4 */
12640 #define OP_String 78 /* synopsis: r[P2]='P4' (len=P1) */
12641 #define OP_Null 79 /* synopsis: r[P2..P3]=NULL */
12642 #define OP_SoftNull 80 /* synopsis: r[P1]=NULL */
12643 #define OP_Blob 81 /* synopsis: r[P2]=P4 (len=P1) */
12644 #define OP_Variable 82 /* synopsis: r[P2]=parameter(P1,P4) */
12645 #define OP_Move 83 /* synopsis: r[P2@P3]=r[P1@P3] */
12646 #define OP_Copy 84 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
12647 #define OP_SCopy 85 /* synopsis: r[P2]=r[P1] */
12648 #define OP_IntCopy 86 /* synopsis: r[P2]=r[P1] */
12649 #define OP_ResultRow 87 /* synopsis: output=r[P1@P2] */
12650 #define OP_CollSeq 88
12651 #define OP_Function0 89 /* synopsis: r[P3]=func(r[P2@P5]) */
12652 #define OP_Function 90 /* synopsis: r[P3]=func(r[P2@P5]) */
12653 #define OP_AddImm 91 /* synopsis: r[P1]=r[P1]+P2 */
12654 #define OP_RealAffinity 92
12655 #define OP_Cast 93 /* synopsis: affinity(r[P1]) */
12656 #define OP_Permutation 94
12657 #define OP_Compare 95 /* synopsis: r[P1@P3] <-> r[P2@P3] */
12658 #define OP_Column 96 /* synopsis: r[P3]=PX */
12659 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
12660 #define OP_Affinity 98 /* synopsis: affinity(r[P1@P2]) */
12661 #define OP_MakeRecord 99 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
12662 #define OP_Count 100 /* synopsis: r[P2]=count() */
12663 #define OP_ReadCookie 101
12664 #define OP_SetCookie 102
12665 #define OP_ReopenIdx 103 /* synopsis: root=P2 iDb=P3 */
12666 #define OP_OpenRead 104 /* synopsis: root=P2 iDb=P3 */
12667 #define OP_OpenWrite 105 /* synopsis: root=P2 iDb=P3 */
12668 #define OP_OpenAutoindex 106 /* synopsis: nColumn=P2 */
12669 #define OP_OpenEphemeral 107 /* synopsis: nColumn=P2 */
12670 #define OP_SorterOpen 108
12671 #define OP_SequenceTest 109 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
12672 #define OP_OpenPseudo 110 /* synopsis: P3 columns in r[P2] */
12673 #define OP_Close 111
12674 #define OP_ColumnsUsed 112
12675 #define OP_Sequence 113 /* synopsis: r[P2]=cursor[P1].ctr++ */
12676 #define OP_NewRowid 114 /* synopsis: r[P2]=rowid */
12677 #define OP_Insert 115 /* synopsis: intkey=r[P3] data=r[P2] */
12678 #define OP_InsertInt 116 /* synopsis: intkey=P3 data=r[P2] */
12679 #define OP_Delete 117
12680 #define OP_ResetCount 118
12681 #define OP_SorterCompare 119 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12682 #define OP_SorterData 120 /* synopsis: r[P2]=data */
12683 #define OP_RowKey 121 /* synopsis: r[P2]=key */
12684 #define OP_RowData 122 /* synopsis: r[P2]=data */
12685 #define OP_Rowid 123 /* synopsis: r[P2]=rowid */
12686 #define OP_NullRow 124
12687 #define OP_SorterInsert 125
12688 #define OP_IdxInsert 126 /* synopsis: key=r[P2] */
12689 #define OP_IdxDelete 127 /* synopsis: key=r[P2@P3] */
12690 #define OP_Seek 128 /* synopsis: Move P3 to P1.rowid */
12691 #define OP_IdxRowid 129 /* synopsis: r[P2]=rowid */
12692 #define OP_Destroy 130
12693 #define OP_Clear 131
12694 #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
12695 #define OP_ResetSorter 133
12696 #define OP_CreateIndex 134 /* synopsis: r[P2]=root iDb=P1 */
12697 #define OP_CreateTable 135 /* synopsis: r[P2]=root iDb=P1 */
12698 #define OP_ParseSchema 136
12699 #define OP_LoadAnalysis 137
12700 #define OP_DropTable 138
12701 #define OP_DropIndex 139
12702 #define OP_DropTrigger 140
12703 #define OP_IntegrityCk 141
12704 #define OP_RowSetAdd 142 /* synopsis: rowset(P1)=r[P2] */
12705 #define OP_Param 143
12706 #define OP_FkCounter 144 /* synopsis: fkctr[P1]+=P2 */
12707 #define OP_MemMax 145 /* synopsis: r[P1]=max(r[P1],r[P2]) */
12708 #define OP_OffsetLimit 146 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12709 #define OP_AggStep0 147 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12710 #define OP_AggStep 148 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12711 #define OP_AggFinal 149 /* synopsis: accum=r[P1] N=P2 */
12712 #define OP_Expire 150
12713 #define OP_TableLock 151 /* synopsis: iDb=P1 root=P2 write=P3 */
12714 #define OP_VBegin 152
12715 #define OP_VCreate 153
12716 #define OP_VDestroy 154
12717 #define OP_VOpen 155
12718 #define OP_VColumn 156 /* synopsis: r[P3]=vcolumn(P2) */
12719 #define OP_VRename 157
12720 #define OP_Pagecount 158
12721 #define OP_MaxPgcnt 159
12722 #define OP_CursorHint 160
12723 #define OP_Noop 161
12724 #define OP_Explain 162
12725 
12726 /* Properties such as "out2" or "jump" that are specified in
12727 ** comments following the "case" for each opcode in the vdbe.c
12728 ** are encoded into bitvectors as follows:
12729 */
12730 #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
12731 #define OPFLG_IN1 0x02 /* in1: P1 is an input */
12732 #define OPFLG_IN2 0x04 /* in2: P2 is an input */
12733 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
12734 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
12735 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
12736 #define OPFLG_INITIALIZER {\
12737 /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12738 /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12739 /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12740 /* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12741 /* 32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12742 /* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12743 /* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12744 /* 56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b,\
12745 /* 64 */ 0x01, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01,\
12746 /* 72 */ 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10,\
12747 /* 80 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00,\
12748 /* 88 */ 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
12749 /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12750 /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12751 /* 112 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
12752 /* 120 */ 0x00, 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00,\
12753 /* 128 */ 0x00, 0x10, 0x10, 0x00, 0x10, 0x00, 0x10, 0x10,\
12754 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10,\
12755 /* 144 */ 0x00, 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00,\
12756 /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
12757 /* 160 */ 0x00, 0x00, 0x00,}
12758 
12759 /* The sqlite3P2Values() routine is able to run faster if it knows
12760 ** the value of the largest JUMP opcode. The smaller the maximum
12761 ** JUMP opcode the better, so the mkopcodeh.tcl script that
12762 ** generated this include file strives to group all JUMP opcodes
12763 ** together near the beginning of the list.
12764 */
12765 #define SQLITE_MX_JUMP_OPCODE 71 /* Maximum JUMP opcode */
12766 
12767 /************** End of opcodes.h *********************************************/
12768 /************** Continuing where we left off in vdbe.h ***********************/
12769 
12770 /*
12771 ** Prototypes for the VDBE interface. See comments on the implementation
12772 ** for a description of what each of these routines does.
12773 */
12776 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
12777 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
12779 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
12780 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
12781 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
12782 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
12783 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
12784 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
12786 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
12788 #else
12789 # define sqlite3VdbeVerifyNoMallocRequired(A,B)
12790 #endif
12791 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
12793 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
12794 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
12795 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
12796 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
12798 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
12801 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
12814 #ifdef SQLITE_DEBUG
12815 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
12816 #endif
12821 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
12824 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
12829 #ifndef SQLITE_OMIT_TRACE
12830 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
12831 #endif
12832 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12833 
12836 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
12838 
12839 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
12841 
12842 #ifndef SQLITE_OMIT_TRIGGER
12844 #endif
12845 
12846 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
12847 ** each VDBE opcode.
12848 **
12849 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
12850 ** comments in VDBE programs that show key decision points in the code
12851 ** generator.
12852 */
12853 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12854 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
12855 # define VdbeComment(X) sqlite3VdbeComment X
12856 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
12857 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
12858 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
12859 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
12860 # else
12861 # define VdbeModuleComment(X)
12862 # endif
12863 #else
12864 # define VdbeComment(X)
12865 # define VdbeNoopComment(X)
12866 # define VdbeModuleComment(X)
12867 #endif
12868 
12869 /*
12870 ** The VdbeCoverage macros are used to set a coverage testing point
12871 ** for VDBE branch instructions. The coverage testing points are line
12872 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
12873 ** only works with an amalagmation build. That's ok since a VDBE branch
12874 ** coverage build designed for testing the test suite only. No application
12875 ** should ever ship with VDBE branch coverage measuring turned on.
12876 **
12877 ** VdbeCoverage(v) // Mark the previously coded instruction
12878 ** // as a branch
12879 **
12880 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
12881 **
12882 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
12883 **
12884 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
12885 **
12886 ** Every VDBE branch operation must be tagged with one of the macros above.
12887 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
12888 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
12889 ** routine in vdbe.c, alerting the developer to the missed tag.
12890 */
12891 #ifdef SQLITE_VDBE_COVERAGE
12892 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
12893 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
12894 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
12895 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
12896 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
12897 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
12898 #else
12899 # define VdbeCoverage(v)
12900 # define VdbeCoverageIf(v,x)
12901 # define VdbeCoverageAlwaysTaken(v)
12902 # define VdbeCoverageNeverTaken(v)
12903 # define VDBE_OFFSET_LINENO(x) 0
12904 #endif
12905 
12906 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
12907 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
12908 #else
12909 # define sqlite3VdbeScanStatus(a,b,c,d,e)
12910 #endif
12911 
12912 #endif /* SQLITE_VDBE_H */
12913 
12914 /************** End of vdbe.h ************************************************/
12915 /************** Continuing where we left off in sqliteInt.h ******************/
12916 /************** Include pager.h in the middle of sqliteInt.h *****************/
12917 /************** Begin file pager.h *******************************************/
12918 /*
12919 ** 2001 September 15
12920 **
12921 ** The author disclaims copyright to this source code. In place of
12922 ** a legal notice, here is a blessing:
12923 **
12924 ** May you do good and not evil.
12925 ** May you find forgiveness for yourself and forgive others.
12926 ** May you share freely, never taking more than you give.
12927 **
12928 *************************************************************************
12929 ** This header file defines the interface that the sqlite page cache
12930 ** subsystem. The page cache subsystem reads and writes a file a page
12931 ** at a time and provides a journal for rollback.
12932 */
12933 
12934 #ifndef SQLITE_PAGER_H
12935 #define SQLITE_PAGER_H
12936 
12937 /*
12938 ** Default maximum size for persistent journal files. A negative
12939 ** value means no limit. This value may be overridden using the
12940 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
12941 */
12942 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
12943  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
12944 #endif
12945 
12946 /*
12947 ** The type used to represent a page number. The first page in a file
12948 ** is called page 1. 0 is used to represent "not a page".
12949 */
12950 typedef u32 Pgno;
12951 
12952 /*
12953 ** Each open file is managed by a separate instance of the "Pager" structure.
12954 */
12955 typedef struct Pager Pager;
12956 
12957 /*
12958 ** Handle type for pages.
12959 */
12960 typedef struct PgHdr DbPage;
12961 
12962 /*
12963 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
12964 ** reserved for working around a windows/posix incompatibility). It is
12965 ** used in the journal to signify that the remainder of the journal file
12966 ** is devoted to storing a master journal name - there are no more pages to
12967 ** roll back. See comments for function writeMasterJournal() in pager.c
12968 ** for details.
12969 */
12970 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
12971 
12972 /*
12973 ** Allowed values for the flags parameter to sqlite3PagerOpen().
12974 **
12975 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
12976 */
12977 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
12978 #define PAGER_MEMORY 0x0002 /* In-memory database */
12979 
12980 /*
12981 ** Valid values for the second argument to sqlite3PagerLockingMode().
12982 */
12983 #define PAGER_LOCKINGMODE_QUERY -1
12984 #define PAGER_LOCKINGMODE_NORMAL 0
12985 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
12986 
12987 /*
12988 ** Numeric constants that encode the journalmode.
12989 **
12990 ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
12991 ** are exposed in the API via the "PRAGMA journal_mode" command and
12992 ** therefore cannot be changed without a compatibility break.
12993 */
12994 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
12995 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
12996 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
12997 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
12998 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
12999 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
13000 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
13001 
13002 /*
13003 ** Flags that make up the mask passed to sqlite3PagerGet().
13004 */
13005 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
13006 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
13007 
13008 /*
13009 ** Flags for sqlite3PagerSetFlags()
13010 **
13011 ** Value constraints (enforced via assert()):
13012 ** PAGER_FULLFSYNC == SQLITE_FullFSync
13013 ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
13014 ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
13015 */
13016 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
13017 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
13018 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
13019 #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
13020 #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
13021 #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
13022 #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
13023 #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
13024 #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
13025 
13026 /*
13027 ** The remainder of this file contains the declarations of the functions
13028 ** that make up the Pager sub-system API. See source code comments for
13029 ** a detailed description of each routine.
13030 */
13031 
13032 /* Open and close a Pager connection. */
13034  sqlite3_vfs*,
13035  Pager **ppPager,
13036  const char*,
13037  int,
13038  int,
13039  int,
13040  void(*)(DbPage*)
13041 );
13043 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
13044 
13045 /* Functions used to configure a Pager object. */
13046 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
13048 #ifdef SQLITE_HAS_CODEC
13049 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
13050 #endif
13054 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
13056 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
13064 
13065 /* Functions used to obtain and release page references. */
13066 SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
13071 
13072 /* Operations on page references. */
13079 
13080 /* Functions used to manage pager transactions and savepoints. */
13082 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
13083 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
13085 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
13089 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
13091 
13092 #ifndef SQLITE_OMIT_WAL
13093 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
13096 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
13099 # ifdef SQLITE_ENABLE_SNAPSHOT
13100 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
13101 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
13102 # endif
13103 #else
13104 # define sqlite3PagerUseWal(x) 0
13105 #endif
13106 
13107 #ifdef SQLITE_ENABLE_ZIPVFS
13108 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
13109 #endif
13110 
13111 /* Functions used to query pager state and configuration. */
13114 #ifdef SQLITE_DEBUG
13115 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
13116 #endif
13118 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
13119 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
13120 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
13121 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
13125 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
13127 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
13128 
13129 /* Functions used to truncate the database file. */
13131 
13132 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
13133 
13134 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
13135 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
13136 #endif
13137 
13138 /* Functions to support testing and debugging. */
13139 #if !defined(NDEBUG) || defined(SQLITE_TEST)
13140 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
13141 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
13142 #endif
13143 #ifdef SQLITE_TEST
13144 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
13145 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
13146  void disable_simulated_io_errors(void);
13147  void enable_simulated_io_errors(void);
13148 #else
13149 # define disable_simulated_io_errors()
13150 # define enable_simulated_io_errors()
13151 #endif
13152 
13153 #endif /* SQLITE_PAGER_H */
13154 
13155 /************** End of pager.h ***********************************************/
13156 /************** Continuing where we left off in sqliteInt.h ******************/
13157 /************** Include pcache.h in the middle of sqliteInt.h ****************/
13158 /************** Begin file pcache.h ******************************************/
13159 /*
13160 ** 2008 August 05
13161 **
13162 ** The author disclaims copyright to this source code. In place of
13163 ** a legal notice, here is a blessing:
13164 **
13165 ** May you do good and not evil.
13166 ** May you find forgiveness for yourself and forgive others.
13167 ** May you share freely, never taking more than you give.
13168 **
13169 *************************************************************************
13170 ** This header file defines the interface that the sqlite page cache
13171 ** subsystem.
13172 */
13173 
13174 #ifndef _PCACHE_H_
13175 
13176 typedef struct PgHdr PgHdr;
13177 typedef struct PCache PCache;
13178 
13179 /*
13180 ** Every page in the cache is controlled by an instance of the following
13181 ** structure.
13182 */
13183 struct PgHdr {
13184  sqlite3_pcache_page *pPage; /* Pcache object page handle */
13185  void *pData; /* Page data */
13186  void *pExtra; /* Extra content */
13187  PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
13188  Pager *pPager; /* The pager this page is part of */
13189  Pgno pgno; /* Page number for this page */
13190 #ifdef SQLITE_CHECK_PAGES
13191  u32 pageHash; /* Hash of page content */
13192 #endif
13193  u16 flags; /* PGHDR flags defined below */
13194 
13195  /**********************************************************************
13196  ** Elements above are public. All that follows is private to pcache.c
13197  ** and should not be accessed by other modules.
13198  */
13199  i16 nRef; /* Number of users of this page */
13200  PCache *pCache; /* Cache that owns this page */
13201 
13202  PgHdr *pDirtyNext; /* Next element in list of dirty pages */
13203  PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
13204 };
13205 
13206 /* Bit values for PgHdr.flags */
13207 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
13208 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
13209 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
13210 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
13211  ** writing this page to the database */
13212 #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
13213 #define PGHDR_MMAP 0x020 /* This is an mmap page object */
13214 
13215 #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
13216 
13217 /* Initialize and shutdown the page cache subsystem */
13220 
13221 /* Page cache buffer management:
13222 ** These routines implement SQLITE_CONFIG_PAGECACHE.
13223 */
13224 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
13225 
13226 /* Create a new pager cache.
13227 ** Under memory stress, invoke xStress to try to make pages clean.
13228 ** Only clean and unpinned pages can be reclaimed.
13229 */
13231  int szPage, /* Size of every page */
13232  int szExtra, /* Extra space associated with each page */
13233  int bPurgeable, /* True if pages are on backing store */
13234  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
13235  void *pStress, /* Argument to xStress */
13236  PCache *pToInit /* Preallocated space for the PCache */
13237 );
13238 
13239 /* Modify the page-size after the cache has been created. */
13241 
13242 /* Return the size in bytes of a PCache object. Used to preallocate
13243 ** storage space.
13244 */
13246 
13247 /* One release per successful fetch. Page is pinned until released.
13248 ** Reference counted.
13249 */
13254 
13255 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
13256 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
13257 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
13258 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
13260 
13261 /* Change a page number. Used by incr-vacuum. */
13263 
13264 /* Remove all pages with pgno>x. Reset the cache if x==0 */
13266 
13267 /* Get a list of all dirty pages in the cache, sorted by page number */
13269 
13270 /* Reset and close the cache object */
13272 
13273 /* Clear flags from pages of the page cache */
13275 
13276 /* Discard the contents of the cache */
13278 
13279 /* Return the total number of outstanding page references */
13281 
13282 /* Increment the reference count of an existing page */
13284 
13286 
13287 /* Return the total number of pages stored in the cache */
13289 
13290 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
13291 /* Iterate through all dirty pages currently stored in the cache. This
13292 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
13293 ** library is built.
13294 */
13295 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13296 #endif
13297 
13298 #if defined(SQLITE_DEBUG)
13299 /* Check invariants on a PgHdr object */
13300 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13301 #endif
13302 
13303 /* Set and get the suggested cache-size for the specified pager-cache.
13304 **
13305 ** If no global maximum is configured, then the system attempts to limit
13306 ** the total number of pages cached by purgeable pager-caches to the sum
13307 ** of the suggested cache-sizes.
13308 */
13310 #ifdef SQLITE_TEST
13311 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
13312 #endif
13313 
13314 /* Set or get the suggested spill-size for the specified pager-cache.
13315 **
13316 ** The spill-size is the minimum number of pages in cache before the cache
13317 ** will attempt to spill dirty pages by calling xStress.
13318 */
13320 
13321 /* Free up as much memory as possible from the page cache */
13323 
13324 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13325 /* Try to return memory used by the pcache module to the main memory heap */
13326 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
13327 #endif
13328 
13329 #ifdef SQLITE_TEST
13330 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
13331 #endif
13332 
13334 
13335 /* Return the header size */
13338 
13339 /* Number of dirty pages as a percentage of the configured cache size */
13341 
13342 #endif /* _PCACHE_H_ */
13343 
13344 /************** End of pcache.h **********************************************/
13345 /************** Continuing where we left off in sqliteInt.h ******************/
13346 /************** Include os.h in the middle of sqliteInt.h ********************/
13347 /************** Begin file os.h **********************************************/
13348 /*
13349 ** 2001 September 16
13350 **
13351 ** The author disclaims copyright to this source code. In place of
13352 ** a legal notice, here is a blessing:
13353 **
13354 ** May you do good and not evil.
13355 ** May you find forgiveness for yourself and forgive others.
13356 ** May you share freely, never taking more than you give.
13357 **
13358 ******************************************************************************
13359 **
13360 ** This header file (together with is companion C source-code file
13361 ** "os.c") attempt to abstract the underlying operating system so that
13362 ** the SQLite library will work on both POSIX and windows systems.
13363 **
13364 ** This header file is #include-ed by sqliteInt.h and thus ends up
13365 ** being included by every source file.
13366 */
13367 #ifndef _SQLITE_OS_H_
13368 #define _SQLITE_OS_H_
13369 
13370 /*
13371 ** Attempt to automatically detect the operating system and setup the
13372 ** necessary pre-processor macros for it.
13373 */
13374 /************** Include os_setup.h in the middle of os.h *********************/
13375 /************** Begin file os_setup.h ****************************************/
13376 /*
13377 ** 2013 November 25
13378 **
13379 ** The author disclaims copyright to this source code. In place of
13380 ** a legal notice, here is a blessing:
13381 **
13382 ** May you do good and not evil.
13383 ** May you find forgiveness for yourself and forgive others.
13384 ** May you share freely, never taking more than you give.
13385 **
13386 ******************************************************************************
13387 **
13388 ** This file contains pre-processor directives related to operating system
13389 ** detection and/or setup.
13390 */
13391 #ifndef SQLITE_OS_SETUP_H
13392 #define SQLITE_OS_SETUP_H
13393 
13394 /*
13395 ** Figure out if we are dealing with Unix, Windows, or some other operating
13396 ** system.
13397 **
13398 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
13399 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
13400 ** the three will be 1. The other two will be 0.
13401 */
13402 #if defined(SQLITE_OS_OTHER)
13403 # if SQLITE_OS_OTHER==1
13404 # undef SQLITE_OS_UNIX
13405 # define SQLITE_OS_UNIX 0
13406 # undef SQLITE_OS_WIN
13407 # define SQLITE_OS_WIN 0
13408 # else
13409 # undef SQLITE_OS_OTHER
13410 # endif
13411 #endif
13412 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
13413 # define SQLITE_OS_OTHER 0
13414 # ifndef SQLITE_OS_WIN
13415 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
13416  defined(__MINGW32__) || defined(__BORLANDC__)
13417 # define SQLITE_OS_WIN 1
13418 # define SQLITE_OS_UNIX 0
13419 # else
13420 # define SQLITE_OS_WIN 0
13421 # define SQLITE_OS_UNIX 1
13422 # endif
13423 # else
13424 # define SQLITE_OS_UNIX 0
13425 # endif
13426 #else
13427 # ifndef SQLITE_OS_WIN
13428 # define SQLITE_OS_WIN 0
13429 # endif
13430 #endif
13431 
13432 #endif /* SQLITE_OS_SETUP_H */
13433 
13434 /************** End of os_setup.h ********************************************/
13435 /************** Continuing where we left off in os.h *************************/
13436 
13437 /* If the SET_FULLSYNC macro is not defined above, then make it
13438 ** a no-op
13439 */
13440 #ifndef SET_FULLSYNC
13441 # define SET_FULLSYNC(x,y)
13442 #endif
13443 
13444 /*
13445 ** The default size of a disk sector
13446 */
13447 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
13448 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
13449 #endif
13450 
13451 /*
13452 ** Temporary files are named starting with this prefix followed by 16 random
13453 ** alphanumeric characters, and no file extension. They are stored in the
13454 ** OS's standard temporary file directory, and are deleted prior to exit.
13455 ** If sqlite is being embedded in another program, you may wish to change the
13456 ** prefix to reflect your program's name, so that if your program exits
13457 ** prematurely, old temporary files can be easily identified. This can be done
13458 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
13459 **
13460 ** 2006-10-31: The default prefix used to be "sqlite_". But then
13461 ** Mcafee started using SQLite in their anti-virus product and it
13462 ** started putting files with the "sqlite" name in the c:/temp folder.
13463 ** This annoyed many windows users. Those users would then do a
13464 ** Google search for "sqlite", find the telephone numbers of the
13465 ** developers and call to wake them up at night and complain.
13466 ** For this reason, the default name prefix is changed to be "sqlite"
13467 ** spelled backwards. So the temp files are still identified, but
13468 ** anybody smart enough to figure out the code is also likely smart
13469 ** enough to know that calling the developer will not help get rid
13470 ** of the file.
13471 */
13472 #ifndef SQLITE_TEMP_FILE_PREFIX
13473 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
13474 #endif
13475 
13476 /*
13477 ** The following values may be passed as the second argument to
13478 ** sqlite3OsLock(). The various locks exhibit the following semantics:
13479 **
13480 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
13481 ** RESERVED: A single process may hold a RESERVED lock on a file at
13482 ** any time. Other processes may hold and obtain new SHARED locks.
13483 ** PENDING: A single process may hold a PENDING lock on a file at
13484 ** any one time. Existing SHARED locks may persist, but no new
13485 ** SHARED locks may be obtained by other processes.
13486 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
13487 **
13488 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
13489 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
13490 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
13491 ** sqlite3OsLock().
13492 */
13493 #define NO_LOCK 0
13494 #define SHARED_LOCK 1
13495 #define RESERVED_LOCK 2
13496 #define PENDING_LOCK 3
13497 #define EXCLUSIVE_LOCK 4
13498 
13499 /*
13500 ** File Locking Notes: (Mostly about windows but also some info for Unix)
13501 **
13502 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
13503 ** those functions are not available. So we use only LockFile() and
13504 ** UnlockFile().
13505 **
13506 ** LockFile() prevents not just writing but also reading by other processes.
13507 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
13508 ** byte out of a specific range of bytes. The lock byte is obtained at
13509 ** random so two separate readers can probably access the file at the
13510 ** same time, unless they are unlucky and choose the same lock byte.
13511 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
13512 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
13513 ** a single byte of the file that is designated as the reserved lock byte.
13514 ** A PENDING_LOCK is obtained by locking a designated byte different from
13515 ** the RESERVED_LOCK byte.
13516 **
13517 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
13518 ** which means we can use reader/writer locks. When reader/writer locks
13519 ** are used, the lock is placed on the same range of bytes that is used
13520 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
13521 ** will support two or more Win95 readers or two or more WinNT readers.
13522 ** But a single Win95 reader will lock out all WinNT readers and a single
13523 ** WinNT reader will lock out all other Win95 readers.
13524 **
13525 ** The following #defines specify the range of bytes used for locking.
13526 ** SHARED_SIZE is the number of bytes available in the pool from which
13527 ** a random byte is selected for a shared lock. The pool of bytes for
13528 ** shared locks begins at SHARED_FIRST.
13529 **
13530 ** The same locking strategy and
13531 ** byte ranges are used for Unix. This leaves open the possibility of having
13532 ** clients on win95, winNT, and unix all talking to the same shared file
13533 ** and all locking correctly. To do so would require that samba (or whatever
13534 ** tool is being used for file sharing) implements locks correctly between
13535 ** windows and unix. I'm guessing that isn't likely to happen, but by
13536 ** using the same locking range we are at least open to the possibility.
13537 **
13538 ** Locking in windows is manditory. For this reason, we cannot store
13539 ** actual data in the bytes used for locking. The pager never allocates
13540 ** the pages involved in locking therefore. SHARED_SIZE is selected so
13541 ** that all locks will fit on a single page even at the minimum page size.
13542 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
13543 ** is set high so that we don't have to allocate an unused page except
13544 ** for very large databases. But one should test the page skipping logic
13545 ** by setting PENDING_BYTE low and running the entire regression suite.
13546 **
13547 ** Changing the value of PENDING_BYTE results in a subtly incompatible
13548 ** file format. Depending on how it is changed, you might not notice
13549 ** the incompatibility right away, even running a full regression test.
13550 ** The default location of PENDING_BYTE is the first byte past the
13551 ** 1GB boundary.
13552 **
13553 */
13554 #ifdef SQLITE_OMIT_WSD
13555 # define PENDING_BYTE (0x40000000)
13556 #else
13557 # define PENDING_BYTE sqlite3PendingByte
13558 #endif
13559 #define RESERVED_BYTE (PENDING_BYTE+1)
13560 #define SHARED_FIRST (PENDING_BYTE+2)
13561 #define SHARED_SIZE 510
13562 
13563 /*
13564 ** Wrapper around OS specific sqlite3_os_init() function.
13565 */
13566 SQLITE_PRIVATE int sqlite3OsInit(void);
13567 
13568 /*
13569 ** Functions for accessing sqlite3_file methods
13570 */
13571 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13572 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13573 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13574 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13575 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13576 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
13577 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
13578 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
13579 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
13580 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
13581 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
13582 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
13583 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
13584 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
13585 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
13586 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
13587 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
13588 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
13589 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
13590 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
13591 
13592 
13593 /*
13594 ** Functions for accessing sqlite3_vfs methods
13595 */
13596 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
13597 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
13598 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
13599 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
13600 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13601 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
13602 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
13603 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
13604 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
13605 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13606 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
13607 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
13608 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
13609 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
13610 
13611 /*
13612 ** Convenience functions for opening and closing files using
13613 ** sqlite3_malloc() to obtain space for the file-handle structure.
13614 */
13615 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13616 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13617 
13618 #endif /* _SQLITE_OS_H_ */
13619 
13620 /************** End of os.h **************************************************/
13621 /************** Continuing where we left off in sqliteInt.h ******************/
13622 /************** Include mutex.h in the middle of sqliteInt.h *****************/
13623 /************** Begin file mutex.h *******************************************/
13624 /*
13625 ** 2007 August 28
13626 **
13627 ** The author disclaims copyright to this source code. In place of
13628 ** a legal notice, here is a blessing:
13629 **
13630 ** May you do good and not evil.
13631 ** May you find forgiveness for yourself and forgive others.
13632 ** May you share freely, never taking more than you give.
13633 **
13634 *************************************************************************
13635 **
13636 ** This file contains the common header for all mutex implementations.
13637 ** The sqliteInt.h header #includes this file so that it is available
13638 ** to all source files. We break it out in an effort to keep the code
13639 ** better organized.
13640 **
13641 ** NOTE: source files should *not* #include this header file directly.
13642 ** Source files should #include the sqliteInt.h file and let that file
13643 ** include this one indirectly.
13644 */
13645 
13646 
13647 /*
13648 ** Figure out what version of the code to use. The choices are
13649 **
13650 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
13651 ** mutexes implementation cannot be overridden
13652 ** at start-time.
13653 **
13654 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
13655 ** mutual exclusion is provided. But this
13656 ** implementation can be overridden at
13657 ** start-time.
13658 **
13659 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
13660 **
13661 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
13662 */
13663 #if !SQLITE_THREADSAFE
13664 # define SQLITE_MUTEX_OMIT
13665 #endif
13666 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
13667 # if SQLITE_OS_UNIX
13668 # define SQLITE_MUTEX_PTHREADS
13669 # elif SQLITE_OS_WIN
13670 # define SQLITE_MUTEX_W32
13671 # else
13672 # define SQLITE_MUTEX_NOOP
13673 # endif
13674 #endif
13675 
13676 #ifdef SQLITE_MUTEX_OMIT
13677 /*
13678 ** If this is a no-op implementation, implement everything as macros.
13679 */
13680 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
13681 #define sqlite3_mutex_free(X)
13682 #define sqlite3_mutex_enter(X)
13683 #define sqlite3_mutex_try(X) SQLITE_OK
13684 #define sqlite3_mutex_leave(X)
13685 #define sqlite3_mutex_held(X) ((void)(X),1)
13686 #define sqlite3_mutex_notheld(X) ((void)(X),1)
13687 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
13688 #define sqlite3MutexInit() SQLITE_OK
13689 #define sqlite3MutexEnd()
13690 #define MUTEX_LOGIC(X)
13691 #else
13692 #define MUTEX_LOGIC(X) X
13693 #endif /* defined(SQLITE_MUTEX_OMIT) */
13694 
13695 /************** End of mutex.h ***********************************************/
13696 /************** Continuing where we left off in sqliteInt.h ******************/
13697 
13698 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
13699 ** synchronous setting to EXTRA. It is no longer supported.
13700 */
13701 #ifdef SQLITE_EXTRA_DURABLE
13702 # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
13703 # define SQLITE_DEFAULT_SYNCHRONOUS 3
13704 #endif
13705 
13706 /*
13707 ** Default synchronous levels.
13708 **
13709 ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
13710 ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
13711 **
13712 ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
13713 ** OFF 1 0
13714 ** NORMAL 2 1
13715 ** FULL 3 2
13716 ** EXTRA 4 3
13717 **
13718 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
13719 ** In other words, the zero-based numbers are used for all external interfaces
13720 ** and the one-based values are used internally.
13721 */
13722 #ifndef SQLITE_DEFAULT_SYNCHRONOUS
13723 # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
13724 #endif
13725 #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
13726 # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
13727 #endif
13728 
13729 /*
13730 ** Each database file to be accessed by the system is an instance
13731 ** of the following structure. There are normally two of these structures
13732 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
13733 ** aDb[1] is the database file used to hold temporary tables. Additional
13734 ** databases may be attached.
13735 */
13736 struct Db {
13737  char *zDbSName; /* Name of this database. (schema name, not filename) */
13738  Btree *pBt; /* The B*Tree structure for this database file */
13739  u8 safety_level; /* How aggressive at syncing data to disk */
13740  u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
13741  Schema *pSchema; /* Pointer to database schema (possibly shared) */
13742 };
13743 
13744 /*
13745 ** An instance of the following structure stores a database schema.
13746 **
13747 ** Most Schema objects are associated with a Btree. The exception is
13748 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
13749 ** In shared cache mode, a single Schema object can be shared by multiple
13750 ** Btrees that refer to the same underlying BtShared object.
13751 **
13752 ** Schema objects are automatically deallocated when the last Btree that
13753 ** references them is destroyed. The TEMP Schema is manually freed by
13754 ** sqlite3_close().
13755 *
13756 ** A thread must be holding a mutex on the corresponding Btree in order
13757 ** to access Schema content. This implies that the thread must also be
13758 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
13759 ** For a TEMP Schema, only the connection mutex is required.
13760 */
13761 struct Schema {
13762  int schema_cookie; /* Database schema version number for this file */
13763  int iGeneration; /* Generation counter. Incremented with each change */
13764  Hash tblHash; /* All tables indexed by name */
13765  Hash idxHash; /* All (named) indices indexed by name */
13766  Hash trigHash; /* All triggers indexed by name */
13767  Hash fkeyHash; /* All foreign keys by referenced table name */
13768  Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
13769  u8 file_format; /* Schema format version for this file */
13770  u8 enc; /* Text encoding used by this database */
13771  u16 schemaFlags; /* Flags associated with this schema */
13772  int cache_size; /* Number of pages to use in the cache */
13773 };
13774 
13775 /*
13776 ** These macros can be used to test, set, or clear bits in the
13777 ** Db.pSchema->flags field.
13778 */
13779 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
13780 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
13781 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
13782 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
13783 
13784 /*
13785 ** Allowed values for the DB.pSchema->flags field.
13786 **
13787 ** The DB_SchemaLoaded flag is set after the database schema has been
13788 ** read into internal hash tables.
13789 **
13790 ** DB_UnresetViews means that one or more views have column names that
13791 ** have been filled out. If the schema changes, these column names might
13792 ** changes and so the view will need to be reset.
13793 */
13794 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
13795 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
13796 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
13797 
13798 /*
13799 ** The number of different kinds of things that can be limited
13800 ** using the sqlite3_limit() interface.
13801 */
13802 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
13803 
13804 /*
13805 ** Lookaside malloc is a set of fixed-size buffers that can be used
13806 ** to satisfy small transient memory allocation requests for objects
13807 ** associated with a particular database connection. The use of
13808 ** lookaside malloc provides a significant performance enhancement
13809 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
13810 ** SQL statements.
13811 **
13812 ** The Lookaside structure holds configuration information about the
13813 ** lookaside malloc subsystem. Each available memory allocation in
13814 ** the lookaside subsystem is stored on a linked list of LookasideSlot
13815 ** objects.
13816 **
13817 ** Lookaside allocations are only allowed for objects that are associated
13818 ** with a particular database connection. Hence, schema information cannot
13819 ** be stored in lookaside because in shared cache mode the schema information
13820 ** is shared by multiple database connections. Therefore, while parsing
13821 ** schema information, the Lookaside.bEnabled flag is cleared so that
13822 ** lookaside allocations are not used to construct the schema objects.
13823 */
13824 struct Lookaside {
13825  u32 bDisable; /* Only operate the lookaside when zero */
13826  u16 sz; /* Size of each buffer in bytes */
13827  u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
13828  int nOut; /* Number of buffers currently checked out */
13829  int mxOut; /* Highwater mark for nOut */
13830  int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
13831  LookasideSlot *pFree; /* List of available buffers */
13832  void *pStart; /* First byte of available memory space */
13833  void *pEnd; /* First byte past end of available space */
13834 };
13836  LookasideSlot *pNext; /* Next buffer in the list of free buffers */
13837 };
13838 
13839 /*
13840 ** A hash table for built-in function definitions. (Application-defined
13841 ** functions use a regular table table from hash.h.)
13842 **
13843 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
13844 ** Collisions are on the FuncDef.u.pHash chain.
13845 */
13846 #define SQLITE_FUNC_HASH_SZ 23
13847 struct FuncDefHash {
13848  FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
13849 };
13850 
13851 #ifdef SQLITE_USER_AUTHENTICATION
13852 /*
13853 ** Information held in the "sqlite3" database connection object and used
13854 ** to manage user authentication.
13855 */
13856 typedef struct sqlite3_userauth sqlite3_userauth;
13857 struct sqlite3_userauth {
13858  u8 authLevel; /* Current authentication level */
13859  int nAuthPW; /* Size of the zAuthPW in bytes */
13860  char *zAuthPW; /* Password used to authenticate */
13861  char *zAuthUser; /* User name used to authenticate */
13862 };
13863 
13864 /* Allowed values for sqlite3_userauth.authLevel */
13865 #define UAUTH_Unknown 0 /* Authentication not yet checked */
13866 #define UAUTH_Fail 1 /* User authentication failed */
13867 #define UAUTH_User 2 /* Authenticated as a normal user */
13868 #define UAUTH_Admin 3 /* Authenticated as an administrator */
13869 
13870 /* Functions used only by user authorization logic */
13871 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
13872 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
13873 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
13874 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
13875 
13876 #endif /* SQLITE_USER_AUTHENTICATION */
13877 
13878 /*
13879 ** typedef for the authorization callback function.
13880 */
13881 #ifdef SQLITE_USER_AUTHENTICATION
13882  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13883  const char*, const char*);
13884 #else
13885  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13886  const char*);
13887 #endif
13888 
13889 #ifndef SQLITE_OMIT_DEPRECATED
13890 /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
13891 ** in the style of sqlite3_trace()
13892 */
13893 #define SQLITE_TRACE_LEGACY 0x80
13894 #else
13895 #define SQLITE_TRACE_LEGACY 0
13896 #endif /* SQLITE_OMIT_DEPRECATED */
13897 
13898 
13899 /*
13900 ** Each database connection is an instance of the following structure.
13901 */
13902 struct sqlite3 {
13903  sqlite3_vfs *pVfs; /* OS Interface */
13904  struct Vdbe *pVdbe; /* List of active virtual machines */
13905  CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
13906  sqlite3_mutex *mutex; /* Connection mutex */
13907  Db *aDb; /* All backends */
13908  int nDb; /* Number of backends currently in use */
13909  int flags; /* Miscellaneous flags. See below */
13910  i64 lastRowid; /* ROWID of most recent insert (see above) */
13911  i64 szMmap; /* Default mmap_size setting */
13912  unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
13913  int errCode; /* Most recent error code (SQLITE_*) */
13914  int errMask; /* & result codes with this before returning */
13915  int iSysErrno; /* Errno value from last system error */
13916  u16 dbOptFlags; /* Flags to enable/disable optimizations */
13917  u8 enc; /* Text encoding */
13918  u8 autoCommit; /* The auto-commit flag. */
13919  u8 temp_store; /* 1: file 2: memory 0: default */
13920  u8 mallocFailed; /* True if we have seen a malloc failure */
13921  u8 bBenignMalloc; /* Do not require OOMs if true */
13922  u8 dfltLockMode; /* Default locking-mode for attached dbs */
13923  signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
13924  u8 suppressErr; /* Do not issue error messages if true */
13925  u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
13926  u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
13927  u8 mTrace; /* zero or more SQLITE_TRACE flags */
13928  int nextPagesize; /* Pagesize after VACUUM if >0 */
13929  u32 magic; /* Magic number for detect library misuse */
13930  int nChange; /* Value returned by sqlite3_changes() */
13931  int nTotalChange; /* Value returned by sqlite3_total_changes() */
13932  int aLimit[SQLITE_N_LIMIT]; /* Limits */
13933  int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
13934  struct sqlite3InitInfo { /* Information used during initialization */
13935  int newTnum; /* Rootpage of table being initialized */
13936  u8 iDb; /* Which db file is being initialized */
13937  u8 busy; /* TRUE if currently initializing */
13938  u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
13939  u8 imposterTable; /* Building an imposter table */
13940  } init;
13941  int nVdbeActive; /* Number of VDBEs currently running */
13942  int nVdbeRead; /* Number of active VDBEs that read or write */
13943  int nVdbeWrite; /* Number of active VDBEs that read and write */
13944  int nVdbeExec; /* Number of nested calls to VdbeExec() */
13945  int nVDestroy; /* Number of active OP_VDestroy operations */
13946  int nExtension; /* Number of loaded extensions */
13947  void **aExtension; /* Array of shared library handles */
13948  int (*xTrace)(u32,void*,void*,void*); /* Trace function */
13949  void *pTraceArg; /* Argument to the trace function */
13950  void (*xProfile)(void*,const char*,u64); /* Profiling function */
13951  void *pProfileArg; /* Argument to profile function */
13952  void *pCommitArg; /* Argument to xCommitCallback() */
13953  int (*xCommitCallback)(void*); /* Invoked at every commit. */
13954  void *pRollbackArg; /* Argument to xRollbackCallback() */
13955  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
13956  void *pUpdateArg;
13957  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13958 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13959  void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
13960  void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
13961  void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13962  );
13963  PreUpdate *pPreUpdate; /* Context for active pre-update callback */
13964 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
13965 #ifndef SQLITE_OMIT_WAL
13966  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
13967  void *pWalArg;
13968 #endif
13969  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
13970  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
13972  sqlite3_value *pErr; /* Most recent error message */
13973  union {
13974  volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
13975  double notUsed1; /* Spacer */
13976  } u1;
13977  Lookaside lookaside; /* Lookaside malloc configuration */
13978 #ifndef SQLITE_OMIT_AUTHORIZATION
13979  sqlite3_xauth xAuth; /* Access authorization function */
13980  void *pAuthArg; /* 1st argument to the access auth function */
13981 #endif
13982 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
13983  int (*xProgress)(void *); /* The progress callback */
13984  void *pProgressArg; /* Argument to the progress callback */
13985  unsigned nProgressOps; /* Number of opcodes for progress callback */
13986 #endif
13987 #ifndef SQLITE_OMIT_VIRTUALTABLE
13988  int nVTrans; /* Allocated size of aVTrans */
13989  Hash aModule; /* populated by sqlite3_create_module() */
13990  VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
13991  VTable **aVTrans; /* Virtual tables with open transactions */
13992  VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
13993 #endif
13994  Hash aFunc; /* Hash table of connection functions */
13995  Hash aCollSeq; /* All collating sequences */
13996  BusyHandler busyHandler; /* Busy callback */
13997  Db aDbStatic[2]; /* Static space for the 2 default backends */
13998  Savepoint *pSavepoint; /* List of active savepoints */
13999  int busyTimeout; /* Busy handler timeout, in msec */
14000  int nSavepoint; /* Number of non-transaction savepoints */
14001  int nStatement; /* Number of nested statement-transactions */
14002  i64 nDeferredCons; /* Net deferred constraints this transaction. */
14003  i64 nDeferredImmCons; /* Net deferred immediate constraints */
14004  int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
14005 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
14006  /* The following variables are all protected by the STATIC_MASTER
14007  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
14008  **
14009  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
14010  ** unlock so that it can proceed.
14011  **
14012  ** When X.pBlockingConnection==Y, that means that something that X tried
14013  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
14014  ** held by Y.
14015  */
14016  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
14017  sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
14018  void *pUnlockArg; /* Argument to xUnlockNotify */
14019  void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
14020  sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
14021 #endif
14022 #ifdef SQLITE_USER_AUTHENTICATION
14023  sqlite3_userauth auth; /* User authentication information */
14024 #endif
14025 };
14026 
14027 /*
14028 ** A macro to discover the encoding of a database.
14029 */
14030 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
14031 #define ENC(db) ((db)->enc)
14032 
14033 /*
14034 ** Possible values for the sqlite3.flags.
14035 **
14036 ** Value constraints (enforced via assert()):
14037 ** SQLITE_FullFSync == PAGER_FULLFSYNC
14038 ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
14039 ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
14040 */
14041 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
14042 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
14043 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
14044 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
14045 #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
14046 #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
14047 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
14048 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
14049  /* DELETE, or UPDATE and return */
14050  /* the count using a callback. */
14051 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
14052  /* result set is empty */
14053 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
14054 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
14055 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
14056 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
14057 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
14058 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
14059 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
14060 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
14061 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
14062 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
14063 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
14064 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
14065 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
14066 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
14067 #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
14068 #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
14069 #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
14070 #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
14071 #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
14072 #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
14073 #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
14074 #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
14075 
14076 
14077 /*
14078 ** Bits of the sqlite3.dbOptFlags field that are used by the
14079 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
14080 ** selectively disable various optimizations.
14081 */
14082 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
14083 #define SQLITE_ColumnCache 0x0002 /* Column cache */
14084 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
14085 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
14086 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
14087 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
14088 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
14089 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
14090 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
14091 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
14092 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
14093 #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
14094 #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
14095 #define SQLITE_AllOpts 0xffff /* All optimizations */
14096 
14097 /*
14098 ** Macros for testing whether or not optimizations are enabled or disabled.
14099 */
14100 #ifndef SQLITE_OMIT_BUILTIN_TEST
14101 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
14102 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
14103 #else
14104 #define OptimizationDisabled(db, mask) 0
14105 #define OptimizationEnabled(db, mask) 1
14106 #endif
14107 
14108 /*
14109 ** Return true if it OK to factor constant expressions into the initialization
14110 ** code. The argument is a Parse object for the code generator.
14111 */
14112 #define ConstFactorOk(P) ((P)->okConstFactor)
14113 
14114 /*
14115 ** Possible values for the sqlite.magic field.
14116 ** The numbers are obtained at random and have no special meaning, other
14117 ** than being distinct from one another.
14118 */
14119 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
14120 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
14121 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
14122 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
14123 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
14124 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
14125 
14126 /*
14127 ** Each SQL function is defined by an instance of the following
14128 ** structure. For global built-in functions (ex: substr(), max(), count())
14129 ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
14130 ** For per-connection application-defined functions, a pointer to this
14131 ** structure is held in the db->aHash hash table.
14132 **
14133 ** The u.pHash field is used by the global built-ins. The u.pDestructor
14134 ** field is used by per-connection app-def functions.
14135 */
14136 struct FuncDef {
14137  i8 nArg; /* Number of arguments. -1 means unlimited */
14138  u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
14139  void *pUserData; /* User data parameter */
14140  FuncDef *pNext; /* Next function with same name */
14141  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
14142  void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
14143  const char *zName; /* SQL name of the function. */
14144  union {
14145  FuncDef *pHash; /* Next with a different name but the same hash */
14146  FuncDestructor *pDestructor; /* Reference counted destructor function */
14147  } u;
14148 };
14149 
14150 /*
14151 ** This structure encapsulates a user-function destructor callback (as
14152 ** configured using create_function_v2()) and a reference counter. When
14153 ** create_function_v2() is called to create a function with a destructor,
14154 ** a single object of this type is allocated. FuncDestructor.nRef is set to
14155 ** the number of FuncDef objects created (either 1 or 3, depending on whether
14156 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
14157 ** member of each of the new FuncDef objects is set to point to the allocated
14158 ** FuncDestructor.
14159 **
14160 ** Thereafter, when one of the FuncDef objects is deleted, the reference
14161 ** count on this object is decremented. When it reaches 0, the destructor
14162 ** is invoked and the FuncDestructor structure freed.
14163 */
14165  int nRef;
14166  void (*xDestroy)(void *);
14167  void *pUserData;
14168 };
14169 
14170 /*
14171 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
14172 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
14173 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
14174 ** are assert() statements in the code to verify this.
14175 **
14176 ** Value constraints (enforced via assert()):
14177 ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
14178 ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
14179 ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
14180 ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
14181 ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
14182 */
14183 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
14184 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
14185 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
14186 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
14187 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
14188 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
14189 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
14190 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
14191 #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
14192 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
14193 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
14194 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
14195 #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
14196  ** single query - might change over time */
14197 
14198 /*
14199 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
14200 ** used to create the initializers for the FuncDef structures.
14201 **
14202 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
14203 ** Used to create a scalar function definition of a function zName
14204 ** implemented by C function xFunc that accepts nArg arguments. The
14205 ** value passed as iArg is cast to a (void*) and made available
14206 ** as the user-data (sqlite3_user_data()) for the function. If
14207 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
14208 **
14209 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
14210 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
14211 **
14212 ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
14213 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
14214 ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
14215 ** and functions like sqlite_version() that can change, but not during
14216 ** a single query.
14217 **
14218 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
14219 ** Used to create an aggregate function definition implemented by
14220 ** the C functions xStep and xFinal. The first four parameters
14221 ** are interpreted in the same way as the first 4 parameters to
14222 ** FUNCTION().
14223 **
14224 ** LIKEFUNC(zName, nArg, pArg, flags)
14225 ** Used to create a scalar function definition of a function zName
14226 ** that accepts nArg arguments and is implemented by a call to C
14227 ** function likeFunc. Argument pArg is cast to a (void *) and made
14228 ** available as the function user-data (sqlite3_user_data()). The
14229 ** FuncDef.flags variable is set to the value passed as the flags
14230 ** parameter.
14231 */
14232 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
14233  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14234  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14235 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14236  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14237  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14238 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14239  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14240  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14241 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
14242  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
14243  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14244 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
14245  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14246  pArg, 0, xFunc, 0, #zName, }
14247 #define LIKEFUNC(zName, nArg, arg, flags) \
14248  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
14249  (void *)arg, 0, likeFunc, 0, #zName, {0} }
14250 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
14251  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
14252  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14253 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
14254  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
14255  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14256 
14257 /*
14258 ** All current savepoints are stored in a linked list starting at
14259 ** sqlite3.pSavepoint. The first element in the list is the most recently
14260 ** opened savepoint. Savepoints are added to the list by the vdbe
14261 ** OP_Savepoint instruction.
14262 */
14263 struct Savepoint {
14264  char *zName; /* Savepoint name (nul-terminated) */
14265  i64 nDeferredCons; /* Number of deferred fk violations */
14266  i64 nDeferredImmCons; /* Number of deferred imm fk. */
14267  Savepoint *pNext; /* Parent savepoint (if any) */
14268 };
14269 
14270 /*
14271 ** The following are used as the second parameter to sqlite3Savepoint(),
14272 ** and as the P1 argument to the OP_Savepoint instruction.
14273 */
14274 #define SAVEPOINT_BEGIN 0
14275 #define SAVEPOINT_RELEASE 1
14276 #define SAVEPOINT_ROLLBACK 2
14277 
14278 
14279 /*
14280 ** Each SQLite module (virtual table definition) is defined by an
14281 ** instance of the following structure, stored in the sqlite3.aModule
14282 ** hash table.
14283 */
14284 struct Module {
14285  const sqlite3_module *pModule; /* Callback pointers */
14286  const char *zName; /* Name passed to create_module() */
14287  void *pAux; /* pAux passed to create_module() */
14288  void (*xDestroy)(void *); /* Module destructor function */
14289  Table *pEpoTab; /* Eponymous table for this module */
14290 };
14291 
14292 /*
14293 ** information about each column of an SQL table is held in an instance
14294 ** of this structure.
14295 */
14296 struct Column {
14297  char *zName; /* Name of this column, \000, then the type */
14298  Expr *pDflt; /* Default value of this column */
14299  char *zColl; /* Collating sequence. If NULL, use the default */
14300  u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
14301  char affinity; /* One of the SQLITE_AFF_... values */
14302  u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
14303  u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
14304 };
14305 
14306 /* Allowed values for Column.colFlags:
14307 */
14308 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
14309 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
14310 #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
14311 
14312 /*
14313 ** A "Collating Sequence" is defined by an instance of the following
14314 ** structure. Conceptually, a collating sequence consists of a name and
14315 ** a comparison routine that defines the order of that sequence.
14316 **
14317 ** If CollSeq.xCmp is NULL, it means that the
14318 ** collating sequence is undefined. Indices built on an undefined
14319 ** collating sequence may not be read or written.
14320 */
14321 struct CollSeq {
14322  char *zName; /* Name of the collating sequence, UTF-8 encoded */
14323  u8 enc; /* Text encoding handled by xCmp() */
14324  void *pUser; /* First argument to xCmp() */
14325  int (*xCmp)(void*,int, const void*, int, const void*);
14326  void (*xDel)(void*); /* Destructor for pUser */
14327 };
14328 
14329 /*
14330 ** A sort order can be either ASC or DESC.
14331 */
14332 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
14333 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
14334 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
14335 
14336 /*
14337 ** Column affinity types.
14338 **
14339 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
14340 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
14341 ** the speed a little by numbering the values consecutively.
14342 **
14343 ** But rather than start with 0 or 1, we begin with 'A'. That way,
14344 ** when multiple affinity types are concatenated into a string and
14345 ** used as the P4 operand, they will be more readable.
14346 **
14347 ** Note also that the numeric types are grouped together so that testing
14348 ** for a numeric type is a single comparison. And the BLOB type is first.
14349 */
14350 #define SQLITE_AFF_BLOB 'A'
14351 #define SQLITE_AFF_TEXT 'B'
14352 #define SQLITE_AFF_NUMERIC 'C'
14353 #define SQLITE_AFF_INTEGER 'D'
14354 #define SQLITE_AFF_REAL 'E'
14355 
14356 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
14357 
14358 /*
14359 ** The SQLITE_AFF_MASK values masks off the significant bits of an
14360 ** affinity value.
14361 */
14362 #define SQLITE_AFF_MASK 0x47
14363 
14364 /*
14365 ** Additional bit values that can be ORed with an affinity without
14366 ** changing the affinity.
14367 **
14368 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
14369 ** It causes an assert() to fire if either operand to a comparison
14370 ** operator is NULL. It is added to certain comparison operators to
14371 ** prove that the operands are always NOT NULL.
14372 */
14373 #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
14374 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
14375 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
14376 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
14377 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
14378 
14379 /*
14380 ** An object of this type is created for each virtual table present in
14381 ** the database schema.
14382 **
14383 ** If the database schema is shared, then there is one instance of this
14384 ** structure for each database connection (sqlite3*) that uses the shared
14385 ** schema. This is because each database connection requires its own unique
14386 ** instance of the sqlite3_vtab* handle used to access the virtual table
14387 ** implementation. sqlite3_vtab* handles can not be shared between
14388 ** database connections, even when the rest of the in-memory database
14389 ** schema is shared, as the implementation often stores the database
14390 ** connection handle passed to it via the xConnect() or xCreate() method
14391 ** during initialization internally. This database connection handle may
14392 ** then be used by the virtual table implementation to access real tables
14393 ** within the database. So that they appear as part of the callers
14394 ** transaction, these accesses need to be made via the same database
14395 ** connection as that used to execute SQL operations on the virtual table.
14396 **
14397 ** All VTable objects that correspond to a single table in a shared
14398 ** database schema are initially stored in a linked-list pointed to by
14399 ** the Table.pVTable member variable of the corresponding Table object.
14400 ** When an sqlite3_prepare() operation is required to access the virtual
14401 ** table, it searches the list for the VTable that corresponds to the
14402 ** database connection doing the preparing so as to use the correct
14403 ** sqlite3_vtab* handle in the compiled query.
14404 **
14405 ** When an in-memory Table object is deleted (for example when the
14406 ** schema is being reloaded for some reason), the VTable objects are not
14407 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
14408 ** immediately. Instead, they are moved from the Table.pVTable list to
14409 ** another linked list headed by the sqlite3.pDisconnect member of the
14410 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
14411 ** next time a statement is prepared using said sqlite3*. This is done
14412 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
14413 ** Refer to comments above function sqlite3VtabUnlockList() for an
14414 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
14415 ** list without holding the corresponding sqlite3.mutex mutex.
14416 **
14417 ** The memory for objects of this type is always allocated by
14418 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
14419 ** the first argument.
14420 */
14421 struct VTable {
14422  sqlite3 *db; /* Database connection associated with this table */
14423  Module *pMod; /* Pointer to module implementation */
14424  sqlite3_vtab *pVtab; /* Pointer to vtab instance */
14425  int nRef; /* Number of pointers to this structure */
14426  u8 bConstraint; /* True if constraints are supported */
14427  int iSavepoint; /* Depth of the SAVEPOINT stack */
14428  VTable *pNext; /* Next in linked list (see above) */
14429 };
14430 
14431 /*
14432 ** The schema for each SQL table and view is represented in memory
14433 ** by an instance of the following structure.
14434 */
14435 struct Table {
14436  char *zName; /* Name of the table or view */
14437  Column *aCol; /* Information about each column */
14438  Index *pIndex; /* List of SQL indexes on this table. */
14439  Select *pSelect; /* NULL for tables. Points to definition if a view. */
14440  FKey *pFKey; /* Linked list of all foreign keys in this table */
14441  char *zColAff; /* String defining the affinity of each column */
14442  ExprList *pCheck; /* All CHECK constraints */
14443  /* ... also used as column name list in a VIEW */
14444  int tnum; /* Root BTree page for this table */
14445  i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
14446  i16 nCol; /* Number of columns in this table */
14447  u16 nRef; /* Number of pointers to this Table */
14448  LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
14449  LogEst szTabRow; /* Estimated size of each table row in bytes */
14450 #ifdef SQLITE_ENABLE_COSTMULT
14451  LogEst costMult; /* Cost multiplier for using this table */
14452 #endif
14453  u8 tabFlags; /* Mask of TF_* values */
14454  u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
14455 #ifndef SQLITE_OMIT_ALTERTABLE
14456  int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
14457 #endif
14458 #ifndef SQLITE_OMIT_VIRTUALTABLE
14459  int nModuleArg; /* Number of arguments to the module */
14460  char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
14461  VTable *pVTable; /* List of VTable objects. */
14462 #endif
14463  Trigger *pTrigger; /* List of triggers stored in pSchema */
14464  Schema *pSchema; /* Schema that contains this table */
14465  Table *pNextZombie; /* Next on the Parse.pZombieTab list */
14466 };
14467 
14468 /*
14469 ** Allowed values for Table.tabFlags.
14470 **
14471 ** TF_OOOHidden applies to tables or view that have hidden columns that are
14472 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
14473 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
14474 ** the TF_OOOHidden attribute would apply in this case. Such tables require
14475 ** special handling during INSERT processing.
14476 */
14477 #define TF_Readonly 0x01 /* Read-only system table */
14478 #define TF_Ephemeral 0x02 /* An ephemeral table */
14479 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
14480 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
14481 #define TF_Virtual 0x10 /* Is a virtual table */
14482 #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
14483 #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
14484 #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
14485 
14486 
14487 /*
14488 ** Test to see whether or not a table is a virtual table. This is
14489 ** done as a macro so that it will be optimized out when virtual
14490 ** table support is omitted from the build.
14491 */
14492 #ifndef SQLITE_OMIT_VIRTUALTABLE
14493 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
14494 #else
14495 # define IsVirtual(X) 0
14496 #endif
14497 
14498 /*
14499 ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
14500 ** only works for non-virtual tables (ordinary tables and views) and is
14501 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
14502 ** IsHiddenColumn() macro is general purpose.
14503 */
14504 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
14505 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14506 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14507 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
14508 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14509 # define IsOrdinaryHiddenColumn(X) 0
14510 #else
14511 # define IsHiddenColumn(X) 0
14512 # define IsOrdinaryHiddenColumn(X) 0
14513 #endif
14514 
14515 
14516 /* Does the table have a rowid */
14517 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
14518 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
14519 
14520 /*
14521 ** Each foreign key constraint is an instance of the following structure.
14522 **
14523 ** A foreign key is associated with two tables. The "from" table is
14524 ** the table that contains the REFERENCES clause that creates the foreign
14525 ** key. The "to" table is the table that is named in the REFERENCES clause.
14526 ** Consider this example:
14527 **
14528 ** CREATE TABLE ex1(
14529 ** a INTEGER PRIMARY KEY,
14530 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
14531 ** );
14532 **
14533 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
14534 ** Equivalent names:
14535 **
14536 ** from-table == child-table
14537 ** to-table == parent-table
14538 **
14539 ** Each REFERENCES clause generates an instance of the following structure
14540 ** which is attached to the from-table. The to-table need not exist when
14541 ** the from-table is created. The existence of the to-table is not checked.
14542 **
14543 ** The list of all parents for child Table X is held at X.pFKey.
14544 **
14545 ** A list of all children for a table named Z (which might not even exist)
14546 ** is held in Schema.fkeyHash with a hash key of Z.
14547 */
14548 struct FKey {
14549  Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
14550  FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
14551  char *zTo; /* Name of table that the key points to (aka: Parent) */
14552  FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
14553  FKey *pPrevTo; /* Previous with the same zTo */
14554  int nCol; /* Number of columns in this key */
14555  /* EV: R-30323-21917 */
14556  u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
14557  u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
14558  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
14559  struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
14560  int iFrom; /* Index of column in pFrom */
14561  char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
14562  } aCol[1]; /* One entry for each of nCol columns */
14563 };
14564 
14565 /*
14566 ** SQLite supports many different ways to resolve a constraint
14567 ** error. ROLLBACK processing means that a constraint violation
14568 ** causes the operation in process to fail and for the current transaction
14569 ** to be rolled back. ABORT processing means the operation in process
14570 ** fails and any prior changes from that one operation are backed out,
14571 ** but the transaction is not rolled back. FAIL processing means that
14572 ** the operation in progress stops and returns an error code. But prior
14573 ** changes due to the same operation are not backed out and no rollback
14574 ** occurs. IGNORE means that the particular row that caused the constraint
14575 ** error is not inserted or updated. Processing continues and no error
14576 ** is returned. REPLACE means that preexisting database rows that caused
14577 ** a UNIQUE constraint violation are removed so that the new insert or
14578 ** update can proceed. Processing continues and no error is reported.
14579 **
14580 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
14581 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
14582 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
14583 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
14584 ** referenced table row is propagated into the row that holds the
14585 ** foreign key.
14586 **
14587 ** The following symbolic values are used to record which type
14588 ** of action to take.
14589 */
14590 #define OE_None 0 /* There is no constraint to check */
14591 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
14592 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
14593 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
14594 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
14595 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
14596 
14597 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
14598 #define OE_SetNull 7 /* Set the foreign key value to NULL */
14599 #define OE_SetDflt 8 /* Set the foreign key value to its default */
14600 #define OE_Cascade 9 /* Cascade the changes */
14601 
14602 #define OE_Default 10 /* Do whatever the default action is */
14603 
14604 
14605 /*
14606 ** An instance of the following structure is passed as the first
14607 ** argument to sqlite3VdbeKeyCompare and is used to control the
14608 ** comparison of the two index keys.
14609 **
14610 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
14611 ** are nField slots for the columns of an index then one extra slot
14612 ** for the rowid at the end.
14613 */
14614 struct KeyInfo {
14615  u32 nRef; /* Number of references to this KeyInfo object */
14616  u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
14617  u16 nField; /* Number of key columns in the index */
14618  u16 nXField; /* Number of columns beyond the key columns */
14619  sqlite3 *db; /* The database connection */
14620  u8 *aSortOrder; /* Sort order for each column. */
14621  CollSeq *aColl[1]; /* Collating sequence for each term of the key */
14622 };
14623 
14624 /*
14625 ** This object holds a record which has been parsed out into individual
14626 ** fields, for the purposes of doing a comparison.
14627 **
14628 ** A record is an object that contains one or more fields of data.
14629 ** Records are used to store the content of a table row and to store
14630 ** the key of an index. A blob encoding of a record is created by
14631 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
14632 ** OP_Column opcode.
14633 **
14634 ** An instance of this object serves as a "key" for doing a search on
14635 ** an index b+tree. The goal of the search is to find the entry that
14636 ** is closed to the key described by this object. This object might hold
14637 ** just a prefix of the key. The number of fields is given by
14638 ** pKeyInfo->nField.
14639 **
14640 ** The r1 and r2 fields are the values to return if this key is less than
14641 ** or greater than a key in the btree, respectively. These are normally
14642 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
14643 ** is in DESC order.
14644 **
14645 ** The key comparison functions actually return default_rc when they find
14646 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
14647 ** multiple entries in the b-tree with the same key (when only looking
14648 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
14649 ** cause the search to find the last match, or +1 to cause the search to
14650 ** find the first match.
14651 **
14652 ** The key comparison functions will set eqSeen to true if they ever
14653 ** get and equal results when comparing this structure to a b-tree record.
14654 ** When default_rc!=0, the search might end up on the record immediately
14655 ** before the first match or immediately after the last match. The
14656 ** eqSeen field will indicate whether or not an exact match exists in the
14657 ** b-tree.
14658 */
14660  KeyInfo *pKeyInfo; /* Collation and sort-order information */
14661  Mem *aMem; /* Values */
14662  u16 nField; /* Number of entries in apMem[] */
14663  i8 default_rc; /* Comparison result if keys are equal */
14664  u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
14665  i8 r1; /* Value to return if (lhs > rhs) */
14666  i8 r2; /* Value to return if (rhs < lhs) */
14667  u8 eqSeen; /* True if an equality comparison has been seen */
14668 };
14669 
14670 
14671 /*
14672 ** Each SQL index is represented in memory by an
14673 ** instance of the following structure.
14674 **
14675 ** The columns of the table that are to be indexed are described
14676 ** by the aiColumn[] field of this structure. For example, suppose
14677 ** we have the following table and index:
14678 **
14679 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
14680 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
14681 **
14682 ** In the Table structure describing Ex1, nCol==3 because there are
14683 ** three columns in the table. In the Index structure describing
14684 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
14685 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
14686 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
14687 ** The second column to be indexed (c1) has an index of 0 in
14688 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
14689 **
14690 ** The Index.onError field determines whether or not the indexed columns
14691 ** must be unique and what to do if they are not. When Index.onError=OE_None,
14692 ** it means this is not a unique index. Otherwise it is a unique index
14693 ** and the value of Index.onError indicate the which conflict resolution
14694 ** algorithm to employ whenever an attempt is made to insert a non-unique
14695 ** element.
14696 **
14697 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
14698 ** generate VDBE code (as opposed to parsing one read from an sqlite_master
14699 ** table as part of parsing an existing database schema), transient instances
14700 ** of this structure may be created. In this case the Index.tnum variable is
14701 ** used to store the address of a VDBE instruction, not a database page
14702 ** number (it cannot - the database page is not allocated until the VDBE
14703 ** program is executed). See convertToWithoutRowidTable() for details.
14704 */
14705 struct Index {
14706  char *zName; /* Name of this index */
14707  i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
14708  LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
14709  Table *pTable; /* The SQL table being indexed */
14710  char *zColAff; /* String defining the affinity of each column */
14711  Index *pNext; /* The next index associated with the same table */
14712  Schema *pSchema; /* Schema containing this index */
14713  u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
14714  const char **azColl; /* Array of collation sequence names for index */
14715  Expr *pPartIdxWhere; /* WHERE clause for partial indices */
14716  ExprList *aColExpr; /* Column expressions */
14717  int tnum; /* DB Page containing root of this index */
14718  LogEst szIdxRow; /* Estimated average row size in bytes */
14719  u16 nKeyCol; /* Number of columns forming the key */
14720  u16 nColumn; /* Number of columns stored in the index */
14721  u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
14722  unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
14723  unsigned bUnordered:1; /* Use this index for == or IN queries only */
14724  unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
14725  unsigned isResized:1; /* True if resizeIndexObject() has been called */
14726  unsigned isCovering:1; /* True if this is a covering index */
14727  unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
14728 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14729  int nSample; /* Number of elements in aSample[] */
14730  int nSampleCol; /* Size of IndexSample.anEq[] and so on */
14731  tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
14732  IndexSample *aSample; /* Samples of the left-most key */
14733  tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
14734  tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
14735 #endif
14736 };
14737 
14738 /*
14739 ** Allowed values for Index.idxType
14740 */
14741 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
14742 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
14743 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
14744 
14745 /* Return true if index X is a PRIMARY KEY index */
14746 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
14747 
14748 /* Return true if index X is a UNIQUE index */
14749 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
14750 
14751 /* The Index.aiColumn[] values are normally positive integer. But
14752 ** there are some negative values that have special meaning:
14753 */
14754 #define XN_ROWID (-1) /* Indexed column is the rowid */
14755 #define XN_EXPR (-2) /* Indexed column is an expression */
14756 
14757 /*
14758 ** Each sample stored in the sqlite_stat3 table is represented in memory
14759 ** using a structure of this type. See documentation at the top of the
14760 ** analyze.c source file for additional information.
14761 */
14762 struct IndexSample {
14763  void *p; /* Pointer to sampled record */
14764  int n; /* Size of record in bytes */
14765  tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
14766  tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
14767  tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
14768 };
14769 
14770 /*
14771 ** Each token coming out of the lexer is an instance of
14772 ** this structure. Tokens are also used as part of an expression.
14773 **
14774 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
14775 ** may contain random values. Do not make any assumptions about Token.dyn
14776 ** and Token.n when Token.z==0.
14777 */
14778 struct Token {
14779  const char *z; /* Text of the token. Not NULL-terminated! */
14780  unsigned int n; /* Number of characters in this token */
14781 };
14782 
14783 /*
14784 ** An instance of this structure contains information needed to generate
14785 ** code for a SELECT that contains aggregate functions.
14786 **
14787 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
14788 ** pointer to this structure. The Expr.iColumn field is the index in
14789 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
14790 ** code for that node.
14791 **
14792 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
14793 ** original Select structure that describes the SELECT statement. These
14794 ** fields do not need to be freed when deallocating the AggInfo structure.
14795 */
14796 struct AggInfo {
14797  u8 directMode; /* Direct rendering mode means take data directly
14798  ** from source tables rather than from accumulators */
14799  u8 useSortingIdx; /* In direct mode, reference the sorting index rather
14800  ** than the source table */
14801  int sortingIdx; /* Cursor number of the sorting index */
14802  int sortingIdxPTab; /* Cursor number of pseudo-table */
14803  int nSortingColumn; /* Number of columns in the sorting index */
14804  int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
14805  ExprList *pGroupBy; /* The group by clause */
14806  struct AggInfo_col { /* For each column used in source tables */
14807  Table *pTab; /* Source table */
14808  int iTable; /* Cursor number of the source table */
14809  int iColumn; /* Column number within the source table */
14810  int iSorterColumn; /* Column number in the sorting index */
14811  int iMem; /* Memory location that acts as accumulator */
14812  Expr *pExpr; /* The original expression */
14813  } *aCol;
14814  int nColumn; /* Number of used entries in aCol[] */
14815  int nAccumulator; /* Number of columns that show through to the output.
14816  ** Additional columns are used only as parameters to
14817  ** aggregate functions */
14818  struct AggInfo_func { /* For each aggregate function */
14819  Expr *pExpr; /* Expression encoding the function */
14820  FuncDef *pFunc; /* The aggregate function implementation */
14821  int iMem; /* Memory location that acts as accumulator */
14822  int iDistinct; /* Ephemeral table used to enforce DISTINCT */
14823  } *aFunc;
14824  int nFunc; /* Number of entries in aFunc[] */
14825 };
14826 
14827 /*
14828 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
14829 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
14830 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
14831 ** it uses less memory in the Expr object, which is a big memory user
14832 ** in systems with lots of prepared statements. And few applications
14833 ** need more than about 10 or 20 variables. But some extreme users want
14834 ** to have prepared statements with over 32767 variables, and for them
14835 ** the option is available (at compile-time).
14836 */
14837 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
14838 typedef i16 ynVar;
14839 #else
14840 typedef int ynVar;
14841 #endif
14842 
14843 /*
14844 ** Each node of an expression in the parse tree is an instance
14845 ** of this structure.
14846 **
14847 ** Expr.op is the opcode. The integer parser token codes are reused
14848 ** as opcodes here. For example, the parser defines TK_GE to be an integer
14849 ** code representing the ">=" operator. This same integer code is reused
14850 ** to represent the greater-than-or-equal-to operator in the expression
14851 ** tree.
14852 **
14853 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
14854 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
14855 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
14856 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
14857 ** then Expr.token contains the name of the function.
14858 **
14859 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
14860 ** binary operator. Either or both may be NULL.
14861 **
14862 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
14863 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
14864 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
14865 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
14866 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
14867 ** valid.
14868 **
14869 ** An expression of the form ID or ID.ID refers to a column in a table.
14870 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
14871 ** the integer cursor number of a VDBE cursor pointing to that table and
14872 ** Expr.iColumn is the column number for the specific column. If the
14873 ** expression is used as a result in an aggregate SELECT, then the
14874 ** value is also stored in the Expr.iAgg column in the aggregate so that
14875 ** it can be accessed after all aggregates are computed.
14876 **
14877 ** If the expression is an unbound variable marker (a question mark
14878 ** character '?' in the original SQL) then the Expr.iTable holds the index
14879 ** number for that variable.
14880 **
14881 ** If the expression is a subquery then Expr.iColumn holds an integer
14882 ** register number containing the result of the subquery. If the
14883 ** subquery gives a constant result, then iTable is -1. If the subquery
14884 ** gives a different answer at different times during statement processing
14885 ** then iTable is the address of a subroutine that computes the subquery.
14886 **
14887 ** If the Expr is of type OP_Column, and the table it is selecting from
14888 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
14889 ** corresponding table definition.
14890 **
14891 ** ALLOCATION NOTES:
14892 **
14893 ** Expr objects can use a lot of memory space in database schema. To
14894 ** help reduce memory requirements, sometimes an Expr object will be
14895 ** truncated. And to reduce the number of memory allocations, sometimes
14896 ** two or more Expr objects will be stored in a single memory allocation,
14897 ** together with Expr.zToken strings.
14898 **
14899 ** If the EP_Reduced and EP_TokenOnly flags are set when
14900 ** an Expr object is truncated. When EP_Reduced is set, then all
14901 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
14902 ** are contained within the same memory allocation. Note, however, that
14903 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
14904 ** allocated, regardless of whether or not EP_Reduced is set.
14905 */
14906 struct Expr {
14907  u8 op; /* Operation performed by this node */
14908  char affinity; /* The affinity of the column or 0 if not a column */
14909  u32 flags; /* Various flags. EP_* See below */
14910  union {
14911  char *zToken; /* Token value. Zero terminated and dequoted */
14912  int iValue; /* Non-negative integer value if EP_IntValue */
14913  } u;
14914 
14915  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
14916  ** space is allocated for the fields below this point. An attempt to
14917  ** access them will result in a segfault or malfunction.
14918  *********************************************************************/
14919 
14920  Expr *pLeft; /* Left subnode */
14921  Expr *pRight; /* Right subnode */
14922  union {
14923  ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
14924  Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
14925  } x;
14926 
14927  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
14928  ** space is allocated for the fields below this point. An attempt to
14929  ** access them will result in a segfault or malfunction.
14930  *********************************************************************/
14931 
14932 #if SQLITE_MAX_EXPR_DEPTH>0
14933  int nHeight; /* Height of the tree headed by this node */
14934 #endif
14935  int iTable; /* TK_COLUMN: cursor number of table holding column
14936  ** TK_REGISTER: register number
14937  ** TK_TRIGGER: 1 -> new, 0 -> old
14938  ** EP_Unlikely: 134217728 times likelihood
14939  ** TK_SELECT: 1st register of result vector */
14940  ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
14941  ** TK_VARIABLE: variable number (always >= 1).
14942  ** TK_SELECT_COLUMN: column of the result vector */
14943  i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
14944  i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
14945  u8 op2; /* TK_REGISTER: original value of Expr.op
14946  ** TK_COLUMN: the value of p5 for OP_Column
14947  ** TK_AGG_FUNCTION: nesting depth */
14948  AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
14949  Table *pTab; /* Table for TK_COLUMN expressions. */
14950 };
14951 
14952 /*
14953 ** The following are the meanings of bits in the Expr.flags field.
14954 */
14955 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
14956 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
14957 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
14958 #define EP_Error 0x000008 /* Expression contains one or more errors */
14959 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
14960 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
14961 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
14962 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
14963 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
14964 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
14965 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
14966 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
14967 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
14968 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
14969 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
14970 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
14971 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
14972 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
14973 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
14974 #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
14975 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
14976 #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
14977 #define EP_Alias 0x400000 /* Is an alias for a result set column */
14978 #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
14979 
14980 /*
14981 ** Combinations of two or more EP_* flags
14982 */
14983 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
14984 
14985 /*
14986 ** These macros can be used to test, set, or clear bits in the
14987 ** Expr.flags field.
14988 */
14989 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
14990 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
14991 #define ExprSetProperty(E,P) (E)->flags|=(P)
14992 #define ExprClearProperty(E,P) (E)->flags&=~(P)
14993 
14994 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
14995 ** and Accreditation only. It works like ExprSetProperty() during VVA
14996 ** processes but is a no-op for delivery.
14997 */
14998 #ifdef SQLITE_DEBUG
14999 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
15000 #else
15001 # define ExprSetVVAProperty(E,P)
15002 #endif
15003 
15004 /*
15005 ** Macros to determine the number of bytes required by a normal Expr
15006 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
15007 ** and an Expr struct with the EP_TokenOnly flag set.
15008 */
15009 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
15010 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
15011 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
15012 
15013 /*
15014 ** Flags passed to the sqlite3ExprDup() function. See the header comment
15015 ** above sqlite3ExprDup() for details.
15016 */
15017 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
15018 
15019 /*
15020 ** A list of expressions. Each expression may optionally have a
15021 ** name. An expr/name combination can be used in several ways, such
15022 ** as the list of "expr AS ID" fields following a "SELECT" or in the
15023 ** list of "ID = expr" items in an UPDATE. A list of expressions can
15024 ** also be used as the argument to a function, in which case the a.zName
15025 ** field is not used.
15026 **
15027 ** By default the Expr.zSpan field holds a human-readable description of
15028 ** the expression that is used in the generation of error messages and
15029 ** column labels. In this case, Expr.zSpan is typically the text of a
15030 ** column expression as it exists in a SELECT statement. However, if
15031 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
15032 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
15033 ** form is used for name resolution with nested FROM clauses.
15034 */
15035 struct ExprList {
15036  int nExpr; /* Number of expressions on the list */
15037  struct ExprList_item { /* For each expression in the list */
15038  Expr *pExpr; /* The list of expressions */
15039  char *zName; /* Token associated with this expression */
15040  char *zSpan; /* Original text of the expression */
15041  u8 sortOrder; /* 1 for DESC or 0 for ASC */
15042  unsigned done :1; /* A flag to indicate when processing is finished */
15043  unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
15044  unsigned reusable :1; /* Constant expression is reusable */
15045  union {
15046  struct {
15047  u16 iOrderByCol; /* For ORDER BY, column number in result set */
15048  u16 iAlias; /* Index into Parse.aAlias[] for zName */
15049  } x;
15050  int iConstExprReg; /* Register in which Expr value is cached */
15051  } u;
15052  } *a; /* Alloc a power of two greater or equal to nExpr */
15053 };
15054 
15055 /*
15056 ** An instance of this structure is used by the parser to record both
15057 ** the parse tree for an expression and the span of input text for an
15058 ** expression.
15059 */
15060 struct ExprSpan {
15061  Expr *pExpr; /* The expression parse tree */
15062  const char *zStart; /* First character of input text */
15063  const char *zEnd; /* One character past the end of input text */
15064 };
15065 
15066 /*
15067 ** An instance of this structure can hold a simple list of identifiers,
15068 ** such as the list "a,b,c" in the following statements:
15069 **
15070 ** INSERT INTO t(a,b,c) VALUES ...;
15071 ** CREATE INDEX idx ON t(a,b,c);
15072 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
15073 **
15074 ** The IdList.a.idx field is used when the IdList represents the list of
15075 ** column names after a table name in an INSERT statement. In the statement
15076 **
15077 ** INSERT INTO t(a,b,c) ...
15078 **
15079 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
15080 */
15081 struct IdList {
15082  struct IdList_item {
15083  char *zName; /* Name of the identifier */
15084  int idx; /* Index in some Table.aCol[] of a column named zName */
15085  } *a;
15086  int nId; /* Number of identifiers on the list */
15087 };
15088 
15089 /*
15090 ** The bitmask datatype defined below is used for various optimizations.
15091 **
15092 ** Changing this from a 64-bit to a 32-bit type limits the number of
15093 ** tables in a join to 32 instead of 64. But it also reduces the size
15094 ** of the library by 738 bytes on ix86.
15095 */
15096 #ifdef SQLITE_BITMASK_TYPE
15097  typedef SQLITE_BITMASK_TYPE Bitmask;
15098 #else
15099  typedef u64 Bitmask;
15100 #endif
15101 
15102 /*
15103 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
15104 */
15105 #define BMS ((int)(sizeof(Bitmask)*8))
15106 
15107 /*
15108 ** A bit in a Bitmask
15109 */
15110 #define MASKBIT(n) (((Bitmask)1)<<(n))
15111 #define MASKBIT32(n) (((unsigned int)1)<<(n))
15112 #define ALLBITS ((Bitmask)-1)
15113 
15114 /*
15115 ** The following structure describes the FROM clause of a SELECT statement.
15116 ** Each table or subquery in the FROM clause is a separate element of
15117 ** the SrcList.a[] array.
15118 **
15119 ** With the addition of multiple database support, the following structure
15120 ** can also be used to describe a particular table such as the table that
15121 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
15122 ** such a table must be a simple name: ID. But in SQLite, the table can
15123 ** now be identified by a database name, a dot, then the table name: ID.ID.
15124 **
15125 ** The jointype starts out showing the join type between the current table
15126 ** and the next table on the list. The parser builds the list this way.
15127 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
15128 ** jointype expresses the join between the table and the previous table.
15129 **
15130 ** In the colUsed field, the high-order bit (bit 63) is set if the table
15131 ** contains more than 63 columns and the 64-th or later column is used.
15132 */
15133 struct SrcList {
15134  int nSrc; /* Number of tables or subqueries in the FROM clause */
15135  u32 nAlloc; /* Number of entries allocated in a[] below */
15136  struct SrcList_item {
15137  Schema *pSchema; /* Schema to which this item is fixed */
15138  char *zDatabase; /* Name of database holding this table */
15139  char *zName; /* Name of the table */
15140  char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
15141  Table *pTab; /* An SQL table corresponding to zName */
15142  Select *pSelect; /* A SELECT statement used in place of a table name */
15143  int addrFillSub; /* Address of subroutine to manifest a subquery */
15144  int regReturn; /* Register holding return address of addrFillSub */
15145  int regResult; /* Registers holding results of a co-routine */
15146  struct {
15147  u8 jointype; /* Type of join between this table and the previous */
15148  unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
15149  unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
15150  unsigned isTabFunc :1; /* True if table-valued-function syntax */
15151  unsigned isCorrelated :1; /* True if sub-query is correlated */
15152  unsigned viaCoroutine :1; /* Implemented as a co-routine */
15153  unsigned isRecursive :1; /* True for recursive reference in WITH */
15154  } fg;
15155 #ifndef SQLITE_OMIT_EXPLAIN
15156  u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
15157 #endif
15158  int iCursor; /* The VDBE cursor number used to access this table */
15159  Expr *pOn; /* The ON clause of a join */
15160  IdList *pUsing; /* The USING clause of a join */
15161  Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
15162  union {
15163  char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
15164  ExprList *pFuncArg; /* Arguments to table-valued-function */
15165  } u1;
15166  Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
15167  } a[1]; /* One entry for each identifier on the list */
15168 };
15169 
15170 /*
15171 ** Permitted values of the SrcList.a.jointype field
15172 */
15173 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
15174 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
15175 #define JT_NATURAL 0x0004 /* True for a "natural" join */
15176 #define JT_LEFT 0x0008 /* Left outer join */
15177 #define JT_RIGHT 0x0010 /* Right outer join */
15178 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
15179 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
15180 
15181 
15182 /*
15183 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
15184 ** and the WhereInfo.wctrlFlags member.
15185 **
15186 ** Value constraints (enforced via assert()):
15187 ** WHERE_USE_LIMIT == SF_FixedLimit
15188 */
15189 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
15190 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
15191 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
15192 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
15193 #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
15194 #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
15195 #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
15196  ** the OR optimization */
15197 #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
15198 #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
15199 #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
15200 #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
15201 #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
15202 #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
15203  /* 0x1000 not currently used */
15204  /* 0x2000 not currently used */
15205 #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
15206  /* 0x8000 not currently used */
15207 
15208 /* Allowed return values from sqlite3WhereIsDistinct()
15209 */
15210 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
15211 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
15212 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
15213 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
15214 
15215 /*
15216 ** A NameContext defines a context in which to resolve table and column
15217 ** names. The context consists of a list of tables (the pSrcList) field and
15218 ** a list of named expression (pEList). The named expression list may
15219 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
15220 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
15221 ** pEList corresponds to the result set of a SELECT and is NULL for
15222 ** other statements.
15223 **
15224 ** NameContexts can be nested. When resolving names, the inner-most
15225 ** context is searched first. If no match is found, the next outer
15226 ** context is checked. If there is still no match, the next context
15227 ** is checked. This process continues until either a match is found
15228 ** or all contexts are check. When a match is found, the nRef member of
15229 ** the context containing the match is incremented.
15230 **
15231 ** Each subquery gets a new NameContext. The pNext field points to the
15232 ** NameContext in the parent query. Thus the process of scanning the
15233 ** NameContext list corresponds to searching through successively outer
15234 ** subqueries looking for a match.
15235 */
15236 struct NameContext {
15237  Parse *pParse; /* The parser */
15238  SrcList *pSrcList; /* One or more tables used to resolve names */
15239  ExprList *pEList; /* Optional list of result-set columns */
15240  AggInfo *pAggInfo; /* Information about aggregates at this level */
15241  NameContext *pNext; /* Next outer name context. NULL for outermost */
15242  int nRef; /* Number of names resolved by this context */
15243  int nErr; /* Number of errors encountered while resolving names */
15244  u16 ncFlags; /* Zero or more NC_* flags defined below */
15245 };
15246 
15247 /*
15248 ** Allowed values for the NameContext, ncFlags field.
15249 **
15250 ** Value constraints (all checked via assert()):
15251 ** NC_HasAgg == SF_HasAgg
15252 ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15253 **
15254 */
15255 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
15256 #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
15257 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
15258 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
15259 #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
15260 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
15261 #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
15262 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
15263 
15264 /*
15265 ** An instance of the following structure contains all information
15266 ** needed to generate code for a single SELECT statement.
15267 **
15268 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
15269 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
15270 ** limit and nOffset to the value of the offset (or 0 if there is not
15271 ** offset). But later on, nLimit and nOffset become the memory locations
15272 ** in the VDBE that record the limit and offset counters.
15273 **
15274 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
15275 ** These addresses must be stored so that we can go back and fill in
15276 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
15277 ** the number of columns in P2 can be computed at the same time
15278 ** as the OP_OpenEphm instruction is coded because not
15279 ** enough information about the compound query is known at that point.
15280 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
15281 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
15282 ** sequences for the ORDER BY clause.
15283 */
15284 struct Select {
15285  ExprList *pEList; /* The fields of the result */
15286  u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
15287  LogEst nSelectRow; /* Estimated number of result rows */
15288  u32 selFlags; /* Various SF_* values */
15289  int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
15290 #if SELECTTRACE_ENABLED
15291  char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
15292 #endif
15293  int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
15294  SrcList *pSrc; /* The FROM clause */
15295  Expr *pWhere; /* The WHERE clause */
15296  ExprList *pGroupBy; /* The GROUP BY clause */
15297  Expr *pHaving; /* The HAVING clause */
15298  ExprList *pOrderBy; /* The ORDER BY clause */
15299  Select *pPrior; /* Prior select in a compound select statement */
15300  Select *pNext; /* Next select to the left in a compound */
15301  Expr *pLimit; /* LIMIT expression. NULL means not used. */
15302  Expr *pOffset; /* OFFSET expression. NULL means not used. */
15303  With *pWith; /* WITH clause attached to this select. Or NULL. */
15304 };
15305 
15306 /*
15307 ** Allowed values for Select.selFlags. The "SF" prefix stands for
15308 ** "Select Flag".
15309 **
15310 ** Value constraints (all checked via assert())
15311 ** SF_HasAgg == NC_HasAgg
15312 ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
15313 ** SF_FixedLimit == WHERE_USE_LIMIT
15314 */
15315 #define SF_Distinct 0x00001 /* Output should be DISTINCT */
15316 #define SF_All 0x00002 /* Includes the ALL keyword */
15317 #define SF_Resolved 0x00004 /* Identifiers have been resolved */
15318 #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
15319 #define SF_HasAgg 0x00010 /* Contains aggregate functions */
15320 #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
15321 #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
15322 #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
15323 #define SF_Compound 0x00100 /* Part of a compound query */
15324 #define SF_Values 0x00200 /* Synthesized from VALUES clause */
15325 #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
15326 #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
15327 #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
15328 #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
15329 #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
15330 #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
15331 #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
15332 #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
15333 
15334 
15335 /*
15336 ** The results of a SELECT can be distributed in several ways, as defined
15337 ** by one of the following macros. The "SRT" prefix means "SELECT Result
15338 ** Type".
15339 **
15340 ** SRT_Union Store results as a key in a temporary index
15341 ** identified by pDest->iSDParm.
15342 **
15343 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
15344 **
15345 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
15346 ** set is not empty.
15347 **
15348 ** SRT_Discard Throw the results away. This is used by SELECT
15349 ** statements within triggers whose only purpose is
15350 ** the side-effects of functions.
15351 **
15352 ** All of the above are free to ignore their ORDER BY clause. Those that
15353 ** follow must honor the ORDER BY clause.
15354 **
15355 ** SRT_Output Generate a row of output (using the OP_ResultRow
15356 ** opcode) for each row in the result set.
15357 **
15358 ** SRT_Mem Only valid if the result is a single column.
15359 ** Store the first column of the first result row
15360 ** in register pDest->iSDParm then abandon the rest
15361 ** of the query. This destination implies "LIMIT 1".
15362 **
15363 ** SRT_Set The result must be a single column. Store each
15364 ** row of result as the key in table pDest->iSDParm.
15365 ** Apply the affinity pDest->affSdst before storing
15366 ** results. Used to implement "IN (SELECT ...)".
15367 **
15368 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
15369 ** the result there. The cursor is left open after
15370 ** returning. This is like SRT_Table except that
15371 ** this destination uses OP_OpenEphemeral to create
15372 ** the table first.
15373 **
15374 ** SRT_Coroutine Generate a co-routine that returns a new row of
15375 ** results each time it is invoked. The entry point
15376 ** of the co-routine is stored in register pDest->iSDParm
15377 ** and the result row is stored in pDest->nDest registers
15378 ** starting with pDest->iSdst.
15379 **
15380 ** SRT_Table Store results in temporary table pDest->iSDParm.
15381 ** SRT_Fifo This is like SRT_EphemTab except that the table
15382 ** is assumed to already be open. SRT_Fifo has
15383 ** the additional property of being able to ignore
15384 ** the ORDER BY clause.
15385 **
15386 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
15387 ** But also use temporary table pDest->iSDParm+1 as
15388 ** a record of all prior results and ignore any duplicate
15389 ** rows. Name means: "Distinct Fifo".
15390 **
15391 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
15392 ** an index). Append a sequence number so that all entries
15393 ** are distinct.
15394 **
15395 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
15396 ** the same record has never been stored before. The
15397 ** index at pDest->iSDParm+1 hold all prior stores.
15398 */
15399 #define SRT_Union 1 /* Store result as keys in an index */
15400 #define SRT_Except 2 /* Remove result from a UNION index */
15401 #define SRT_Exists 3 /* Store 1 if the result is not empty */
15402 #define SRT_Discard 4 /* Do not save the results anywhere */
15403 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
15404 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
15405 #define SRT_Queue 7 /* Store result in an queue */
15406 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
15407 
15408 /* The ORDER BY clause is ignored for all of the above */
15409 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
15410 
15411 #define SRT_Output 9 /* Output each row of result */
15412 #define SRT_Mem 10 /* Store result in a memory cell */
15413 #define SRT_Set 11 /* Store results as keys in an index */
15414 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
15415 #define SRT_Coroutine 13 /* Generate a single row of result */
15416 #define SRT_Table 14 /* Store result as data with an automatic rowid */
15417 
15418 /*
15419 ** An instance of this object describes where to put of the results of
15420 ** a SELECT statement.
15421 */
15422 struct SelectDest {
15423  u8 eDest; /* How to dispose of the results. On of SRT_* above. */
15424  char *zAffSdst; /* Affinity used when eDest==SRT_Set */
15425  int iSDParm; /* A parameter used by the eDest disposal method */
15426  int iSdst; /* Base register where results are written */
15427  int nSdst; /* Number of registers allocated */
15428  ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
15429 };
15430 
15431 /*
15432 ** During code generation of statements that do inserts into AUTOINCREMENT
15433 ** tables, the following information is attached to the Table.u.autoInc.p
15434 ** pointer of each autoincrement table to record some side information that
15435 ** the code generator needs. We have to keep per-table autoincrement
15436 ** information in case inserts are done within triggers. Triggers do not
15437 ** normally coordinate their activities, but we do need to coordinate the
15438 ** loading and saving of autoincrement information.
15439 */
15440 struct AutoincInfo {
15441  AutoincInfo *pNext; /* Next info block in a list of them all */
15442  Table *pTab; /* Table this info block refers to */
15443  int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
15444  int regCtr; /* Memory register holding the rowid counter */
15445 };
15446 
15447 /*
15448 ** Size of the column cache
15449 */
15450 #ifndef SQLITE_N_COLCACHE
15451 # define SQLITE_N_COLCACHE 10
15452 #endif
15453 
15454 /*
15455 ** At least one instance of the following structure is created for each
15456 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
15457 ** statement. All such objects are stored in the linked list headed at
15458 ** Parse.pTriggerPrg and deleted once statement compilation has been
15459 ** completed.
15460 **
15461 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
15462 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
15463 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
15464 ** The Parse.pTriggerPrg list never contains two entries with the same
15465 ** values for both pTrigger and orconf.
15466 **
15467 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
15468 ** accessed (or set to 0 for triggers fired as a result of INSERT
15469 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
15470 ** a mask of new.* columns used by the program.
15471 */
15472 struct TriggerPrg {
15473  Trigger *pTrigger; /* Trigger this program was coded from */
15474  TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
15475  SubProgram *pProgram; /* Program implementing pTrigger/orconf */
15476  int orconf; /* Default ON CONFLICT policy */
15477  u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
15478 };
15479 
15480 /*
15481 ** The yDbMask datatype for the bitmask of all attached databases.
15482 */
15483 #if SQLITE_MAX_ATTACHED>30
15484  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
15485 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
15486 # define DbMaskZero(M) memset((M),0,sizeof(M))
15487 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
15488 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
15489 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
15490 #else
15491  typedef unsigned int yDbMask;
15492 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
15493 # define DbMaskZero(M) (M)=0
15494 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
15495 # define DbMaskAllZero(M) (M)==0
15496 # define DbMaskNonZero(M) (M)!=0
15497 #endif
15498 
15499 /*
15500 ** An SQL parser context. A copy of this structure is passed through
15501 ** the parser and down into all the parser action routine in order to
15502 ** carry around information that is global to the entire parse.
15503 **
15504 ** The structure is divided into two parts. When the parser and code
15505 ** generate call themselves recursively, the first part of the structure
15506 ** is constant but the second part is reset at the beginning and end of
15507 ** each recursion.
15508 **
15509 ** The nTableLock and aTableLock variables are only used if the shared-cache
15510 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
15511 ** used to store the set of table-locks required by the statement being
15512 ** compiled. Function sqlite3TableLock() is used to add entries to the
15513 ** list.
15514 */
15515 struct Parse {
15516  sqlite3 *db; /* The main database structure */
15517  char *zErrMsg; /* An error message */
15518  Vdbe *pVdbe; /* An engine for executing database bytecode */
15519  int rc; /* Return code from execution */
15520  u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
15521  u8 checkSchema; /* Causes schema cookie check after an error */
15522  u8 nested; /* Number of nested calls to the parser/code generator */
15523  u8 nTempReg; /* Number of temporary registers in aTempReg[] */
15524  u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
15525  u8 mayAbort; /* True if statement may throw an ABORT exception */
15526  u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
15527  u8 okConstFactor; /* OK to factor out constants */
15528  u8 disableLookaside; /* Number of times lookaside has been disabled */
15529  u8 nColCache; /* Number of entries in aColCache[] */
15530  int nRangeReg; /* Size of the temporary register block */
15531  int iRangeReg; /* First register in temporary register block */
15532  int nErr; /* Number of errors seen */
15533  int nTab; /* Number of previously allocated VDBE cursors */
15534  int nMem; /* Number of memory cells used so far */
15535  int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
15536  int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
15537  int ckBase; /* Base register of data during check constraints */
15538  int iSelfTab; /* Table of an index whose exprs are being coded */
15539  int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
15540  int iCacheCnt; /* Counter used to generate aColCache[].lru values */
15541  int nLabel; /* Number of labels used */
15542  int *aLabel; /* Space to hold the labels */
15543  ExprList *pConstExpr;/* Constant expressions */
15544  Token constraintName;/* Name of the constraint currently being parsed */
15545  yDbMask writeMask; /* Start a write transaction on these databases */
15546  yDbMask cookieMask; /* Bitmask of schema verified databases */
15547  int regRowid; /* Register holding rowid of CREATE TABLE entry */
15548  int regRoot; /* Register holding root page number for new objects */
15549  int nMaxArg; /* Max args passed to user function by sub-program */
15550 #if SELECTTRACE_ENABLED
15551  int nSelect; /* Number of SELECT statements seen */
15552  int nSelectIndent; /* How far to indent SELECTTRACE() output */
15553 #endif
15554 #ifndef SQLITE_OMIT_SHARED_CACHE
15555  int nTableLock; /* Number of locks in aTableLock */
15556  TableLock *aTableLock; /* Required table locks for shared-cache mode */
15557 #endif
15558  AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
15559  Parse *pToplevel; /* Parse structure for main program (or NULL) */
15560  Table *pTriggerTab; /* Table triggers are being coded for */
15561  int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
15562  u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
15563  u32 oldmask; /* Mask of old.* columns referenced */
15564  u32 newmask; /* Mask of new.* columns referenced */
15565  u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
15566  u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
15567  u8 disableTriggers; /* True to disable triggers */
15568 
15569  /**************************************************************************
15570  ** Fields above must be initialized to zero. The fields that follow,
15571  ** down to the beginning of the recursive section, do not need to be
15572  ** initialized as they will be set before being used. The boundary is
15573  ** determined by offsetof(Parse,aColCache).
15574  **************************************************************************/
15575 
15576  struct yColCache {
15577  int iTable; /* Table cursor number */
15578  i16 iColumn; /* Table column number */
15579  u8 tempReg; /* iReg is a temp register that needs to be freed */
15580  int iLevel; /* Nesting level */
15581  int iReg; /* Reg with value of this column. 0 means none. */
15582  int lru; /* Least recently used entry has the smallest value */
15583  } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
15584  int aTempReg[8]; /* Holding area for temporary registers */
15585  Token sNameToken; /* Token with unqualified schema object name */
15586 
15587  /************************************************************************
15588  ** Above is constant between recursions. Below is reset before and after
15589  ** each recursion. The boundary between these two regions is determined
15590  ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
15591  ** first field in the recursive region.
15592  ************************************************************************/
15593 
15594  Token sLastToken; /* The last token parsed */
15595  ynVar nVar; /* Number of '?' variables seen in the SQL so far */
15596  int nzVar; /* Number of available slots in azVar[] */
15597  u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
15598  u8 explain; /* True if the EXPLAIN flag is found on the query */
15599 #ifndef SQLITE_OMIT_VIRTUALTABLE
15600  u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
15601  int nVtabLock; /* Number of virtual tables to lock */
15602 #endif
15603  int nHeight; /* Expression tree height of current sub-select */
15604 #ifndef SQLITE_OMIT_EXPLAIN
15605  int iSelectId; /* ID of current select for EXPLAIN output */
15606  int iNextSelectId; /* Next available select ID for EXPLAIN output */
15607 #endif
15608  char **azVar; /* Pointers to names of parameters */
15609  Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
15610  const char *zTail; /* All SQL text past the last semicolon parsed */
15611  Table *pNewTable; /* A table being constructed by CREATE TABLE */
15612  Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
15613  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
15614 #ifndef SQLITE_OMIT_VIRTUALTABLE
15615  Token sArg; /* Complete text of a module argument */
15616  Table **apVtabLock; /* Pointer to virtual tables needing locking */
15617 #endif
15618  Table *pZombieTab; /* List of Table objects to delete after code gen */
15619  TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
15620  With *pWith; /* Current WITH clause, or NULL */
15621  With *pWithToFree; /* Free this WITH object at the end of the parse */
15622 };
15623 
15624 /*
15625 ** Sizes and pointers of various parts of the Parse object.
15626 */
15627 #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
15628 #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
15629 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
15630 #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
15631 
15632 /*
15633 ** Return true if currently inside an sqlite3_declare_vtab() call.
15634 */
15635 #ifdef SQLITE_OMIT_VIRTUALTABLE
15636  #define IN_DECLARE_VTAB 0
15637 #else
15638  #define IN_DECLARE_VTAB (pParse->declareVtab)
15639 #endif
15640 
15641 /*
15642 ** An instance of the following structure can be declared on a stack and used
15643 ** to save the Parse.zAuthContext value so that it can be restored later.
15644 */
15645 struct AuthContext {
15646  const char *zAuthContext; /* Put saved Parse.zAuthContext here */
15647  Parse *pParse; /* The Parse structure */
15648 };
15649 
15650 /*
15651 ** Bitfield flags for P5 value in various opcodes.
15652 **
15653 ** Value constraints (enforced via assert()):
15654 ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
15655 ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
15656 ** OPFLAG_BULKCSR == BTREE_BULKLOAD
15657 ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
15658 ** OPFLAG_FORDELETE == BTREE_FORDELETE
15659 ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15660 ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
15661 */
15662 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
15663  /* Also used in P2 (not P5) of OP_Delete */
15664 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
15665 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
15666 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
15667 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
15668 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
15669 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15670 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
15671 #endif
15672 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
15673 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
15674 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
15675 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
15676 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
15677 #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
15678 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
15679 #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete: keep cursor position */
15680 #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
15681 
15682 /*
15683  * Each trigger present in the database schema is stored as an instance of
15684  * struct Trigger.
15685  *
15686  * Pointers to instances of struct Trigger are stored in two ways.
15687  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
15688  * database). This allows Trigger structures to be retrieved by name.
15689  * 2. All triggers associated with a single table form a linked list, using the
15690  * pNext member of struct Trigger. A pointer to the first element of the
15691  * linked list is stored as the "pTrigger" member of the associated
15692  * struct Table.
15693  *
15694  * The "step_list" member points to the first element of a linked list
15695  * containing the SQL statements specified as the trigger program.
15696  */
15697 struct Trigger {
15698  char *zName; /* The name of the trigger */
15699  char *table; /* The table or view to which the trigger applies */
15700  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
15701  u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
15702  Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
15703  IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
15704  the <column-list> is stored here */
15705  Schema *pSchema; /* Schema containing the trigger */
15706  Schema *pTabSchema; /* Schema containing the table */
15707  TriggerStep *step_list; /* Link list of trigger program steps */
15708  Trigger *pNext; /* Next trigger associated with the table */
15709 };
15710 
15711 /*
15712 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
15713 ** determine which.
15714 **
15715 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
15716 ** In that cases, the constants below can be ORed together.
15717 */
15718 #define TRIGGER_BEFORE 1
15719 #define TRIGGER_AFTER 2
15720 
15721 /*
15722  * An instance of struct TriggerStep is used to store a single SQL statement
15723  * that is a part of a trigger-program.
15724  *
15725  * Instances of struct TriggerStep are stored in a singly linked list (linked
15726  * using the "pNext" member) referenced by the "step_list" member of the
15727  * associated struct Trigger instance. The first element of the linked list is
15728  * the first step of the trigger-program.
15729  *
15730  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
15731  * "SELECT" statement. The meanings of the other members is determined by the
15732  * value of "op" as follows:
15733  *
15734  * (op == TK_INSERT)
15735  * orconf -> stores the ON CONFLICT algorithm
15736  * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
15737  * this stores a pointer to the SELECT statement. Otherwise NULL.
15738  * zTarget -> Dequoted name of the table to insert into.
15739  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
15740  * this stores values to be inserted. Otherwise NULL.
15741  * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
15742  * statement, then this stores the column-names to be
15743  * inserted into.
15744  *
15745  * (op == TK_DELETE)
15746  * zTarget -> Dequoted name of the table to delete from.
15747  * pWhere -> The WHERE clause of the DELETE statement if one is specified.
15748  * Otherwise NULL.
15749  *
15750  * (op == TK_UPDATE)
15751  * zTarget -> Dequoted name of the table to update.
15752  * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
15753  * Otherwise NULL.
15754  * pExprList -> A list of the columns to update and the expressions to update
15755  * them to. See sqlite3Update() documentation of "pChanges"
15756  * argument.
15757  *
15758  */
15759 struct TriggerStep {
15760  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
15761  u8 orconf; /* OE_Rollback etc. */
15762  Trigger *pTrig; /* The trigger that this step is a part of */
15763  Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
15764  char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
15765  Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
15766  ExprList *pExprList; /* SET clause for UPDATE. */
15767  IdList *pIdList; /* Column names for INSERT */
15768  TriggerStep *pNext; /* Next in the link-list */
15769  TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
15770 };
15771 
15772 /*
15773 ** The following structure contains information used by the sqliteFix...
15774 ** routines as they walk the parse tree to make database references
15775 ** explicit.
15776 */
15777 typedef struct DbFixer DbFixer;
15778 struct DbFixer {
15779  Parse *pParse; /* The parsing context. Error messages written here */
15780  Schema *pSchema; /* Fix items to this schema */
15781  int bVarOnly; /* Check for variable references only */
15782  const char *zDb; /* Make sure all objects are contained in this database */
15783  const char *zType; /* Type of the container - used for error messages */
15784  const Token *pName; /* Name of the container - used for error messages */
15785 };
15786 
15787 /*
15788 ** An objected used to accumulate the text of a string where we
15789 ** do not necessarily know how big the string will be in the end.
15790 */
15791 struct StrAccum {
15792  sqlite3 *db; /* Optional database for lookaside. Can be NULL */
15793  char *zBase; /* A base allocation. Not from malloc. */
15794  char *zText; /* The string collected so far */
15795  u32 nChar; /* Length of the string so far */
15796  u32 nAlloc; /* Amount of space allocated in zText */
15797  u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
15798  u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
15799  u8 printfFlags; /* SQLITE_PRINTF flags below */
15800 };
15801 #define STRACCUM_NOMEM 1
15802 #define STRACCUM_TOOBIG 2
15803 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
15804 #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
15805 #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
15806 
15807 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
15808 
15809 
15810 /*
15811 ** A pointer to this structure is used to communicate information
15812 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
15813 */
15814 typedef struct {
15815  sqlite3 *db; /* The database being initialized */
15816  char **pzErrMsg; /* Error message stored here */
15817  int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
15818  int rc; /* Result code stored here */
15819 } InitData;
15820 
15821 /*
15822 ** Structure containing global configuration data for the SQLite library.
15823 **
15824 ** This structure also contains some state information.
15825 */
15827  int bMemstat; /* True to enable memory status */
15828  int bCoreMutex; /* True to enable core mutexing */
15829  int bFullMutex; /* True to enable full mutexing */
15830  int bOpenUri; /* True to interpret filenames as URIs */
15831  int bUseCis; /* Use covering indices for full-scans */
15832  int mxStrlen; /* Maximum string length */
15833  int neverCorrupt; /* Database is always well-formed */
15834  int szLookaside; /* Default lookaside buffer size */
15835  int nLookaside; /* Default lookaside buffer count */
15836  int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
15837  sqlite3_mem_methods m; /* Low-level memory allocation interface */
15838  sqlite3_mutex_methods mutex; /* Low-level mutex interface */
15839  sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
15840  void *pHeap; /* Heap storage space */
15841  int nHeap; /* Size of pHeap[] */
15842  int mnReq, mxReq; /* Min and max heap requests sizes */
15843  sqlite3_int64 szMmap; /* mmap() space per open file */
15844  sqlite3_int64 mxMmap; /* Maximum value for szMmap */
15845  void *pScratch; /* Scratch memory */
15846  int szScratch; /* Size of each scratch buffer */
15847  int nScratch; /* Number of scratch buffers */
15848  void *pPage; /* Page cache memory */
15849  int szPage; /* Size of each page in pPage[] */
15850  int nPage; /* Number of pages in pPage[] */
15851  int mxParserStack; /* maximum depth of the parser stack */
15852  int sharedCacheEnabled; /* true if shared-cache mode enabled */
15853  u32 szPma; /* Maximum Sorter PMA size */
15854  /* The above might be initialized to non-zero. The following need to always
15855  ** initially be zero, however. */
15856  int isInit; /* True after initialization has finished */
15857  int inProgress; /* True while initialization in progress */
15858  int isMutexInit; /* True after mutexes are initialized */
15859  int isMallocInit; /* True after malloc is initialized */
15860  int isPCacheInit; /* True after malloc is initialized */
15861  int nRefInitMutex; /* Number of users of pInitMutex */
15862  sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
15863  void (*xLog)(void*,int,const char*); /* Function for logging */
15864  void *pLogArg; /* First argument to xLog() */
15865 #ifdef SQLITE_ENABLE_SQLLOG
15866  void(*xSqllog)(void*,sqlite3*,const char*, int);
15867  void *pSqllogArg;
15868 #endif
15869 #ifdef SQLITE_VDBE_COVERAGE
15870  /* The following callback (if not NULL) is invoked on every VDBE branch
15871  ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
15872  */
15873  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
15874  void *pVdbeBranchArg; /* 1st argument */
15875 #endif
15876 #ifndef SQLITE_OMIT_BUILTIN_TEST
15877  int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
15878 #endif
15879  int bLocaltimeFault; /* True to fail localtime() calls */
15880  int iOnceResetThreshold; /* When to reset OP_Once counters */
15881 };
15882 
15883 /*
15884 ** This macro is used inside of assert() statements to indicate that
15885 ** the assert is only valid on a well-formed database. Instead of:
15886 **
15887 ** assert( X );
15888 **
15889 ** One writes:
15890 **
15891 ** assert( X || CORRUPT_DB );
15892 **
15893 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
15894 ** that the database is definitely corrupt, only that it might be corrupt.
15895 ** For most test cases, CORRUPT_DB is set to false using a special
15896 ** sqlite3_test_control(). This enables assert() statements to prove
15897 ** things that are always true for well-formed databases.
15898 */
15899 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
15900 
15901 /*
15902 ** Context pointer passed down through the tree-walk.
15903 */
15904 struct Walker {
15905  Parse *pParse; /* Parser context. */
15906  int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
15907  int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
15908  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
15909  int walkerDepth; /* Number of subqueries */
15910  u8 eCode; /* A small processing code */
15911  union { /* Extra data for callback */
15912  NameContext *pNC; /* Naming context */
15913  int n; /* A counter */
15914  int iCur; /* A cursor number */
15915  SrcList *pSrcList; /* FROM clause */
15916  struct SrcCount *pSrcCount; /* Counting column references */
15917  struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
15918  int *aiCol; /* array of column indexes */
15919  struct IdxCover *pIdxCover; /* Check for index coverage */
15920  } u;
15921 };
15922 
15923 /* Forward declarations */
15930 
15931 /*
15932 ** Return code from the parse-tree walking primitives and their
15933 ** callbacks.
15934 */
15935 #define WRC_Continue 0 /* Continue down into children */
15936 #define WRC_Prune 1 /* Omit children but continue walking siblings */
15937 #define WRC_Abort 2 /* Abandon the tree walk */
15938 
15939 /*
15940 ** An instance of this structure represents a set of one or more CTEs
15941 ** (common table expressions) created by a single WITH clause.
15942 */
15943 struct With {
15944  int nCte; /* Number of CTEs in the WITH clause */
15945  With *pOuter; /* Containing WITH clause, or NULL */
15946  struct Cte { /* For each CTE in the WITH clause.... */
15947  char *zName; /* Name of this CTE */
15948  ExprList *pCols; /* List of explicit column names, or NULL */
15949  Select *pSelect; /* The definition of this CTE */
15950  const char *zCteErr; /* Error message for circular references */
15951  } a[1];
15952 };
15953 
15954 #ifdef SQLITE_DEBUG
15955 /*
15956 ** An instance of the TreeView object is used for printing the content of
15957 ** data structures on sqlite3DebugPrintf() using a tree-like view.
15958 */
15959 struct TreeView {
15960  int iLevel; /* Which level of the tree we are on */
15961  u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
15962 };
15963 #endif /* SQLITE_DEBUG */
15964 
15965 /*
15966 ** Assuming zIn points to the first byte of a UTF-8 character,
15967 ** advance zIn to point to the first byte of the next UTF-8 character.
15968 */
15969 #define SQLITE_SKIP_UTF8(zIn) { \
15970  if( (*(zIn++))>=0xc0 ){ \
15971  while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
15972  } \
15973 }
15974 
15975 /*
15976 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
15977 ** the same name but without the _BKPT suffix. These macros invoke
15978 ** routines that report the line-number on which the error originated
15979 ** using sqlite3_log(). The routines also provide a convenient place
15980 ** to set a debugger breakpoint.
15981 */
15985 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
15986 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
15987 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
15988 #ifdef SQLITE_DEBUG
15989 SQLITE_PRIVATE int sqlite3NomemError(int);
15990 SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
15991 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
15992 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
15993 #else
15994 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
15995 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
15996 #endif
15997 
15998 /*
15999 ** FTS3 and FTS4 both require virtual table support
16000 */
16001 #if defined(SQLITE_OMIT_VIRTUALTABLE)
16002 # undef SQLITE_ENABLE_FTS3
16003 # undef SQLITE_ENABLE_FTS4
16004 #endif
16005 
16006 /*
16007 ** FTS4 is really an extension for FTS3. It is enabled using the
16008 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
16009 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
16010 */
16011 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
16012 # define SQLITE_ENABLE_FTS3 1
16013 #endif
16014 
16015 /*
16016 ** The ctype.h header is needed for non-ASCII systems. It is also
16017 ** needed by FTS3 when FTS3 is included in the amalgamation.
16018 */
16019 #if !defined(SQLITE_ASCII) || \
16020  (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
16021 # include <ctype.h>
16022 #endif
16023 
16024 /*
16025 ** The following macros mimic the standard library functions toupper(),
16026 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
16027 ** sqlite versions only work for ASCII characters, regardless of locale.
16028 */
16029 #ifdef SQLITE_ASCII
16030 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
16031 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
16032 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
16033 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
16034 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
16035 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
16036 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
16037 # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
16038 #else
16039 # define sqlite3Toupper(x) toupper((unsigned char)(x))
16040 # define sqlite3Isspace(x) isspace((unsigned char)(x))
16041 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
16042 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
16043 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
16044 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
16045 # define sqlite3Tolower(x) tolower((unsigned char)(x))
16046 # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
16047 #endif
16048 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
16050 #endif
16051 
16052 /*
16053 ** Internal function prototypes
16054 */
16055 SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
16056 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
16058 #define sqlite3StrNICmp sqlite3_strnicmp
16059 
16061 SQLITE_PRIVATE void sqlite3MallocEnd(void);
16062 SQLITE_PRIVATE void *sqlite3Malloc(u64);
16067 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
16068 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
16069 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
16070 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
16071 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
16072 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
16078 SQLITE_PRIVATE void sqlite3PageFree(void*);
16080 #ifndef SQLITE_OMIT_BUILTIN_TEST
16081 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
16082 #endif
16084 
16085 /*
16086 ** On systems with ample stack space and that support alloca(), make
16087 ** use of alloca() to obtain space for large automatic objects. By default,
16088 ** obtain space from malloc().
16089 **
16090 ** The alloca() routine never returns NULL. This will cause code paths
16091 ** that deal with sqlite3StackAlloc() failures to be unreachable.
16092 */
16093 #ifdef SQLITE_USE_ALLOCA
16094 # define sqlite3StackAllocRaw(D,N) alloca(N)
16095 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
16096 # define sqlite3StackFree(D,P)
16097 #else
16098 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
16099 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
16100 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
16101 #endif
16102 
16103 /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
16104 ** are, disable MEMSYS3
16105 */
16106 #ifdef SQLITE_ENABLE_MEMSYS5
16107 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
16108 #undef SQLITE_ENABLE_MEMSYS3
16109 #endif
16110 #ifdef SQLITE_ENABLE_MEMSYS3
16111 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
16112 #endif
16113 
16114 
16115 #ifndef SQLITE_MUTEX_OMIT
16121 #endif
16122 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
16124 #else
16125 # define sqlite3MemoryBarrier()
16126 #endif
16127 
16128 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
16129 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
16130 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
16131 SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
16132 
16133 /* Access to mutexes used by sqlite3_status() */
16136 
16137 #ifndef SQLITE_OMIT_FLOATING_POINT
16138 SQLITE_PRIVATE int sqlite3IsNaN(double);
16139 #else
16140 # define sqlite3IsNaN(X) 0
16141 #endif
16142 
16143 /*
16144 ** An instance of the following structure holds information about SQL
16145 ** functions arguments that are the parameters to the printf() function.
16146 */
16148  int nArg; /* Total number of arguments */
16149  int nUsed; /* Number of arguments used so far */
16150  sqlite3_value **apArg; /* The argument values */
16151 };
16152 
16153 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
16154 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
16155 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
16156 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
16157 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
16158 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
16159 #endif
16160 #if defined(SQLITE_TEST)
16161 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
16162 #endif
16163 
16164 #if defined(SQLITE_DEBUG)
16165 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
16166 SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
16167 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
16168 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
16169 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
16170 #endif
16171 
16172 
16173 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
16174 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
16175 SQLITE_PRIVATE void sqlite3Dequote(char*);
16177 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
16178 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
16185 #ifdef SQLITE_DEBUG
16186 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
16187 #endif
16189 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
16191 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
16204 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
16205 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
16218 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
16219 #if SQLITE_ENABLE_HIDDEN_COLUMNS
16221 #else
16222 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
16223 #endif
16226 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
16231 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
16232  sqlite3_vfs**,char**,char **);
16234 
16235 #ifdef SQLITE_OMIT_BUILTIN_TEST
16236 # define sqlite3FaultSim(X) SQLITE_OK
16237 #else
16239 #endif
16240 
16245 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
16248 #ifndef SQLITE_OMIT_BUILTIN_TEST
16250 #endif
16251 
16252 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
16255 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
16257 
16259 
16260 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
16262 #else
16263 # define sqlite3ViewGetColumnNames(A,B) 0
16264 #endif
16265 
16266 #if SQLITE_MAX_ATTACHED>30
16267 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
16268 #endif
16269 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
16270 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
16272 #ifndef SQLITE_OMIT_AUTOINCREMENT
16275 #else
16276 # define sqlite3AutoincrementBegin(X)
16277 # define sqlite3AutoincrementEnd(X)
16278 #endif
16280 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
16282 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
16286  Token*, Select*, Expr*, IdList*);
16289 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
16296  Expr*, int, int, u8);
16300  Expr*,ExprList*,u32,Expr*,Expr*);
16304 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
16305 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
16306 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
16307 #endif
16320 #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
16321 #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
16322 #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
16324 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
16327 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
16328 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
16342 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
16343 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
16344 #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
16345 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
16346 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
16347 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
16348 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
16349 #define LOCATE_VIEW 0x01
16350 #define LOCATE_NOERR 0x02
16351 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
16352 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
16353 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
16354 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
16355 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
16357 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
16364 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
16367 #ifndef SQLITE_OMIT_BUILTIN_TEST
16370 #endif
16373 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
16384 #ifdef SQLITE_ENABLE_CURSOR_HINTS
16385 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
16386 #endif
16390 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
16392  Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
16393 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
16394 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
16396 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
16397  u8,u8,int,int*,int*);
16398 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
16399 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
16403 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
16411 #if SELECTTRACE_ENABLED
16412 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
16413 #else
16414 # define sqlite3SelectSetName(A,B)
16415 #endif
16417 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
16424 
16425 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
16427 #endif
16428 
16429 #ifndef SQLITE_OMIT_TRIGGER
16431  Expr*,int, int);
16438  int, int, int);
16439 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
16440  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
16444  Select*,u8);
16450 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
16451 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
16452 #else
16453 # define sqlite3TriggersExist(B,C,D,E,F) 0
16454 # define sqlite3DeleteTrigger(A,B)
16455 # define sqlite3DropTriggerPtr(A,B)
16456 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
16457 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
16458 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
16459 # define sqlite3TriggerList(X, Y) 0
16460 # define sqlite3ParseToplevel(p) p
16461 # define sqlite3IsToplevel(p) 1
16462 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
16463 #endif
16464 
16468 #ifndef SQLITE_OMIT_AUTHORIZATION
16470 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
16473 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
16474 #else
16475 # define sqlite3AuthRead(a,b,c,d)
16476 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
16477 # define sqlite3AuthContextPush(a,b,c)
16478 # define sqlite3AuthContextPop(a) ((void)(a))
16479 #endif
16482 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
16488 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
16489 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
16490 SQLITE_PRIVATE int sqlite3Atoi(const char*);
16491 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
16492 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
16493 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
16494 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
16495 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
16496 #ifndef SQLITE_OMIT_VIRTUALTABLE
16498 #endif
16499 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
16500  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
16501  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
16502 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
16503 #endif
16504 
16505 /*
16506 ** Routines to read and write variable-length integers. These used to
16507 ** be defined locally, but now we use the varint routines in the util.c
16508 ** file.
16509 */
16510 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
16511 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
16512 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
16513 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
16514 
16515 /*
16516 ** The common case is for a varint to be a single byte. They following
16517 ** macros handle the common case without a procedure call, but then call
16518 ** the procedure for larger varints.
16519 */
16520 #define getVarint32(A,B) \
16521  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
16522 #define putVarint32(A,B) \
16523  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
16524  sqlite3PutVarint((A),(B)))
16525 #define getVarint sqlite3GetVarint
16526 #define putVarint sqlite3PutVarint
16527 
16528 
16531 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
16532 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
16535 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
16536 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
16537 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
16540 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
16543 
16544 #if defined(SQLITE_NEED_ERR_NAME)
16545 SQLITE_PRIVATE const char *sqlite3ErrName(int);
16546 #endif
16547 
16548 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
16550 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
16551 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
16557 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
16559 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
16560 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
16561 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
16563 #ifdef SQLITE_ENABLE_8_3_NAMES
16564 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
16565 #else
16566 # define sqlite3FileSuffix3(X,Y)
16567 #endif
16568 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
16569 
16572 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
16573  void(*)(void*));
16577 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
16580 #ifndef SQLITE_AMALGAMATION
16581 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
16582 SQLITE_PRIVATE const char sqlite3StrBINARY[];
16583 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
16584 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
16588 #ifndef SQLITE_OMIT_WSD
16590 #endif
16591 #endif
16592 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
16596 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
16597 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
16599 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
16602 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
16608 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
16611 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
16612 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
16616 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
16622 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
16629 #ifdef SQLITE_DEBUG
16630 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
16631 #endif
16632 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
16633  void (*)(sqlite3_context*,int,sqlite3_value **),
16634  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
16635  FuncDestructor *pDestructor
16636 );
16639 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
16641 
16642 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
16643 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
16645 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
16650 
16652 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
16653 
16654 #ifndef SQLITE_OMIT_SUBQUERY
16656 #else
16657 # define sqlite3ExprCheckIN(x,y) SQLITE_OK
16658 #endif
16659 
16660 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
16661 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
16662 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
16663  Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
16664 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
16665 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
16666 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
16667 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
16668 #endif
16669 
16670 /*
16671 ** The interface to the LEMON-generated parser
16672 */
16673 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
16674 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
16675 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
16676 #ifdef YYTRACKMAXSTACKDEPTH
16677 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
16678 #endif
16679 
16681 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16683 #else
16684 # define sqlite3CloseExtensions(X)
16685 #endif
16686 
16687 #ifndef SQLITE_OMIT_SHARED_CACHE
16688 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
16689 #else
16690  #define sqlite3TableLock(v,w,x,y,z)
16691 #endif
16692 
16693 #ifdef SQLITE_TEST
16694 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
16695 #endif
16696 
16697 #ifdef SQLITE_OMIT_VIRTUALTABLE
16698 # define sqlite3VtabClear(Y)
16699 # define sqlite3VtabSync(X,Y) SQLITE_OK
16700 # define sqlite3VtabRollback(X)
16701 # define sqlite3VtabCommit(X)
16702 # define sqlite3VtabInSync(db) 0
16703 # define sqlite3VtabLock(X)
16704 # define sqlite3VtabUnlock(X)
16705 # define sqlite3VtabUnlockList(X)
16706 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
16707 # define sqlite3GetVTable(X,Y) ((VTable*)0)
16708 #else
16720 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
16721 #endif
16729 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
16731 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
16736 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
16743 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
16744 #ifndef SQLITE_OMIT_WAL
16745 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
16746 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
16747 #endif
16748 #ifndef SQLITE_OMIT_CTE
16752 #else
16753 #define sqlite3WithPush(x,y,z)
16754 #define sqlite3WithDelete(x,y)
16755 #endif
16756 
16757 /* Declarations for functions in fkey.c. All of these are replaced by
16758 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
16759 ** key functionality is available. If OMIT_TRIGGER is defined but
16760 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
16761 ** this case foreign keys are parsed, but no other functionality is
16762 ** provided (enforcement of FK constraints requires the triggers sub-system).
16763 */
16764 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
16765 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
16767 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
16768 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
16771 #else
16772  #define sqlite3FkActions(a,b,c,d,e,f)
16773  #define sqlite3FkCheck(a,b,c,d,e,f)
16774  #define sqlite3FkDropTable(a,b,c)
16775  #define sqlite3FkOldmask(a,b) 0
16776  #define sqlite3FkRequired(a,b,c,d) 0
16777 #endif
16778 #ifndef SQLITE_OMIT_FOREIGN_KEY
16781 #else
16782  #define sqlite3FkDelete(a,b)
16783  #define sqlite3FkLocateIndex(a,b,c,d,e)
16784 #endif
16785 
16786 
16787 /*
16788 ** Available fault injectors. Should be numbered beginning with 0.
16789 */
16790 #define SQLITE_FAULTINJECTOR_MALLOC 0
16791 #define SQLITE_FAULTINJECTOR_COUNT 1
16792 
16793 /*
16794 ** The interface to the code in fault.c used for identifying "benign"
16795 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
16796 ** is not defined.
16797 */
16798 #ifndef SQLITE_OMIT_BUILTIN_TEST
16801 #else
16802  #define sqlite3BeginBenignMalloc()
16803  #define sqlite3EndBenignMalloc()
16804 #endif
16805 
16806 /*
16807 ** Allowed return values from sqlite3FindInIndex()
16808 */
16809 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
16810 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
16811 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
16812 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
16813 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
16814 /*
16815 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
16816 */
16817 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
16818 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
16819 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
16820 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
16821 
16822 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
16823 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
16824 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
16825 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
16826 #endif
16827 
16828 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
16829 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
16830 
16832 #if SQLITE_MAX_EXPR_DEPTH>0
16835 #else
16836  #define sqlite3SelectExprHeight(x) 0
16837  #define sqlite3ExprCheckHeight(x,y)
16838 #endif
16839 
16840 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
16841 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
16842 
16843 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
16847 #else
16848  #define sqlite3ConnectionBlocked(x,y)
16849  #define sqlite3ConnectionUnlocked(x)
16850  #define sqlite3ConnectionClosed(x)
16851 #endif
16852 
16853 #ifdef SQLITE_DEBUG
16854 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
16855 #endif
16856 
16857 /*
16858 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
16859 ** sqlite3IoTrace is a pointer to a printf-like routine used to
16860 ** print I/O tracing messages.
16861 */
16862 #ifdef SQLITE_ENABLE_IOTRACE
16863 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
16865 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
16866 #else
16867 # define IOTRACE(A)
16868 # define sqlite3VdbeIOTraceSql(X)
16869 #endif
16870 
16871 /*
16872 ** These routines are available for the mem2.c debugging memory allocator
16873 ** only. They are used to verify that different "types" of memory
16874 ** allocations are properly tracked by the system.
16875 **
16876 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
16877 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
16878 ** a single bit set.
16879 **
16880 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
16881 ** argument match the type set by the previous sqlite3MemdebugSetType().
16882 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
16883 **
16884 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
16885 ** argument match the type set by the previous sqlite3MemdebugSetType().
16886 **
16887 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
16888 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
16889 ** it might have been allocated by lookaside, except the allocation was
16890 ** too large or lookaside was already full. It is important to verify
16891 ** that allocations that might have been satisfied by lookaside are not
16892 ** passed back to non-lookaside free() routines. Asserts such as the
16893 ** example above are placed on the non-lookaside free() routines to verify
16894 ** this constraint.
16895 **
16896 ** All of this is no-op for a production build. It only comes into
16897 ** play when the SQLITE_MEMDEBUG compile-time option is used.
16898 */
16899 #ifdef SQLITE_MEMDEBUG
16900 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
16903 #else
16904 # define sqlite3MemdebugSetType(X,Y) /* no-op */
16905 # define sqlite3MemdebugHasType(X,Y) 1
16906 # define sqlite3MemdebugNoType(X,Y) 1
16907 #endif
16908 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
16909 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
16910 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
16911 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
16912 
16913 /*
16914 ** Threading interface
16915 */
16916 #if SQLITE_MAX_WORKER_THREADS>0
16917 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
16919 #endif
16920 
16921 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
16922 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
16923 #endif
16924 
16929 
16930 #endif /* SQLITEINT_H */
16931 
16932 /************** End of sqliteInt.h *******************************************/
16933 /************** Begin file global.c ******************************************/
16934 /*
16935 ** 2008 June 13
16936 **
16937 ** The author disclaims copyright to this source code. In place of
16938 ** a legal notice, here is a blessing:
16939 **
16940 ** May you do good and not evil.
16941 ** May you find forgiveness for yourself and forgive others.
16942 ** May you share freely, never taking more than you give.
16943 **
16944 *************************************************************************
16945 **
16946 ** This file contains definitions of global variables and constants.
16947 */
16948 /* #include "sqliteInt.h" */
16949 
16950 /* An array to map all upper-case characters into their corresponding
16951 ** lower-case character.
16952 **
16953 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
16954 ** handle case conversions for the UTF character set since the tables
16955 ** involved are nearly as big or bigger than SQLite itself.
16956 */
16957 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
16958 #ifdef SQLITE_ASCII
16959  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
16960  18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
16961  36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
16962  54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
16963  104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
16964  122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
16965  108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
16966  126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
16967  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
16968  162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
16969  180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
16970  198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
16971  216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
16972  234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
16973  252,253,254,255
16974 #endif
16975 #ifdef SQLITE_EBCDIC
16976  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
16977  16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
16978  32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
16979  48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
16980  64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
16981  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
16982  96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
16983  112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
16984  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
16985  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
16986  160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
16987  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
16988  192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
16989  208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
16990  224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
16991  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
16992 #endif
16993 };
16994 
16995 /*
16996 ** The following 256 byte lookup table is used to support SQLites built-in
16997 ** equivalents to the following standard library functions:
16998 **
16999 ** isspace() 0x01
17000 ** isalpha() 0x02
17001 ** isdigit() 0x04
17002 ** isalnum() 0x06
17003 ** isxdigit() 0x08
17004 ** toupper() 0x20
17005 ** SQLite identifier character 0x40
17006 ** Quote character 0x80
17007 **
17008 ** Bit 0x20 is set if the mapped character requires translation to upper
17009 ** case. i.e. if the character is a lower-case ASCII character.
17010 ** If x is a lower-case ASCII character, then its upper-case equivalent
17011 ** is (x - 0x20). Therefore toupper() can be implemented as:
17012 **
17013 ** (x & ~(map[x]&0x20))
17014 **
17015 ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
17016 ** array. tolower() is used more often than toupper() by SQLite.
17017 **
17018 ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
17019 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
17020 ** non-ASCII UTF character. Hence the test for whether or not a character is
17021 ** part of an identifier is 0x46.
17022 */
17023 #ifdef SQLITE_ASCII
17024 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
17025  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
17026  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
17027  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
17028  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
17029  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
17030  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
17031  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
17032  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
17033 
17034  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
17035  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
17036  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
17037  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
17038  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
17039  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
17040  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
17041  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
17042 
17043  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
17044  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
17045  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
17046  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
17047  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
17048  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
17049  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
17050  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
17051 
17052  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
17053  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
17054  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
17055  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
17056  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
17057  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
17058  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
17059  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
17060 };
17061 #endif
17062 
17063 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
17064 ** compatibility for legacy applications, the URI filename capability is
17065 ** disabled by default.
17066 **
17067 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
17068 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
17069 **
17070 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
17071 ** disabled. The default value may be changed by compiling with the
17072 ** SQLITE_USE_URI symbol defined.
17073 */
17074 #ifndef SQLITE_USE_URI
17075 # define SQLITE_USE_URI 0
17076 #endif
17077 
17078 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
17079 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
17080 ** that compile-time option is omitted.
17081 */
17082 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
17083 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
17084 #endif
17085 
17086 /* The minimum PMA size is set to this value multiplied by the database
17087 ** page size in bytes.
17088 */
17089 #ifndef SQLITE_SORTER_PMASZ
17090 # define SQLITE_SORTER_PMASZ 250
17091 #endif
17092 
17093 /* Statement journals spill to disk when their size exceeds the following
17094 ** threshold (in bytes). 0 means that statement journals are created and
17095 ** written to disk immediately (the default behavior for SQLite versions
17096 ** before 3.12.0). -1 means always keep the entire statement journal in
17097 ** memory. (The statement journal is also always held entirely in memory
17098 ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
17099 ** setting.)
17100 */
17101 #ifndef SQLITE_STMTJRNL_SPILL
17102 # define SQLITE_STMTJRNL_SPILL (64*1024)
17103 #endif
17104 
17105 /*
17106 ** The following singleton contains the global configuration for
17107 ** the SQLite library.
17108 */
17110  SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
17111  1, /* bCoreMutex */
17112  SQLITE_THREADSAFE==1, /* bFullMutex */
17113  SQLITE_USE_URI, /* bOpenUri */
17114  SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
17115  0x7ffffffe, /* mxStrlen */
17116  0, /* neverCorrupt */
17117  128, /* szLookaside */
17118  500, /* nLookaside */
17119  SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
17120  {0,0,0,0,0,0,0,0}, /* m */
17121  {0,0,0,0,0,0,0,0,0}, /* mutex */
17122  {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
17123  (void*)0, /* pHeap */
17124  0, /* nHeap */
17125  0, 0, /* mnHeap, mxHeap */
17126  SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
17127  SQLITE_MAX_MMAP_SIZE, /* mxMmap */
17128  (void*)0, /* pScratch */
17129  0, /* szScratch */
17130  0, /* nScratch */
17131  (void*)0, /* pPage */
17132  0, /* szPage */
17133  SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
17134  0, /* mxParserStack */
17135  0, /* sharedCacheEnabled */
17136  SQLITE_SORTER_PMASZ, /* szPma */
17137  /* All the rest should always be initialized to zero */
17138  0, /* isInit */
17139  0, /* inProgress */
17140  0, /* isMutexInit */
17141  0, /* isMallocInit */
17142  0, /* isPCacheInit */
17143  0, /* nRefInitMutex */
17144  0, /* pInitMutex */
17145  0, /* xLog */
17146  0, /* pLogArg */
17147 #ifdef SQLITE_ENABLE_SQLLOG
17148  0, /* xSqllog */
17149  0, /* pSqllogArg */
17150 #endif
17151 #ifdef SQLITE_VDBE_COVERAGE
17152  0, /* xVdbeBranch */
17153  0, /* pVbeBranchArg */
17154 #endif
17155 #ifndef SQLITE_OMIT_BUILTIN_TEST
17156  0, /* xTestCallback */
17157 #endif
17158  0, /* bLocaltimeFault */
17159  0x7ffffffe /* iOnceResetThreshold */
17160 };
17161 
17162 /*
17163 ** Hash table for global functions - functions common to all
17164 ** database connections. After initialization, this table is
17165 ** read-only.
17166 */
17168 
17169 /*
17170 ** Constant tokens for values 0 and 1.
17171 */
17172 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
17173  { "0", 1 },
17174  { "1", 1 }
17175 };
17176 
17177 
17178 /*
17179 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
17180 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
17181 ** the database page that contains the pending byte. It never attempts
17182 ** to read or write that page. The pending byte page is set aside
17183 ** for use by the VFS layers as space for managing file locks.
17184 **
17185 ** During testing, it is often desirable to move the pending byte to
17186 ** a different position in the file. This allows code that has to
17187 ** deal with the pending byte to run on files that are much smaller
17188 ** than 1 GiB. The sqlite3_test_control() interface can be used to
17189 ** move the pending byte.
17190 **
17191 ** IMPORTANT: Changing the pending byte to any value other than
17192 ** 0x40000000 results in an incompatible database file format!
17193 ** Changing the pending byte during operation will result in undefined
17194 ** and incorrect behavior.
17195 */
17196 #ifndef SQLITE_OMIT_WSD
17197 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
17198 #endif
17199 
17200 /* #include "opcodes.h" */
17201 /*
17202 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
17203 ** created by mkopcodeh.awk during compilation. Data is obtained
17204 ** from the comments following the "case OP_xxxx:" statements in
17205 ** the vdbe.c file.
17206 */
17207 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
17208 
17209 /*
17210 ** Name of the default collating sequence
17211 */
17212 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
17213 
17214 /************** End of global.c **********************************************/
17215 /************** Begin file ctime.c *******************************************/
17216 /*
17217 ** 2010 February 23
17218 **
17219 ** The author disclaims copyright to this source code. In place of
17220 ** a legal notice, here is a blessing:
17221 **
17222 ** May you do good and not evil.
17223 ** May you find forgiveness for yourself and forgive others.
17224 ** May you share freely, never taking more than you give.
17225 **
17226 *************************************************************************
17227 **
17228 ** This file implements routines used to report what compile-time options
17229 ** SQLite was built with.
17230 */
17231 
17232 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17233 
17234 /* #include "sqliteInt.h" */
17235 
17236 /*
17237 ** An array of names of all compile-time options. This array should
17238 ** be sorted A-Z.
17239 **
17240 ** This array looks large, but in a typical installation actually uses
17241 ** only a handful of compile-time options, so most times this array is usually
17242 ** rather short and uses little memory space.
17243 */
17244 static const char * const azCompileOpt[] = {
17245 
17246 /* These macros are provided to "stringify" the value of the define
17247 ** for those options in which the value is meaningful. */
17248 #define CTIMEOPT_VAL_(opt) #opt
17249 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
17250 
17251 #if SQLITE_32BIT_ROWID
17252  "32BIT_ROWID",
17253 #endif
17254 #if SQLITE_4_BYTE_ALIGNED_MALLOC
17255  "4_BYTE_ALIGNED_MALLOC",
17256 #endif
17257 #if SQLITE_CASE_SENSITIVE_LIKE
17258  "CASE_SENSITIVE_LIKE",
17259 #endif
17260 #if SQLITE_CHECK_PAGES
17261  "CHECK_PAGES",
17262 #endif
17263 #if defined(__clang__) && defined(__clang_major__)
17264  "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
17265  CTIMEOPT_VAL(__clang_minor__) "."
17266  CTIMEOPT_VAL(__clang_patchlevel__),
17267 #elif defined(_MSC_VER)
17268  "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
17269 #elif defined(__GNUC__) && defined(__VERSION__)
17270  "COMPILER=gcc-" __VERSION__,
17271 #endif
17272 #if SQLITE_COVERAGE_TEST
17273  "COVERAGE_TEST",
17274 #endif
17275 #if SQLITE_DEBUG
17276  "DEBUG",
17277 #endif
17278 #if SQLITE_DEFAULT_LOCKING_MODE
17279  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
17280 #endif
17281 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
17282  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
17283 #endif
17284 #if SQLITE_DISABLE_DIRSYNC
17285  "DISABLE_DIRSYNC",
17286 #endif
17287 #if SQLITE_DISABLE_LFS
17288  "DISABLE_LFS",
17289 #endif
17290 #if SQLITE_ENABLE_8_3_NAMES
17291  "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
17292 #endif
17293 #if SQLITE_ENABLE_API_ARMOR
17294  "ENABLE_API_ARMOR",
17295 #endif
17296 #if SQLITE_ENABLE_ATOMIC_WRITE
17297  "ENABLE_ATOMIC_WRITE",
17298 #endif
17299 #if SQLITE_ENABLE_CEROD
17300  "ENABLE_CEROD",
17301 #endif
17302 #if SQLITE_ENABLE_COLUMN_METADATA
17303  "ENABLE_COLUMN_METADATA",
17304 #endif
17305 #if SQLITE_ENABLE_DBSTAT_VTAB
17306  "ENABLE_DBSTAT_VTAB",
17307 #endif
17308 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
17309  "ENABLE_EXPENSIVE_ASSERT",
17310 #endif
17311 #if SQLITE_ENABLE_FTS1
17312  "ENABLE_FTS1",
17313 #endif
17314 #if SQLITE_ENABLE_FTS2
17315  "ENABLE_FTS2",
17316 #endif
17317 #if SQLITE_ENABLE_FTS3
17318  "ENABLE_FTS3",
17319 #endif
17320 #if SQLITE_ENABLE_FTS3_PARENTHESIS
17321  "ENABLE_FTS3_PARENTHESIS",
17322 #endif
17323 #if SQLITE_ENABLE_FTS4
17324  "ENABLE_FTS4",
17325 #endif
17326 #if SQLITE_ENABLE_FTS5
17327  "ENABLE_FTS5",
17328 #endif
17329 #if SQLITE_ENABLE_ICU
17330  "ENABLE_ICU",
17331 #endif
17332 #if SQLITE_ENABLE_IOTRACE
17333  "ENABLE_IOTRACE",
17334 #endif
17335 #if SQLITE_ENABLE_JSON1
17336  "ENABLE_JSON1",
17337 #endif
17338 #if SQLITE_ENABLE_LOAD_EXTENSION
17339  "ENABLE_LOAD_EXTENSION",
17340 #endif
17341 #if SQLITE_ENABLE_LOCKING_STYLE
17342  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
17343 #endif
17344 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
17345  "ENABLE_MEMORY_MANAGEMENT",
17346 #endif
17347 #if SQLITE_ENABLE_MEMSYS3
17348  "ENABLE_MEMSYS3",
17349 #endif
17350 #if SQLITE_ENABLE_MEMSYS5
17351  "ENABLE_MEMSYS5",
17352 #endif
17353 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
17354  "ENABLE_OVERSIZE_CELL_CHECK",
17355 #endif
17356 #if SQLITE_ENABLE_RTREE
17357  "ENABLE_RTREE",
17358 #endif
17359 #if defined(SQLITE_ENABLE_STAT4)
17360  "ENABLE_STAT4",
17361 #elif defined(SQLITE_ENABLE_STAT3)
17362  "ENABLE_STAT3",
17363 #endif
17364 #if SQLITE_ENABLE_UNLOCK_NOTIFY
17365  "ENABLE_UNLOCK_NOTIFY",
17366 #endif
17367 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
17368  "ENABLE_UPDATE_DELETE_LIMIT",
17369 #endif
17370 #if SQLITE_HAS_CODEC
17371  "HAS_CODEC",
17372 #endif
17373 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
17374  "HAVE_ISNAN",
17375 #endif
17376 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17377  "HOMEGROWN_RECURSIVE_MUTEX",
17378 #endif
17379 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
17380  "IGNORE_AFP_LOCK_ERRORS",
17381 #endif
17382 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
17383  "IGNORE_FLOCK_LOCK_ERRORS",
17384 #endif
17385 #ifdef SQLITE_INT64_TYPE
17386  "INT64_TYPE",
17387 #endif
17388 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17389  "LIKE_DOESNT_MATCH_BLOBS",
17390 #endif
17391 #if SQLITE_LOCK_TRACE
17392  "LOCK_TRACE",
17393 #endif
17394 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
17395  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
17396 #endif
17397 #ifdef SQLITE_MAX_SCHEMA_RETRY
17398  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
17399 #endif
17400 #if SQLITE_MEMDEBUG
17401  "MEMDEBUG",
17402 #endif
17403 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
17404  "MIXED_ENDIAN_64BIT_FLOAT",
17405 #endif
17406 #if SQLITE_NO_SYNC
17407  "NO_SYNC",
17408 #endif
17409 #if SQLITE_OMIT_ALTERTABLE
17410  "OMIT_ALTERTABLE",
17411 #endif
17412 #if SQLITE_OMIT_ANALYZE
17413  "OMIT_ANALYZE",
17414 #endif
17415 #if SQLITE_OMIT_ATTACH
17416  "OMIT_ATTACH",
17417 #endif
17418 #if SQLITE_OMIT_AUTHORIZATION
17419  "OMIT_AUTHORIZATION",
17420 #endif
17421 #if SQLITE_OMIT_AUTOINCREMENT
17422  "OMIT_AUTOINCREMENT",
17423 #endif
17424 #if SQLITE_OMIT_AUTOINIT
17425  "OMIT_AUTOINIT",
17426 #endif
17427 #if SQLITE_OMIT_AUTOMATIC_INDEX
17428  "OMIT_AUTOMATIC_INDEX",
17429 #endif
17430 #if SQLITE_OMIT_AUTORESET
17431  "OMIT_AUTORESET",
17432 #endif
17433 #if SQLITE_OMIT_AUTOVACUUM
17434  "OMIT_AUTOVACUUM",
17435 #endif
17436 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
17437  "OMIT_BETWEEN_OPTIMIZATION",
17438 #endif
17439 #if SQLITE_OMIT_BLOB_LITERAL
17440  "OMIT_BLOB_LITERAL",
17441 #endif
17442 #if SQLITE_OMIT_BTREECOUNT
17443  "OMIT_BTREECOUNT",
17444 #endif
17445 #if SQLITE_OMIT_BUILTIN_TEST
17446  "OMIT_BUILTIN_TEST",
17447 #endif
17448 #if SQLITE_OMIT_CAST
17449  "OMIT_CAST",
17450 #endif
17451 #if SQLITE_OMIT_CHECK
17452  "OMIT_CHECK",
17453 #endif
17454 #if SQLITE_OMIT_COMPLETE
17455  "OMIT_COMPLETE",
17456 #endif
17457 #if SQLITE_OMIT_COMPOUND_SELECT
17458  "OMIT_COMPOUND_SELECT",
17459 #endif
17460 #if SQLITE_OMIT_CTE
17461  "OMIT_CTE",
17462 #endif
17463 #if SQLITE_OMIT_DATETIME_FUNCS
17464  "OMIT_DATETIME_FUNCS",
17465 #endif
17466 #if SQLITE_OMIT_DECLTYPE
17467  "OMIT_DECLTYPE",
17468 #endif
17469 #if SQLITE_OMIT_DEPRECATED
17470  "OMIT_DEPRECATED",
17471 #endif
17472 #if SQLITE_OMIT_DISKIO
17473  "OMIT_DISKIO",
17474 #endif
17475 #if SQLITE_OMIT_EXPLAIN
17476  "OMIT_EXPLAIN",
17477 #endif
17478 #if SQLITE_OMIT_FLAG_PRAGMAS
17479  "OMIT_FLAG_PRAGMAS",
17480 #endif
17481 #if SQLITE_OMIT_FLOATING_POINT
17482  "OMIT_FLOATING_POINT",
17483 #endif
17484 #if SQLITE_OMIT_FOREIGN_KEY
17485  "OMIT_FOREIGN_KEY",
17486 #endif
17487 #if SQLITE_OMIT_GET_TABLE
17488  "OMIT_GET_TABLE",
17489 #endif
17490 #if SQLITE_OMIT_INCRBLOB
17491  "OMIT_INCRBLOB",
17492 #endif
17493 #if SQLITE_OMIT_INTEGRITY_CHECK
17494  "OMIT_INTEGRITY_CHECK",
17495 #endif
17496 #if SQLITE_OMIT_LIKE_OPTIMIZATION
17497  "OMIT_LIKE_OPTIMIZATION",
17498 #endif
17499 #if SQLITE_OMIT_LOAD_EXTENSION
17500  "OMIT_LOAD_EXTENSION",
17501 #endif
17502 #if SQLITE_OMIT_LOCALTIME
17503  "OMIT_LOCALTIME",
17504 #endif
17505 #if SQLITE_OMIT_LOOKASIDE
17506  "OMIT_LOOKASIDE",
17507 #endif
17508 #if SQLITE_OMIT_MEMORYDB
17509  "OMIT_MEMORYDB",
17510 #endif
17511 #if SQLITE_OMIT_OR_OPTIMIZATION
17512  "OMIT_OR_OPTIMIZATION",
17513 #endif
17514 #if SQLITE_OMIT_PAGER_PRAGMAS
17515  "OMIT_PAGER_PRAGMAS",
17516 #endif
17517 #if SQLITE_OMIT_PRAGMA
17518  "OMIT_PRAGMA",
17519 #endif
17520 #if SQLITE_OMIT_PROGRESS_CALLBACK
17521  "OMIT_PROGRESS_CALLBACK",
17522 #endif
17523 #if SQLITE_OMIT_QUICKBALANCE
17524  "OMIT_QUICKBALANCE",
17525 #endif
17526 #if SQLITE_OMIT_REINDEX
17527  "OMIT_REINDEX",
17528 #endif
17529 #if SQLITE_OMIT_SCHEMA_PRAGMAS
17530  "OMIT_SCHEMA_PRAGMAS",
17531 #endif
17532 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
17533  "OMIT_SCHEMA_VERSION_PRAGMAS",
17534 #endif
17535 #if SQLITE_OMIT_SHARED_CACHE
17536  "OMIT_SHARED_CACHE",
17537 #endif
17538 #if SQLITE_OMIT_SUBQUERY
17539  "OMIT_SUBQUERY",
17540 #endif
17541 #if SQLITE_OMIT_TCL_VARIABLE
17542  "OMIT_TCL_VARIABLE",
17543 #endif
17544 #if SQLITE_OMIT_TEMPDB
17545  "OMIT_TEMPDB",
17546 #endif
17547 #if SQLITE_OMIT_TRACE
17548  "OMIT_TRACE",
17549 #endif
17550 #if SQLITE_OMIT_TRIGGER
17551  "OMIT_TRIGGER",
17552 #endif
17553 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
17554  "OMIT_TRUNCATE_OPTIMIZATION",
17555 #endif
17556 #if SQLITE_OMIT_UTF16
17557  "OMIT_UTF16",
17558 #endif
17559 #if SQLITE_OMIT_VACUUM
17560  "OMIT_VACUUM",
17561 #endif
17562 #if SQLITE_OMIT_VIEW
17563  "OMIT_VIEW",
17564 #endif
17565 #if SQLITE_OMIT_VIRTUALTABLE
17566  "OMIT_VIRTUALTABLE",
17567 #endif
17568 #if SQLITE_OMIT_WAL
17569  "OMIT_WAL",
17570 #endif
17571 #if SQLITE_OMIT_WSD
17572  "OMIT_WSD",
17573 #endif
17574 #if SQLITE_OMIT_XFER_OPT
17575  "OMIT_XFER_OPT",
17576 #endif
17577 #if SQLITE_PERFORMANCE_TRACE
17578  "PERFORMANCE_TRACE",
17579 #endif
17580 #if SQLITE_PROXY_DEBUG
17581  "PROXY_DEBUG",
17582 #endif
17583 #if SQLITE_RTREE_INT_ONLY
17584  "RTREE_INT_ONLY",
17585 #endif
17586 #if SQLITE_SECURE_DELETE
17587  "SECURE_DELETE",
17588 #endif
17589 #if SQLITE_SMALL_STACK
17590  "SMALL_STACK",
17591 #endif
17592 #if SQLITE_SOUNDEX
17593  "SOUNDEX",
17594 #endif
17595 #if SQLITE_SYSTEM_MALLOC
17596  "SYSTEM_MALLOC",
17597 #endif
17598 #if SQLITE_TCL
17599  "TCL",
17600 #endif
17601 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
17602  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
17603 #endif
17604 #if SQLITE_TEST
17605  "TEST",
17606 #endif
17607 #if defined(SQLITE_THREADSAFE)
17608  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
17609 #endif
17610 #if SQLITE_USE_ALLOCA
17611  "USE_ALLOCA",
17612 #endif
17613 #if SQLITE_USER_AUTHENTICATION
17614  "USER_AUTHENTICATION",
17615 #endif
17616 #if SQLITE_WIN32_MALLOC
17617  "WIN32_MALLOC",
17618 #endif
17619 #if SQLITE_ZERO_MALLOC
17620  "ZERO_MALLOC"
17621 #endif
17622 };
17623 
17624 /*
17625 ** Given the name of a compile-time option, return true if that option
17626 ** was used and false if not.
17627 **
17628 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
17629 ** is not required for a match.
17630 */
17631 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
17632  int i, n;
17633 
17634 #if SQLITE_ENABLE_API_ARMOR
17635  if( zOptName==0 ){
17636  (void)SQLITE_MISUSE_BKPT;
17637  return 0;
17638  }
17639 #endif
17640  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
17641  n = sqlite3Strlen30(zOptName);
17642 
17643  /* Since ArraySize(azCompileOpt) is normally in single digits, a
17644  ** linear search is adequate. No need for a binary search. */
17645  for(i=0; i<ArraySize(azCompileOpt); i++){
17646  if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
17647  && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
17648  ){
17649  return 1;
17650  }
17651  }
17652  return 0;
17653 }
17654 
17655 /*
17656 ** Return the N-th compile-time option string. If N is out of range,
17657 ** return a NULL pointer.
17658 */
17660  if( N>=0 && N<ArraySize(azCompileOpt) ){
17661  return azCompileOpt[N];
17662  }
17663  return 0;
17664 }
17665 
17666 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17667 
17668 /************** End of ctime.c ***********************************************/
17669 /************** Begin file status.c ******************************************/
17670 /*
17671 ** 2008 June 18
17672 **
17673 ** The author disclaims copyright to this source code. In place of
17674 ** a legal notice, here is a blessing:
17675 **
17676 ** May you do good and not evil.
17677 ** May you find forgiveness for yourself and forgive others.
17678 ** May you share freely, never taking more than you give.
17679 **
17680 *************************************************************************
17681 **
17682 ** This module implements the sqlite3_status() interface and related
17683 ** functionality.
17684 */
17685 /* #include "sqliteInt.h" */
17686 /************** Include vdbeInt.h in the middle of status.c ******************/
17687 /************** Begin file vdbeInt.h *****************************************/
17688 /*
17689 ** 2003 September 6
17690 **
17691 ** The author disclaims copyright to this source code. In place of
17692 ** a legal notice, here is a blessing:
17693 **
17694 ** May you do good and not evil.
17695 ** May you find forgiveness for yourself and forgive others.
17696 ** May you share freely, never taking more than you give.
17697 **
17698 *************************************************************************
17699 ** This is the header file for information that is private to the
17700 ** VDBE. This information used to all be at the top of the single
17701 ** source code file "vdbe.c". When that file became too big (over
17702 ** 6000 lines long) it was split up into several smaller files and
17703 ** this header information was factored out.
17704 */
17705 #ifndef SQLITE_VDBEINT_H
17706 #define SQLITE_VDBEINT_H
17707 
17708 /*
17709 ** The maximum number of times that a statement will try to reparse
17710 ** itself before giving up and returning SQLITE_SCHEMA.
17711 */
17712 #ifndef SQLITE_MAX_SCHEMA_RETRY
17713 # define SQLITE_MAX_SCHEMA_RETRY 50
17714 #endif
17715 
17716 /*
17717 ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
17718 ** "explain" P4 display logic is enabled.
17719 */
17720 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
17721  || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17722 # define VDBE_DISPLAY_P4 1
17723 #else
17724 # define VDBE_DISPLAY_P4 0
17725 #endif
17726 
17727 /*
17728 ** SQL is translated into a sequence of instructions to be
17729 ** executed by a virtual machine. Each instruction is an instance
17730 ** of the following structure.
17731 */
17732 typedef struct VdbeOp Op;
17733 
17734 /*
17735 ** Boolean values
17736 */
17737 typedef unsigned Bool;
17738 
17739 /* Opaque type used by code in vdbesort.c */
17740 typedef struct VdbeSorter VdbeSorter;
17741 
17742 /* Elements of the linked list at Vdbe.pAuxData */
17743 typedef struct AuxData AuxData;
17744 
17745 /* Types of VDBE cursors */
17746 #define CURTYPE_BTREE 0
17747 #define CURTYPE_SORTER 1
17748 #define CURTYPE_VTAB 2
17749 #define CURTYPE_PSEUDO 3
17750 
17751 /*
17752 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
17753 **
17754 ** * A b-tree cursor
17755 ** - In the main database or in an ephemeral database
17756 ** - On either an index or a table
17757 ** * A sorter
17758 ** * A virtual table
17759 ** * A one-row "pseudotable" stored in a single register
17760 */
17761 typedef struct VdbeCursor VdbeCursor;
17762 struct VdbeCursor {
17763  u8 eCurType; /* One of the CURTYPE_* values above */
17764  i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
17765  u8 nullRow; /* True if pointing to a row with no data */
17766  u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
17767  u8 isTable; /* True for rowid tables. False for indexes */
17768 #ifdef SQLITE_DEBUG
17769  u8 seekOp; /* Most recent seek operation on this cursor */
17770  u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
17771 #endif
17772  Bool isEphemeral:1; /* True for an ephemeral table */
17773  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
17774  Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
17775  Pgno pgnoRoot; /* Root page of the open btree cursor */
17776  i16 nField; /* Number of fields in the header */
17777  u16 nHdrParsed; /* Number of header fields parsed so far */
17778  union {
17779  BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
17780  sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
17781  int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
17782  VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
17783  } uc;
17784  Btree *pBt; /* Separate file holding temporary table */
17785  KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
17786  int seekResult; /* Result of previous sqlite3BtreeMoveto() */
17787  i64 seqCount; /* Sequence counter */
17788  i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
17789  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
17790  int *aAltMap; /* Mapping from table to index column numbers */
17791 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
17792  u64 maskUsed; /* Mask of columns used by this cursor */
17793 #endif
17794 
17795  /* Cached information about the header for the data record that the
17796  ** cursor is currently pointing to. Only valid if cacheStatus matches
17797  ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
17798  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17799  ** the cache is out of date.
17800  **
17801  ** aRow might point to (ephemeral) data for the current row, or it might
17802  ** be NULL.
17803  */
17804  u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
17805  u32 payloadSize; /* Total number of bytes in the record */
17806  u32 szRow; /* Byte available in aRow */
17807  u32 iHdrOffset; /* Offset to next unparsed byte of the header */
17808  const u8 *aRow; /* Data for the current row, if all on one page */
17809  u32 *aOffset; /* Pointer to aType[nField] */
17810  u32 aType[1]; /* Type values for all entries in the record */
17811  /* 2*nField extra array elements allocated for aType[], beyond the one
17812  ** static element declared in the structure. nField total array slots for
17813  ** aType[] and nField+1 array slots for aOffset[] */
17814 };
17815 
17816 
17817 /*
17818 ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
17819 */
17820 #define CACHE_STALE 0
17821 
17822 /*
17823 ** When a sub-program is executed (OP_Program), a structure of this type
17824 ** is allocated to store the current value of the program counter, as
17825 ** well as the current memory cell array and various other frame specific
17826 ** values stored in the Vdbe struct. When the sub-program is finished,
17827 ** these values are copied back to the Vdbe from the VdbeFrame structure,
17828 ** restoring the state of the VM to as it was before the sub-program
17829 ** began executing.
17830 **
17831 ** The memory for a VdbeFrame object is allocated and managed by a memory
17832 ** cell in the parent (calling) frame. When the memory cell is deleted or
17833 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
17834 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
17835 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
17836 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
17837 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
17838 ** child frame are released.
17839 **
17840 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
17841 ** set to NULL if the currently executing frame is the main program.
17842 */
17843 typedef struct VdbeFrame VdbeFrame;
17844 struct VdbeFrame {
17845  Vdbe *v; /* VM this frame belongs to */
17846  VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
17847  Op *aOp; /* Program instructions for parent frame */
17848  i64 *anExec; /* Event counters from parent frame */
17849  Mem *aMem; /* Array of memory cells for parent frame */
17850  VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
17851  void *token; /* Copy of SubProgram.token */
17852  i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
17853  AuxData *pAuxData; /* Linked list of auxdata allocations */
17854  int nCursor; /* Number of entries in apCsr */
17855  int pc; /* Program Counter in parent (calling) frame */
17856  int nOp; /* Size of aOp array */
17857  int nMem; /* Number of entries in aMem */
17858  int nChildMem; /* Number of memory cells for child frame */
17859  int nChildCsr; /* Number of cursors for child frame */
17860  int nChange; /* Statement changes (Vdbe.nChange) */
17861  int nDbChange; /* Value of db->nChange */
17862 };
17863 
17864 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17865 
17866 /*
17867 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17868 ** structures. Each Mem struct may cache multiple representations (string,
17869 ** integer etc.) of the same value.
17870 */
17871 struct Mem {
17872  union MemValue {
17873  double r; /* Real value used when MEM_Real is set in flags */
17874  i64 i; /* Integer value used when MEM_Int is set in flags */
17875  int nZero; /* Used when bit MEM_Zero is set in flags */
17876  FuncDef *pDef; /* Used only when flags==MEM_Agg */
17877  RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
17878  VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
17879  } u;
17880  u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17881  u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17882  u8 eSubtype; /* Subtype for this value */
17883  int n; /* Number of characters in string value, excluding '\0' */
17884  char *z; /* String or BLOB value */
17885  /* ShallowCopy only needs to copy the information above */
17886  char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
17887  int szMalloc; /* Size of the zMalloc allocation */
17888  u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
17889  sqlite3 *db; /* The associated database connection */
17890  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
17891 #ifdef SQLITE_DEBUG
17892  Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
17893  void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
17894 #endif
17895 };
17896 
17897 /*
17898 ** Size of struct Mem not including the Mem.zMalloc member or anything that
17899 ** follows.
17900 */
17901 #define MEMCELLSIZE offsetof(Mem,zMalloc)
17902 
17903 /* One or more of the following flags are set to indicate the validOK
17904 ** representations of the value stored in the Mem struct.
17905 **
17906 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17907 ** No other flags may be set in this case.
17908 **
17909 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17910 ** Usually this is encoded in the same unicode encoding as the main
17911 ** database (see below for exceptions). If the MEM_Term flag is also
17912 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
17913 ** flags may coexist with the MEM_Str flag.
17914 */
17915 #define MEM_Null 0x0001 /* Value is NULL */
17916 #define MEM_Str 0x0002 /* Value is a string */
17917 #define MEM_Int 0x0004 /* Value is an integer */
17918 #define MEM_Real 0x0008 /* Value is a real number */
17919 #define MEM_Blob 0x0010 /* Value is a BLOB */
17920 #define MEM_AffMask 0x001f /* Mask of affinity bits */
17921 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
17922 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
17923 #define MEM_Undefined 0x0080 /* Value is undefined */
17924 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
17925 #define MEM_TypeMask 0x81ff /* Mask of type bits */
17926 
17927 
17928 /* Whenever Mem contains a valid string or blob representation, one of
17929 ** the following flags must be set to determine the memory management
17930 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
17931 ** string is \000 or \u0000 terminated
17932 */
17933 #define MEM_Term 0x0200 /* String rep is nul terminated */
17934 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
17935 #define MEM_Static 0x0800 /* Mem.z points to a static string */
17936 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
17937 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
17938 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
17939 #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
17940 #ifdef SQLITE_OMIT_INCRBLOB
17941  #undef MEM_Zero
17942  #define MEM_Zero 0x0000
17943 #endif
17944 
17945 /* Return TRUE if Mem X contains dynamically allocated content - anything
17946 ** that needs to be deallocated to avoid a leak.
17947 */
17948 #define VdbeMemDynamic(X) \
17949  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
17950 
17951 /*
17952 ** Clear any existing type flags from a Mem and replace them with f
17953 */
17954 #define MemSetTypeFlag(p, f) \
17955  ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17956 
17957 /*
17958 ** Return true if a memory cell is not marked as invalid. This macro
17959 ** is for use inside assert() statements only.
17960 */
17961 #ifdef SQLITE_DEBUG
17962 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
17963 #endif
17964 
17965 /*
17966 ** Each auxiliary data pointer stored by a user defined function
17967 ** implementation calling sqlite3_set_auxdata() is stored in an instance
17968 ** of this structure. All such structures associated with a single VM
17969 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
17970 ** when the VM is halted (if not before).
17971 */
17972 struct AuxData {
17973  int iOp; /* Instruction number of OP_Function opcode */
17974  int iArg; /* Index of function argument. */
17975  void *pAux; /* Aux data pointer */
17976  void (*xDelete)(void *); /* Destructor for the aux data */
17977  AuxData *pNext; /* Next element in list */
17978 };
17979 
17980 /*
17981 ** The "context" argument for an installable function. A pointer to an
17982 ** instance of this structure is the first argument to the routines used
17983 ** implement the SQL functions.
17984 **
17985 ** There is a typedef for this structure in sqlite.h. So all routines,
17986 ** even the public interface to SQLite, can use a pointer to this structure.
17987 ** But this file is the only place where the internal details of this
17988 ** structure are known.
17989 **
17990 ** This structure is defined inside of vdbeInt.h because it uses substructures
17991 ** (Mem) which are only defined there.
17992 */
17994  Mem *pOut; /* The return value is stored here */
17995  FuncDef *pFunc; /* Pointer to function information */
17996  Mem *pMem; /* Memory cell used to store aggregate context */
17997  Vdbe *pVdbe; /* The VM that owns this context */
17998  int iOp; /* Instruction number of OP_Function */
17999  int isError; /* Error code returned by the function. */
18000  u8 skipFlag; /* Skip accumulator loading if true */
18001  u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
18002  u8 argc; /* Number of arguments */
18003  sqlite3_value *argv[1]; /* Argument set */
18004 };
18005 
18006 /* A bitfield type for use inside of structures. Always follow with :N where
18007 ** N is the number of bits.
18008 */
18009 typedef unsigned bft; /* Bit Field Type */
18010 
18011 typedef struct ScanStatus ScanStatus;
18012 struct ScanStatus {
18013  int addrExplain; /* OP_Explain for loop */
18014  int addrLoop; /* Address of "loops" counter */
18015  int addrVisit; /* Address of "rows visited" counter */
18016  int iSelectID; /* The "Select-ID" for this loop */
18017  LogEst nEst; /* Estimated output rows per loop */
18018  char *zName; /* Name of table or index */
18019 };
18020 
18021 /*
18022 ** An instance of the virtual machine. This structure contains the complete
18023 ** state of the virtual machine.
18024 **
18025 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
18026 ** is really a pointer to an instance of this structure.
18027 */
18028 struct Vdbe {
18029  sqlite3 *db; /* The database connection that owns this statement */
18030  Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
18031  Parse *pParse; /* Parsing context used to create this Vdbe */
18032  ynVar nVar; /* Number of entries in aVar[] */
18033  ynVar nzVar; /* Number of entries in azVar[] */
18034  u32 magic; /* Magic number for sanity checking */
18035  int nMem; /* Number of memory locations currently allocated */
18036  int nCursor; /* Number of slots in apCsr[] */
18037  u32 cacheCtr; /* VdbeCursor row cache generation counter */
18038  int pc; /* The program counter */
18039  int rc; /* Value to return */
18040  int nChange; /* Number of db changes made since last reset */
18041  int iStatement; /* Statement number (or 0 if has not opened stmt) */
18042  i64 iCurrentTime; /* Value of julianday('now') for this statement */
18043  i64 nFkConstraint; /* Number of imm. FK constraints this VM */
18044  i64 nStmtDefCons; /* Number of def. constraints when stmt started */
18045  i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
18046 
18047  /* When allocating a new Vdbe object, all of the fields below should be
18048  ** initialized to zero or NULL */
18049 
18050  Op *aOp; /* Space to hold the virtual machine's program */
18051  Mem *aMem; /* The memory locations */
18052  Mem **apArg; /* Arguments to currently executing user function */
18053  Mem *aColName; /* Column names to return */
18054  Mem *pResultSet; /* Pointer to an array of results */
18055  char *zErrMsg; /* Error message written here */
18056  VdbeCursor **apCsr; /* One element of this array for each open cursor */
18057  Mem *aVar; /* Values for the OP_Variable opcode. */
18058  char **azVar; /* Name of variables */
18059 #ifndef SQLITE_OMIT_TRACE
18060  i64 startTime; /* Time when query started - used for profiling */
18061 #endif
18062  int nOp; /* Number of instructions in the program */
18063 #ifdef SQLITE_DEBUG
18064  int rcApp; /* errcode set by sqlite3_result_error_code() */
18065 #endif
18066  u16 nResColumn; /* Number of columns in one row of the result set */
18067  u8 errorAction; /* Recovery action to do in case of an error */
18068  u8 minWriteFileFormat; /* Minimum file format for writable database files */
18069  bft expired:1; /* True if the VM needs to be recompiled */
18070  bft doingRerun:1; /* True if rerunning after an auto-reprepare */
18071  bft explain:2; /* True if EXPLAIN present on SQL command */
18072  bft changeCntOn:1; /* True to update the change-counter */
18073  bft runOnlyOnce:1; /* Automatically expire on reset */
18074  bft usesStmtJournal:1; /* True if uses a statement journal */
18075  bft readOnly:1; /* True for statements that do not write */
18076  bft bIsReader:1; /* True for statements that read */
18077  bft isPrepareV2:1; /* True if prepared with prepare_v2() */
18078  yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
18079  yDbMask lockMask; /* Subset of btreeMask that requires a lock */
18080  u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
18081  char *zSql; /* Text of the SQL statement that generated this */
18082  void *pFree; /* Free this when deleting the vdbe */
18083  VdbeFrame *pFrame; /* Parent frame */
18084  VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
18085  int nFrame; /* Number of frames in pFrame list */
18086  u32 expmask; /* Binding to these vars invalidates VM */
18087  SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
18088  AuxData *pAuxData; /* Linked list of auxdata allocations */
18089 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18090  i64 *anExec; /* Number of times each op has been executed */
18091  int nScan; /* Entries in aScan[] */
18092  ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
18093 #endif
18094 };
18095 
18096 /*
18097 ** The following are allowed values for Vdbe.magic
18098 */
18099 #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
18100 #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
18101 #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
18102 #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
18103 #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
18104 
18105 /*
18106 ** Structure used to store the context required by the
18107 ** sqlite3_preupdate_*() API functions.
18108 */
18109 struct PreUpdate {
18111  VdbeCursor *pCsr; /* Cursor to read old values from */
18112  int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
18113  u8 *aRecord; /* old.* database record */
18115  UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
18116  UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
18117  int iNewReg; /* Register for new.* values */
18118  i64 iKey1; /* First key value passed to hook */
18119  i64 iKey2; /* Second key value passed to hook */
18120  Mem *aNew; /* Array of new.* values */
18121  Table *pTab; /* Schema object being upated */
18122 };
18123 
18124 /*
18125 ** Function prototypes
18126 */
18127 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18129 void sqliteVdbePopStack(Vdbe*,int);
18132 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18133 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18134 #endif
18137 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18138 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18139 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18141 
18142 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18151 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18154 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18156 #ifdef SQLITE_OMIT_FLOATING_POINT
18157 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18158 #else
18160 #endif
18177 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18178 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18183 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
18184 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
18185 #endif
18187 
18195 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
18196 
18197 #if !defined(SQLITE_OMIT_SHARED_CACHE)
18199 #else
18200 # define sqlite3VdbeEnter(X)
18201 #endif
18202 
18203 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
18205 #else
18206 # define sqlite3VdbeLeave(X)
18207 #endif
18208 
18209 #ifdef SQLITE_DEBUG
18210 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
18211 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
18212 #endif
18213 
18214 #ifndef SQLITE_OMIT_FOREIGN_KEY
18216 #else
18217 # define sqlite3VdbeCheckFk(p,i) 0
18218 #endif
18219 
18221 #ifdef SQLITE_DEBUG
18222 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
18223 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18224 #endif
18226 
18227 #ifndef SQLITE_OMIT_INCRBLOB
18229  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
18230 #else
18231  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18232  #define ExpandBlob(P) SQLITE_OK
18233 #endif
18234 
18235 #endif /* !defined(SQLITE_VDBEINT_H) */
18236 
18237 /************** End of vdbeInt.h *********************************************/
18238 /************** Continuing where we left off in status.c *********************/
18239 
18240 /*
18241 ** Variables in which to record status information.
18242 */
18243 #if SQLITE_PTRSIZE>4
18244 typedef sqlite3_int64 sqlite3StatValueType;
18245 #else
18246 typedef u32 sqlite3StatValueType;
18247 #endif
18250  sqlite3StatValueType nowValue[10]; /* Current value */
18251  sqlite3StatValueType mxValue[10]; /* Maximum value */
18252 } sqlite3Stat = { {0,}, {0,} };
18253 
18254 /*
18255 ** Elements of sqlite3Stat[] are protected by either the memory allocator
18256 ** mutex, or by the pcache1 mutex. The following array determines which.
18257 */
18258 static const char statMutex[] = {
18259  0, /* SQLITE_STATUS_MEMORY_USED */
18260  1, /* SQLITE_STATUS_PAGECACHE_USED */
18261  1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
18262  0, /* SQLITE_STATUS_SCRATCH_USED */
18263  0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
18264  0, /* SQLITE_STATUS_MALLOC_SIZE */
18265  0, /* SQLITE_STATUS_PARSER_STACK */
18266  1, /* SQLITE_STATUS_PAGECACHE_SIZE */
18267  0, /* SQLITE_STATUS_SCRATCH_SIZE */
18268  0, /* SQLITE_STATUS_MALLOC_COUNT */
18269 };
18270 
18271 
18272 /* The "wsdStat" macro will resolve to the status information
18273 ** state vector. If writable static data is unsupported on the target,
18274 ** we have to locate the state vector at run-time. In the more common
18275 ** case where writable static data is supported, wsdStat can refer directly
18276 ** to the "sqlite3Stat" state vector declared above.
18277 */
18278 #ifdef SQLITE_OMIT_WSD
18279 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
18280 # define wsdStat x[0]
18281 #else
18282 # define wsdStatInit
18283 # define wsdStat sqlite3Stat
18284 #endif
18285 
18286 /*
18287 ** Return the current value of a status parameter. The caller must
18288 ** be holding the appropriate mutex.
18289 */
18290 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
18291  wsdStatInit;
18292  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18293  assert( op>=0 && op<ArraySize(statMutex) );
18294  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18295  : sqlite3MallocMutex()) );
18296  return wsdStat.nowValue[op];
18297 }
18298 
18299 /*
18300 ** Add N to the value of a status record. The caller must hold the
18301 ** appropriate mutex. (Locking is checked by assert()).
18302 **
18303 ** The StatusUp() routine can accept positive or negative values for N.
18304 ** The value of N is added to the current status value and the high-water
18305 ** mark is adjusted if necessary.
18306 **
18307 ** The StatusDown() routine lowers the current value by N. The highwater
18308 ** mark is unchanged. N must be non-negative for StatusDown().
18309 */
18310 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
18311  wsdStatInit;
18312  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18313  assert( op>=0 && op<ArraySize(statMutex) );
18314  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18315  : sqlite3MallocMutex()) );
18316  wsdStat.nowValue[op] += N;
18317  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
18318  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18319  }
18320 }
18321 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
18322  wsdStatInit;
18323  assert( N>=0 );
18324  assert( op>=0 && op<ArraySize(statMutex) );
18325  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18326  : sqlite3MallocMutex()) );
18327  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18328  wsdStat.nowValue[op] -= N;
18329 }
18330 
18331 /*
18332 ** Adjust the highwater mark if necessary.
18333 ** The caller must hold the appropriate mutex.
18334 */
18336  sqlite3StatValueType newValue;
18337  wsdStatInit;
18338  assert( X>=0 );
18339  newValue = (sqlite3StatValueType)X;
18340  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18341  assert( op>=0 && op<ArraySize(statMutex) );
18342  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18343  : sqlite3MallocMutex()) );
18344  assert( op==SQLITE_STATUS_MALLOC_SIZE
18347  || op==SQLITE_STATUS_PARSER_STACK );
18348  if( newValue>wsdStat.mxValue[op] ){
18349  wsdStat.mxValue[op] = newValue;
18350  }
18351 }
18352 
18353 /*
18354 ** Query status information.
18355 */
18357  int op,
18358  sqlite3_int64 *pCurrent,
18359  sqlite3_int64 *pHighwater,
18360  int resetFlag
18361 ){
18362  sqlite3_mutex *pMutex;
18363  wsdStatInit;
18364  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
18365  return SQLITE_MISUSE_BKPT;
18366  }
18367 #ifdef SQLITE_ENABLE_API_ARMOR
18368  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18369 #endif
18370  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
18371  sqlite3_mutex_enter(pMutex);
18372  *pCurrent = wsdStat.nowValue[op];
18373  *pHighwater = wsdStat.mxValue[op];
18374  if( resetFlag ){
18375  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18376  }
18377  sqlite3_mutex_leave(pMutex);
18378  (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
18379  return SQLITE_OK;
18380 }
18381 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
18382  sqlite3_int64 iCur = 0, iHwtr = 0;
18383  int rc;
18384 #ifdef SQLITE_ENABLE_API_ARMOR
18385  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18386 #endif
18387  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
18388  if( rc==0 ){
18389  *pCurrent = (int)iCur;
18390  *pHighwater = (int)iHwtr;
18391  }
18392  return rc;
18393 }
18394 
18395 /*
18396 ** Query status information for a single database connection
18397 */
18399  sqlite3 *db, /* The database connection whose status is desired */
18400  int op, /* Status verb */
18401  int *pCurrent, /* Write current value here */
18402  int *pHighwater, /* Write high-water mark here */
18403  int resetFlag /* Reset high-water mark if true */
18404 ){
18405  int rc = SQLITE_OK; /* Return code */
18406 #ifdef SQLITE_ENABLE_API_ARMOR
18407  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
18408  return SQLITE_MISUSE_BKPT;
18409  }
18410 #endif
18412  switch( op ){
18414  *pCurrent = db->lookaside.nOut;
18415  *pHighwater = db->lookaside.mxOut;
18416  if( resetFlag ){
18417  db->lookaside.mxOut = db->lookaside.nOut;
18418  }
18419  break;
18420  }
18421 
18428  assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
18429  assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
18430  *pCurrent = 0;
18431  *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
18432  if( resetFlag ){
18434  }
18435  break;
18436  }
18437 
18438  /*
18439  ** Return an approximation for the amount of memory currently used
18440  ** by all pagers associated with the given database connection. The
18441  ** highwater mark is meaningless and is returned as zero.
18442  */
18445  int totalUsed = 0;
18446  int i;
18448  for(i=0; i<db->nDb; i++){
18449  Btree *pBt = db->aDb[i].pBt;
18450  if( pBt ){
18451  Pager *pPager = sqlite3BtreePager(pBt);
18452  int nByte = sqlite3PagerMemUsed(pPager);
18454  nByte = nByte / sqlite3BtreeConnectionCount(pBt);
18455  }
18456  totalUsed += nByte;
18457  }
18458  }
18460  *pCurrent = totalUsed;
18461  *pHighwater = 0;
18462  break;
18463  }
18464 
18465  /*
18466  ** *pCurrent gets an accurate estimate of the amount of memory used
18467  ** to store the schema for all databases (main, temp, and any ATTACHed
18468  ** databases. *pHighwater is set to zero.
18469  */
18471  int i; /* Used to iterate through schemas */
18472  int nByte = 0; /* Used to accumulate return value */
18473 
18475  db->pnBytesFreed = &nByte;
18476  for(i=0; i<db->nDb; i++){
18477  Schema *pSchema = db->aDb[i].pSchema;
18478  if( ALWAYS(pSchema!=0) ){
18479  HashElem *p;
18480 
18481  nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
18482  pSchema->tblHash.count
18483  + pSchema->trigHash.count
18484  + pSchema->idxHash.count
18485  + pSchema->fkeyHash.count
18486  );
18487  nByte += sqlite3_msize(pSchema->tblHash.ht);
18488  nByte += sqlite3_msize(pSchema->trigHash.ht);
18489  nByte += sqlite3_msize(pSchema->idxHash.ht);
18490  nByte += sqlite3_msize(pSchema->fkeyHash.ht);
18491 
18492  for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
18494  }
18495  for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
18497  }
18498  }
18499  }
18500  db->pnBytesFreed = 0;
18502 
18503  *pHighwater = 0;
18504  *pCurrent = nByte;
18505  break;
18506  }
18507 
18508  /*
18509  ** *pCurrent gets an accurate estimate of the amount of memory used
18510  ** to store all prepared statements.
18511  ** *pHighwater is set to zero.
18512  */
18514  struct Vdbe *pVdbe; /* Used to iterate through VMs */
18515  int nByte = 0; /* Used to accumulate return value */
18516 
18517  db->pnBytesFreed = &nByte;
18518  for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
18519  sqlite3VdbeClearObject(db, pVdbe);
18520  sqlite3DbFree(db, pVdbe);
18521  }
18522  db->pnBytesFreed = 0;
18523 
18524  *pHighwater = 0; /* IMP: R-64479-57858 */
18525  *pCurrent = nByte;
18526 
18527  break;
18528  }
18529 
18530  /*
18531  ** Set *pCurrent to the total cache hits or misses encountered by all
18532  ** pagers the database handle is connected to. *pHighwater is always set
18533  ** to zero.
18534  */
18538  int i;
18539  int nRet = 0;
18542 
18543  for(i=0; i<db->nDb; i++){
18544  if( db->aDb[i].pBt ){
18545  Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
18546  sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
18547  }
18548  }
18549  *pHighwater = 0; /* IMP: R-42420-56072 */
18550  /* IMP: R-54100-20147 */
18551  /* IMP: R-29431-39229 */
18552  *pCurrent = nRet;
18553  break;
18554  }
18555 
18556  /* Set *pCurrent to non-zero if there are unresolved deferred foreign
18557  ** key constraints. Set *pCurrent to zero if all foreign key constraints
18558  ** have been satisfied. The *pHighwater is always set to zero.
18559  */
18561  *pHighwater = 0; /* IMP: R-11967-56545 */
18562  *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
18563  break;
18564  }
18565 
18566  default: {
18567  rc = SQLITE_ERROR;
18568  }
18569  }
18571  return rc;
18572 }
18573 
18574 /************** End of status.c **********************************************/
18575 /************** Begin file date.c ********************************************/
18576 /*
18577 ** 2003 October 31
18578 **
18579 ** The author disclaims copyright to this source code. In place of
18580 ** a legal notice, here is a blessing:
18581 **
18582 ** May you do good and not evil.
18583 ** May you find forgiveness for yourself and forgive others.
18584 ** May you share freely, never taking more than you give.
18585 **
18586 *************************************************************************
18587 ** This file contains the C functions that implement date and time
18588 ** functions for SQLite.
18589 **
18590 ** There is only one exported symbol in this file - the function
18591 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
18592 ** All other code has file scope.
18593 **
18594 ** SQLite processes all times and dates as julian day numbers. The
18595 ** dates and times are stored as the number of days since noon
18596 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
18597 ** calendar system.
18598 **
18599 ** 1970-01-01 00:00:00 is JD 2440587.5
18600 ** 2000-01-01 00:00:00 is JD 2451544.5
18601 **
18602 ** This implementation requires years to be expressed as a 4-digit number
18603 ** which means that only dates between 0000-01-01 and 9999-12-31 can
18604 ** be represented, even though julian day numbers allow a much wider
18605 ** range of dates.
18606 **
18607 ** The Gregorian calendar system is used for all dates and times,
18608 ** even those that predate the Gregorian calendar. Historians usually
18609 ** use the julian calendar for dates prior to 1582-10-15 and for some
18610 ** dates afterwards, depending on locale. Beware of this difference.
18611 **
18612 ** The conversion algorithms are implemented based on descriptions
18613 ** in the following text:
18614 **
18615 ** Jean Meeus
18616 ** Astronomical Algorithms, 2nd Edition, 1998
18617 ** ISBM 0-943396-61-1
18618 ** Willmann-Bell, Inc
18619 ** Richmond, Virginia (USA)
18620 */
18621 /* #include "sqliteInt.h" */
18622 /* #include <stdlib.h> */
18623 /* #include <assert.h> */
18624 #include <time.h>
18625 
18626 #ifndef SQLITE_OMIT_DATETIME_FUNCS
18627 
18628 /*
18629 ** The MSVC CRT on Windows CE may not have a localtime() function.
18630 ** So declare a substitute. The substitute function itself is
18631 ** defined in "os_win.c".
18632 */
18633 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18634  (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18635 struct tm *__cdecl localtime(const time_t *);
18636 #endif
18637 
18638 /*
18639 ** A structure for holding a single date and time.
18640 */
18641 typedef struct DateTime DateTime;
18642 struct DateTime {
18643  sqlite3_int64 iJD; /* The julian day number times 86400000 */
18644  int Y, M, D; /* Year, month, and day */
18645  int h, m; /* Hour and minutes */
18646  int tz; /* Timezone offset in minutes */
18647  double s; /* Seconds */
18648  char validYMD; /* True (1) if Y,M,D are valid */
18649  char validHMS; /* True (1) if h,m,s are valid */
18650  char validJD; /* True (1) if iJD is valid */
18651  char validTZ; /* True (1) if tz is valid */
18652  char tzSet; /* Timezone was set explicitly */
18653 };
18654 
18655 
18656 /*
18657 ** Convert zDate into one or more integers according to the conversion
18658 ** specifier zFormat.
18659 **
18660 ** zFormat[] contains 4 characters for each integer converted, except for
18661 ** the last integer which is specified by three characters. The meaning
18662 ** of a four-character format specifiers ABCD is:
18663 **
18664 ** A: number of digits to convert. Always "2" or "4".
18665 ** B: minimum value. Always "0" or "1".
18666 ** C: maximum value, decoded as:
18667 ** a: 12
18668 ** b: 14
18669 ** c: 24
18670 ** d: 31
18671 ** e: 59
18672 ** f: 9999
18673 ** D: the separator character, or \000 to indicate this is the
18674 ** last number to convert.
18675 **
18676 ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
18677 ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
18678 ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
18679 ** the 2-digit day which is the last integer in the set.
18680 **
18681 ** The function returns the number of successful conversions.
18682 */
18683 static int getDigits(const char *zDate, const char *zFormat, ...){
18684  /* The aMx[] array translates the 3rd character of each format
18685  ** spec into a max size: a b c d e f */
18686  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
18687  va_list ap;
18688  int cnt = 0;
18689  char nextC;
18690  va_start(ap, zFormat);
18691  do{
18692  char N = zFormat[0] - '0';
18693  char min = zFormat[1] - '0';
18694  int val = 0;
18695  u16 max;
18696 
18697  assert( zFormat[2]>='a' && zFormat[2]<='f' );
18698  max = aMx[zFormat[2] - 'a'];
18699  nextC = zFormat[3];
18700  val = 0;
18701  while( N-- ){
18702  if( !sqlite3Isdigit(*zDate) ){
18703  goto end_getDigits;
18704  }
18705  val = val*10 + *zDate - '0';
18706  zDate++;
18707  }
18708  if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
18709  goto end_getDigits;
18710  }
18711  *va_arg(ap,int*) = val;
18712  zDate++;
18713  cnt++;
18714  zFormat += 4;
18715  }while( nextC );
18716 end_getDigits:
18717  va_end(ap);
18718  return cnt;
18719 }
18720 
18721 /*
18722 ** Parse a timezone extension on the end of a date-time.
18723 ** The extension is of the form:
18724 **
18725 ** (+/-)HH:MM
18726 **
18727 ** Or the "zulu" notation:
18728 **
18729 ** Z
18730 **
18731 ** If the parse is successful, write the number of minutes
18732 ** of change in p->tz and return 0. If a parser error occurs,
18733 ** return non-zero.
18734 **
18735 ** A missing specifier is not considered an error.
18736 */
18737 static int parseTimezone(const char *zDate, DateTime *p){
18738  int sgn = 0;
18739  int nHr, nMn;
18740  int c;
18741  while( sqlite3Isspace(*zDate) ){ zDate++; }
18742  p->tz = 0;
18743  c = *zDate;
18744  if( c=='-' ){
18745  sgn = -1;
18746  }else if( c=='+' ){
18747  sgn = +1;
18748  }else if( c=='Z' || c=='z' ){
18749  zDate++;
18750  goto zulu_time;
18751  }else{
18752  return c!=0;
18753  }
18754  zDate++;
18755  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
18756  return 1;
18757  }
18758  zDate += 5;
18759  p->tz = sgn*(nMn + nHr*60);
18760 zulu_time:
18761  while( sqlite3Isspace(*zDate) ){ zDate++; }
18762  p->tzSet = 1;
18763  return *zDate!=0;
18764 }
18765 
18766 /*
18767 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
18768 ** The HH, MM, and SS must each be exactly 2 digits. The
18769 ** fractional seconds FFFF can be one or more digits.
18770 **
18771 ** Return 1 if there is a parsing error and 0 on success.
18772 */
18773 static int parseHhMmSs(const char *zDate, DateTime *p){
18774  int h, m, s;
18775  double ms = 0.0;
18776  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
18777  return 1;
18778  }
18779  zDate += 5;
18780  if( *zDate==':' ){
18781  zDate++;
18782  if( getDigits(zDate, "20e", &s)!=1 ){
18783  return 1;
18784  }
18785  zDate += 2;
18786  if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
18787  double rScale = 1.0;
18788  zDate++;
18789  while( sqlite3Isdigit(*zDate) ){
18790  ms = ms*10.0 + *zDate - '0';
18791  rScale *= 10.0;
18792  zDate++;
18793  }
18794  ms /= rScale;
18795  }
18796  }else{
18797  s = 0;
18798  }
18799  p->validJD = 0;
18800  p->validHMS = 1;
18801  p->h = h;
18802  p->m = m;
18803  p->s = s + ms;
18804  if( parseTimezone(zDate, p) ) return 1;
18805  p->validTZ = (p->tz!=0)?1:0;
18806  return 0;
18807 }
18808 
18809 /*
18810 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
18811 ** that the YYYY-MM-DD is according to the Gregorian calendar.
18812 **
18813 ** Reference: Meeus page 61
18814 */
18815 static void computeJD(DateTime *p){
18816  int Y, M, D, A, B, X1, X2;
18817 
18818  if( p->validJD ) return;
18819  if( p->validYMD ){
18820  Y = p->Y;
18821  M = p->M;
18822  D = p->D;
18823  }else{
18824  Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
18825  M = 1;
18826  D = 1;
18827  }
18828  if( M<=2 ){
18829  Y--;
18830  M += 12;
18831  }
18832  A = Y/100;
18833  B = 2 - A + (A/4);
18834  X1 = 36525*(Y+4716)/100;
18835  X2 = 306001*(M+1)/10000;
18836  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
18837  p->validJD = 1;
18838  if( p->validHMS ){
18839  p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
18840  if( p->validTZ ){
18841  p->iJD -= p->tz*60000;
18842  p->validYMD = 0;
18843  p->validHMS = 0;
18844  p->validTZ = 0;
18845  }
18846  }
18847 }
18848 
18849 /*
18850 ** Parse dates of the form
18851 **
18852 ** YYYY-MM-DD HH:MM:SS.FFF
18853 ** YYYY-MM-DD HH:MM:SS
18854 ** YYYY-MM-DD HH:MM
18855 ** YYYY-MM-DD
18856 **
18857 ** Write the result into the DateTime structure and return 0
18858 ** on success and 1 if the input string is not a well-formed
18859 ** date.
18860 */
18861 static int parseYyyyMmDd(const char *zDate, DateTime *p){
18862  int Y, M, D, neg;
18863 
18864  if( zDate[0]=='-' ){
18865  zDate++;
18866  neg = 1;
18867  }else{
18868  neg = 0;
18869  }
18870  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
18871  return 1;
18872  }
18873  zDate += 10;
18874  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
18875  if( parseHhMmSs(zDate, p)==0 ){
18876  /* We got the time */
18877  }else if( *zDate==0 ){
18878  p->validHMS = 0;
18879  }else{
18880  return 1;
18881  }
18882  p->validJD = 0;
18883  p->validYMD = 1;
18884  p->Y = neg ? -Y : Y;
18885  p->M = M;
18886  p->D = D;
18887  if( p->validTZ ){
18888  computeJD(p);
18889  }
18890  return 0;
18891 }
18892 
18893 /*
18894 ** Set the time to the current time reported by the VFS.
18895 **
18896 ** Return the number of errors.
18897 */
18899  p->iJD = sqlite3StmtCurrentTime(context);
18900  if( p->iJD>0 ){
18901  p->validJD = 1;
18902  return 0;
18903  }else{
18904  return 1;
18905  }
18906 }
18907 
18908 /*
18909 ** Attempt to parse the given string into a julian day number. Return
18910 ** the number of errors.
18911 **
18912 ** The following are acceptable forms for the input string:
18913 **
18914 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
18915 ** DDDD.DD
18916 ** now
18917 **
18918 ** In the first form, the +/-HH:MM is always optional. The fractional
18919 ** seconds extension (the ".FFF") is optional. The seconds portion
18920 ** (":SS.FFF") is option. The year and date can be omitted as long
18921 ** as there is a time string. The time string can be omitted as long
18922 ** as there is a year and date.
18923 */
18924 static int parseDateOrTime(
18925  sqlite3_context *context,
18926  const char *zDate,
18927  DateTime *p
18928 ){
18929  double r;
18930  if( parseYyyyMmDd(zDate,p)==0 ){
18931  return 0;
18932  }else if( parseHhMmSs(zDate, p)==0 ){
18933  return 0;
18934  }else if( sqlite3StrICmp(zDate,"now")==0){
18935  return setDateTimeToCurrent(context, p);
18936  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
18937  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
18938  p->validJD = 1;
18939  return 0;
18940  }
18941  return 1;
18942 }
18943 
18944 /*
18945 ** Compute the Year, Month, and Day from the julian day number.
18946 */
18947 static void computeYMD(DateTime *p){
18948  int Z, A, B, C, D, E, X1;
18949  if( p->validYMD ) return;
18950  if( !p->validJD ){
18951  p->Y = 2000;
18952  p->M = 1;
18953  p->D = 1;
18954  }else{
18955  Z = (int)((p->iJD + 43200000)/86400000);
18956  A = (int)((Z - 1867216.25)/36524.25);
18957  A = Z + 1 + A - (A/4);
18958  B = A + 1524;
18959  C = (int)((B - 122.1)/365.25);
18960  D = (36525*(C&32767))/100;
18961  E = (int)((B-D)/30.6001);
18962  X1 = (int)(30.6001*E);
18963  p->D = B - D - X1;
18964  p->M = E<14 ? E-1 : E-13;
18965  p->Y = p->M>2 ? C - 4716 : C - 4715;
18966  }
18967  p->validYMD = 1;
18968 }
18969 
18970 /*
18971 ** Compute the Hour, Minute, and Seconds from the julian day number.
18972 */
18973 static void computeHMS(DateTime *p){
18974  int s;
18975  if( p->validHMS ) return;
18976  computeJD(p);
18977  s = (int)((p->iJD + 43200000) % 86400000);
18978  p->s = s/1000.0;
18979  s = (int)p->s;
18980  p->s -= s;
18981  p->h = s/3600;
18982  s -= p->h*3600;
18983  p->m = s/60;
18984  p->s += s - p->m*60;
18985  p->validHMS = 1;
18986 }
18987 
18988 /*
18989 ** Compute both YMD and HMS
18990 */
18991 static void computeYMD_HMS(DateTime *p){
18992  computeYMD(p);
18993  computeHMS(p);
18994 }
18995 
18996 /*
18997 ** Clear the YMD and HMS and the TZ
18998 */
18999 static void clearYMD_HMS_TZ(DateTime *p){
19000  p->validYMD = 0;
19001  p->validHMS = 0;
19002  p->validTZ = 0;
19003 }
19004 
19005 #ifndef SQLITE_OMIT_LOCALTIME
19006 /*
19007 ** On recent Windows platforms, the localtime_s() function is available
19008 ** as part of the "Secure CRT". It is essentially equivalent to
19009 ** localtime_r() available under most POSIX platforms, except that the
19010 ** order of the parameters is reversed.
19011 **
19012 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
19013 **
19014 ** If the user has not indicated to use localtime_r() or localtime_s()
19015 ** already, check for an MSVC build environment that provides
19016 ** localtime_s().
19017 */
19018 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
19019  && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
19020 #undef HAVE_LOCALTIME_S
19021 #define HAVE_LOCALTIME_S 1
19022 #endif
19023 
19024 /*
19025 ** The following routine implements the rough equivalent of localtime_r()
19026 ** using whatever operating-system specific localtime facility that
19027 ** is available. This routine returns 0 on success and
19028 ** non-zero on any kind of error.
19029 **
19030 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
19031 ** routine will always fail.
19032 **
19033 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
19034 ** library function localtime_r() is used to assist in the calculation of
19035 ** local time.
19036 */
19037 static int osLocaltime(time_t *t, struct tm *pTm){
19038  int rc;
19039 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
19040  struct tm *pX;
19041 #if SQLITE_THREADSAFE>0
19043 #endif
19044  sqlite3_mutex_enter(mutex);
19045  pX = localtime(t);
19046 #ifndef SQLITE_OMIT_BUILTIN_TEST
19047  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
19048 #endif
19049  if( pX ) *pTm = *pX;
19050  sqlite3_mutex_leave(mutex);
19051  rc = pX==0;
19052 #else
19053 #ifndef SQLITE_OMIT_BUILTIN_TEST
19054  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19055 #endif
19056 #if HAVE_LOCALTIME_R
19057  rc = localtime_r(t, pTm)==0;
19058 #else
19059  rc = localtime_s(pTm, t);
19060 #endif /* HAVE_LOCALTIME_R */
19061 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19062  return rc;
19063 }
19064 #endif /* SQLITE_OMIT_LOCALTIME */
19065 
19066 
19067 #ifndef SQLITE_OMIT_LOCALTIME
19068 /*
19069 ** Compute the difference (in milliseconds) between localtime and UTC
19070 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19071 ** return this value and set *pRc to SQLITE_OK.
19072 **
19073 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19074 ** is undefined in this case.
19075 */
19076 static sqlite3_int64 localtimeOffset(
19077  DateTime *p, /* Date at which to calculate offset */
19078  sqlite3_context *pCtx, /* Write error here if one occurs */
19079  int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
19080 ){
19081  DateTime x, y;
19082  time_t t;
19083  struct tm sLocal;
19084 
19085  /* Initialize the contents of sLocal to avoid a compiler warning. */
19086  memset(&sLocal, 0, sizeof(sLocal));
19087 
19088  x = *p;
19089  computeYMD_HMS(&x);
19090  if( x.Y<1971 || x.Y>=2038 ){
19091  /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
19092  ** works for years between 1970 and 2037. For dates outside this range,
19093  ** SQLite attempts to map the year into an equivalent year within this
19094  ** range, do the calculation, then map the year back.
19095  */
19096  x.Y = 2000;
19097  x.M = 1;
19098  x.D = 1;
19099  x.h = 0;
19100  x.m = 0;
19101  x.s = 0.0;
19102  } else {
19103  int s = (int)(x.s + 0.5);
19104  x.s = s;
19105  }
19106  x.tz = 0;
19107  x.validJD = 0;
19108  computeJD(&x);
19109  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
19110  if( osLocaltime(&t, &sLocal) ){
19111  sqlite3_result_error(pCtx, "local time unavailable", -1);
19112  *pRc = SQLITE_ERROR;
19113  return 0;
19114  }
19115  y.Y = sLocal.tm_year + 1900;
19116  y.M = sLocal.tm_mon + 1;
19117  y.D = sLocal.tm_mday;
19118  y.h = sLocal.tm_hour;
19119  y.m = sLocal.tm_min;
19120  y.s = sLocal.tm_sec;
19121  y.validYMD = 1;
19122  y.validHMS = 1;
19123  y.validJD = 0;
19124  y.validTZ = 0;
19125  computeJD(&y);
19126  *pRc = SQLITE_OK;
19127  return y.iJD - x.iJD;
19128 }
19129 #endif /* SQLITE_OMIT_LOCALTIME */
19130 
19131 /*
19132 ** Process a modifier to a date-time stamp. The modifiers are
19133 ** as follows:
19134 **
19135 ** NNN days
19136 ** NNN hours
19137 ** NNN minutes
19138 ** NNN.NNNN seconds
19139 ** NNN months
19140 ** NNN years
19141 ** start of month
19142 ** start of year
19143 ** start of week
19144 ** start of day
19145 ** weekday N
19146 ** unixepoch
19147 ** localtime
19148 ** utc
19149 **
19150 ** Return 0 on success and 1 if there is any kind of error. If the error
19151 ** is in a system call (i.e. localtime()), then an error message is written
19152 ** to context pCtx. If the error is an unrecognized modifier, no error is
19153 ** written to pCtx.
19154 */
19155 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
19156  int rc = 1;
19157  int n;
19158  double r;
19159  char *z, zBuf[30];
19160  z = zBuf;
19161  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
19162  z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
19163  }
19164  z[n] = 0;
19165  switch( z[0] ){
19166 #ifndef SQLITE_OMIT_LOCALTIME
19167  case 'l': {
19168  /* localtime
19169  **
19170  ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
19171  ** show local time.
19172  */
19173  if( strcmp(z, "localtime")==0 ){
19174  computeJD(p);
19175  p->iJD += localtimeOffset(p, pCtx, &rc);
19176  clearYMD_HMS_TZ(p);
19177  }
19178  break;
19179  }
19180 #endif
19181  case 'u': {
19182  /*
19183  ** unixepoch
19184  **
19185  ** Treat the current value of p->iJD as the number of
19186  ** seconds since 1970. Convert to a real julian day number.
19187  */
19188  if( strcmp(z, "unixepoch")==0 && p->validJD ){
19189  p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
19190  clearYMD_HMS_TZ(p);
19191  rc = 0;
19192  }
19193 #ifndef SQLITE_OMIT_LOCALTIME
19194  else if( strcmp(z, "utc")==0 ){
19195  if( p->tzSet==0 ){
19196  sqlite3_int64 c1;
19197  computeJD(p);
19198  c1 = localtimeOffset(p, pCtx, &rc);
19199  if( rc==SQLITE_OK ){
19200  p->iJD -= c1;
19201  clearYMD_HMS_TZ(p);
19202  p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
19203  }
19204  p->tzSet = 1;
19205  }else{
19206  rc = SQLITE_OK;
19207  }
19208  }
19209 #endif
19210  break;
19211  }
19212  case 'w': {
19213  /*
19214  ** weekday N
19215  **
19216  ** Move the date to the same time on the next occurrence of
19217  ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
19218  ** date is already on the appropriate weekday, this is a no-op.
19219  */
19220  if( strncmp(z, "weekday ", 8)==0
19221  && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
19222  && (n=(int)r)==r && n>=0 && r<7 ){
19223  sqlite3_int64 Z;
19224  computeYMD_HMS(p);
19225  p->validTZ = 0;
19226  p->validJD = 0;
19227  computeJD(p);
19228  Z = ((p->iJD + 129600000)/86400000) % 7;
19229  if( Z>n ) Z -= 7;
19230  p->iJD += (n - Z)*86400000;
19231  clearYMD_HMS_TZ(p);
19232  rc = 0;
19233  }
19234  break;
19235  }
19236  case 's': {
19237  /*
19238  ** start of TTTTT
19239  **
19240  ** Move the date backwards to the beginning of the current day,
19241  ** or month or year.
19242  */
19243  if( strncmp(z, "start of ", 9)!=0 ) break;
19244  z += 9;
19245  computeYMD(p);
19246  p->validHMS = 1;
19247  p->h = p->m = 0;
19248  p->s = 0.0;
19249  p->validTZ = 0;
19250  p->validJD = 0;
19251  if( strcmp(z,"month")==0 ){
19252  p->D = 1;
19253  rc = 0;
19254  }else if( strcmp(z,"year")==0 ){
19255  computeYMD(p);
19256  p->M = 1;
19257  p->D = 1;
19258  rc = 0;
19259  }else if( strcmp(z,"day")==0 ){
19260  rc = 0;
19261  }
19262  break;
19263  }
19264  case '+':
19265  case '-':
19266  case '0':
19267  case '1':
19268  case '2':
19269  case '3':
19270  case '4':
19271  case '5':
19272  case '6':
19273  case '7':
19274  case '8':
19275  case '9': {
19276  double rRounder;
19277  for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
19278  if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
19279  rc = 1;
19280  break;
19281  }
19282  if( z[n]==':' ){
19283  /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
19284  ** specified number of hours, minutes, seconds, and fractional seconds
19285  ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
19286  ** omitted.
19287  */
19288  const char *z2 = z;
19289  DateTime tx;
19290  sqlite3_int64 day;
19291  if( !sqlite3Isdigit(*z2) ) z2++;
19292  memset(&tx, 0, sizeof(tx));
19293  if( parseHhMmSs(z2, &tx) ) break;
19294  computeJD(&tx);
19295  tx.iJD -= 43200000;
19296  day = tx.iJD/86400000;
19297  tx.iJD -= day*86400000;
19298  if( z[0]=='-' ) tx.iJD = -tx.iJD;
19299  computeJD(p);
19300  clearYMD_HMS_TZ(p);
19301  p->iJD += tx.iJD;
19302  rc = 0;
19303  break;
19304  }
19305  z += n;
19306  while( sqlite3Isspace(*z) ) z++;
19307  n = sqlite3Strlen30(z);
19308  if( n>10 || n<3 ) break;
19309  if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
19310  computeJD(p);
19311  rc = 0;
19312  rRounder = r<0 ? -0.5 : +0.5;
19313  if( n==3 && strcmp(z,"day")==0 ){
19314  p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
19315  }else if( n==4 && strcmp(z,"hour")==0 ){
19316  p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
19317  }else if( n==6 && strcmp(z,"minute")==0 ){
19318  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
19319  }else if( n==6 && strcmp(z,"second")==0 ){
19320  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
19321  }else if( n==5 && strcmp(z,"month")==0 ){
19322  int x, y;
19323  computeYMD_HMS(p);
19324  p->M += (int)r;
19325  x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
19326  p->Y += x;
19327  p->M -= x*12;
19328  p->validJD = 0;
19329  computeJD(p);
19330  y = (int)r;
19331  if( y!=r ){
19332  p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
19333  }
19334  }else if( n==4 && strcmp(z,"year")==0 ){
19335  int y = (int)r;
19336  computeYMD_HMS(p);
19337  p->Y += y;
19338  p->validJD = 0;
19339  computeJD(p);
19340  if( y!=r ){
19341  p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
19342  }
19343  }else{
19344  rc = 1;
19345  }
19346  clearYMD_HMS_TZ(p);
19347  break;
19348  }
19349  default: {
19350  break;
19351  }
19352  }
19353  return rc;
19354 }
19355 
19356 /*
19357 ** Process time function arguments. argv[0] is a date-time stamp.
19358 ** argv[1] and following are modifiers. Parse them all and write
19359 ** the resulting time into the DateTime structure p. Return 0
19360 ** on success and 1 if there are any errors.
19361 **
19362 ** If there are zero parameters (if even argv[0] is undefined)
19363 ** then assume a default value of "now" for argv[0].
19364 */
19365 static int isDate(
19366  sqlite3_context *context,
19367  int argc,
19368  sqlite3_value **argv,
19369  DateTime *p
19370 ){
19371  int i;
19372  const unsigned char *z;
19373  int eType;
19374  memset(p, 0, sizeof(*p));
19375  if( argc==0 ){
19376  return setDateTimeToCurrent(context, p);
19377  }
19378  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
19379  || eType==SQLITE_INTEGER ){
19380  p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
19381  p->validJD = 1;
19382  }else{
19383  z = sqlite3_value_text(argv[0]);
19384  if( !z || parseDateOrTime(context, (char*)z, p) ){
19385  return 1;
19386  }
19387  }
19388  for(i=1; i<argc; i++){
19389  z = sqlite3_value_text(argv[i]);
19390  if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
19391  }
19392  return 0;
19393 }
19394 
19395 
19396 /*
19397 ** The following routines implement the various date and time functions
19398 ** of SQLite.
19399 */
19400 
19401 /*
19402 ** julianday( TIMESTRING, MOD, MOD, ...)
19403 **
19404 ** Return the julian day number of the date specified in the arguments
19405 */
19406 static void juliandayFunc(
19407  sqlite3_context *context,
19408  int argc,
19409  sqlite3_value **argv
19410 ){
19411  DateTime x;
19412  if( isDate(context, argc, argv, &x)==0 ){
19413  computeJD(&x);
19414  sqlite3_result_double(context, x.iJD/86400000.0);
19415  }
19416 }
19417 
19418 /*
19419 ** datetime( TIMESTRING, MOD, MOD, ...)
19420 **
19421 ** Return YYYY-MM-DD HH:MM:SS
19422 */
19423 static void datetimeFunc(
19424  sqlite3_context *context,
19425  int argc,
19426  sqlite3_value **argv
19427 ){
19428  DateTime x;
19429  if( isDate(context, argc, argv, &x)==0 ){
19430  char zBuf[100];
19431  computeYMD_HMS(&x);
19432  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
19433  x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
19434  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19435  }
19436 }
19437 
19438 /*
19439 ** time( TIMESTRING, MOD, MOD, ...)
19440 **
19441 ** Return HH:MM:SS
19442 */
19443 static void timeFunc(
19444  sqlite3_context *context,
19445  int argc,
19446  sqlite3_value **argv
19447 ){
19448  DateTime x;
19449  if( isDate(context, argc, argv, &x)==0 ){
19450  char zBuf[100];
19451  computeHMS(&x);
19452  sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
19453  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19454  }
19455 }
19456 
19457 /*
19458 ** date( TIMESTRING, MOD, MOD, ...)
19459 **
19460 ** Return YYYY-MM-DD
19461 */
19462 static void dateFunc(
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  computeYMD(&x);
19471  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
19472  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19473  }
19474 }
19475 
19476 /*
19477 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
19478 **
19479 ** Return a string described by FORMAT. Conversions as follows:
19480 **
19481 ** %d day of month
19482 ** %f ** fractional seconds SS.SSS
19483 ** %H hour 00-24
19484 ** %j day of year 000-366
19485 ** %J ** julian day number
19486 ** %m month 01-12
19487 ** %M minute 00-59
19488 ** %s seconds since 1970-01-01
19489 ** %S seconds 00-59
19490 ** %w day of week 0-6 sunday==0
19491 ** %W week of year 00-53
19492 ** %Y year 0000-9999
19493 ** %% %
19494 */
19495 static void strftimeFunc(
19496  sqlite3_context *context,
19497  int argc,
19498  sqlite3_value **argv
19499 ){
19500  DateTime x;
19501  u64 n;
19502  size_t i,j;
19503  char *z;
19504  sqlite3 *db;
19505  const char *zFmt;
19506  char zBuf[100];
19507  if( argc==0 ) return;
19508  zFmt = (const char*)sqlite3_value_text(argv[0]);
19509  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
19510  db = sqlite3_context_db_handle(context);
19511  for(i=0, n=1; zFmt[i]; i++, n++){
19512  if( zFmt[i]=='%' ){
19513  switch( zFmt[i+1] ){
19514  case 'd':
19515  case 'H':
19516  case 'm':
19517  case 'M':
19518  case 'S':
19519  case 'W':
19520  n++;
19521  /* fall thru */
19522  case 'w':
19523  case '%':
19524  break;
19525  case 'f':
19526  n += 8;
19527  break;
19528  case 'j':
19529  n += 3;
19530  break;
19531  case 'Y':
19532  n += 8;
19533  break;
19534  case 's':
19535  case 'J':
19536  n += 50;
19537  break;
19538  default:
19539  return; /* ERROR. return a NULL */
19540  }
19541  i++;
19542  }
19543  }
19544  testcase( n==sizeof(zBuf)-1 );
19545  testcase( n==sizeof(zBuf) );
19546  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
19547  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
19548  if( n<sizeof(zBuf) ){
19549  z = zBuf;
19550  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
19551  sqlite3_result_error_toobig(context);
19552  return;
19553  }else{
19554  z = sqlite3DbMallocRawNN(db, (int)n);
19555  if( z==0 ){
19556  sqlite3_result_error_nomem(context);
19557  return;
19558  }
19559  }
19560  computeJD(&x);
19561  computeYMD_HMS(&x);
19562  for(i=j=0; zFmt[i]; i++){
19563  if( zFmt[i]!='%' ){
19564  z[j++] = zFmt[i];
19565  }else{
19566  i++;
19567  switch( zFmt[i] ){
19568  case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
19569  case 'f': {
19570  double s = x.s;
19571  if( s>59.999 ) s = 59.999;
19572  sqlite3_snprintf(7, &z[j],"%06.3f", s);
19573  j += sqlite3Strlen30(&z[j]);
19574  break;
19575  }
19576  case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
19577  case 'W': /* Fall thru */
19578  case 'j': {
19579  int nDay; /* Number of days since 1st day of year */
19580  DateTime y = x;
19581  y.validJD = 0;
19582  y.M = 1;
19583  y.D = 1;
19584  computeJD(&y);
19585  nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
19586  if( zFmt[i]=='W' ){
19587  int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
19588  wd = (int)(((x.iJD+43200000)/86400000)%7);
19589  sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
19590  j += 2;
19591  }else{
19592  sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
19593  j += 3;
19594  }
19595  break;
19596  }
19597  case 'J': {
19598  sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
19599  j+=sqlite3Strlen30(&z[j]);
19600  break;
19601  }
19602  case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
19603  case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
19604  case 's': {
19605  sqlite3_snprintf(30,&z[j],"%lld",
19606  (i64)(x.iJD/1000 - 21086676*(i64)10000));
19607  j += sqlite3Strlen30(&z[j]);
19608  break;
19609  }
19610  case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
19611  case 'w': {
19612  z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
19613  break;
19614  }
19615  case 'Y': {
19616  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
19617  break;
19618  }
19619  default: z[j++] = '%'; break;
19620  }
19621  }
19622  }
19623  z[j] = 0;
19624  sqlite3_result_text(context, z, -1,
19625  z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
19626 }
19627 
19628 /*
19629 ** current_time()
19630 **
19631 ** This function returns the same value as time('now').
19632 */
19633 static void ctimeFunc(
19634  sqlite3_context *context,
19635  int NotUsed,
19636  sqlite3_value **NotUsed2
19637 ){
19638  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19639  timeFunc(context, 0, 0);
19640 }
19641 
19642 /*
19643 ** current_date()
19644 **
19645 ** This function returns the same value as date('now').
19646 */
19647 static void cdateFunc(
19648  sqlite3_context *context,
19649  int NotUsed,
19650  sqlite3_value **NotUsed2
19651 ){
19652  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19653  dateFunc(context, 0, 0);
19654 }
19655 
19656 /*
19657 ** current_timestamp()
19658 **
19659 ** This function returns the same value as datetime('now').
19660 */
19661 static void ctimestampFunc(
19662  sqlite3_context *context,
19663  int NotUsed,
19664  sqlite3_value **NotUsed2
19665 ){
19666  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19667  datetimeFunc(context, 0, 0);
19668 }
19669 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
19670 
19671 #ifdef SQLITE_OMIT_DATETIME_FUNCS
19672 /*
19673 ** If the library is compiled to omit the full-scale date and time
19674 ** handling (to get a smaller binary), the following minimal version
19675 ** of the functions current_time(), current_date() and current_timestamp()
19676 ** are included instead. This is to support column declarations that
19677 ** include "DEFAULT CURRENT_TIME" etc.
19678 **
19679 ** This function uses the C-library functions time(), gmtime()
19680 ** and strftime(). The format string to pass to strftime() is supplied
19681 ** as the user-data for the function.
19682 */
19683 static void currentTimeFunc(
19684  sqlite3_context *context,
19685  int argc,
19686  sqlite3_value **argv
19687 ){
19688  time_t t;
19689  char *zFormat = (char *)sqlite3_user_data(context);
19690  sqlite3_int64 iT;
19691  struct tm *pTm;
19692  struct tm sNow;
19693  char zBuf[20];
19694 
19695  UNUSED_PARAMETER(argc);
19696  UNUSED_PARAMETER(argv);
19697 
19698  iT = sqlite3StmtCurrentTime(context);
19699  if( iT<=0 ) return;
19700  t = iT/1000 - 10000*(sqlite3_int64)21086676;
19701 #if HAVE_GMTIME_R
19702  pTm = gmtime_r(&t, &sNow);
19703 #else
19705  pTm = gmtime(&t);
19706  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
19708 #endif
19709  if( pTm ){
19710  strftime(zBuf, 20, zFormat, &sNow);
19711  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19712  }
19713 }
19714 #endif
19715 
19716 /*
19717 ** This function registered all of the above C functions as SQL
19718 ** functions. This should be the only routine in this file with
19719 ** external linkage.
19720 */
19722  static FuncDef aDateTimeFuncs[] = {
19723 #ifndef SQLITE_OMIT_DATETIME_FUNCS
19724  DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
19725  DFUNCTION(date, -1, 0, 0, dateFunc ),
19726  DFUNCTION(time, -1, 0, 0, timeFunc ),
19727  DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
19728  DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
19729  DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
19730  DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
19731  DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
19732 #else
19733  STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
19734  STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
19735  STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
19736 #endif
19737  };
19738  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
19739 }
19740 
19741 /************** End of date.c ************************************************/
19742 /************** Begin file os.c **********************************************/
19743 /*
19744 ** 2005 November 29
19745 **
19746 ** The author disclaims copyright to this source code. In place of
19747 ** a legal notice, here is a blessing:
19748 **
19749 ** May you do good and not evil.
19750 ** May you find forgiveness for yourself and forgive others.
19751 ** May you share freely, never taking more than you give.
19752 **
19753 ******************************************************************************
19754 **
19755 ** This file contains OS interface code that is common to all
19756 ** architectures.
19757 */
19758 /* #include "sqliteInt.h" */
19759 
19760 /*
19761 ** If we compile with the SQLITE_TEST macro set, then the following block
19762 ** of code will give us the ability to simulate a disk I/O error. This
19763 ** is used for testing the I/O recovery logic.
19764 */
19765 #if defined(SQLITE_TEST)
19766 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
19767 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
19768 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
19769 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
19770 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
19771 SQLITE_API int sqlite3_diskfull_pending = 0;
19772 SQLITE_API int sqlite3_diskfull = 0;
19773 #endif /* defined(SQLITE_TEST) */
19774 
19775 /*
19776 ** When testing, also keep a count of the number of open files.
19777 */
19778 #if defined(SQLITE_TEST)
19779 SQLITE_API int sqlite3_open_file_count = 0;
19780 #endif /* defined(SQLITE_TEST) */
19781 
19782 /*
19783 ** The default SQLite sqlite3_vfs implementations do not allocate
19784 ** memory (actually, os_unix.c allocates a small amount of memory
19785 ** from within OsOpen()), but some third-party implementations may.
19786 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
19787 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
19788 **
19789 ** The following functions are instrumented for malloc() failure
19790 ** testing:
19791 **
19792 ** sqlite3OsRead()
19793 ** sqlite3OsWrite()
19794 ** sqlite3OsSync()
19795 ** sqlite3OsFileSize()
19796 ** sqlite3OsLock()
19797 ** sqlite3OsCheckReservedLock()
19798 ** sqlite3OsFileControl()
19799 ** sqlite3OsShmMap()
19800 ** sqlite3OsOpen()
19801 ** sqlite3OsDelete()
19802 ** sqlite3OsAccess()
19803 ** sqlite3OsFullPathname()
19804 **
19805 */
19806 #if defined(SQLITE_TEST)
19807 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
19808  #define DO_OS_MALLOC_TEST(x) \
19809  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
19810  void *pTstAlloc = sqlite3Malloc(10); \
19811  if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
19812  sqlite3_free(pTstAlloc); \
19813  }
19814 #else
19815  #define DO_OS_MALLOC_TEST(x)
19816 #endif
19817 
19818 /*
19819 ** The following routines are convenience wrappers around methods
19820 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
19821 ** of this would be completely automatic if SQLite were coded using
19822 ** C++ instead of plain old C.
19823 */
19824 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
19825  if( pId->pMethods ){
19826  pId->pMethods->xClose(pId);
19827  pId->pMethods = 0;
19828  }
19829 }
19830 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
19831  DO_OS_MALLOC_TEST(id);
19832  return id->pMethods->xRead(id, pBuf, amt, offset);
19833 }
19834 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
19835  DO_OS_MALLOC_TEST(id);
19836  return id->pMethods->xWrite(id, pBuf, amt, offset);
19837 }
19838 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
19839  return id->pMethods->xTruncate(id, size);
19840 }
19841 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
19842  DO_OS_MALLOC_TEST(id);
19843  return id->pMethods->xSync(id, flags);
19844 }
19845 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
19846  DO_OS_MALLOC_TEST(id);
19847  return id->pMethods->xFileSize(id, pSize);
19848 }
19849 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
19850  DO_OS_MALLOC_TEST(id);
19851  return id->pMethods->xLock(id, lockType);
19852 }
19853 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
19854  return id->pMethods->xUnlock(id, lockType);
19855 }
19856 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
19857  DO_OS_MALLOC_TEST(id);
19858  return id->pMethods->xCheckReservedLock(id, pResOut);
19859 }
19860 
19861 /*
19862 ** Use sqlite3OsFileControl() when we are doing something that might fail
19863 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
19864 ** when simply tossing information over the wall to the VFS and we do not
19865 ** really care if the VFS receives and understands the information since it
19866 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
19867 ** routine has no return value since the return value would be meaningless.
19868 */
19869 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
19870 #ifdef SQLITE_TEST
19871  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
19872  /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
19873  ** is using a regular VFS, it is called after the corresponding
19874  ** transaction has been committed. Injecting a fault at this point
19875  ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
19876  ** but the transaction is committed anyway.
19877  **
19878  ** The core must call OsFileControl() though, not OsFileControlHint(),
19879  ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
19880  ** means the commit really has failed and an error should be returned
19881  ** to the user. */
19882  DO_OS_MALLOC_TEST(id);
19883  }
19884 #endif
19885  return id->pMethods->xFileControl(id, op, pArg);
19886 }
19887 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
19888  (void)id->pMethods->xFileControl(id, op, pArg);
19889 }
19890 
19891 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
19892  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
19893  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
19894 }
19896  return id->pMethods->xDeviceCharacteristics(id);
19897 }
19898 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
19899  return id->pMethods->xShmLock(id, offset, n, flags);
19900 }
19901 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
19902  id->pMethods->xShmBarrier(id);
19903 }
19904 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
19905  return id->pMethods->xShmUnmap(id, deleteFlag);
19906 }
19908  sqlite3_file *id, /* Database file handle */
19909  int iPage,
19910  int pgsz,
19911  int bExtend, /* True to extend file if necessary */
19912  void volatile **pp /* OUT: Pointer to mapping */
19913 ){
19914  DO_OS_MALLOC_TEST(id);
19915  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
19916 }
19917 
19918 #if SQLITE_MAX_MMAP_SIZE>0
19919 /* The real implementation of xFetch and xUnfetch */
19920 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19921  DO_OS_MALLOC_TEST(id);
19922  return id->pMethods->xFetch(id, iOff, iAmt, pp);
19923 }
19924 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19925  return id->pMethods->xUnfetch(id, iOff, p);
19926 }
19927 #else
19928 /* No-op stubs to use when memory-mapped I/O is disabled */
19929 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19930  *pp = 0;
19931  return SQLITE_OK;
19932 }
19933 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19934  return SQLITE_OK;
19935 }
19936 #endif
19937 
19938 /*
19939 ** The next group of routines are convenience wrappers around the
19940 ** VFS methods.
19941 */
19943  sqlite3_vfs *pVfs,
19944  const char *zPath,
19945  sqlite3_file *pFile,
19946  int flags,
19947  int *pFlagsOut
19948 ){
19949  int rc;
19950  DO_OS_MALLOC_TEST(0);
19951  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
19952  ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
19953  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
19954  ** reaching the VFS. */
19955  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
19956  assert( rc==SQLITE_OK || pFile->pMethods==0 );
19957  return rc;
19958 }
19959 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
19960  DO_OS_MALLOC_TEST(0);
19961  assert( dirSync==0 || dirSync==1 );
19962  return pVfs->xDelete(pVfs, zPath, dirSync);
19963 }
19965  sqlite3_vfs *pVfs,
19966  const char *zPath,
19967  int flags,
19968  int *pResOut
19969 ){
19970  DO_OS_MALLOC_TEST(0);
19971  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
19972 }
19974  sqlite3_vfs *pVfs,
19975  const char *zPath,
19976  int nPathOut,
19977  char *zPathOut
19978 ){
19979  DO_OS_MALLOC_TEST(0);
19980  zPathOut[0] = 0;
19981  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
19982 }
19983 #ifndef SQLITE_OMIT_LOAD_EXTENSION
19984 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
19985  return pVfs->xDlOpen(pVfs, zPath);
19986 }
19987 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19988  pVfs->xDlError(pVfs, nByte, zBufOut);
19989 }
19990 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
19991  return pVfs->xDlSym(pVfs, pHdle, zSym);
19992 }
19993 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
19994  pVfs->xDlClose(pVfs, pHandle);
19995 }
19996 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
19997 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19998  return pVfs->xRandomness(pVfs, nByte, zBufOut);
19999 }
20000 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
20001  return pVfs->xSleep(pVfs, nMicro);
20002 }
20003 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
20004  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
20005 }
20006 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
20007  int rc;
20008  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
20009  ** method to get the current date and time if that method is available
20010  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
20011  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
20012  ** unavailable.
20013  */
20014  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
20015  rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
20016  }else{
20017  double r;
20018  rc = pVfs->xCurrentTime(pVfs, &r);
20019  *pTimeOut = (sqlite3_int64)(r*86400000.0);
20020  }
20021  return rc;
20022 }
20023 
20025  sqlite3_vfs *pVfs,
20026  const char *zFile,
20027  sqlite3_file **ppFile,
20028  int flags,
20029  int *pOutFlags
20030 ){
20031  int rc;
20032  sqlite3_file *pFile;
20033  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
20034  if( pFile ){
20035  rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
20036  if( rc!=SQLITE_OK ){
20037  sqlite3_free(pFile);
20038  }else{
20039  *ppFile = pFile;
20040  }
20041  }else{
20042  rc = SQLITE_NOMEM_BKPT;
20043  }
20044  return rc;
20045 }
20046 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
20047  assert( pFile );
20048  sqlite3OsClose(pFile);
20049  sqlite3_free(pFile);
20050 }
20051 
20052 /*
20053 ** This function is a wrapper around the OS specific implementation of
20054 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
20055 ** ability to simulate a malloc failure, so that the handling of an
20056 ** error in sqlite3_os_init() by the upper layers can be tested.
20057 */
20059  void *p = sqlite3_malloc(10);
20060  if( p==0 ) return SQLITE_NOMEM_BKPT;
20061  sqlite3_free(p);
20062  return sqlite3_os_init();
20063 }
20064 
20065 /*
20066 ** The list of all registered VFS implementations.
20067 */
20068 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
20069 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
20070 
20071 /*
20072 ** Locate a VFS by name. If no name is given, simply return the
20073 ** first VFS on the list.
20074 */
20075 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
20076  sqlite3_vfs *pVfs = 0;
20077 #if SQLITE_THREADSAFE
20078  sqlite3_mutex *mutex;
20079 #endif
20080 #ifndef SQLITE_OMIT_AUTOINIT
20081  int rc = sqlite3_initialize();
20082  if( rc ) return 0;
20083 #endif
20084 #if SQLITE_THREADSAFE
20086 #endif
20087  sqlite3_mutex_enter(mutex);
20088  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
20089  if( zVfs==0 ) break;
20090  if( strcmp(zVfs, pVfs->zName)==0 ) break;
20091  }
20092  sqlite3_mutex_leave(mutex);
20093  return pVfs;
20094 }
20095 
20096 /*
20097 ** Unlink a VFS from the linked list
20098 */
20099 static void vfsUnlink(sqlite3_vfs *pVfs){
20101  if( pVfs==0 ){
20102  /* No-op */
20103  }else if( vfsList==pVfs ){
20104  vfsList = pVfs->pNext;
20105  }else if( vfsList ){
20106  sqlite3_vfs *p = vfsList;
20107  while( p->pNext && p->pNext!=pVfs ){
20108  p = p->pNext;
20109  }
20110  if( p->pNext==pVfs ){
20111  p->pNext = pVfs->pNext;
20112  }
20113  }
20114 }
20115 
20116 /*
20117 ** Register a VFS with the system. It is harmless to register the same
20118 ** VFS multiple times. The new VFS becomes the default if makeDflt is
20119 ** true.
20120 */
20121 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
20122  MUTEX_LOGIC(sqlite3_mutex *mutex;)
20123 #ifndef SQLITE_OMIT_AUTOINIT
20124  int rc = sqlite3_initialize();
20125  if( rc ) return rc;
20126 #endif
20127 #ifdef SQLITE_ENABLE_API_ARMOR
20128  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
20129 #endif
20130 
20132  sqlite3_mutex_enter(mutex);
20133  vfsUnlink(pVfs);
20134  if( makeDflt || vfsList==0 ){
20135  pVfs->pNext = vfsList;
20136  vfsList = pVfs;
20137  }else{
20138  pVfs->pNext = vfsList->pNext;
20139  vfsList->pNext = pVfs;
20140  }
20141  assert(vfsList);
20142  sqlite3_mutex_leave(mutex);
20143  return SQLITE_OK;
20144 }
20145 
20146 /*
20147 ** Unregister a VFS so that it is no longer accessible.
20148 */
20149 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
20150 #if SQLITE_THREADSAFE
20152 #endif
20153  sqlite3_mutex_enter(mutex);
20154  vfsUnlink(pVfs);
20155  sqlite3_mutex_leave(mutex);
20156  return SQLITE_OK;
20157 }
20158 
20159 /************** End of os.c **************************************************/
20160 /************** Begin file fault.c *******************************************/
20161 /*
20162 ** 2008 Jan 22
20163 **
20164 ** The author disclaims copyright to this source code. In place of
20165 ** a legal notice, here is a blessing:
20166 **
20167 ** May you do good and not evil.
20168 ** May you find forgiveness for yourself and forgive others.
20169 ** May you share freely, never taking more than you give.
20170 **
20171 *************************************************************************
20172 **
20173 ** This file contains code to support the concept of "benign"
20174 ** malloc failures (when the xMalloc() or xRealloc() method of the
20175 ** sqlite3_mem_methods structure fails to allocate a block of memory
20176 ** and returns 0).
20177 **
20178 ** Most malloc failures are non-benign. After they occur, SQLite
20179 ** abandons the current operation and returns an error code (usually
20180 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
20181 ** fatal. For example, if a malloc fails while resizing a hash table, this
20182 ** is completely recoverable simply by not carrying out the resize. The
20183 ** hash table will continue to function normally. So a malloc failure
20184 ** during a hash table resize is a benign fault.
20185 */
20186 
20187 /* #include "sqliteInt.h" */
20188 
20189 #ifndef SQLITE_OMIT_BUILTIN_TEST
20190 
20191 /*
20192 ** Global variables.
20193 */
20196  void (*xBenignBegin)(void);
20197  void (*xBenignEnd)(void);
20198 } sqlite3Hooks = { 0, 0 };
20199 
20200 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
20201 ** structure. If writable static data is unsupported on the target,
20202 ** we have to locate the state vector at run-time. In the more common
20203 ** case where writable static data is supported, wsdHooks can refer directly
20204 ** to the "sqlite3Hooks" state vector declared above.
20205 */
20206 #ifdef SQLITE_OMIT_WSD
20207 # define wsdHooksInit \
20208  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
20209 # define wsdHooks x[0]
20210 #else
20211 # define wsdHooksInit
20212 # define wsdHooks sqlite3Hooks
20213 #endif
20214 
20215 
20216 /*
20217 ** Register hooks to call when sqlite3BeginBenignMalloc() and
20218 ** sqlite3EndBenignMalloc() are called, respectively.
20219 */
20221  void (*xBenignBegin)(void),
20222  void (*xBenignEnd)(void)
20223 ){
20224  wsdHooksInit;
20225  wsdHooks.xBenignBegin = xBenignBegin;
20226  wsdHooks.xBenignEnd = xBenignEnd;
20227 }
20228 
20229 /*
20230 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
20231 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
20232 ** indicates that subsequent malloc failures are non-benign.
20233 */
20235  wsdHooksInit;
20236  if( wsdHooks.xBenignBegin ){
20237  wsdHooks.xBenignBegin();
20238  }
20239 }
20241  wsdHooksInit;
20242  if( wsdHooks.xBenignEnd ){
20243  wsdHooks.xBenignEnd();
20244  }
20245 }
20246 
20247 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
20248 
20249 /************** End of fault.c ***********************************************/
20250 /************** Begin file mem0.c ********************************************/
20251 /*
20252 ** 2008 October 28
20253 **
20254 ** The author disclaims copyright to this source code. In place of
20255 ** a legal notice, here is a blessing:
20256 **
20257 ** May you do good and not evil.
20258 ** May you find forgiveness for yourself and forgive others.
20259 ** May you share freely, never taking more than you give.
20260 **
20261 *************************************************************************
20262 **
20263 ** This file contains a no-op memory allocation drivers for use when
20264 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
20265 ** here always fail. SQLite will not operate with these drivers. These
20266 ** are merely placeholders. Real drivers must be substituted using
20267 ** sqlite3_config() before SQLite will operate.
20268 */
20269 /* #include "sqliteInt.h" */
20270 
20271 /*
20272 ** This version of the memory allocator is the default. It is
20273 ** used when no other memory allocator is specified using compile-time
20274 ** macros.
20275 */
20276 #ifdef SQLITE_ZERO_MALLOC
20277 
20278 /*
20279 ** No-op versions of all memory allocation routines
20280 */
20281 static void *sqlite3MemMalloc(int nByte){ return 0; }
20282 static void sqlite3MemFree(void *pPrior){ return; }
20283 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
20284 static int sqlite3MemSize(void *pPrior){ return 0; }
20285 static int sqlite3MemRoundup(int n){ return n; }
20286 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
20287 static void sqlite3MemShutdown(void *NotUsed){ return; }
20288 
20289 /*
20290 ** This routine is the only routine in this file with external linkage.
20291 **
20292 ** Populate the low-level memory allocation function pointers in
20293 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20294 */
20296  static const sqlite3_mem_methods defaultMethods = {
20304  0
20305  };
20306  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20307 }
20308 
20309 #endif /* SQLITE_ZERO_MALLOC */
20310 
20311 /************** End of mem0.c ************************************************/
20312 /************** Begin file mem1.c ********************************************/
20313 /*
20314 ** 2007 August 14
20315 **
20316 ** The author disclaims copyright to this source code. In place of
20317 ** a legal notice, here is a blessing:
20318 **
20319 ** May you do good and not evil.
20320 ** May you find forgiveness for yourself and forgive others.
20321 ** May you share freely, never taking more than you give.
20322 **
20323 *************************************************************************
20324 **
20325 ** This file contains low-level memory allocation drivers for when
20326 ** SQLite will use the standard C-library malloc/realloc/free interface
20327 ** to obtain the memory it needs.
20328 **
20329 ** This file contains implementations of the low-level memory allocation
20330 ** routines specified in the sqlite3_mem_methods object. The content of
20331 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
20332 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
20333 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
20334 ** default configuration is to use memory allocation routines in this
20335 ** file.
20336 **
20337 ** C-preprocessor macro summary:
20338 **
20339 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
20340 ** the malloc_usable_size() interface exists
20341 ** on the target platform. Or, this symbol
20342 ** can be set manually, if desired.
20343 ** If an equivalent interface exists by
20344 ** a different name, using a separate -D
20345 ** option to rename it.
20346 **
20347 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
20348 ** memory allocator. Set this symbol to enable
20349 ** building on older macs.
20350 **
20351 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
20352 ** _msize() on windows systems. This might
20353 ** be necessary when compiling for Delphi,
20354 ** for example.
20355 */
20356 /* #include "sqliteInt.h" */
20357 
20358 /*
20359 ** This version of the memory allocator is the default. It is
20360 ** used when no other memory allocator is specified using compile-time
20361 ** macros.
20362 */
20363 #ifdef SQLITE_SYSTEM_MALLOC
20364 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20365 
20366 /*
20367 ** Use the zone allocator available on apple products unless the
20368 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
20369 */
20370 #include <sys/sysctl.h>
20371 #include <malloc/malloc.h>
20372 #include <libkern/OSAtomic.h>
20373 static malloc_zone_t* _sqliteZone_;
20374 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
20375 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
20376 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
20377 #define SQLITE_MALLOCSIZE(x) \
20378  (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
20379 
20380 #else /* if not __APPLE__ */
20381 
20382 /*
20383 ** Use standard C library malloc and free on non-Apple systems.
20384 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
20385 */
20386 #define SQLITE_MALLOC(x) malloc(x)
20387 #define SQLITE_FREE(x) free(x)
20388 #define SQLITE_REALLOC(x,y) realloc((x),(y))
20389 
20390 /*
20391 ** The malloc.h header file is needed for malloc_usable_size() function
20392 ** on some systems (e.g. Linux).
20393 */
20394 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
20395 # define SQLITE_USE_MALLOC_H 1
20396 # define SQLITE_USE_MALLOC_USABLE_SIZE 1
20397 /*
20398 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
20399 ** use of _msize() is automatic, but can be disabled by compiling with
20400 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
20401 ** the malloc.h header file.
20402 */
20403 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
20404 # define SQLITE_USE_MALLOC_H
20405 # define SQLITE_USE_MSIZE
20406 #endif
20407 
20408 /*
20409 ** Include the malloc.h header file, if necessary. Also set define macro
20410 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
20411 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
20412 ** The memory size function can always be overridden manually by defining
20413 ** the macro SQLITE_MALLOCSIZE to the desired function name.
20414 */
20415 #if defined(SQLITE_USE_MALLOC_H)
20416 # include <malloc.h>
20417 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
20418 # if !defined(SQLITE_MALLOCSIZE)
20419 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
20420 # endif
20421 # elif defined(SQLITE_USE_MSIZE)
20422 # if !defined(SQLITE_MALLOCSIZE)
20423 # define SQLITE_MALLOCSIZE _msize
20424 # endif
20425 # endif
20426 #endif /* defined(SQLITE_USE_MALLOC_H) */
20427 
20428 #endif /* __APPLE__ or not __APPLE__ */
20429 
20430 /*
20431 ** Like malloc(), but remember the size of the allocation
20432 ** so that we can find it later using sqlite3MemSize().
20433 **
20434 ** For this low-level routine, we are guaranteed that nByte>0 because
20435 ** cases of nByte<=0 will be intercepted and dealt with by higher level
20436 ** routines.
20437 */
20438 static void *sqlite3MemMalloc(int nByte){
20439 #ifdef SQLITE_MALLOCSIZE
20440  void *p = SQLITE_MALLOC( nByte );
20441  if( p==0 ){
20442  testcase( sqlite3GlobalConfig.xLog!=0 );
20443  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20444  }
20445  return p;
20446 #else
20447  sqlite3_int64 *p;
20448  assert( nByte>0 );
20449  nByte = ROUND8(nByte);
20450  p = SQLITE_MALLOC( nByte+8 );
20451  if( p ){
20452  p[0] = nByte;
20453  p++;
20454  }else{
20455  testcase( sqlite3GlobalConfig.xLog!=0 );
20456  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20457  }
20458  return (void *)p;
20459 #endif
20460 }
20461 
20462 /*
20463 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
20464 ** or sqlite3MemRealloc().
20465 **
20466 ** For this low-level routine, we already know that pPrior!=0 since
20467 ** cases where pPrior==0 will have been intecepted and dealt with
20468 ** by higher-level routines.
20469 */
20470 static void sqlite3MemFree(void *pPrior){
20471 #ifdef SQLITE_MALLOCSIZE
20472  SQLITE_FREE(pPrior);
20473 #else
20474  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20475  assert( pPrior!=0 );
20476  p--;
20477  SQLITE_FREE(p);
20478 #endif
20479 }
20480 
20481 /*
20482 ** Report the allocated size of a prior return from xMalloc()
20483 ** or xRealloc().
20484 */
20485 static int sqlite3MemSize(void *pPrior){
20486 #ifdef SQLITE_MALLOCSIZE
20487  assert( pPrior!=0 );
20488  return (int)SQLITE_MALLOCSIZE(pPrior);
20489 #else
20490  sqlite3_int64 *p;
20491  assert( pPrior!=0 );
20492  p = (sqlite3_int64*)pPrior;
20493  p--;
20494  return (int)p[0];
20495 #endif
20496 }
20497 
20498 /*
20499 ** Like realloc(). Resize an allocation previously obtained from
20500 ** sqlite3MemMalloc().
20501 **
20502 ** For this low-level interface, we know that pPrior!=0. Cases where
20503 ** pPrior==0 while have been intercepted by higher-level routine and
20504 ** redirected to xMalloc. Similarly, we know that nByte>0 because
20505 ** cases where nByte<=0 will have been intercepted by higher-level
20506 ** routines and redirected to xFree.
20507 */
20508 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20509 #ifdef SQLITE_MALLOCSIZE
20510  void *p = SQLITE_REALLOC(pPrior, nByte);
20511  if( p==0 ){
20512  testcase( sqlite3GlobalConfig.xLog!=0 );
20514  "failed memory resize %u to %u bytes",
20515  SQLITE_MALLOCSIZE(pPrior), nByte);
20516  }
20517  return p;
20518 #else
20519  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20520  assert( pPrior!=0 && nByte>0 );
20521  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
20522  p--;
20523  p = SQLITE_REALLOC(p, nByte+8 );
20524  if( p ){
20525  p[0] = nByte;
20526  p++;
20527  }else{
20528  testcase( sqlite3GlobalConfig.xLog!=0 );
20530  "failed memory resize %u to %u bytes",
20531  sqlite3MemSize(pPrior), nByte);
20532  }
20533  return (void*)p;
20534 #endif
20535 }
20536 
20537 /*
20538 ** Round up a request size to the next valid allocation size.
20539 */
20540 static int sqlite3MemRoundup(int n){
20541  return ROUND8(n);
20542 }
20543 
20544 /*
20545 ** Initialize this module.
20546 */
20547 static int sqlite3MemInit(void *NotUsed){
20548 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20549  int cpuCount;
20550  size_t len;
20551  if( _sqliteZone_ ){
20552  return SQLITE_OK;
20553  }
20554  len = sizeof(cpuCount);
20555  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
20556  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
20557  if( cpuCount>1 ){
20558  /* defer MT decisions to system malloc */
20559  _sqliteZone_ = malloc_default_zone();
20560  }else{
20561  /* only 1 core, use our own zone to contention over global locks,
20562  ** e.g. we have our own dedicated locks */
20563  bool success;
20564  malloc_zone_t* newzone = malloc_create_zone(4096, 0);
20565  malloc_set_zone_name(newzone, "Sqlite_Heap");
20566  do{
20567  success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
20568  (void * volatile *)&_sqliteZone_);
20569  }while(!_sqliteZone_);
20570  if( !success ){
20571  /* somebody registered a zone first */
20572  malloc_destroy_zone(newzone);
20573  }
20574  }
20575 #endif
20576  UNUSED_PARAMETER(NotUsed);
20577  return SQLITE_OK;
20578 }
20579 
20580 /*
20581 ** Deinitialize this module.
20582 */
20583 static void sqlite3MemShutdown(void *NotUsed){
20584  UNUSED_PARAMETER(NotUsed);
20585  return;
20586 }
20587 
20588 /*
20589 ** This routine is the only routine in this file with external linkage.
20590 **
20591 ** Populate the low-level memory allocation function pointers in
20592 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20593 */
20595  static const sqlite3_mem_methods defaultMethods = {
20603  0
20604  };
20605  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20606 }
20607 
20608 #endif /* SQLITE_SYSTEM_MALLOC */
20609 
20610 /************** End of mem1.c ************************************************/
20611 /************** Begin file mem2.c ********************************************/
20612 /*
20613 ** 2007 August 15
20614 **
20615 ** The author disclaims copyright to this source code. In place of
20616 ** a legal notice, here is a blessing:
20617 **
20618 ** May you do good and not evil.
20619 ** May you find forgiveness for yourself and forgive others.
20620 ** May you share freely, never taking more than you give.
20621 **
20622 *************************************************************************
20623 **
20624 ** This file contains low-level memory allocation drivers for when
20625 ** SQLite will use the standard C-library malloc/realloc/free interface
20626 ** to obtain the memory it needs while adding lots of additional debugging
20627 ** information to each allocation in order to help detect and fix memory
20628 ** leaks and memory usage errors.
20629 **
20630 ** This file contains implementations of the low-level memory allocation
20631 ** routines specified in the sqlite3_mem_methods object.
20632 */
20633 /* #include "sqliteInt.h" */
20634 
20635 /*
20636 ** This version of the memory allocator is used only if the
20637 ** SQLITE_MEMDEBUG macro is defined
20638 */
20639 #ifdef SQLITE_MEMDEBUG
20640 
20641 /*
20642 ** The backtrace functionality is only available with GLIBC
20643 */
20644 #ifdef __GLIBC__
20645  extern int backtrace(void**,int);
20646  extern void backtrace_symbols_fd(void*const*,int,int);
20647 #else
20648 # define backtrace(A,B) 1
20649 # define backtrace_symbols_fd(A,B,C)
20650 #endif
20651 /* #include <stdio.h> */
20652 
20653 /*
20654 ** Each memory allocation looks like this:
20655 **
20656 ** ------------------------------------------------------------------------
20657 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
20658 ** ------------------------------------------------------------------------
20659 **
20660 ** The application code sees only a pointer to the allocation. We have
20661 ** to back up from the allocation pointer to find the MemBlockHdr. The
20662 ** MemBlockHdr tells us the size of the allocation and the number of
20663 ** backtrace pointers. There is also a guard word at the end of the
20664 ** MemBlockHdr.
20665 */
20666 struct MemBlockHdr {
20667  i64 iSize; /* Size of this allocation */
20668  struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
20669  char nBacktrace; /* Number of backtraces on this alloc */
20670  char nBacktraceSlots; /* Available backtrace slots */
20671  u8 nTitle; /* Bytes of title; includes '\0' */
20672  u8 eType; /* Allocation type code */
20673  int iForeGuard; /* Guard word for sanity */
20674 };
20675 
20676 /*
20677 ** Guard words
20678 */
20679 #define FOREGUARD 0x80F5E153
20680 #define REARGUARD 0xE4676B53
20681 
20682 /*
20683 ** Number of malloc size increments to track.
20684 */
20685 #define NCSIZE 1000
20686 
20687 /*
20688 ** All of the static variables used by this module are collected
20689 ** into a single structure named "mem". This is to keep the
20690 ** static variables organized and to reduce namespace pollution
20691 ** when this module is combined with other in the amalgamation.
20692 */
20693 static struct {
20694 
20695  /*
20696  ** Mutex to control access to the memory allocation subsystem.
20697  */
20698  sqlite3_mutex *mutex;
20699 
20700  /*
20701  ** Head and tail of a linked list of all outstanding allocations
20702  */
20703  struct MemBlockHdr *pFirst;
20704  struct MemBlockHdr *pLast;
20705 
20706  /*
20707  ** The number of levels of backtrace to save in new allocations.
20708  */
20709  int nBacktrace;
20710  void (*xBacktrace)(int, int, void **);
20711 
20712  /*
20713  ** Title text to insert in front of each block
20714  */
20715  int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
20716  char zTitle[100]; /* The title text */
20717 
20718  /*
20719  ** sqlite3MallocDisallow() increments the following counter.
20720  ** sqlite3MallocAllow() decrements it.
20721  */
20722  int disallow; /* Do not allow memory allocation */
20723 
20724  /*
20725  ** Gather statistics on the sizes of memory allocations.
20726  ** nAlloc[i] is the number of allocation attempts of i*8
20727  ** bytes. i==NCSIZE is the number of allocation attempts for
20728  ** sizes more than NCSIZE*8 bytes.
20729  */
20730  int nAlloc[NCSIZE]; /* Total number of allocations */
20731  int nCurrent[NCSIZE]; /* Current number of allocations */
20732  int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
20733 
20734 } mem;
20735 
20736 
20737 /*
20738 ** Adjust memory usage statistics
20739 */
20740 static void adjustStats(int iSize, int increment){
20741  int i = ROUND8(iSize)/8;
20742  if( i>NCSIZE-1 ){
20743  i = NCSIZE - 1;
20744  }
20745  if( increment>0 ){
20746  mem.nAlloc[i]++;
20747  mem.nCurrent[i]++;
20748  if( mem.nCurrent[i]>mem.mxCurrent[i] ){
20749  mem.mxCurrent[i] = mem.nCurrent[i];
20750  }
20751  }else{
20752  mem.nCurrent[i]--;
20753  assert( mem.nCurrent[i]>=0 );
20754  }
20755 }
20756 
20757 /*
20758 ** Given an allocation, find the MemBlockHdr for that allocation.
20759 **
20760 ** This routine checks the guards at either end of the allocation and
20761 ** if they are incorrect it asserts.
20762 */
20763 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
20764  struct MemBlockHdr *p;
20765  int *pInt;
20766  u8 *pU8;
20767  int nReserve;
20768 
20769  p = (struct MemBlockHdr*)pAllocation;
20770  p--;
20771  assert( p->iForeGuard==(int)FOREGUARD );
20772  nReserve = ROUND8(p->iSize);
20773  pInt = (int*)pAllocation;
20774  pU8 = (u8*)pAllocation;
20775  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
20776  /* This checks any of the "extra" bytes allocated due
20777  ** to rounding up to an 8 byte boundary to ensure
20778  ** they haven't been overwritten.
20779  */
20780  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
20781  return p;
20782 }
20783 
20784 /*
20785 ** Return the number of bytes currently allocated at address p.
20786 */
20787 static int sqlite3MemSize(void *p){
20788  struct MemBlockHdr *pHdr;
20789  if( !p ){
20790  return 0;
20791  }
20792  pHdr = sqlite3MemsysGetHeader(p);
20793  return (int)pHdr->iSize;
20794 }
20795 
20796 /*
20797 ** Initialize the memory allocation subsystem.
20798 */
20799 static int sqlite3MemInit(void *NotUsed){
20800  UNUSED_PARAMETER(NotUsed);
20801  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
20802  if( !sqlite3GlobalConfig.bMemstat ){
20803  /* If memory status is enabled, then the malloc.c wrapper will already
20804  ** hold the STATIC_MEM mutex when the routines here are invoked. */
20806  }
20807  return SQLITE_OK;
20808 }
20809 
20810 /*
20811 ** Deinitialize the memory allocation subsystem.
20812 */
20813 static void sqlite3MemShutdown(void *NotUsed){
20814  UNUSED_PARAMETER(NotUsed);
20815  mem.mutex = 0;
20816 }
20817 
20818 /*
20819 ** Round up a request size to the next valid allocation size.
20820 */
20821 static int sqlite3MemRoundup(int n){
20822  return ROUND8(n);
20823 }
20824 
20825 /*
20826 ** Fill a buffer with pseudo-random bytes. This is used to preset
20827 ** the content of a new memory allocation to unpredictable values and
20828 ** to clear the content of a freed allocation to unpredictable values.
20829 */
20830 static void randomFill(char *pBuf, int nByte){
20831  unsigned int x, y, r;
20832  x = SQLITE_PTR_TO_INT(pBuf);
20833  y = nByte | 1;
20834  while( nByte >= 4 ){
20835  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20836  y = y*1103515245 + 12345;
20837  r = x ^ y;
20838  *(int*)pBuf = r;
20839  pBuf += 4;
20840  nByte -= 4;
20841  }
20842  while( nByte-- > 0 ){
20843  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20844  y = y*1103515245 + 12345;
20845  r = x ^ y;
20846  *(pBuf++) = r & 0xff;
20847  }
20848 }
20849 
20850 /*
20851 ** Allocate nByte bytes of memory.
20852 */
20853 static void *sqlite3MemMalloc(int nByte){
20854  struct MemBlockHdr *pHdr;
20855  void **pBt;
20856  char *z;
20857  int *pInt;
20858  void *p = 0;
20859  int totalSize;
20860  int nReserve;
20861  sqlite3_mutex_enter(mem.mutex);
20862  assert( mem.disallow==0 );
20863  nReserve = ROUND8(nByte);
20864  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
20865  mem.nBacktrace*sizeof(void*) + mem.nTitle;
20866  p = malloc(totalSize);
20867  if( p ){
20868  z = p;
20869  pBt = (void**)&z[mem.nTitle];
20870  pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
20871  pHdr->pNext = 0;
20872  pHdr->pPrev = mem.pLast;
20873  if( mem.pLast ){
20874  mem.pLast->pNext = pHdr;
20875  }else{
20876  mem.pFirst = pHdr;
20877  }
20878  mem.pLast = pHdr;
20879  pHdr->iForeGuard = FOREGUARD;
20880  pHdr->eType = MEMTYPE_HEAP;
20881  pHdr->nBacktraceSlots = mem.nBacktrace;
20882  pHdr->nTitle = mem.nTitle;
20883  if( mem.nBacktrace ){
20884  void *aAddr[40];
20885  pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
20886  memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
20887  assert(pBt[0]);
20888  if( mem.xBacktrace ){
20889  mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
20890  }
20891  }else{
20892  pHdr->nBacktrace = 0;
20893  }
20894  if( mem.nTitle ){
20895  memcpy(z, mem.zTitle, mem.nTitle);
20896  }
20897  pHdr->iSize = nByte;
20898  adjustStats(nByte, +1);
20899  pInt = (int*)&pHdr[1];
20900  pInt[nReserve/sizeof(int)] = REARGUARD;
20901  randomFill((char*)pInt, nByte);
20902  memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
20903  p = (void*)pInt;
20904  }
20905  sqlite3_mutex_leave(mem.mutex);
20906  return p;
20907 }
20908 
20909 /*
20910 ** Free memory.
20911 */
20912 static void sqlite3MemFree(void *pPrior){
20913  struct MemBlockHdr *pHdr;
20914  void **pBt;
20915  char *z;
20916  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
20917  || mem.mutex!=0 );
20918  pHdr = sqlite3MemsysGetHeader(pPrior);
20919  pBt = (void**)pHdr;
20920  pBt -= pHdr->nBacktraceSlots;
20921  sqlite3_mutex_enter(mem.mutex);
20922  if( pHdr->pPrev ){
20923  assert( pHdr->pPrev->pNext==pHdr );
20924  pHdr->pPrev->pNext = pHdr->pNext;
20925  }else{
20926  assert( mem.pFirst==pHdr );
20927  mem.pFirst = pHdr->pNext;
20928  }
20929  if( pHdr->pNext ){
20930  assert( pHdr->pNext->pPrev==pHdr );
20931  pHdr->pNext->pPrev = pHdr->pPrev;
20932  }else{
20933  assert( mem.pLast==pHdr );
20934  mem.pLast = pHdr->pPrev;
20935  }
20936  z = (char*)pBt;
20937  z -= pHdr->nTitle;
20938  adjustStats((int)pHdr->iSize, -1);
20939  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
20940  (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
20941  free(z);
20942  sqlite3_mutex_leave(mem.mutex);
20943 }
20944 
20945 /*
20946 ** Change the size of an existing memory allocation.
20947 **
20948 ** For this debugging implementation, we *always* make a copy of the
20949 ** allocation into a new place in memory. In this way, if the
20950 ** higher level code is using pointer to the old allocation, it is
20951 ** much more likely to break and we are much more liking to find
20952 ** the error.
20953 */
20954 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20955  struct MemBlockHdr *pOldHdr;
20956  void *pNew;
20957  assert( mem.disallow==0 );
20958  assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
20959  pOldHdr = sqlite3MemsysGetHeader(pPrior);
20960  pNew = sqlite3MemMalloc(nByte);
20961  if( pNew ){
20962  memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
20963  if( nByte>pOldHdr->iSize ){
20964  randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
20965  }
20966  sqlite3MemFree(pPrior);
20967  }
20968  return pNew;
20969 }
20970 
20971 /*
20972 ** Populate the low-level memory allocation function pointers in
20973 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20974 */
20976  static const sqlite3_mem_methods defaultMethods = {
20984  0
20985  };
20986  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20987 }
20988 
20989 /*
20990 ** Set the "type" of an allocation.
20991 */
20992 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
20993  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20994  struct MemBlockHdr *pHdr;
20995  pHdr = sqlite3MemsysGetHeader(p);
20996  assert( pHdr->iForeGuard==FOREGUARD );
20997  pHdr->eType = eType;
20998  }
20999 }
21000 
21001 /*
21002 ** Return TRUE if the mask of type in eType matches the type of the
21003 ** allocation p. Also return true if p==NULL.
21004 **
21005 ** This routine is designed for use within an assert() statement, to
21006 ** verify the type of an allocation. For example:
21007 **
21008 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21009 */
21010 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
21011  int rc = 1;
21012  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21013  struct MemBlockHdr *pHdr;
21014  pHdr = sqlite3MemsysGetHeader(p);
21015  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
21016  if( (pHdr->eType&eType)==0 ){
21017  rc = 0;
21018  }
21019  }
21020  return rc;
21021 }
21022 
21023 /*
21024 ** Return TRUE if the mask of type in eType matches no bits of the type of the
21025 ** allocation p. Also return true if p==NULL.
21026 **
21027 ** This routine is designed for use within an assert() statement, to
21028 ** verify the type of an allocation. For example:
21029 **
21030 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21031 */
21032 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
21033  int rc = 1;
21034  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
21035  struct MemBlockHdr *pHdr;
21036  pHdr = sqlite3MemsysGetHeader(p);
21037  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
21038  if( (pHdr->eType&eType)!=0 ){
21039  rc = 0;
21040  }
21041  }
21042  return rc;
21043 }
21044 
21045 /*
21046 ** Set the number of backtrace levels kept for each allocation.
21047 ** A value of zero turns off backtracing. The number is always rounded
21048 ** up to a multiple of 2.
21049 */
21050 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
21051  if( depth<0 ){ depth = 0; }
21052  if( depth>20 ){ depth = 20; }
21053  depth = (depth+1)&0xfe;
21054  mem.nBacktrace = depth;
21055 }
21056 
21057 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
21058  mem.xBacktrace = xBacktrace;
21059 }
21060 
21061 /*
21062 ** Set the title string for subsequent allocations.
21063 */
21064 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
21065  unsigned int n = sqlite3Strlen30(zTitle) + 1;
21066  sqlite3_mutex_enter(mem.mutex);
21067  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
21068  memcpy(mem.zTitle, zTitle, n);
21069  mem.zTitle[n] = 0;
21070  mem.nTitle = ROUND8(n);
21071  sqlite3_mutex_leave(mem.mutex);
21072 }
21073 
21074 SQLITE_PRIVATE void sqlite3MemdebugSync(){
21075  struct MemBlockHdr *pHdr;
21076  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21077  void **pBt = (void**)pHdr;
21078  pBt -= pHdr->nBacktraceSlots;
21079  mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
21080  }
21081 }
21082 
21083 /*
21084 ** Open the file indicated and write a log of all unfreed memory
21085 ** allocations into that log.
21086 */
21087 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
21088  FILE *out;
21089  struct MemBlockHdr *pHdr;
21090  void **pBt;
21091  int i;
21092  out = fopen(zFilename, "w");
21093  if( out==0 ){
21094  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21095  zFilename);
21096  return;
21097  }
21098  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21099  char *z = (char*)pHdr;
21100  z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
21101  fprintf(out, "**** %lld bytes at %p from %s ****\n",
21102  pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
21103  if( pHdr->nBacktrace ){
21104  fflush(out);
21105  pBt = (void**)pHdr;
21106  pBt -= pHdr->nBacktraceSlots;
21107  backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
21108  fprintf(out, "\n");
21109  }
21110  }
21111  fprintf(out, "COUNTS:\n");
21112  for(i=0; i<NCSIZE-1; i++){
21113  if( mem.nAlloc[i] ){
21114  fprintf(out, " %5d: %10d %10d %10d\n",
21115  i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
21116  }
21117  }
21118  if( mem.nAlloc[NCSIZE-1] ){
21119  fprintf(out, " %5d: %10d %10d %10d\n",
21120  NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
21121  mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
21122  }
21123  fclose(out);
21124 }
21125 
21126 /*
21127 ** Return the number of times sqlite3MemMalloc() has been called.
21128 */
21129 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
21130  int i;
21131  int nTotal = 0;
21132  for(i=0; i<NCSIZE; i++){
21133  nTotal += mem.nAlloc[i];
21134  }
21135  return nTotal;
21136 }
21137 
21138 
21139 #endif /* SQLITE_MEMDEBUG */
21140 
21141 /************** End of mem2.c ************************************************/
21142 /************** Begin file mem3.c ********************************************/
21143 /*
21144 ** 2007 October 14
21145 **
21146 ** The author disclaims copyright to this source code. In place of
21147 ** a legal notice, here is a blessing:
21148 **
21149 ** May you do good and not evil.
21150 ** May you find forgiveness for yourself and forgive others.
21151 ** May you share freely, never taking more than you give.
21152 **
21153 *************************************************************************
21154 ** This file contains the C functions that implement a memory
21155 ** allocation subsystem for use by SQLite.
21156 **
21157 ** This version of the memory allocation subsystem omits all
21158 ** use of malloc(). The SQLite user supplies a block of memory
21159 ** before calling sqlite3_initialize() from which allocations
21160 ** are made and returned by the xMalloc() and xRealloc()
21161 ** implementations. Once sqlite3_initialize() has been called,
21162 ** the amount of memory available to SQLite is fixed and cannot
21163 ** be changed.
21164 **
21165 ** This version of the memory allocation subsystem is included
21166 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
21167 */
21168 /* #include "sqliteInt.h" */
21169 
21170 /*
21171 ** This version of the memory allocator is only built into the library
21172 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
21173 ** mean that the library will use a memory-pool by default, just that
21174 ** it is available. The mempool allocator is activated by calling
21175 ** sqlite3_config().
21176 */
21177 #ifdef SQLITE_ENABLE_MEMSYS3
21178 
21179 /*
21180 ** Maximum size (in Mem3Blocks) of a "small" chunk.
21181 */
21182 #define MX_SMALL 10
21183 
21184 
21185 /*
21186 ** Number of freelist hash slots
21187 */
21188 #define N_HASH 61
21189 
21190 /*
21191 ** A memory allocation (also called a "chunk") consists of two or
21192 ** more blocks where each block is 8 bytes. The first 8 bytes are
21193 ** a header that is not returned to the user.
21194 **
21195 ** A chunk is two or more blocks that is either checked out or
21196 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
21197 ** size of the allocation in blocks if the allocation is free.
21198 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
21199 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
21200 ** is true if the previous chunk is checked out and false if the
21201 ** previous chunk is free. The u.hdr.prevSize field is the size of
21202 ** the previous chunk in blocks if the previous chunk is on the
21203 ** freelist. If the previous chunk is checked out, then
21204 ** u.hdr.prevSize can be part of the data for that chunk and should
21205 ** not be read or written.
21206 **
21207 ** We often identify a chunk by its index in mem3.aPool[]. When
21208 ** this is done, the chunk index refers to the second block of
21209 ** the chunk. In this way, the first chunk has an index of 1.
21210 ** A chunk index of 0 means "no such chunk" and is the equivalent
21211 ** of a NULL pointer.
21212 **
21213 ** The second block of free chunks is of the form u.list. The
21214 ** two fields form a double-linked list of chunks of related sizes.
21215 ** Pointers to the head of the list are stored in mem3.aiSmall[]
21216 ** for smaller chunks and mem3.aiHash[] for larger chunks.
21217 **
21218 ** The second block of a chunk is user data if the chunk is checked
21219 ** out. If a chunk is checked out, the user data may extend into
21220 ** the u.hdr.prevSize value of the following chunk.
21221 */
21222 typedef struct Mem3Block Mem3Block;
21223 struct Mem3Block {
21224  union {
21225  struct {
21226  u32 prevSize; /* Size of previous chunk in Mem3Block elements */
21227  u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
21228  } hdr;
21229  struct {
21230  u32 next; /* Index in mem3.aPool[] of next free chunk */
21231  u32 prev; /* Index in mem3.aPool[] of previous free chunk */
21232  } list;
21233  } u;
21234 };
21235 
21236 /*
21237 ** All of the static variables used by this module are collected
21238 ** into a single structure named "mem3". This is to keep the
21239 ** static variables organized and to reduce namespace pollution
21240 ** when this module is combined with other in the amalgamation.
21241 */
21242 static SQLITE_WSD struct Mem3Global {
21243  /*
21244  ** Memory available for allocation. nPool is the size of the array
21245  ** (in Mem3Blocks) pointed to by aPool less 2.
21246  */
21247  u32 nPool;
21248  Mem3Block *aPool;
21249 
21250  /*
21251  ** True if we are evaluating an out-of-memory callback.
21252  */
21253  int alarmBusy;
21254 
21255  /*
21256  ** Mutex to control access to the memory allocation subsystem.
21257  */
21258  sqlite3_mutex *mutex;
21259 
21260  /*
21261  ** The minimum amount of free space that we have seen.
21262  */
21263  u32 mnMaster;
21264 
21265  /*
21266  ** iMaster is the index of the master chunk. Most new allocations
21267  ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
21268  ** of the current master. iMaster is 0 if there is not master chunk.
21269  ** The master chunk is not in either the aiHash[] or aiSmall[].
21270  */
21271  u32 iMaster;
21272  u32 szMaster;
21273 
21274  /*
21275  ** Array of lists of free blocks according to the block size
21276  ** for smaller chunks, or a hash on the block size for larger
21277  ** chunks.
21278  */
21279  u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
21280  u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
21281 } mem3 = { 97535575 };
21282 
21283 #define mem3 GLOBAL(struct Mem3Global, mem3)
21284 
21285 /*
21286 ** Unlink the chunk at mem3.aPool[i] from list it is currently
21287 ** on. *pRoot is the list that i is a member of.
21288 */
21289 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
21290  u32 next = mem3.aPool[i].u.list.next;
21291  u32 prev = mem3.aPool[i].u.list.prev;
21292  assert( sqlite3_mutex_held(mem3.mutex) );
21293  if( prev==0 ){
21294  *pRoot = next;
21295  }else{
21296  mem3.aPool[prev].u.list.next = next;
21297  }
21298  if( next ){
21299  mem3.aPool[next].u.list.prev = prev;
21300  }
21301  mem3.aPool[i].u.list.next = 0;
21302  mem3.aPool[i].u.list.prev = 0;
21303 }
21304 
21305 /*
21306 ** Unlink the chunk at index i from
21307 ** whatever list is currently a member of.
21308 */
21309 static void memsys3Unlink(u32 i){
21310  u32 size, hash;
21311  assert( sqlite3_mutex_held(mem3.mutex) );
21312  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21313  assert( i>=1 );
21314  size = mem3.aPool[i-1].u.hdr.size4x/4;
21315  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21316  assert( size>=2 );
21317  if( size <= MX_SMALL ){
21318  memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
21319  }else{
21320  hash = size % N_HASH;
21321  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21322  }
21323 }
21324 
21325 /*
21326 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
21327 ** at *pRoot.
21328 */
21329 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
21330  assert( sqlite3_mutex_held(mem3.mutex) );
21331  mem3.aPool[i].u.list.next = *pRoot;
21332  mem3.aPool[i].u.list.prev = 0;
21333  if( *pRoot ){
21334  mem3.aPool[*pRoot].u.list.prev = i;
21335  }
21336  *pRoot = i;
21337 }
21338 
21339 /*
21340 ** Link the chunk at index i into either the appropriate
21341 ** small chunk list, or into the large chunk hash table.
21342 */
21343 static void memsys3Link(u32 i){
21344  u32 size, hash;
21345  assert( sqlite3_mutex_held(mem3.mutex) );
21346  assert( i>=1 );
21347  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21348  size = mem3.aPool[i-1].u.hdr.size4x/4;
21349  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21350  assert( size>=2 );
21351  if( size <= MX_SMALL ){
21352  memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
21353  }else{
21354  hash = size % N_HASH;
21355  memsys3LinkIntoList(i, &mem3.aiHash[hash]);
21356  }
21357 }
21358 
21359 /*
21360 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
21361 ** will already be held (obtained by code in malloc.c) if
21362 ** sqlite3GlobalConfig.bMemStat is true.
21363 */
21364 static void memsys3Enter(void){
21365  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
21367  }
21368  sqlite3_mutex_enter(mem3.mutex);
21369 }
21370 static void memsys3Leave(void){
21371  sqlite3_mutex_leave(mem3.mutex);
21372 }
21373 
21374 /*
21375 ** Called when we are unable to satisfy an allocation of nBytes.
21376 */
21377 static void memsys3OutOfMemory(int nByte){
21378  if( !mem3.alarmBusy ){
21379  mem3.alarmBusy = 1;
21380  assert( sqlite3_mutex_held(mem3.mutex) );
21381  sqlite3_mutex_leave(mem3.mutex);
21382  sqlite3_release_memory(nByte);
21383  sqlite3_mutex_enter(mem3.mutex);
21384  mem3.alarmBusy = 0;
21385  }
21386 }
21387 
21388 
21389 /*
21390 ** Chunk i is a free chunk that has been unlinked. Adjust its
21391 ** size parameters for check-out and return a pointer to the
21392 ** user portion of the chunk.
21393 */
21394 static void *memsys3Checkout(u32 i, u32 nBlock){
21395  u32 x;
21396  assert( sqlite3_mutex_held(mem3.mutex) );
21397  assert( i>=1 );
21398  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
21399  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
21400  x = mem3.aPool[i-1].u.hdr.size4x;
21401  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
21402  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
21403  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
21404  return &mem3.aPool[i];
21405 }
21406 
21407 /*
21408 ** Carve a piece off of the end of the mem3.iMaster free chunk.
21409 ** Return a pointer to the new allocation. Or, if the master chunk
21410 ** is not large enough, return 0.
21411 */
21412 static void *memsys3FromMaster(u32 nBlock){
21413  assert( sqlite3_mutex_held(mem3.mutex) );
21414  assert( mem3.szMaster>=nBlock );
21415  if( nBlock>=mem3.szMaster-1 ){
21416  /* Use the entire master */
21417  void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
21418  mem3.iMaster = 0;
21419  mem3.szMaster = 0;
21420  mem3.mnMaster = 0;
21421  return p;
21422  }else{
21423  /* Split the master block. Return the tail. */
21424  u32 newi, x;
21425  newi = mem3.iMaster + mem3.szMaster - nBlock;
21426  assert( newi > mem3.iMaster+1 );
21427  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
21428  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
21429  mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
21430  mem3.szMaster -= nBlock;
21431  mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
21432  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21433  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21434  if( mem3.szMaster < mem3.mnMaster ){
21435  mem3.mnMaster = mem3.szMaster;
21436  }
21437  return (void*)&mem3.aPool[newi];
21438  }
21439 }
21440 
21441 /*
21442 ** *pRoot is the head of a list of free chunks of the same size
21443 ** or same size hash. In other words, *pRoot is an entry in either
21444 ** mem3.aiSmall[] or mem3.aiHash[].
21445 **
21446 ** This routine examines all entries on the given list and tries
21447 ** to coalesce each entries with adjacent free chunks.
21448 **
21449 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
21450 ** the current mem3.iMaster with the new larger chunk. In order for
21451 ** this mem3.iMaster replacement to work, the master chunk must be
21452 ** linked into the hash tables. That is not the normal state of
21453 ** affairs, of course. The calling routine must link the master
21454 ** chunk before invoking this routine, then must unlink the (possibly
21455 ** changed) master chunk once this routine has finished.
21456 */
21457 static void memsys3Merge(u32 *pRoot){
21458  u32 iNext, prev, size, i, x;
21459 
21460  assert( sqlite3_mutex_held(mem3.mutex) );
21461  for(i=*pRoot; i>0; i=iNext){
21462  iNext = mem3.aPool[i].u.list.next;
21463  size = mem3.aPool[i-1].u.hdr.size4x;
21464  assert( (size&1)==0 );
21465  if( (size&2)==0 ){
21466  memsys3UnlinkFromList(i, pRoot);
21467  assert( i > mem3.aPool[i-1].u.hdr.prevSize );
21468  prev = i - mem3.aPool[i-1].u.hdr.prevSize;
21469  if( prev==iNext ){
21470  iNext = mem3.aPool[prev].u.list.next;
21471  }
21472  memsys3Unlink(prev);
21473  size = i + size/4 - prev;
21474  x = mem3.aPool[prev-1].u.hdr.size4x & 2;
21475  mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
21476  mem3.aPool[prev+size-1].u.hdr.prevSize = size;
21477  memsys3Link(prev);
21478  i = prev;
21479  }else{
21480  size /= 4;
21481  }
21482  if( size>mem3.szMaster ){
21483  mem3.iMaster = i;
21484  mem3.szMaster = size;
21485  }
21486  }
21487 }
21488 
21489 /*
21490 ** Return a block of memory of at least nBytes in size.
21491 ** Return NULL if unable.
21492 **
21493 ** This function assumes that the necessary mutexes, if any, are
21494 ** already held by the caller. Hence "Unsafe".
21495 */
21496 static void *memsys3MallocUnsafe(int nByte){
21497  u32 i;
21498  u32 nBlock;
21499  u32 toFree;
21500 
21501  assert( sqlite3_mutex_held(mem3.mutex) );
21502  assert( sizeof(Mem3Block)==8 );
21503  if( nByte<=12 ){
21504  nBlock = 2;
21505  }else{
21506  nBlock = (nByte + 11)/8;
21507  }
21508  assert( nBlock>=2 );
21509 
21510  /* STEP 1:
21511  ** Look for an entry of the correct size in either the small
21512  ** chunk table or in the large chunk hash table. This is
21513  ** successful most of the time (about 9 times out of 10).
21514  */
21515  if( nBlock <= MX_SMALL ){
21516  i = mem3.aiSmall[nBlock-2];
21517  if( i>0 ){
21518  memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
21519  return memsys3Checkout(i, nBlock);
21520  }
21521  }else{
21522  int hash = nBlock % N_HASH;
21523  for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
21524  if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
21525  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21526  return memsys3Checkout(i, nBlock);
21527  }
21528  }
21529  }
21530 
21531  /* STEP 2:
21532  ** Try to satisfy the allocation by carving a piece off of the end
21533  ** of the master chunk. This step usually works if step 1 fails.
21534  */
21535  if( mem3.szMaster>=nBlock ){
21536  return memsys3FromMaster(nBlock);
21537  }
21538 
21539 
21540  /* STEP 3:
21541  ** Loop through the entire memory pool. Coalesce adjacent free
21542  ** chunks. Recompute the master chunk as the largest free chunk.
21543  ** Then try again to satisfy the allocation by carving a piece off
21544  ** of the end of the master chunk. This step happens very
21545  ** rarely (we hope!)
21546  */
21547  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
21548  memsys3OutOfMemory(toFree);
21549  if( mem3.iMaster ){
21550  memsys3Link(mem3.iMaster);
21551  mem3.iMaster = 0;
21552  mem3.szMaster = 0;
21553  }
21554  for(i=0; i<N_HASH; i++){
21555  memsys3Merge(&mem3.aiHash[i]);
21556  }
21557  for(i=0; i<MX_SMALL-1; i++){
21558  memsys3Merge(&mem3.aiSmall[i]);
21559  }
21560  if( mem3.szMaster ){
21561  memsys3Unlink(mem3.iMaster);
21562  if( mem3.szMaster>=nBlock ){
21563  return memsys3FromMaster(nBlock);
21564  }
21565  }
21566  }
21567 
21568  /* If none of the above worked, then we fail. */
21569  return 0;
21570 }
21571 
21572 /*
21573 ** Free an outstanding memory allocation.
21574 **
21575 ** This function assumes that the necessary mutexes, if any, are
21576 ** already held by the caller. Hence "Unsafe".
21577 */
21578 static void memsys3FreeUnsafe(void *pOld){
21579  Mem3Block *p = (Mem3Block*)pOld;
21580  int i;
21581  u32 size, x;
21582  assert( sqlite3_mutex_held(mem3.mutex) );
21583  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
21584  i = p - mem3.aPool;
21585  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
21586  size = mem3.aPool[i-1].u.hdr.size4x/4;
21587  assert( i+size<=mem3.nPool+1 );
21588  mem3.aPool[i-1].u.hdr.size4x &= ~1;
21589  mem3.aPool[i+size-1].u.hdr.prevSize = size;
21590  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
21591  memsys3Link(i);
21592 
21593  /* Try to expand the master using the newly freed chunk */
21594  if( mem3.iMaster ){
21595  while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
21596  size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
21597  mem3.iMaster -= size;
21598  mem3.szMaster += size;
21599  memsys3Unlink(mem3.iMaster);
21600  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21601  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21602  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21603  }
21604  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21605  while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
21606  memsys3Unlink(mem3.iMaster+mem3.szMaster);
21607  mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
21608  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21609  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21610  }
21611  }
21612 }
21613 
21614 /*
21615 ** Return the size of an outstanding allocation, in bytes. The
21616 ** size returned omits the 8-byte header overhead. This only
21617 ** works for chunks that are currently checked out.
21618 */
21619 static int memsys3Size(void *p){
21620  Mem3Block *pBlock;
21621  assert( p!=0 );
21622  pBlock = (Mem3Block*)p;
21623  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
21624  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
21625 }
21626 
21627 /*
21628 ** Round up a request size to the next valid allocation size.
21629 */
21630 static int memsys3Roundup(int n){
21631  if( n<=12 ){
21632  return 12;
21633  }else{
21634  return ((n+11)&~7) - 4;
21635  }
21636 }
21637 
21638 /*
21639 ** Allocate nBytes of memory.
21640 */
21641 static void *memsys3Malloc(int nBytes){
21642  sqlite3_int64 *p;
21643  assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
21644  memsys3Enter();
21645  p = memsys3MallocUnsafe(nBytes);
21646  memsys3Leave();
21647  return (void*)p;
21648 }
21649 
21650 /*
21651 ** Free memory.
21652 */
21653 static void memsys3Free(void *pPrior){
21654  assert( pPrior );
21655  memsys3Enter();
21656  memsys3FreeUnsafe(pPrior);
21657  memsys3Leave();
21658 }
21659 
21660 /*
21661 ** Change the size of an existing memory allocation
21662 */
21663 static void *memsys3Realloc(void *pPrior, int nBytes){
21664  int nOld;
21665  void *p;
21666  if( pPrior==0 ){
21667  return sqlite3_malloc(nBytes);
21668  }
21669  if( nBytes<=0 ){
21670  sqlite3_free(pPrior);
21671  return 0;
21672  }
21673  nOld = memsys3Size(pPrior);
21674  if( nBytes<=nOld && nBytes>=nOld-128 ){
21675  return pPrior;
21676  }
21677  memsys3Enter();
21678  p = memsys3MallocUnsafe(nBytes);
21679  if( p ){
21680  if( nOld<nBytes ){
21681  memcpy(p, pPrior, nOld);
21682  }else{
21683  memcpy(p, pPrior, nBytes);
21684  }
21685  memsys3FreeUnsafe(pPrior);
21686  }
21687  memsys3Leave();
21688  return p;
21689 }
21690 
21691 /*
21692 ** Initialize this module.
21693 */
21694 static int memsys3Init(void *NotUsed){
21695  UNUSED_PARAMETER(NotUsed);
21696  if( !sqlite3GlobalConfig.pHeap ){
21697  return SQLITE_ERROR;
21698  }
21699 
21700  /* Store a pointer to the memory block in global structure mem3. */
21701  assert( sizeof(Mem3Block)==8 );
21702  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
21703  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
21704 
21705  /* Initialize the master block. */
21706  mem3.szMaster = mem3.nPool;
21707  mem3.mnMaster = mem3.szMaster;
21708  mem3.iMaster = 1;
21709  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
21710  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
21711  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
21712 
21713  return SQLITE_OK;
21714 }
21715 
21716 /*
21717 ** Deinitialize this module.
21718 */
21719 static void memsys3Shutdown(void *NotUsed){
21720  UNUSED_PARAMETER(NotUsed);
21721  mem3.mutex = 0;
21722  return;
21723 }
21724 
21725 
21726 
21727 /*
21728 ** Open the file indicated and write a log of all unfreed memory
21729 ** allocations into that log.
21730 */
21731 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
21732 #ifdef SQLITE_DEBUG
21733  FILE *out;
21734  u32 i, j;
21735  u32 size;
21736  if( zFilename==0 || zFilename[0]==0 ){
21737  out = stdout;
21738  }else{
21739  out = fopen(zFilename, "w");
21740  if( out==0 ){
21741  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21742  zFilename);
21743  return;
21744  }
21745  }
21746  memsys3Enter();
21747  fprintf(out, "CHUNKS:\n");
21748  for(i=1; i<=mem3.nPool; i+=size/4){
21749  size = mem3.aPool[i-1].u.hdr.size4x;
21750  if( size/4<=1 ){
21751  fprintf(out, "%p size error\n", &mem3.aPool[i]);
21752  assert( 0 );
21753  break;
21754  }
21755  if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
21756  fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
21757  assert( 0 );
21758  break;
21759  }
21760  if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
21761  fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
21762  assert( 0 );
21763  break;
21764  }
21765  if( size&1 ){
21766  fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
21767  }else{
21768  fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
21769  i==mem3.iMaster ? " **master**" : "");
21770  }
21771  }
21772  for(i=0; i<MX_SMALL-1; i++){
21773  if( mem3.aiSmall[i]==0 ) continue;
21774  fprintf(out, "small(%2d):", i);
21775  for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
21776  fprintf(out, " %p(%d)", &mem3.aPool[j],
21777  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21778  }
21779  fprintf(out, "\n");
21780  }
21781  for(i=0; i<N_HASH; i++){
21782  if( mem3.aiHash[i]==0 ) continue;
21783  fprintf(out, "hash(%2d):", i);
21784  for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
21785  fprintf(out, " %p(%d)", &mem3.aPool[j],
21786  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21787  }
21788  fprintf(out, "\n");
21789  }
21790  fprintf(out, "master=%d\n", mem3.iMaster);
21791  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
21792  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
21793  sqlite3_mutex_leave(mem3.mutex);
21794  if( out==stdout ){
21795  fflush(stdout);
21796  }else{
21797  fclose(out);
21798  }
21799 #else
21800  UNUSED_PARAMETER(zFilename);
21801 #endif
21802 }
21803 
21804 /*
21805 ** This routine is the only routine in this file with external
21806 ** linkage.
21807 **
21808 ** Populate the low-level memory allocation function pointers in
21809 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
21810 ** arguments specify the block of memory to manage.
21811 **
21812 ** This routine is only called by sqlite3_config(), and therefore
21813 ** is not required to be threadsafe (it is not).
21814 */
21815 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
21816  static const sqlite3_mem_methods mempoolMethods = {
21817  memsys3Malloc,
21818  memsys3Free,
21819  memsys3Realloc,
21820  memsys3Size,
21821  memsys3Roundup,
21822  memsys3Init,
21823  memsys3Shutdown,
21824  0
21825  };
21826  return &mempoolMethods;
21827 }
21828 
21829 #endif /* SQLITE_ENABLE_MEMSYS3 */
21830 
21831 /************** End of mem3.c ************************************************/
21832 /************** Begin file mem5.c ********************************************/
21833 /*
21834 ** 2007 October 14
21835 **
21836 ** The author disclaims copyright to this source code. In place of
21837 ** a legal notice, here is a blessing:
21838 **
21839 ** May you do good and not evil.
21840 ** May you find forgiveness for yourself and forgive others.
21841 ** May you share freely, never taking more than you give.
21842 **
21843 *************************************************************************
21844 ** This file contains the C functions that implement a memory
21845 ** allocation subsystem for use by SQLite.
21846 **
21847 ** This version of the memory allocation subsystem omits all
21848 ** use of malloc(). The application gives SQLite a block of memory
21849 ** before calling sqlite3_initialize() from which allocations
21850 ** are made and returned by the xMalloc() and xRealloc()
21851 ** implementations. Once sqlite3_initialize() has been called,
21852 ** the amount of memory available to SQLite is fixed and cannot
21853 ** be changed.
21854 **
21855 ** This version of the memory allocation subsystem is included
21856 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
21857 **
21858 ** This memory allocator uses the following algorithm:
21859 **
21860 ** 1. All memory allocation sizes are rounded up to a power of 2.
21861 **
21862 ** 2. If two adjacent free blocks are the halves of a larger block,
21863 ** then the two blocks are coalesced into the single larger block.
21864 **
21865 ** 3. New memory is allocated from the first available free block.
21866 **
21867 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
21868 ** Concerning Dynamic Storage Allocation". Journal of the Association for
21869 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
21870 **
21871 ** Let n be the size of the largest allocation divided by the minimum
21872 ** allocation size (after rounding all sizes up to a power of 2.) Let M
21873 ** be the maximum amount of memory ever outstanding at one time. Let
21874 ** N be the total amount of memory available for allocation. Robson
21875 ** proved that this memory allocator will never breakdown due to
21876 ** fragmentation as long as the following constraint holds:
21877 **
21878 ** N >= M*(1 + log2(n)/2) - n + 1
21879 **
21880 ** The sqlite3_status() logic tracks the maximum values of n and M so
21881 ** that an application can, at any time, verify this constraint.
21882 */
21883 /* #include "sqliteInt.h" */
21884 
21885 /*
21886 ** This version of the memory allocator is used only when
21887 ** SQLITE_ENABLE_MEMSYS5 is defined.
21888 */
21889 #ifdef SQLITE_ENABLE_MEMSYS5
21890 
21891 /*
21892 ** A minimum allocation is an instance of the following structure.
21893 ** Larger allocations are an array of these structures where the
21894 ** size of the array is a power of 2.
21895 **
21896 ** The size of this object must be a power of two. That fact is
21897 ** verified in memsys5Init().
21898 */
21899 typedef struct Mem5Link Mem5Link;
21900 struct Mem5Link {
21901  int next; /* Index of next free chunk */
21902  int prev; /* Index of previous free chunk */
21903 };
21904 
21905 /*
21906 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
21907 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
21908 ** it is not actually possible to reach this limit.
21909 */
21910 #define LOGMAX 30
21911 
21912 /*
21913 ** Masks used for mem5.aCtrl[] elements.
21914 */
21915 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
21916 #define CTRL_FREE 0x20 /* True if not checked out */
21917 
21918 /*
21919 ** All of the static variables used by this module are collected
21920 ** into a single structure named "mem5". This is to keep the
21921 ** static variables organized and to reduce namespace pollution
21922 ** when this module is combined with other in the amalgamation.
21923 */
21924 static SQLITE_WSD struct Mem5Global {
21925  /*
21926  ** Memory available for allocation
21927  */
21928  int szAtom; /* Smallest possible allocation in bytes */
21929  int nBlock; /* Number of szAtom sized blocks in zPool */
21930  u8 *zPool; /* Memory available to be allocated */
21931 
21932  /*
21933  ** Mutex to control access to the memory allocation subsystem.
21934  */
21935  sqlite3_mutex *mutex;
21936 
21937 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21938  /*
21939  ** Performance statistics
21940  */
21941  u64 nAlloc; /* Total number of calls to malloc */
21942  u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
21943  u64 totalExcess; /* Total internal fragmentation */
21944  u32 currentOut; /* Current checkout, including internal fragmentation */
21945  u32 currentCount; /* Current number of distinct checkouts */
21946  u32 maxOut; /* Maximum instantaneous currentOut */
21947  u32 maxCount; /* Maximum instantaneous currentCount */
21948  u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
21949 #endif
21950 
21951  /*
21952  ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
21953  ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
21954  ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
21955  */
21956  int aiFreelist[LOGMAX+1];
21957 
21958  /*
21959  ** Space for tracking which blocks are checked out and the size
21960  ** of each block. One byte per block.
21961  */
21962  u8 *aCtrl;
21963 
21964 } mem5;
21965 
21966 /*
21967 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
21968 */
21969 #define mem5 GLOBAL(struct Mem5Global, mem5)
21970 
21971 /*
21972 ** Assuming mem5.zPool is divided up into an array of Mem5Link
21973 ** structures, return a pointer to the idx-th such link.
21974 */
21975 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
21976 
21977 /*
21978 ** Unlink the chunk at mem5.aPool[i] from list it is currently
21979 ** on. It should be found on mem5.aiFreelist[iLogsize].
21980 */
21981 static void memsys5Unlink(int i, int iLogsize){
21982  int next, prev;
21983  assert( i>=0 && i<mem5.nBlock );
21984  assert( iLogsize>=0 && iLogsize<=LOGMAX );
21985  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21986 
21987  next = MEM5LINK(i)->next;
21988  prev = MEM5LINK(i)->prev;
21989  if( prev<0 ){
21990  mem5.aiFreelist[iLogsize] = next;
21991  }else{
21992  MEM5LINK(prev)->next = next;
21993  }
21994  if( next>=0 ){
21995  MEM5LINK(next)->prev = prev;
21996  }
21997 }
21998 
21999 /*
22000 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
22001 ** free list.
22002 */
22003 static void memsys5Link(int i, int iLogsize){
22004  int x;
22005  assert( sqlite3_mutex_held(mem5.mutex) );
22006  assert( i>=0 && i<mem5.nBlock );
22007  assert( iLogsize>=0 && iLogsize<=LOGMAX );
22008  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
22009 
22010  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
22011  MEM5LINK(i)->prev = -1;
22012  if( x>=0 ){
22013  assert( x<mem5.nBlock );
22014  MEM5LINK(x)->prev = i;
22015  }
22016  mem5.aiFreelist[iLogsize] = i;
22017 }
22018 
22019 /*
22020 ** Obtain or release the mutex needed to access global data structures.
22021 */
22022 static void memsys5Enter(void){
22023  sqlite3_mutex_enter(mem5.mutex);
22024 }
22025 static void memsys5Leave(void){
22026  sqlite3_mutex_leave(mem5.mutex);
22027 }
22028 
22029 /*
22030 ** Return the size of an outstanding allocation, in bytes.
22031 ** This only works for chunks that are currently checked out.
22032 */
22033 static int memsys5Size(void *p){
22034  int iSize, i;
22035  assert( p!=0 );
22036  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
22037  assert( i>=0 && i<mem5.nBlock );
22038  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
22039  return iSize;
22040 }
22041 
22042 /*
22043 ** Return a block of memory of at least nBytes in size.
22044 ** Return NULL if unable. Return NULL if nBytes==0.
22045 **
22046 ** The caller guarantees that nByte is positive.
22047 **
22048 ** The caller has obtained a mutex prior to invoking this
22049 ** routine so there is never any chance that two or more
22050 ** threads can be in this routine at the same time.
22051 */
22052 static void *memsys5MallocUnsafe(int nByte){
22053  int i; /* Index of a mem5.aPool[] slot */
22054  int iBin; /* Index into mem5.aiFreelist[] */
22055  int iFullSz; /* Size of allocation rounded up to power of 2 */
22056  int iLogsize; /* Log2 of iFullSz/POW2_MIN */
22057 
22058  /* nByte must be a positive */
22059  assert( nByte>0 );
22060 
22061  /* No more than 1GiB per allocation */
22062  if( nByte > 0x40000000 ) return 0;
22063 
22064 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22065  /* Keep track of the maximum allocation request. Even unfulfilled
22066  ** requests are counted */
22067  if( (u32)nByte>mem5.maxRequest ){
22068  mem5.maxRequest = nByte;
22069  }
22070 #endif
22071 
22072 
22073  /* Round nByte up to the next valid power of two */
22074  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
22075 
22076  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
22077  ** block. If not, then split a block of the next larger power of
22078  ** two in order to create a new free block of size iLogsize.
22079  */
22080  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
22081  if( iBin>LOGMAX ){
22082  testcase( sqlite3GlobalConfig.xLog!=0 );
22083  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
22084  return 0;
22085  }
22086  i = mem5.aiFreelist[iBin];
22087  memsys5Unlink(i, iBin);
22088  while( iBin>iLogsize ){
22089  int newSize;
22090 
22091  iBin--;
22092  newSize = 1 << iBin;
22093  mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
22094  memsys5Link(i+newSize, iBin);
22095  }
22096  mem5.aCtrl[i] = iLogsize;
22097 
22098 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22099  /* Update allocator performance statistics. */
22100  mem5.nAlloc++;
22101  mem5.totalAlloc += iFullSz;
22102  mem5.totalExcess += iFullSz - nByte;
22103  mem5.currentCount++;
22104  mem5.currentOut += iFullSz;
22105  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
22106  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
22107 #endif
22108 
22109 #ifdef SQLITE_DEBUG
22110  /* Make sure the allocated memory does not assume that it is set to zero
22111  ** or retains a value from a previous allocation */
22112  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
22113 #endif
22114 
22115  /* Return a pointer to the allocated memory. */
22116  return (void*)&mem5.zPool[i*mem5.szAtom];
22117 }
22118 
22119 /*
22120 ** Free an outstanding memory allocation.
22121 */
22122 static void memsys5FreeUnsafe(void *pOld){
22123  u32 size, iLogsize;
22124  int iBlock;
22125 
22126  /* Set iBlock to the index of the block pointed to by pOld in
22127  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
22128  */
22129  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
22130 
22131  /* Check that the pointer pOld points to a valid, non-free block. */
22132  assert( iBlock>=0 && iBlock<mem5.nBlock );
22133  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
22134  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
22135 
22136  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
22137  size = 1<<iLogsize;
22138  assert( iBlock+size-1<(u32)mem5.nBlock );
22139 
22140  mem5.aCtrl[iBlock] |= CTRL_FREE;
22141  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
22142 
22143 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22144  assert( mem5.currentCount>0 );
22145  assert( mem5.currentOut>=(size*mem5.szAtom) );
22146  mem5.currentCount--;
22147  mem5.currentOut -= size*mem5.szAtom;
22148  assert( mem5.currentOut>0 || mem5.currentCount==0 );
22149  assert( mem5.currentCount>0 || mem5.currentOut==0 );
22150 #endif
22151 
22152  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22153  while( ALWAYS(iLogsize<LOGMAX) ){
22154  int iBuddy;
22155  if( (iBlock>>iLogsize) & 1 ){
22156  iBuddy = iBlock - size;
22157  assert( iBuddy>=0 );
22158  }else{
22159  iBuddy = iBlock + size;
22160  if( iBuddy>=mem5.nBlock ) break;
22161  }
22162  if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
22163  memsys5Unlink(iBuddy, iLogsize);
22164  iLogsize++;
22165  if( iBuddy<iBlock ){
22166  mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
22167  mem5.aCtrl[iBlock] = 0;
22168  iBlock = iBuddy;
22169  }else{
22170  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22171  mem5.aCtrl[iBuddy] = 0;
22172  }
22173  size *= 2;
22174  }
22175 
22176 #ifdef SQLITE_DEBUG
22177  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
22178  ** not used after being freed */
22179  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
22180 #endif
22181 
22182  memsys5Link(iBlock, iLogsize);
22183 }
22184 
22185 /*
22186 ** Allocate nBytes of memory.
22187 */
22188 static void *memsys5Malloc(int nBytes){
22189  sqlite3_int64 *p = 0;
22190  if( nBytes>0 ){
22191  memsys5Enter();
22192  p = memsys5MallocUnsafe(nBytes);
22193  memsys5Leave();
22194  }
22195  return (void*)p;
22196 }
22197 
22198 /*
22199 ** Free memory.
22200 **
22201 ** The outer layer memory allocator prevents this routine from
22202 ** being called with pPrior==0.
22203 */
22204 static void memsys5Free(void *pPrior){
22205  assert( pPrior!=0 );
22206  memsys5Enter();
22207  memsys5FreeUnsafe(pPrior);
22208  memsys5Leave();
22209 }
22210 
22211 /*
22212 ** Change the size of an existing memory allocation.
22213 **
22214 ** The outer layer memory allocator prevents this routine from
22215 ** being called with pPrior==0.
22216 **
22217 ** nBytes is always a value obtained from a prior call to
22218 ** memsys5Round(). Hence nBytes is always a non-negative power
22219 ** of two. If nBytes==0 that means that an oversize allocation
22220 ** (an allocation larger than 0x40000000) was requested and this
22221 ** routine should return 0 without freeing pPrior.
22222 */
22223 static void *memsys5Realloc(void *pPrior, int nBytes){
22224  int nOld;
22225  void *p;
22226  assert( pPrior!=0 );
22227  assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
22228  assert( nBytes>=0 );
22229  if( nBytes==0 ){
22230  return 0;
22231  }
22232  nOld = memsys5Size(pPrior);
22233  if( nBytes<=nOld ){
22234  return pPrior;
22235  }
22236  p = memsys5Malloc(nBytes);
22237  if( p ){
22238  memcpy(p, pPrior, nOld);
22239  memsys5Free(pPrior);
22240  }
22241  return p;
22242 }
22243 
22244 /*
22245 ** Round up a request size to the next valid allocation size. If
22246 ** the allocation is too large to be handled by this allocation system,
22247 ** return 0.
22248 **
22249 ** All allocations must be a power of two and must be expressed by a
22250 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
22251 ** or 1073741824 bytes.
22252 */
22253 static int memsys5Roundup(int n){
22254  int iFullSz;
22255  if( n > 0x40000000 ) return 0;
22256  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
22257  return iFullSz;
22258 }
22259 
22260 /*
22261 ** Return the ceiling of the logarithm base 2 of iValue.
22262 **
22263 ** Examples: memsys5Log(1) -> 0
22264 ** memsys5Log(2) -> 1
22265 ** memsys5Log(4) -> 2
22266 ** memsys5Log(5) -> 3
22267 ** memsys5Log(8) -> 3
22268 ** memsys5Log(9) -> 4
22269 */
22270 static int memsys5Log(int iValue){
22271  int iLog;
22272  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
22273  return iLog;
22274 }
22275 
22276 /*
22277 ** Initialize the memory allocator.
22278 **
22279 ** This routine is not threadsafe. The caller must be holding a mutex
22280 ** to prevent multiple threads from entering at the same time.
22281 */
22282 static int memsys5Init(void *NotUsed){
22283  int ii; /* Loop counter */
22284  int nByte; /* Number of bytes of memory available to this allocator */
22285  u8 *zByte; /* Memory usable by this allocator */
22286  int nMinLog; /* Log base 2 of minimum allocation size in bytes */
22287  int iOffset; /* An offset into mem5.aCtrl[] */
22288 
22289  UNUSED_PARAMETER(NotUsed);
22290 
22291  /* For the purposes of this routine, disable the mutex */
22292  mem5.mutex = 0;
22293 
22294  /* The size of a Mem5Link object must be a power of two. Verify that
22295  ** this is case.
22296  */
22297  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
22298 
22299  nByte = sqlite3GlobalConfig.nHeap;
22300  zByte = (u8*)sqlite3GlobalConfig.pHeap;
22301  assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
22302 
22303  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
22304  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
22305  mem5.szAtom = (1<<nMinLog);
22306  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
22307  mem5.szAtom = mem5.szAtom << 1;
22308  }
22309 
22310  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
22311  mem5.zPool = zByte;
22312  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
22313 
22314  for(ii=0; ii<=LOGMAX; ii++){
22315  mem5.aiFreelist[ii] = -1;
22316  }
22317 
22318  iOffset = 0;
22319  for(ii=LOGMAX; ii>=0; ii--){
22320  int nAlloc = (1<<ii);
22321  if( (iOffset+nAlloc)<=mem5.nBlock ){
22322  mem5.aCtrl[iOffset] = ii | CTRL_FREE;
22323  memsys5Link(iOffset, ii);
22324  iOffset += nAlloc;
22325  }
22326  assert((iOffset+nAlloc)>mem5.nBlock);
22327  }
22328 
22329  /* If a mutex is required for normal operation, allocate one */
22330  if( sqlite3GlobalConfig.bMemstat==0 ){
22332  }
22333 
22334  return SQLITE_OK;
22335 }
22336 
22337 /*
22338 ** Deinitialize this module.
22339 */
22340 static void memsys5Shutdown(void *NotUsed){
22341  UNUSED_PARAMETER(NotUsed);
22342  mem5.mutex = 0;
22343  return;
22344 }
22345 
22346 #ifdef SQLITE_TEST
22347 /*
22348 ** Open the file indicated and write a log of all unfreed memory
22349 ** allocations into that log.
22350 */
22351 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
22352  FILE *out;
22353  int i, j, n;
22354  int nMinLog;
22355 
22356  if( zFilename==0 || zFilename[0]==0 ){
22357  out = stdout;
22358  }else{
22359  out = fopen(zFilename, "w");
22360  if( out==0 ){
22361  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22362  zFilename);
22363  return;
22364  }
22365  }
22366  memsys5Enter();
22367  nMinLog = memsys5Log(mem5.szAtom);
22368  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
22369  for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
22370  fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
22371  }
22372  fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
22373  fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
22374  fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
22375  fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
22376  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
22377  fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
22378  fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
22379  fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
22380  memsys5Leave();
22381  if( out==stdout ){
22382  fflush(stdout);
22383  }else{
22384  fclose(out);
22385  }
22386 }
22387 #endif
22388 
22389 /*
22390 ** This routine is the only routine in this file with external
22391 ** linkage. It returns a pointer to a static sqlite3_mem_methods
22392 ** struct populated with the memsys5 methods.
22393 */
22394 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
22395  static const sqlite3_mem_methods memsys5Methods = {
22396  memsys5Malloc,
22397  memsys5Free,
22398  memsys5Realloc,
22399  memsys5Size,
22400  memsys5Roundup,
22401  memsys5Init,
22402  memsys5Shutdown,
22403  0
22404  };
22405  return &memsys5Methods;
22406 }
22407 
22408 #endif /* SQLITE_ENABLE_MEMSYS5 */
22409 
22410 /************** End of mem5.c ************************************************/
22411 /************** Begin file mutex.c *******************************************/
22412 /*
22413 ** 2007 August 14
22414 **
22415 ** The author disclaims copyright to this source code. In place of
22416 ** a legal notice, here is a blessing:
22417 **
22418 ** May you do good and not evil.
22419 ** May you find forgiveness for yourself and forgive others.
22420 ** May you share freely, never taking more than you give.
22421 **
22422 *************************************************************************
22423 ** This file contains the C functions that implement mutexes.
22424 **
22425 ** This file contains code that is common across all mutex implementations.
22426 */
22427 /* #include "sqliteInt.h" */
22428 
22429 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
22430 /*
22431 ** For debugging purposes, record when the mutex subsystem is initialized
22432 ** and uninitialized so that we can assert() if there is an attempt to
22433 ** allocate a mutex while the system is uninitialized.
22434 */
22435 static SQLITE_WSD int mutexIsInit = 0;
22436 #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
22437 
22438 
22439 #ifndef SQLITE_MUTEX_OMIT
22440 /*
22441 ** Initialize the mutex system.
22442 */
22444  int rc = SQLITE_OK;
22445  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
22446  /* If the xMutexAlloc method has not been set, then the user did not
22447  ** install a mutex implementation via sqlite3_config() prior to
22448  ** sqlite3_initialize() being called. This block copies pointers to
22449  ** the default implementation into the sqlite3GlobalConfig structure.
22450  */
22451  sqlite3_mutex_methods const *pFrom;
22453 
22454  if( sqlite3GlobalConfig.bCoreMutex ){
22455  pFrom = sqlite3DefaultMutex();
22456  }else{
22457  pFrom = sqlite3NoopMutex();
22458  }
22459  pTo->xMutexInit = pFrom->xMutexInit;
22460  pTo->xMutexEnd = pFrom->xMutexEnd;
22461  pTo->xMutexFree = pFrom->xMutexFree;
22462  pTo->xMutexEnter = pFrom->xMutexEnter;
22463  pTo->xMutexTry = pFrom->xMutexTry;
22464  pTo->xMutexLeave = pFrom->xMutexLeave;
22465  pTo->xMutexHeld = pFrom->xMutexHeld;
22466  pTo->xMutexNotheld = pFrom->xMutexNotheld;
22468  pTo->xMutexAlloc = pFrom->xMutexAlloc;
22469  }
22470  assert( sqlite3GlobalConfig.mutex.xMutexInit );
22471  rc = sqlite3GlobalConfig.mutex.xMutexInit();
22472 
22473 #ifdef SQLITE_DEBUG
22474  GLOBAL(int, mutexIsInit) = 1;
22475 #endif
22476 
22477  return rc;
22478 }
22479 
22480 /*
22481 ** Shutdown the mutex system. This call frees resources allocated by
22482 ** sqlite3MutexInit().
22483 */
22485  int rc = SQLITE_OK;
22486  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
22487  rc = sqlite3GlobalConfig.mutex.xMutexEnd();
22488  }
22489 
22490 #ifdef SQLITE_DEBUG
22491  GLOBAL(int, mutexIsInit) = 0;
22492 #endif
22493 
22494  return rc;
22495 }
22496 
22497 /*
22498 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
22499 */
22501 #ifndef SQLITE_OMIT_AUTOINIT
22502  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
22503  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
22504 #endif
22505  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22506  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22507 }
22508 
22510  if( !sqlite3GlobalConfig.bCoreMutex ){
22511  return 0;
22512  }
22513  assert( GLOBAL(int, mutexIsInit) );
22514  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22515  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22516 }
22517 
22518 /*
22519 ** Free a dynamic mutex.
22520 */
22522  if( p ){
22523  assert( sqlite3GlobalConfig.mutex.xMutexFree );
22524  sqlite3GlobalConfig.mutex.xMutexFree(p);
22525  }
22526 }
22527 
22528 /*
22529 ** Obtain the mutex p. If some other thread already has the mutex, block
22530 ** until it can be obtained.
22531 */
22533  if( p ){
22534  assert( sqlite3GlobalConfig.mutex.xMutexEnter );
22535  sqlite3GlobalConfig.mutex.xMutexEnter(p);
22536  }
22537 }
22538 
22539 /*
22540 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
22541 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
22542 */
22544  int rc = SQLITE_OK;
22545  if( p ){
22546  assert( sqlite3GlobalConfig.mutex.xMutexTry );
22547  return sqlite3GlobalConfig.mutex.xMutexTry(p);
22548  }
22549  return rc;
22550 }
22551 
22552 /*
22553 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
22554 ** entered by the same thread. The behavior is undefined if the mutex
22555 ** is not currently entered. If a NULL pointer is passed as an argument
22556 ** this function is a no-op.
22557 */
22559  if( p ){
22560  assert( sqlite3GlobalConfig.mutex.xMutexLeave );
22561  sqlite3GlobalConfig.mutex.xMutexLeave(p);
22562  }
22563 }
22564 
22565 #ifndef NDEBUG
22566 /*
22567 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22568 ** intended for use inside assert() statements.
22569 */
22571  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
22572  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
22573 }
22575  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
22576  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
22577 }
22578 #endif
22579 
22580 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22581 
22582 /************** End of mutex.c ***********************************************/
22583 /************** Begin file mutex_noop.c **************************************/
22584 /*
22585 ** 2008 October 07
22586 **
22587 ** The author disclaims copyright to this source code. In place of
22588 ** a legal notice, here is a blessing:
22589 **
22590 ** May you do good and not evil.
22591 ** May you find forgiveness for yourself and forgive others.
22592 ** May you share freely, never taking more than you give.
22593 **
22594 *************************************************************************
22595 ** This file contains the C functions that implement mutexes.
22596 **
22597 ** This implementation in this file does not provide any mutual
22598 ** exclusion and is thus suitable for use only in applications
22599 ** that use SQLite in a single thread. The routines defined
22600 ** here are place-holders. Applications can substitute working
22601 ** mutex routines at start-time using the
22602 **
22603 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
22604 **
22605 ** interface.
22606 **
22607 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
22608 ** that does error checking on mutexes to make sure they are being
22609 ** called correctly.
22610 */
22611 /* #include "sqliteInt.h" */
22612 
22613 #ifndef SQLITE_MUTEX_OMIT
22614 
22615 #ifndef SQLITE_DEBUG
22616 /*
22617 ** Stub routines for all mutex methods.
22618 **
22619 ** This routines provide no mutual exclusion or error checking.
22620 */
22621 static int noopMutexInit(void){ return SQLITE_OK; }
22622 static int noopMutexEnd(void){ return SQLITE_OK; }
22624  UNUSED_PARAMETER(id);
22625  return (sqlite3_mutex*)8;
22626 }
22627 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22628 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22630  UNUSED_PARAMETER(p);
22631  return SQLITE_OK;
22632 }
22633 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22634 
22636  static const sqlite3_mutex_methods sMutex = {
22637  noopMutexInit,
22638  noopMutexEnd,
22640  noopMutexFree,
22642  noopMutexTry,
22644 
22645  0,
22646  0,
22647  };
22648 
22649  return &sMutex;
22650 }
22651 #endif /* !SQLITE_DEBUG */
22652 
22653 #ifdef SQLITE_DEBUG
22654 /*
22655 ** In this implementation, error checking is provided for testing
22656 ** and debugging purposes. The mutexes still do not provide any
22657 ** mutual exclusion.
22658 */
22659 
22660 /*
22661 ** The mutex object
22662 */
22663 typedef struct sqlite3_debug_mutex {
22664  int id; /* The mutex type */
22665  int cnt; /* Number of entries without a matching leave */
22666 } sqlite3_debug_mutex;
22667 
22668 /*
22669 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22670 ** intended for use inside assert() statements.
22671 */
22672 static int debugMutexHeld(sqlite3_mutex *pX){
22673  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22674  return p==0 || p->cnt>0;
22675 }
22676 static int debugMutexNotheld(sqlite3_mutex *pX){
22677  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22678  return p==0 || p->cnt==0;
22679 }
22680 
22681 /*
22682 ** Initialize and deinitialize the mutex subsystem.
22683 */
22684 static int debugMutexInit(void){ return SQLITE_OK; }
22685 static int debugMutexEnd(void){ return SQLITE_OK; }
22686 
22687 /*
22688 ** The sqlite3_mutex_alloc() routine allocates a new
22689 ** mutex and returns a pointer to it. If it returns NULL
22690 ** that means that a mutex could not be allocated.
22691 */
22692 static sqlite3_mutex *debugMutexAlloc(int id){
22693  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
22694  sqlite3_debug_mutex *pNew = 0;
22695  switch( id ){
22696  case SQLITE_MUTEX_FAST:
22697  case SQLITE_MUTEX_RECURSIVE: {
22698  pNew = sqlite3Malloc(sizeof(*pNew));
22699  if( pNew ){
22700  pNew->id = id;
22701  pNew->cnt = 0;
22702  }
22703  break;
22704  }
22705  default: {
22706 #ifdef SQLITE_ENABLE_API_ARMOR
22707  if( id-2<0 || id-2>=ArraySize(aStatic) ){
22708  (void)SQLITE_MISUSE_BKPT;
22709  return 0;
22710  }
22711 #endif
22712  pNew = &aStatic[id-2];
22713  pNew->id = id;
22714  break;
22715  }
22716  }
22717  return (sqlite3_mutex*)pNew;
22718 }
22719 
22720 /*
22721 ** This routine deallocates a previously allocated mutex.
22722 */
22723 static void debugMutexFree(sqlite3_mutex *pX){
22724  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22725  assert( p->cnt==0 );
22726  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
22727  sqlite3_free(p);
22728  }else{
22729 #ifdef SQLITE_ENABLE_API_ARMOR
22730  (void)SQLITE_MISUSE_BKPT;
22731 #endif
22732  }
22733 }
22734 
22735 /*
22736 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22737 ** to enter a mutex. If another thread is already within the mutex,
22738 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22739 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
22740 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
22741 ** be entered multiple times by the same thread. In such cases the,
22742 ** mutex must be exited an equal number of times before another thread
22743 ** can enter. If the same thread tries to enter any other kind of mutex
22744 ** more than once, the behavior is undefined.
22745 */
22746 static void debugMutexEnter(sqlite3_mutex *pX){
22747  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22748  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22749  p->cnt++;
22750 }
22751 static int debugMutexTry(sqlite3_mutex *pX){
22752  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22753  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22754  p->cnt++;
22755  return SQLITE_OK;
22756 }
22757 
22758 /*
22759 ** The sqlite3_mutex_leave() routine exits a mutex that was
22760 ** previously entered by the same thread. The behavior
22761 ** is undefined if the mutex is not currently entered or
22762 ** is not currently allocated. SQLite will never do either.
22763 */
22764 static void debugMutexLeave(sqlite3_mutex *pX){
22765  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22766  assert( debugMutexHeld(pX) );
22767  p->cnt--;
22768  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22769 }
22770 
22772  static const sqlite3_mutex_methods sMutex = {
22773  debugMutexInit,
22774  debugMutexEnd,
22775  debugMutexAlloc,
22776  debugMutexFree,
22777  debugMutexEnter,
22778  debugMutexTry,
22779  debugMutexLeave,
22780 
22781  debugMutexHeld,
22782  debugMutexNotheld
22783  };
22784 
22785  return &sMutex;
22786 }
22787 #endif /* SQLITE_DEBUG */
22788 
22789 /*
22790 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
22791 ** is used regardless of the run-time threadsafety setting.
22792 */
22793 #ifdef SQLITE_MUTEX_NOOP
22795  return sqlite3NoopMutex();
22796 }
22797 #endif /* defined(SQLITE_MUTEX_NOOP) */
22798 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22799 
22800 /************** End of mutex_noop.c ******************************************/
22801 /************** Begin file mutex_unix.c **************************************/
22802 /*
22803 ** 2007 August 28
22804 **
22805 ** The author disclaims copyright to this source code. In place of
22806 ** a legal notice, here is a blessing:
22807 **
22808 ** May you do good and not evil.
22809 ** May you find forgiveness for yourself and forgive others.
22810 ** May you share freely, never taking more than you give.
22811 **
22812 *************************************************************************
22813 ** This file contains the C functions that implement mutexes for pthreads
22814 */
22815 /* #include "sqliteInt.h" */
22816 
22817 /*
22818 ** The code in this file is only used if we are compiling threadsafe
22819 ** under unix with pthreads.
22820 **
22821 ** Note that this implementation requires a version of pthreads that
22822 ** supports recursive mutexes.
22823 */
22824 #ifdef SQLITE_MUTEX_PTHREADS
22825 
22826 #include <pthread.h>
22827 
22828 /*
22829 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
22830 ** are necessary under two condidtions: (1) Debug builds and (2) using
22831 ** home-grown mutexes. Encapsulate these conditions into a single #define.
22832 */
22833 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
22834 # define SQLITE_MUTEX_NREF 1
22835 #else
22836 # define SQLITE_MUTEX_NREF 0
22837 #endif
22838 
22839 /*
22840 ** Each recursive mutex is an instance of the following structure.
22841 */
22843  pthread_mutex_t mutex; /* Mutex controlling the lock */
22844 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22845  int id; /* Mutex type */
22846 #endif
22847 #if SQLITE_MUTEX_NREF
22848  volatile int nRef; /* Number of entrances */
22849  volatile pthread_t owner; /* Thread that is within this mutex */
22850  int trace; /* True to trace changes */
22851 #endif
22852 };
22853 #if SQLITE_MUTEX_NREF
22854 #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
22855 #elif defined(SQLITE_ENABLE_API_ARMOR)
22856 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
22857 #else
22858 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
22859 #endif
22860 
22861 /*
22862 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22863 ** intended for use only inside assert() statements. On some platforms,
22864 ** there might be race conditions that can cause these routines to
22865 ** deliver incorrect results. In particular, if pthread_equal() is
22866 ** not an atomic operation, then these routines might delivery
22867 ** incorrect results. On most platforms, pthread_equal() is a
22868 ** comparison of two integers and is therefore atomic. But we are
22869 ** told that HPUX is not such a platform. If so, then these routines
22870 ** will not always work correctly on HPUX.
22871 **
22872 ** On those platforms where pthread_equal() is not atomic, SQLite
22873 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
22874 ** make sure no assert() statements are evaluated and hence these
22875 ** routines are never called.
22876 */
22877 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
22878 static int pthreadMutexHeld(sqlite3_mutex *p){
22879  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
22880 }
22881 static int pthreadMutexNotheld(sqlite3_mutex *p){
22882  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
22883 }
22884 #endif
22885 
22886 /*
22887 ** Try to provide a memory barrier operation, needed for initialization
22888 ** and also for the implementation of xShmBarrier in the VFS in cases
22889 ** where SQLite is compiled without mutexes.
22890 */
22892 #if defined(SQLITE_MEMORY_BARRIER)
22893  SQLITE_MEMORY_BARRIER;
22894 #elif defined(__GNUC__) && GCC_VERSION>=4001000
22895  __sync_synchronize();
22896 #endif
22897 }
22898 
22899 /*
22900 ** Initialize and deinitialize the mutex subsystem.
22901 */
22902 static int pthreadMutexInit(void){ return SQLITE_OK; }
22903 static int pthreadMutexEnd(void){ return SQLITE_OK; }
22904 
22905 /*
22906 ** The sqlite3_mutex_alloc() routine allocates a new
22907 ** mutex and returns a pointer to it. If it returns NULL
22908 ** that means that a mutex could not be allocated. SQLite
22909 ** will unwind its stack and return an error. The argument
22910 ** to sqlite3_mutex_alloc() is one of these integer constants:
22911 **
22912 ** <ul>
22913 ** <li> SQLITE_MUTEX_FAST
22914 ** <li> SQLITE_MUTEX_RECURSIVE
22915 ** <li> SQLITE_MUTEX_STATIC_MASTER
22916 ** <li> SQLITE_MUTEX_STATIC_MEM
22917 ** <li> SQLITE_MUTEX_STATIC_OPEN
22918 ** <li> SQLITE_MUTEX_STATIC_PRNG
22919 ** <li> SQLITE_MUTEX_STATIC_LRU
22920 ** <li> SQLITE_MUTEX_STATIC_PMEM
22921 ** <li> SQLITE_MUTEX_STATIC_APP1
22922 ** <li> SQLITE_MUTEX_STATIC_APP2
22923 ** <li> SQLITE_MUTEX_STATIC_APP3
22924 ** <li> SQLITE_MUTEX_STATIC_VFS1
22925 ** <li> SQLITE_MUTEX_STATIC_VFS2
22926 ** <li> SQLITE_MUTEX_STATIC_VFS3
22927 ** </ul>
22928 **
22929 ** The first two constants cause sqlite3_mutex_alloc() to create
22930 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
22931 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
22932 ** The mutex implementation does not need to make a distinction
22933 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
22934 ** not want to. But SQLite will only request a recursive mutex in
22935 ** cases where it really needs one. If a faster non-recursive mutex
22936 ** implementation is available on the host platform, the mutex subsystem
22937 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
22938 **
22939 ** The other allowed parameters to sqlite3_mutex_alloc() each return
22940 ** a pointer to a static preexisting mutex. Six static mutexes are
22941 ** used by the current version of SQLite. Future versions of SQLite
22942 ** may add additional static mutexes. Static mutexes are for internal
22943 ** use by SQLite only. Applications that use SQLite mutexes should
22944 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
22945 ** SQLITE_MUTEX_RECURSIVE.
22946 **
22947 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
22948 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
22949 ** returns a different mutex on every call. But for the static
22950 ** mutex types, the same mutex is returned on every call that has
22951 ** the same type number.
22952 */
22954  static sqlite3_mutex staticMutexes[] = {
22966  SQLITE3_MUTEX_INITIALIZER
22967  };
22968  sqlite3_mutex *p;
22969  switch( iType ){
22970  case SQLITE_MUTEX_RECURSIVE: {
22971  p = sqlite3MallocZero( sizeof(*p) );
22972  if( p ){
22973 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22974  /* If recursive mutexes are not available, we will have to
22975  ** build our own. See below. */
22976  pthread_mutex_init(&p->mutex, 0);
22977 #else
22978  /* Use a recursive mutex if it is available */
22979  pthread_mutexattr_t recursiveAttr;
22980  pthread_mutexattr_init(&recursiveAttr);
22981  pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
22982  pthread_mutex_init(&p->mutex, &recursiveAttr);
22983  pthread_mutexattr_destroy(&recursiveAttr);
22984 #endif
22985  }
22986  break;
22987  }
22988  case SQLITE_MUTEX_FAST: {
22989  p = sqlite3MallocZero( sizeof(*p) );
22990  if( p ){
22991  pthread_mutex_init(&p->mutex, 0);
22992  }
22993  break;
22994  }
22995  default: {
22996 #ifdef SQLITE_ENABLE_API_ARMOR
22997  if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
22998  (void)SQLITE_MISUSE_BKPT;
22999  return 0;
23000  }
23001 #endif
23002  p = &staticMutexes[iType-2];
23003  break;
23004  }
23005  }
23006 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
23007  if( p ) p->id = iType;
23008 #endif
23009  return p;
23010 }
23011 
23012 
23013 /*
23014 ** This routine deallocates a previously
23015 ** allocated mutex. SQLite is careful to deallocate every
23016 ** mutex that it allocates.
23017 */
23019  assert( p->nRef==0 );
23020 #if SQLITE_ENABLE_API_ARMOR
23021  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
23022 #endif
23023  {
23024  pthread_mutex_destroy(&p->mutex);
23025  sqlite3_free(p);
23026  }
23027 #ifdef SQLITE_ENABLE_API_ARMOR
23028  else{
23029  (void)SQLITE_MISUSE_BKPT;
23030  }
23031 #endif
23032 }
23033 
23034 /*
23035 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23036 ** to enter a mutex. If another thread is already within the mutex,
23037 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23038 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23039 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23040 ** be entered multiple times by the same thread. In such cases the,
23041 ** mutex must be exited an equal number of times before another thread
23042 ** can enter. If the same thread tries to enter any other kind of mutex
23043 ** more than once, the behavior is undefined.
23044 */
23046  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23047 
23048 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23049  /* If recursive mutexes are not available, then we have to grow
23050  ** our own. This implementation assumes that pthread_equal()
23051  ** is atomic - that it cannot be deceived into thinking self
23052  ** and p->owner are equal if p->owner changes between two values
23053  ** that are not equal to self while the comparison is taking place.
23054  ** This implementation also assumes a coherent cache - that
23055  ** separate processes cannot read different values from the same
23056  ** address at the same time. If either of these two conditions
23057  ** are not met, then the mutexes will fail and problems will result.
23058  */
23059  {
23060  pthread_t self = pthread_self();
23061  if( p->nRef>0 && pthread_equal(p->owner, self) ){
23062  p->nRef++;
23063  }else{
23064  pthread_mutex_lock(&p->mutex);
23065  assert( p->nRef==0 );
23066  p->owner = self;
23067  p->nRef = 1;
23068  }
23069  }
23070 #else
23071  /* Use the built-in recursive mutexes if they are available.
23072  */
23073  pthread_mutex_lock(&p->mutex);
23074 #if SQLITE_MUTEX_NREF
23075  assert( p->nRef>0 || p->owner==0 );
23076  p->owner = pthread_self();
23077  p->nRef++;
23078 #endif
23079 #endif
23080 
23081 #ifdef SQLITE_DEBUG
23082  if( p->trace ){
23083  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23084  }
23085 #endif
23086 }
23088  int rc;
23089  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23090 
23091 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23092  /* If recursive mutexes are not available, then we have to grow
23093  ** our own. This implementation assumes that pthread_equal()
23094  ** is atomic - that it cannot be deceived into thinking self
23095  ** and p->owner are equal if p->owner changes between two values
23096  ** that are not equal to self while the comparison is taking place.
23097  ** This implementation also assumes a coherent cache - that
23098  ** separate processes cannot read different values from the same
23099  ** address at the same time. If either of these two conditions
23100  ** are not met, then the mutexes will fail and problems will result.
23101  */
23102  {
23103  pthread_t self = pthread_self();
23104  if( p->nRef>0 && pthread_equal(p->owner, self) ){
23105  p->nRef++;
23106  rc = SQLITE_OK;
23107  }else if( pthread_mutex_trylock(&p->mutex)==0 ){
23108  assert( p->nRef==0 );
23109  p->owner = self;
23110  p->nRef = 1;
23111  rc = SQLITE_OK;
23112  }else{
23113  rc = SQLITE_BUSY;
23114  }
23115  }
23116 #else
23117  /* Use the built-in recursive mutexes if they are available.
23118  */
23119  if( pthread_mutex_trylock(&p->mutex)==0 ){
23120 #if SQLITE_MUTEX_NREF
23121  p->owner = pthread_self();
23122  p->nRef++;
23123 #endif
23124  rc = SQLITE_OK;
23125  }else{
23126  rc = SQLITE_BUSY;
23127  }
23128 #endif
23129 
23130 #ifdef SQLITE_DEBUG
23131  if( rc==SQLITE_OK && p->trace ){
23132  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23133  }
23134 #endif
23135  return rc;
23136 }
23137 
23138 /*
23139 ** The sqlite3_mutex_leave() routine exits a mutex that was
23140 ** previously entered by the same thread. The behavior
23141 ** is undefined if the mutex is not currently entered or
23142 ** is not currently allocated. SQLite will never do either.
23143 */
23145  assert( pthreadMutexHeld(p) );
23146 #if SQLITE_MUTEX_NREF
23147  p->nRef--;
23148  if( p->nRef==0 ) p->owner = 0;
23149 #endif
23150  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23151 
23152 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23153  if( p->nRef==0 ){
23154  pthread_mutex_unlock(&p->mutex);
23155  }
23156 #else
23157  pthread_mutex_unlock(&p->mutex);
23158 #endif
23159 
23160 #ifdef SQLITE_DEBUG
23161  if( p->trace ){
23162  printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23163  }
23164 #endif
23165 }
23166 
23168  static const sqlite3_mutex_methods sMutex = {
23176 #ifdef SQLITE_DEBUG
23177  pthreadMutexHeld,
23178  pthreadMutexNotheld
23179 #else
23180  0,
23181  0
23182 #endif
23183  };
23184 
23185  return &sMutex;
23186 }
23187 
23188 #endif /* SQLITE_MUTEX_PTHREADS */
23189 
23190 /************** End of mutex_unix.c ******************************************/
23191 /************** Begin file mutex_w32.c ***************************************/
23192 /*
23193 ** 2007 August 14
23194 **
23195 ** The author disclaims copyright to this source code. In place of
23196 ** a legal notice, here is a blessing:
23197 **
23198 ** May you do good and not evil.
23199 ** May you find forgiveness for yourself and forgive others.
23200 ** May you share freely, never taking more than you give.
23201 **
23202 *************************************************************************
23203 ** This file contains the C functions that implement mutexes for Win32.
23204 */
23205 /* #include "sqliteInt.h" */
23206 
23207 #if SQLITE_OS_WIN
23208 /*
23209 ** Include code that is common to all os_*.c files
23210 */
23211 /************** Include os_common.h in the middle of mutex_w32.c *************/
23212 /************** Begin file os_common.h ***************************************/
23213 /*
23214 ** 2004 May 22
23215 **
23216 ** The author disclaims copyright to this source code. In place of
23217 ** a legal notice, here is a blessing:
23218 **
23219 ** May you do good and not evil.
23220 ** May you find forgiveness for yourself and forgive others.
23221 ** May you share freely, never taking more than you give.
23222 **
23223 ******************************************************************************
23224 **
23225 ** This file contains macros and a little bit of code that is common to
23226 ** all of the platform-specific files (os_*.c) and is #included into those
23227 ** files.
23228 **
23229 ** This file should be #included by the os_*.c files only. It is not a
23230 ** general purpose header file.
23231 */
23232 #ifndef _OS_COMMON_H_
23233 #define _OS_COMMON_H_
23234 
23235 /*
23236 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23237 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23238 ** switch. The following code should catch this problem at compile-time.
23239 */
23240 #ifdef MEMORY_DEBUG
23241 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
23242 #endif
23243 
23244 /*
23245 ** Macros for performance tracing. Normally turned off. Only works
23246 ** on i486 hardware.
23247 */
23248 #ifdef SQLITE_PERFORMANCE_TRACE
23249 
23250 /*
23251 ** hwtime.h contains inline assembler code for implementing
23252 ** high-performance timing routines.
23253 */
23254 /************** Include hwtime.h in the middle of os_common.h ****************/
23255 /************** Begin file hwtime.h ******************************************/
23256 /*
23257 ** 2008 May 27
23258 **
23259 ** The author disclaims copyright to this source code. In place of
23260 ** a legal notice, here is a blessing:
23261 **
23262 ** May you do good and not evil.
23263 ** May you find forgiveness for yourself and forgive others.
23264 ** May you share freely, never taking more than you give.
23265 **
23266 ******************************************************************************
23267 **
23268 ** This file contains inline asm code for retrieving "high-performance"
23269 ** counters for x86 class CPUs.
23270 */
23271 #ifndef SQLITE_HWTIME_H
23272 #define SQLITE_HWTIME_H
23273 
23274 /*
23275 ** The following routine only works on pentium-class (or newer) processors.
23276 ** It uses the RDTSC opcode to read the cycle count value out of the
23277 ** processor and returns that value. This can be used for high-res
23278 ** profiling.
23279 */
23280 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23281  (defined(i386) || defined(__i386__) || defined(_M_IX86))
23282 
23283  #if defined(__GNUC__)
23284 
23285  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23286  unsigned int lo, hi;
23287  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23288  return (sqlite_uint64)hi << 32 | lo;
23289  }
23290 
23291  #elif defined(_MSC_VER)
23292 
23293  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23294  __asm {
23295  rdtsc
23296  ret ; return value at EDX:EAX
23297  }
23298  }
23299 
23300  #endif
23301 
23302 #elif (defined(__GNUC__) && defined(__x86_64__))
23303 
23304  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23305  unsigned long val;
23306  __asm__ __volatile__ ("rdtsc" : "=A" (val));
23307  return val;
23308  }
23309 
23310 #elif (defined(__GNUC__) && defined(__ppc__))
23311 
23312  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23313  unsigned long long retval;
23314  unsigned long junk;
23315  __asm__ __volatile__ ("\n\
23316  1: mftbu %1\n\
23317  mftb %L0\n\
23318  mftbu %0\n\
23319  cmpw %0,%1\n\
23320  bne 1b"
23321  : "=r" (retval), "=r" (junk));
23322  return retval;
23323  }
23324 
23325 #else
23326 
23327  #error Need implementation of sqlite3Hwtime() for your platform.
23328 
23329  /*
23330  ** To compile without implementing sqlite3Hwtime() for your platform,
23331  ** you can remove the above #error and use the following
23332  ** stub function. You will lose timing support for many
23333  ** of the debugging and testing utilities, but it should at
23334  ** least compile and run.
23335  */
23336 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23337 
23338 #endif
23339 
23340 #endif /* !defined(SQLITE_HWTIME_H) */
23341 
23342 /************** End of hwtime.h **********************************************/
23343 /************** Continuing where we left off in os_common.h ******************/
23344 
23345 static sqlite_uint64 g_start;
23346 static sqlite_uint64 g_elapsed;
23347 #define TIMER_START g_start=sqlite3Hwtime()
23348 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
23349 #define TIMER_ELAPSED g_elapsed
23350 #else
23351 #define TIMER_START
23352 #define TIMER_END
23353 #define TIMER_ELAPSED ((sqlite_uint64)0)
23354 #endif
23355 
23356 /*
23357 ** If we compile with the SQLITE_TEST macro set, then the following block
23358 ** of code will give us the ability to simulate a disk I/O error. This
23359 ** is used for testing the I/O recovery logic.
23360 */
23361 #if defined(SQLITE_TEST)
23362 SQLITE_API extern int sqlite3_io_error_hit;
23363 SQLITE_API extern int sqlite3_io_error_hardhit;
23364 SQLITE_API extern int sqlite3_io_error_pending;
23365 SQLITE_API extern int sqlite3_io_error_persist;
23366 SQLITE_API extern int sqlite3_io_error_benign;
23367 SQLITE_API extern int sqlite3_diskfull_pending;
23368 SQLITE_API extern int sqlite3_diskfull;
23369 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23370 #define SimulateIOError(CODE) \
23371  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23372  || sqlite3_io_error_pending-- == 1 ) \
23373  { local_ioerr(); CODE; }
23374 static void local_ioerr(){
23375  IOTRACE(("IOERR\n"));
23376  sqlite3_io_error_hit++;
23377  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23378 }
23379 #define SimulateDiskfullError(CODE) \
23380  if( sqlite3_diskfull_pending ){ \
23381  if( sqlite3_diskfull_pending == 1 ){ \
23382  local_ioerr(); \
23383  sqlite3_diskfull = 1; \
23384  sqlite3_io_error_hit = 1; \
23385  CODE; \
23386  }else{ \
23387  sqlite3_diskfull_pending--; \
23388  } \
23389  }
23390 #else
23391 #define SimulateIOErrorBenign(X)
23392 #define SimulateIOError(A)
23393 #define SimulateDiskfullError(A)
23394 #endif /* defined(SQLITE_TEST) */
23395 
23396 /*
23397 ** When testing, keep a count of the number of open files.
23398 */
23399 #if defined(SQLITE_TEST)
23400 SQLITE_API extern int sqlite3_open_file_count;
23401 #define OpenCounter(X) sqlite3_open_file_count+=(X)
23402 #else
23403 #define OpenCounter(X)
23404 #endif /* defined(SQLITE_TEST) */
23405 
23406 #endif /* !defined(_OS_COMMON_H_) */
23407 
23408 /************** End of os_common.h *******************************************/
23409 /************** Continuing where we left off in mutex_w32.c ******************/
23410 
23411 /*
23412 ** Include the header file for the Windows VFS.
23413 */
23414 /************** Include os_win.h in the middle of mutex_w32.c ****************/
23415 /************** Begin file os_win.h ******************************************/
23416 /*
23417 ** 2013 November 25
23418 **
23419 ** The author disclaims copyright to this source code. In place of
23420 ** a legal notice, here is a blessing:
23421 **
23422 ** May you do good and not evil.
23423 ** May you find forgiveness for yourself and forgive others.
23424 ** May you share freely, never taking more than you give.
23425 **
23426 ******************************************************************************
23427 **
23428 ** This file contains code that is specific to Windows.
23429 */
23430 #ifndef SQLITE_OS_WIN_H
23431 #define SQLITE_OS_WIN_H
23432 
23433 /*
23434 ** Include the primary Windows SDK header file.
23435 */
23436 #include "windows.h"
23437 
23438 #ifdef __CYGWIN__
23439 # include <sys/cygwin.h>
23440 # include <errno.h> /* amalgamator: dontcache */
23441 #endif
23442 
23443 /*
23444 ** Determine if we are dealing with Windows NT.
23445 **
23446 ** We ought to be able to determine if we are compiling for Windows 9x or
23447 ** Windows NT using the _WIN32_WINNT macro as follows:
23448 **
23449 ** #if defined(_WIN32_WINNT)
23450 ** # define SQLITE_OS_WINNT 1
23451 ** #else
23452 ** # define SQLITE_OS_WINNT 0
23453 ** #endif
23454 **
23455 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
23456 ** it ought to, so the above test does not work. We'll just assume that
23457 ** everything is Windows NT unless the programmer explicitly says otherwise
23458 ** by setting SQLITE_OS_WINNT to 0.
23459 */
23460 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
23461 # define SQLITE_OS_WINNT 1
23462 #endif
23463 
23464 /*
23465 ** Determine if we are dealing with Windows CE - which has a much reduced
23466 ** API.
23467 */
23468 #if defined(_WIN32_WCE)
23469 # define SQLITE_OS_WINCE 1
23470 #else
23471 # define SQLITE_OS_WINCE 0
23472 #endif
23473 
23474 /*
23475 ** Determine if we are dealing with WinRT, which provides only a subset of
23476 ** the full Win32 API.
23477 */
23478 #if !defined(SQLITE_OS_WINRT)
23479 # define SQLITE_OS_WINRT 0
23480 #endif
23481 
23482 /*
23483 ** For WinCE, some API function parameters do not appear to be declared as
23484 ** volatile.
23485 */
23486 #if SQLITE_OS_WINCE
23487 # define SQLITE_WIN32_VOLATILE
23488 #else
23489 # define SQLITE_WIN32_VOLATILE volatile
23490 #endif
23491 
23492 /*
23493 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
23494 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
23495 */
23496 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
23497  SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
23498 # define SQLITE_OS_WIN_THREADS 1
23499 #else
23500 # define SQLITE_OS_WIN_THREADS 0
23501 #endif
23502 
23503 #endif /* SQLITE_OS_WIN_H */
23504 
23505 /************** End of os_win.h **********************************************/
23506 /************** Continuing where we left off in mutex_w32.c ******************/
23507 #endif
23508 
23509 /*
23510 ** The code in this file is only used if we are compiling multithreaded
23511 ** on a Win32 system.
23512 */
23513 #ifdef SQLITE_MUTEX_W32
23514 
23515 /*
23516 ** Each recursive mutex is an instance of the following structure.
23517 */
23518 struct sqlite3_mutex {
23519  CRITICAL_SECTION mutex; /* Mutex controlling the lock */
23520  int id; /* Mutex type */
23521 #ifdef SQLITE_DEBUG
23522  volatile int nRef; /* Number of enterances */
23523  volatile DWORD owner; /* Thread holding this mutex */
23524  volatile int trace; /* True to trace changes */
23525 #endif
23526 };
23527 
23528 /*
23529 ** These are the initializer values used when declaring a "static" mutex
23530 ** on Win32. It should be noted that all mutexes require initialization
23531 ** on the Win32 platform.
23532 */
23533 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
23534 
23535 #ifdef SQLITE_DEBUG
23536 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
23537  0L, (DWORD)0, 0 }
23538 #else
23539 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
23540 #endif
23541 
23542 #ifdef SQLITE_DEBUG
23543 /*
23544 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23545 ** intended for use only inside assert() statements.
23546 */
23547 static int winMutexHeld(sqlite3_mutex *p){
23548  return p->nRef!=0 && p->owner==GetCurrentThreadId();
23549 }
23550 
23551 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
23552  return p->nRef==0 || p->owner!=tid;
23553 }
23554 
23555 static int winMutexNotheld(sqlite3_mutex *p){
23556  DWORD tid = GetCurrentThreadId();
23557  return winMutexNotheld2(p, tid);
23558 }
23559 #endif
23560 
23561 /*
23562 ** Try to provide a memory barrier operation, needed for initialization
23563 ** and also for the xShmBarrier method of the VFS in cases when SQLite is
23564 ** compiled without mutexes (SQLITE_THREADSAFE=0).
23565 */
23567 #if defined(SQLITE_MEMORY_BARRIER)
23568  SQLITE_MEMORY_BARRIER;
23569 #elif defined(__GNUC__)
23570  __sync_synchronize();
23571 #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
23572  defined(_MSC_VER) && _MSC_VER>=1300
23573  _ReadWriteBarrier();
23574 #elif defined(MemoryBarrier)
23575  MemoryBarrier();
23576 #endif
23577 }
23578 
23579 /*
23580 ** Initialize and deinitialize the mutex subsystem.
23581 */
23582 static sqlite3_mutex winMutex_staticMutexes[] = {
23594  SQLITE3_MUTEX_INITIALIZER
23595 };
23596 
23597 static int winMutex_isInit = 0;
23598 static int winMutex_isNt = -1; /* <0 means "need to query" */
23599 
23600 /* As the winMutexInit() and winMutexEnd() functions are called as part
23601 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
23602 ** "interlocked" magic used here is probably not strictly necessary.
23603 */
23604 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
23605 
23606 SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
23607 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
23608 
23609 static int winMutexInit(void){
23610  /* The first to increment to 1 does actual initialization */
23611  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
23612  int i;
23613  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23614 #if SQLITE_OS_WINRT
23615  InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
23616 #else
23617  InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
23618 #endif
23619  }
23620  winMutex_isInit = 1;
23621  }else{
23622  /* Another thread is (in the process of) initializing the static
23623  ** mutexes */
23624  while( !winMutex_isInit ){
23625  sqlite3_win32_sleep(1);
23626  }
23627  }
23628  return SQLITE_OK;
23629 }
23630 
23631 static int winMutexEnd(void){
23632  /* The first to decrement to 0 does actual shutdown
23633  ** (which should be the last to shutdown.) */
23634  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
23635  if( winMutex_isInit==1 ){
23636  int i;
23637  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23638  DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
23639  }
23640  winMutex_isInit = 0;
23641  }
23642  }
23643  return SQLITE_OK;
23644 }
23645 
23646 /*
23647 ** The sqlite3_mutex_alloc() routine allocates a new
23648 ** mutex and returns a pointer to it. If it returns NULL
23649 ** that means that a mutex could not be allocated. SQLite
23650 ** will unwind its stack and return an error. The argument
23651 ** to sqlite3_mutex_alloc() is one of these integer constants:
23652 **
23653 ** <ul>
23654 ** <li> SQLITE_MUTEX_FAST
23655 ** <li> SQLITE_MUTEX_RECURSIVE
23656 ** <li> SQLITE_MUTEX_STATIC_MASTER
23657 ** <li> SQLITE_MUTEX_STATIC_MEM
23658 ** <li> SQLITE_MUTEX_STATIC_OPEN
23659 ** <li> SQLITE_MUTEX_STATIC_PRNG
23660 ** <li> SQLITE_MUTEX_STATIC_LRU
23661 ** <li> SQLITE_MUTEX_STATIC_PMEM
23662 ** <li> SQLITE_MUTEX_STATIC_APP1
23663 ** <li> SQLITE_MUTEX_STATIC_APP2
23664 ** <li> SQLITE_MUTEX_STATIC_APP3
23665 ** <li> SQLITE_MUTEX_STATIC_VFS1
23666 ** <li> SQLITE_MUTEX_STATIC_VFS2
23667 ** <li> SQLITE_MUTEX_STATIC_VFS3
23668 ** </ul>
23669 **
23670 ** The first two constants cause sqlite3_mutex_alloc() to create
23671 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23672 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23673 ** The mutex implementation does not need to make a distinction
23674 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23675 ** not want to. But SQLite will only request a recursive mutex in
23676 ** cases where it really needs one. If a faster non-recursive mutex
23677 ** implementation is available on the host platform, the mutex subsystem
23678 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
23679 **
23680 ** The other allowed parameters to sqlite3_mutex_alloc() each return
23681 ** a pointer to a static preexisting mutex. Six static mutexes are
23682 ** used by the current version of SQLite. Future versions of SQLite
23683 ** may add additional static mutexes. Static mutexes are for internal
23684 ** use by SQLite only. Applications that use SQLite mutexes should
23685 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23686 ** SQLITE_MUTEX_RECURSIVE.
23687 **
23688 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23689 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23690 ** returns a different mutex on every call. But for the static
23691 ** mutex types, the same mutex is returned on every call that has
23692 ** the same type number.
23693 */
23694 static sqlite3_mutex *winMutexAlloc(int iType){
23695  sqlite3_mutex *p;
23696 
23697  switch( iType ){
23698  case SQLITE_MUTEX_FAST:
23699  case SQLITE_MUTEX_RECURSIVE: {
23700  p = sqlite3MallocZero( sizeof(*p) );
23701  if( p ){
23702  p->id = iType;
23703 #ifdef SQLITE_DEBUG
23704 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
23705  p->trace = 1;
23706 #endif
23707 #endif
23708 #if SQLITE_OS_WINRT
23709  InitializeCriticalSectionEx(&p->mutex, 0, 0);
23710 #else
23711  InitializeCriticalSection(&p->mutex);
23712 #endif
23713  }
23714  break;
23715  }
23716  default: {
23717 #ifdef SQLITE_ENABLE_API_ARMOR
23718  if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
23719  (void)SQLITE_MISUSE_BKPT;
23720  return 0;
23721  }
23722 #endif
23723  p = &winMutex_staticMutexes[iType-2];
23724  p->id = iType;
23725 #ifdef SQLITE_DEBUG
23726 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
23727  p->trace = 1;
23728 #endif
23729 #endif
23730  break;
23731  }
23732  }
23733  return p;
23734 }
23735 
23736 
23737 /*
23738 ** This routine deallocates a previously
23739 ** allocated mutex. SQLite is careful to deallocate every
23740 ** mutex that it allocates.
23741 */
23742 static void winMutexFree(sqlite3_mutex *p){
23743  assert( p );
23744  assert( p->nRef==0 && p->owner==0 );
23745  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
23746  DeleteCriticalSection(&p->mutex);
23747  sqlite3_free(p);
23748  }else{
23749 #ifdef SQLITE_ENABLE_API_ARMOR
23750  (void)SQLITE_MISUSE_BKPT;
23751 #endif
23752  }
23753 }
23754 
23755 /*
23756 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23757 ** to enter a mutex. If another thread is already within the mutex,
23758 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23759 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23760 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23761 ** be entered multiple times by the same thread. In such cases the,
23762 ** mutex must be exited an equal number of times before another thread
23763 ** can enter. If the same thread tries to enter any other kind of mutex
23764 ** more than once, the behavior is undefined.
23765 */
23766 static void winMutexEnter(sqlite3_mutex *p){
23767 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23768  DWORD tid = GetCurrentThreadId();
23769 #endif
23770 #ifdef SQLITE_DEBUG
23771  assert( p );
23772  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23773 #else
23774  assert( p );
23775 #endif
23776  assert( winMutex_isInit==1 );
23777  EnterCriticalSection(&p->mutex);
23778 #ifdef SQLITE_DEBUG
23779  assert( p->nRef>0 || p->owner==0 );
23780  p->owner = tid;
23781  p->nRef++;
23782  if( p->trace ){
23783  OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23784  tid, p, p->trace, p->nRef));
23785  }
23786 #endif
23787 }
23788 
23789 static int winMutexTry(sqlite3_mutex *p){
23790 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23791  DWORD tid = GetCurrentThreadId();
23792 #endif
23793  int rc = SQLITE_BUSY;
23794  assert( p );
23795  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23796  /*
23797  ** The sqlite3_mutex_try() routine is very rarely used, and when it
23798  ** is used it is merely an optimization. So it is OK for it to always
23799  ** fail.
23800  **
23801  ** The TryEnterCriticalSection() interface is only available on WinNT.
23802  ** And some windows compilers complain if you try to use it without
23803  ** first doing some #defines that prevent SQLite from building on Win98.
23804  ** For that reason, we will omit this optimization for now. See
23805  ** ticket #2685.
23806  */
23807 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
23808  assert( winMutex_isInit==1 );
23809  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
23810  if( winMutex_isNt<0 ){
23811  winMutex_isNt = sqlite3_win32_is_nt();
23812  }
23813  assert( winMutex_isNt==0 || winMutex_isNt==1 );
23814  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
23815 #ifdef SQLITE_DEBUG
23816  p->owner = tid;
23817  p->nRef++;
23818 #endif
23819  rc = SQLITE_OK;
23820  }
23821 #else
23822  UNUSED_PARAMETER(p);
23823 #endif
23824 #ifdef SQLITE_DEBUG
23825  if( p->trace ){
23826  OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
23827  tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
23828  }
23829 #endif
23830  return rc;
23831 }
23832 
23833 /*
23834 ** The sqlite3_mutex_leave() routine exits a mutex that was
23835 ** previously entered by the same thread. The behavior
23836 ** is undefined if the mutex is not currently entered or
23837 ** is not currently allocated. SQLite will never do either.
23838 */
23839 static void winMutexLeave(sqlite3_mutex *p){
23840 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23841  DWORD tid = GetCurrentThreadId();
23842 #endif
23843  assert( p );
23844 #ifdef SQLITE_DEBUG
23845  assert( p->nRef>0 );
23846  assert( p->owner==tid );
23847  p->nRef--;
23848  if( p->nRef==0 ) p->owner = 0;
23849  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23850 #endif
23851  assert( winMutex_isInit==1 );
23852  LeaveCriticalSection(&p->mutex);
23853 #ifdef SQLITE_DEBUG
23854  if( p->trace ){
23855  OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23856  tid, p, p->trace, p->nRef));
23857  }
23858 #endif
23859 }
23860 
23862  static const sqlite3_mutex_methods sMutex = {
23863  winMutexInit,
23864  winMutexEnd,
23865  winMutexAlloc,
23866  winMutexFree,
23867  winMutexEnter,
23868  winMutexTry,
23869  winMutexLeave,
23870 #ifdef SQLITE_DEBUG
23871  winMutexHeld,
23872  winMutexNotheld
23873 #else
23874  0,
23875  0
23876 #endif
23877  };
23878  return &sMutex;
23879 }
23880 
23881 #endif /* SQLITE_MUTEX_W32 */
23882 
23883 /************** End of mutex_w32.c *******************************************/
23884 /************** Begin file malloc.c ******************************************/
23885 /*
23886 ** 2001 September 15
23887 **
23888 ** The author disclaims copyright to this source code. In place of
23889 ** a legal notice, here is a blessing:
23890 **
23891 ** May you do good and not evil.
23892 ** May you find forgiveness for yourself and forgive others.
23893 ** May you share freely, never taking more than you give.
23894 **
23895 *************************************************************************
23896 **
23897 ** Memory allocation functions used throughout sqlite.
23898 */
23899 /* #include "sqliteInt.h" */
23900 /* #include <stdarg.h> */
23901 
23902 /*
23903 ** Attempt to release up to n bytes of non-essential memory currently
23904 ** held by SQLite. An example of non-essential memory is memory used to
23905 ** cache database pages that are not currently in use.
23906 */
23908 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23909  return sqlite3PcacheReleaseMemory(n);
23910 #else
23911  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
23912  ** is a no-op returning zero if SQLite is not compiled with
23913  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
23914  UNUSED_PARAMETER(n);
23915  return 0;
23916 #endif
23917 }
23918 
23919 /*
23920 ** An instance of the following object records the location of
23921 ** each unused scratch buffer.
23922 */
23923 typedef struct ScratchFreeslot {
23924  struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
23925 } ScratchFreeslot;
23926 
23927 /*
23928 ** State information local to the memory allocation subsystem.
23929 */
23930 static SQLITE_WSD struct Mem0Global {
23931  sqlite3_mutex *mutex; /* Mutex to serialize access */
23932  sqlite3_int64 alarmThreshold; /* The soft heap limit */
23933 
23934  /*
23935  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
23936  ** (so that a range test can be used to determine if an allocation
23937  ** being freed came from pScratch) and a pointer to the list of
23938  ** unused scratch allocations.
23939  */
23943 
23944  /*
23945  ** True if heap is nearly "full" where "full" is defined by the
23946  ** sqlite3_soft_heap_limit() setting.
23947  */
23949 } mem0 = { 0, 0, 0, 0, 0, 0 };
23950 
23951 #define mem0 GLOBAL(struct Mem0Global, mem0)
23952 
23953 /*
23954 ** Return the memory allocator mutex. sqlite3_status() needs it.
23955 */
23957  return mem0.mutex;
23958 }
23959 
23960 #ifndef SQLITE_OMIT_DEPRECATED
23961 /*
23962 ** Deprecated external interface. It used to set an alarm callback
23963 ** that was invoked when memory usage grew too large. Now it is a
23964 ** no-op.
23965 */
23967  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
23968  void *pArg,
23969  sqlite3_int64 iThreshold
23970 ){
23971  (void)xCallback;
23972  (void)pArg;
23973  (void)iThreshold;
23974  return SQLITE_OK;
23975 }
23976 #endif
23977 
23978 /*
23979 ** Set the soft heap-size limit for the library. Passing a zero or
23980 ** negative value indicates no limit.
23981 */
23982 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
23983  sqlite3_int64 priorLimit;
23984  sqlite3_int64 excess;
23985  sqlite3_int64 nUsed;
23986 #ifndef SQLITE_OMIT_AUTOINIT
23987  int rc = sqlite3_initialize();
23988  if( rc ) return -1;
23989 #endif
23990  sqlite3_mutex_enter(mem0.mutex);
23991  priorLimit = mem0.alarmThreshold;
23992  if( n<0 ){
23993  sqlite3_mutex_leave(mem0.mutex);
23994  return priorLimit;
23995  }
23996  mem0.alarmThreshold = n;
23998  mem0.nearlyFull = (n>0 && n<=nUsed);
23999  sqlite3_mutex_leave(mem0.mutex);
24000  excess = sqlite3_memory_used() - n;
24001  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
24002  return priorLimit;
24003 }
24005  if( n<0 ) n = 0;
24007 }
24008 
24009 /*
24010 ** Initialize the memory allocation subsystem.
24011 */
24013  int rc;
24014  if( sqlite3GlobalConfig.m.xMalloc==0 ){
24016  }
24017  memset(&mem0, 0, sizeof(mem0));
24019  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
24020  && sqlite3GlobalConfig.nScratch>0 ){
24021  int i, n, sz;
24022  ScratchFreeslot *pSlot;
24023  sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
24024  sqlite3GlobalConfig.szScratch = sz;
24025  pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
24026  n = sqlite3GlobalConfig.nScratch;
24027  mem0.pScratchFree = pSlot;
24028  mem0.nScratchFree = n;
24029  for(i=0; i<n-1; i++){
24030  pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
24031  pSlot = pSlot->pNext;
24032  }
24033  pSlot->pNext = 0;
24034  mem0.pScratchEnd = (void*)&pSlot[1];
24035  }else{
24036  mem0.pScratchEnd = 0;
24037  sqlite3GlobalConfig.pScratch = 0;
24038  sqlite3GlobalConfig.szScratch = 0;
24039  sqlite3GlobalConfig.nScratch = 0;
24040  }
24041  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
24042  || sqlite3GlobalConfig.nPage<=0 ){
24043  sqlite3GlobalConfig.pPage = 0;
24044  sqlite3GlobalConfig.szPage = 0;
24045  }
24046  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
24047  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
24048  return rc;
24049 }
24050 
24051 /*
24052 ** Return true if the heap is currently under memory pressure - in other
24053 ** words if the amount of heap used is close to the limit set by
24054 ** sqlite3_soft_heap_limit().
24055 */
24057  return mem0.nearlyFull;
24058 }
24059 
24060 /*
24061 ** Deinitialize the memory allocation subsystem.
24062 */
24064  if( sqlite3GlobalConfig.m.xShutdown ){
24065  sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24066  }
24067  memset(&mem0, 0, sizeof(mem0));
24068 }
24069 
24070 /*
24071 ** Return the amount of memory currently checked out.
24072 */
24073 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
24074  sqlite3_int64 res, mx;
24076  return res;
24077 }
24078 
24079 /*
24080 ** Return the maximum amount of memory that has ever been
24081 ** checked out since either the beginning of this process
24082 ** or since the most recent reset.
24083 */
24084 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
24085  sqlite3_int64 res, mx;
24086  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24087  return mx;
24088 }
24089 
24090 /*
24091 ** Trigger the alarm
24092 */
24093 static void sqlite3MallocAlarm(int nByte){
24094  if( mem0.alarmThreshold<=0 ) return;
24095  sqlite3_mutex_leave(mem0.mutex);
24096  sqlite3_release_memory(nByte);
24097  sqlite3_mutex_enter(mem0.mutex);
24098 }
24099 
24100 /*
24101 ** Do a memory allocation with statistics and alarms. Assume the
24102 ** lock is already held.
24103 */
24104 static int mallocWithAlarm(int n, void **pp){
24105  int nFull;
24106  void *p;
24107  assert( sqlite3_mutex_held(mem0.mutex) );
24108  nFull = sqlite3GlobalConfig.m.xRoundup(n);
24110  if( mem0.alarmThreshold>0 ){
24111  sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24112  if( nUsed >= mem0.alarmThreshold - nFull ){
24113  mem0.nearlyFull = 1;
24114  sqlite3MallocAlarm(nFull);
24115  }else{
24116  mem0.nearlyFull = 0;
24117  }
24118  }
24119  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24120 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24121  if( p==0 && mem0.alarmThreshold>0 ){
24122  sqlite3MallocAlarm(nFull);
24123  p = sqlite3GlobalConfig.m.xMalloc(nFull);
24124  }
24125 #endif
24126  if( p ){
24127  nFull = sqlite3MallocSize(p);
24130  }
24131  *pp = p;
24132  return nFull;
24133 }
24134 
24135 /*
24136 ** Allocate memory. This routine is like sqlite3_malloc() except that it
24137 ** assumes the memory subsystem has already been initialized.
24138 */
24140  void *p;
24141  if( n==0 || n>=0x7fffff00 ){
24142  /* A memory allocation of a number of bytes which is near the maximum
24143  ** signed integer value might cause an integer overflow inside of the
24144  ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
24145  ** 255 bytes of overhead. SQLite itself will never use anything near
24146  ** this amount. The only way to reach the limit is with sqlite3_malloc() */
24147  p = 0;
24148  }else if( sqlite3GlobalConfig.bMemstat ){
24149  sqlite3_mutex_enter(mem0.mutex);
24150  mallocWithAlarm((int)n, &p);
24151  sqlite3_mutex_leave(mem0.mutex);
24152  }else{
24153  p = sqlite3GlobalConfig.m.xMalloc((int)n);
24154  }
24155  assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
24156  return p;
24157 }
24158 
24159 /*
24160 ** This version of the memory allocation is for use by the application.
24161 ** First make sure the memory subsystem is initialized, then do the
24162 ** allocation.
24163 */
24165 #ifndef SQLITE_OMIT_AUTOINIT
24166  if( sqlite3_initialize() ) return 0;
24167 #endif
24168  return n<=0 ? 0 : sqlite3Malloc(n);
24169 }
24170 SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
24171 #ifndef SQLITE_OMIT_AUTOINIT
24172  if( sqlite3_initialize() ) return 0;
24173 #endif
24174  return sqlite3Malloc(n);
24175 }
24176 
24177 /*
24178 ** Each thread may only have a single outstanding allocation from
24179 ** xScratchMalloc(). We verify this constraint in the single-threaded
24180 ** case by setting scratchAllocOut to 1 when an allocation
24181 ** is outstanding clearing it when the allocation is freed.
24182 */
24183 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24184 static int scratchAllocOut = 0;
24185 #endif
24186 
24187 
24188 /*
24189 ** Allocate memory that is to be used and released right away.
24190 ** This routine is similar to alloca() in that it is not intended
24191 ** for situations where the memory might be held long-term. This
24192 ** routine is intended to get memory to old large transient data
24193 ** structures that would not normally fit on the stack of an
24194 ** embedded processor.
24195 */
24197  void *p;
24198  assert( n>0 );
24199 
24200  sqlite3_mutex_enter(mem0.mutex);
24202  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
24203  p = mem0.pScratchFree;
24204  mem0.pScratchFree = mem0.pScratchFree->pNext;
24205  mem0.nScratchFree--;
24207  sqlite3_mutex_leave(mem0.mutex);
24208  }else{
24209  sqlite3_mutex_leave(mem0.mutex);
24210  p = sqlite3Malloc(n);
24211  if( sqlite3GlobalConfig.bMemstat && p ){
24212  sqlite3_mutex_enter(mem0.mutex);
24214  sqlite3_mutex_leave(mem0.mutex);
24215  }
24217  }
24218  assert( sqlite3_mutex_notheld(mem0.mutex) );
24219 
24220 
24221 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24222  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
24223  ** buffers per thread.
24224  **
24225  ** This can only be checked in single-threaded mode.
24226  */
24227  assert( scratchAllocOut==0 );
24228  if( p ) scratchAllocOut++;
24229 #endif
24230 
24231  return p;
24232 }
24234  if( p ){
24235 
24236 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24237  /* Verify that no more than two scratch allocation per thread
24238  ** is outstanding at one time. (This is only checked in the
24239  ** single-threaded case since checking in the multi-threaded case
24240  ** would be much more complicated.) */
24241  assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
24242  scratchAllocOut--;
24243 #endif
24244 
24245  if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
24246  /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
24247  ScratchFreeslot *pSlot;
24248  pSlot = (ScratchFreeslot*)p;
24249  sqlite3_mutex_enter(mem0.mutex);
24250  pSlot->pNext = mem0.pScratchFree;
24251  mem0.pScratchFree = pSlot;
24252  mem0.nScratchFree++;
24253  assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
24255  sqlite3_mutex_leave(mem0.mutex);
24256  }else{
24257  /* Release memory back to the heap */
24259  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
24261  if( sqlite3GlobalConfig.bMemstat ){
24262  int iSize = sqlite3MallocSize(p);
24263  sqlite3_mutex_enter(mem0.mutex);
24267  sqlite3GlobalConfig.m.xFree(p);
24268  sqlite3_mutex_leave(mem0.mutex);
24269  }else{
24270  sqlite3GlobalConfig.m.xFree(p);
24271  }
24272  }
24273  }
24274 }
24275 
24276 /*
24277 ** TRUE if p is a lookaside memory allocation from db
24278 */
24279 #ifndef SQLITE_OMIT_LOOKASIDE
24280 static int isLookaside(sqlite3 *db, void *p){
24281  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
24282 }
24283 #else
24284 #define isLookaside(A,B) 0
24285 #endif
24286 
24287 /*
24288 ** Return the size of a memory allocation previously obtained from
24289 ** sqlite3Malloc() or sqlite3_malloc().
24290 */
24292  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24293  return sqlite3GlobalConfig.m.xSize(p);
24294 }
24296  assert( p!=0 );
24297  if( db==0 || !isLookaside(db,p) ){
24298 #if SQLITE_DEBUG
24299  if( db==0 ){
24300  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24301  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24302  }else{
24305  }
24306 #endif
24307  return sqlite3GlobalConfig.m.xSize(p);
24308  }else{
24309  assert( sqlite3_mutex_held(db->mutex) );
24310  return db->lookaside.sz;
24311  }
24312 }
24313 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
24314  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24315  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24316  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
24317 }
24318 
24319 /*
24320 ** Free memory previously obtained from sqlite3Malloc().
24321 */
24322 SQLITE_API void sqlite3_free(void *p){
24323  if( p==0 ) return; /* IMP: R-49053-54554 */
24324  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24325  assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24326  if( sqlite3GlobalConfig.bMemstat ){
24327  sqlite3_mutex_enter(mem0.mutex);
24330  sqlite3GlobalConfig.m.xFree(p);
24331  sqlite3_mutex_leave(mem0.mutex);
24332  }else{
24333  sqlite3GlobalConfig.m.xFree(p);
24334  }
24335 }
24336 
24337 /*
24338 ** Add the size of memory allocation "p" to the count in
24339 ** *db->pnBytesFreed.
24340 */
24342  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
24343 }
24344 
24345 /*
24346 ** Free memory that might be associated with a particular database
24347 ** connection.
24348 */
24350  assert( db==0 || sqlite3_mutex_held(db->mutex) );
24351  if( p==0 ) return;
24352  if( db ){
24353  if( db->pnBytesFreed ){
24354  measureAllocationSize(db, p);
24355  return;
24356  }
24357  if( isLookaside(db, p) ){
24358  LookasideSlot *pBuf = (LookasideSlot*)p;
24359 #if SQLITE_DEBUG
24360  /* Trash all content in the buffer being freed */
24361  memset(p, 0xaa, db->lookaside.sz);
24362 #endif
24363  pBuf->pNext = db->lookaside.pFree;
24364  db->lookaside.pFree = pBuf;
24365  db->lookaside.nOut--;
24366  return;
24367  }
24368  }
24371  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
24373  sqlite3_free(p);
24374 }
24375 
24376 /*
24377 ** Change the size of an existing memory allocation
24378 */
24379 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
24380  int nOld, nNew, nDiff;
24381  void *pNew;
24382  assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
24383  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
24384  if( pOld==0 ){
24385  return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
24386  }
24387  if( nBytes==0 ){
24388  sqlite3_free(pOld); /* IMP: R-26507-47431 */
24389  return 0;
24390  }
24391  if( nBytes>=0x7fffff00 ){
24392  /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
24393  return 0;
24394  }
24395  nOld = sqlite3MallocSize(pOld);
24396  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
24397  ** argument to xRealloc is always a value returned by a prior call to
24398  ** xRoundup. */
24399  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
24400  if( nOld==nNew ){
24401  pNew = pOld;
24402  }else if( sqlite3GlobalConfig.bMemstat ){
24403  sqlite3_mutex_enter(mem0.mutex);
24405  nDiff = nNew - nOld;
24407  mem0.alarmThreshold-nDiff ){
24408  sqlite3MallocAlarm(nDiff);
24409  }
24410  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24411  if( pNew==0 && mem0.alarmThreshold>0 ){
24412  sqlite3MallocAlarm((int)nBytes);
24413  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24414  }
24415  if( pNew ){
24416  nNew = sqlite3MallocSize(pNew);
24418  }
24419  sqlite3_mutex_leave(mem0.mutex);
24420  }else{
24421  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24422  }
24423  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
24424  return pNew;
24425 }
24426 
24427 /*
24428 ** The public interface to sqlite3Realloc. Make sure that the memory
24429 ** subsystem is initialized prior to invoking sqliteRealloc.
24430 */
24431 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
24432 #ifndef SQLITE_OMIT_AUTOINIT
24433  if( sqlite3_initialize() ) return 0;
24434 #endif
24435  if( n<0 ) n = 0; /* IMP: R-26507-47431 */
24436  return sqlite3Realloc(pOld, n);
24437 }
24438 SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
24439 #ifndef SQLITE_OMIT_AUTOINIT
24440  if( sqlite3_initialize() ) return 0;
24441 #endif
24442  return sqlite3Realloc(pOld, n);
24443 }
24444 
24445 
24446 /*
24447 ** Allocate and zero memory.
24448 */
24450  void *p = sqlite3Malloc(n);
24451  if( p ){
24452  memset(p, 0, (size_t)n);
24453  }
24454  return p;
24455 }
24456 
24457 /*
24458 ** Allocate and zero memory. If the allocation fails, make
24459 ** the mallocFailed flag in the connection pointer.
24460 */
24462  void *p;
24463  testcase( db==0 );
24464  p = sqlite3DbMallocRaw(db, n);
24465  if( p ) memset(p, 0, (size_t)n);
24466  return p;
24467 }
24468 
24469 
24470 /* Finish the work of sqlite3DbMallocRawNN for the unusual and
24471 ** slower case when the allocation cannot be fulfilled using lookaside.
24472 */
24473 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
24474  void *p;
24475  assert( db!=0 );
24476  p = sqlite3Malloc(n);
24477  if( !p ) sqlite3OomFault(db);
24480  return p;
24481 }
24482 
24483 /*
24484 ** Allocate memory, either lookaside (if possible) or heap.
24485 ** If the allocation fails, set the mallocFailed flag in
24486 ** the connection pointer.
24487 **
24488 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
24489 ** failure on the same database connection) then always return 0.
24490 ** Hence for a particular database connection, once malloc starts
24491 ** failing, it fails consistently until mallocFailed is reset.
24492 ** This is an important assumption. There are many places in the
24493 ** code that do things like this:
24494 **
24495 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
24496 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
24497 ** if( b ) a[10] = 9;
24498 **
24499 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
24500 ** that all prior mallocs (ex: "a") worked too.
24501 **
24502 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
24503 ** not a NULL pointer.
24504 */
24506  void *p;
24507  if( db ) return sqlite3DbMallocRawNN(db, n);
24508  p = sqlite3Malloc(n);
24510  return p;
24511 }
24513 #ifndef SQLITE_OMIT_LOOKASIDE
24514  LookasideSlot *pBuf;
24515  assert( db!=0 );
24516  assert( sqlite3_mutex_held(db->mutex) );
24517  assert( db->pnBytesFreed==0 );
24518  if( db->lookaside.bDisable==0 ){
24519  assert( db->mallocFailed==0 );
24520  if( n>db->lookaside.sz ){
24521  db->lookaside.anStat[1]++;
24522  }else if( (pBuf = db->lookaside.pFree)==0 ){
24523  db->lookaside.anStat[2]++;
24524  }else{
24525  db->lookaside.pFree = pBuf->pNext;
24526  db->lookaside.nOut++;
24527  db->lookaside.anStat[0]++;
24528  if( db->lookaside.nOut>db->lookaside.mxOut ){
24529  db->lookaside.mxOut = db->lookaside.nOut;
24530  }
24531  return (void*)pBuf;
24532  }
24533  }else if( db->mallocFailed ){
24534  return 0;
24535  }
24536 #else
24537  assert( db!=0 );
24538  assert( sqlite3_mutex_held(db->mutex) );
24539  assert( db->pnBytesFreed==0 );
24540  if( db->mallocFailed ){
24541  return 0;
24542  }
24543 #endif
24544  return dbMallocRawFinish(db, n);
24545 }
24546 
24547 /* Forward declaration */
24548 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
24549 
24550 /*
24551 ** Resize the block of memory pointed to by p to n bytes. If the
24552 ** resize fails, set the mallocFailed flag in the connection object.
24553 */
24554 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
24555  assert( db!=0 );
24556  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
24557  assert( sqlite3_mutex_held(db->mutex) );
24558  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
24559  return dbReallocFinish(db, p, n);
24560 }
24561 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
24562  void *pNew = 0;
24563  assert( db!=0 );
24564  assert( p!=0 );
24565  if( db->mallocFailed==0 ){
24566  if( isLookaside(db, p) ){
24567  pNew = sqlite3DbMallocRawNN(db, n);
24568  if( pNew ){
24569  memcpy(pNew, p, db->lookaside.sz);
24570  sqlite3DbFree(db, p);
24571  }
24572  }else{
24576  pNew = sqlite3_realloc64(p, n);
24577  if( !pNew ){
24578  sqlite3OomFault(db);
24579  }
24582  }
24583  }
24584  return pNew;
24585 }
24586 
24587 /*
24588 ** Attempt to reallocate p. If the reallocation fails, then free p
24589 ** and set the mallocFailed flag in the database connection.
24590 */
24591 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
24592  void *pNew;
24593  pNew = sqlite3DbRealloc(db, p, n);
24594  if( !pNew ){
24595  sqlite3DbFree(db, p);
24596  }
24597  return pNew;
24598 }
24599 
24600 /*
24601 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
24602 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
24603 ** is because when memory debugging is turned on, these two functions are
24604 ** called via macros that record the current file and line number in the
24605 ** ThreadData structure.
24606 */
24607 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
24608  char *zNew;
24609  size_t n;
24610  if( z==0 ){
24611  return 0;
24612  }
24613  n = sqlite3Strlen30(z) + 1;
24614  assert( (n&0x7fffffff)==n );
24615  zNew = sqlite3DbMallocRaw(db, (int)n);
24616  if( zNew ){
24617  memcpy(zNew, z, n);
24618  }
24619  return zNew;
24620 }
24621 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
24622  char *zNew;
24623  assert( db!=0 );
24624  if( z==0 ){
24625  return 0;
24626  }
24627  assert( (n&0x7fffffff)==n );
24628  zNew = sqlite3DbMallocRawNN(db, n+1);
24629  if( zNew ){
24630  memcpy(zNew, z, (size_t)n);
24631  zNew[n] = 0;
24632  }
24633  return zNew;
24634 }
24635 
24636 /*
24637 ** Free any prior content in *pz and replace it with a copy of zNew.
24638 */
24639 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
24640  sqlite3DbFree(db, *pz);
24641  *pz = sqlite3DbStrDup(db, zNew);
24642 }
24643 
24644 /*
24645 ** Call this routine to record the fact that an OOM (out-of-memory) error
24646 ** has happened. This routine will set db->mallocFailed, and also
24647 ** temporarily disable the lookaside memory allocator and interrupt
24648 ** any running VDBEs.
24649 */
24651  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
24652  db->mallocFailed = 1;
24653  if( db->nVdbeExec>0 ){
24654  db->u1.isInterrupted = 1;
24655  }
24656  db->lookaside.bDisable++;
24657  }
24658 }
24659 
24660 /*
24661 ** This routine reactivates the memory allocator and clears the
24662 ** db->mallocFailed flag as necessary.
24663 **
24664 ** The memory allocator is not restarted if there are running
24665 ** VDBEs.
24666 */
24668  if( db->mallocFailed && db->nVdbeExec==0 ){
24669  db->mallocFailed = 0;
24670  db->u1.isInterrupted = 0;
24671  assert( db->lookaside.bDisable>0 );
24672  db->lookaside.bDisable--;
24673  }
24674 }
24675 
24676 /*
24677 ** Take actions at the end of an API call to indicate an OOM error
24678 */
24680  sqlite3OomClear(db);
24682  return SQLITE_NOMEM_BKPT;
24683 }
24684 
24685 /*
24686 ** This function must be called before exiting any API function (i.e.
24687 ** returning control to the user) that has called sqlite3_malloc or
24688 ** sqlite3_realloc.
24689 **
24690 ** The returned value is normally a copy of the second argument to this
24691 ** function. However, if a malloc() failure has occurred since the previous
24692 ** invocation SQLITE_NOMEM is returned instead.
24693 **
24694 ** If an OOM as occurred, then the connection error-code (the value
24695 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
24696 */
24698  /* If the db handle must hold the connection handle mutex here.
24699  ** Otherwise the read (and possible write) of db->mallocFailed
24700  ** is unsafe, as is the call to sqlite3Error().
24701  */
24702  assert( db!=0 );
24703  assert( sqlite3_mutex_held(db->mutex) );
24704  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
24705  return apiOomError(db);
24706  }
24707  return rc & db->errMask;
24708 }
24709 
24710 /************** End of malloc.c **********************************************/
24711 /************** Begin file printf.c ******************************************/
24712 /*
24713 ** The "printf" code that follows dates from the 1980's. It is in
24714 ** the public domain.
24715 **
24716 **************************************************************************
24717 **
24718 ** This file contains code for a set of "printf"-like routines. These
24719 ** routines format strings much like the printf() from the standard C
24720 ** library, though the implementation here has enhancements to support
24721 ** SQLite.
24722 */
24723 /* #include "sqliteInt.h" */
24724 
24725 /*
24726 ** Conversion types fall into various categories as defined by the
24727 ** following enumeration.
24728 */
24729 #define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */
24730 #define etFLOAT 1 /* Floating point. %f */
24731 #define etEXP 2 /* Exponentional notation. %e and %E */
24732 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
24733 #define etSIZE 4 /* Return number of characters processed so far. %n */
24734 #define etSTRING 5 /* Strings. %s */
24735 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
24736 #define etPERCENT 7 /* Percent symbol. %% */
24737 #define etCHARX 8 /* Characters. %c */
24738 /* The rest are extensions, not normally found in printf() */
24739 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
24740 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
24741  NULL pointers replaced by SQL NULL. %Q */
24742 #define etTOKEN 11 /* a pointer to a Token structure */
24743 #define etSRCLIST 12 /* a pointer to a SrcList */
24744 #define etPOINTER 13 /* The %p conversion */
24745 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24746 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
24747 
24748 #define etINVALID 16 /* Any unrecognized conversion type */
24749 
24750 
24751 /*
24752 ** An "etByte" is an 8-bit unsigned value.
24753 */
24754 typedef unsigned char etByte;
24755 
24756 /*
24757 ** Each builtin conversion character (ex: the 'd' in "%d") is described
24758 ** by an instance of the following structure
24759 */
24760 typedef struct et_info { /* Information about each format field */
24761  char fmttype; /* The format field code letter */
24762  etByte base; /* The base for radix conversion */
24763  etByte flags; /* One or more of FLAG_ constants below */
24764  etByte type; /* Conversion paradigm */
24765  etByte charset; /* Offset into aDigits[] of the digits string */
24766  etByte prefix; /* Offset into aPrefix[] of the prefix string */
24767 } et_info;
24768 
24769 /*
24770 ** Allowed values for et_info.flags
24771 */
24772 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
24773 #define FLAG_INTERN 2 /* True if for internal use only */
24774 #define FLAG_STRING 4 /* Allow infinity precision */
24775 
24776 
24777 /*
24778 ** The following table is searched linearly, so it is good to put the
24779 ** most frequently used conversion types first.
24780 */
24781 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
24782 static const char aPrefix[] = "-x0\000X0";
24783 static const et_info fmtinfo[] = {
24784  { 'd', 10, 1, etRADIX, 0, 0 },
24785  { 's', 0, 4, etSTRING, 0, 0 },
24786  { 'g', 0, 1, etGENERIC, 30, 0 },
24787  { 'z', 0, 4, etDYNSTRING, 0, 0 },
24788  { 'q', 0, 4, etSQLESCAPE, 0, 0 },
24789  { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
24790  { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
24791  { 'c', 0, 0, etCHARX, 0, 0 },
24792  { 'o', 8, 0, etRADIX, 0, 2 },
24793  { 'u', 10, 0, etRADIX, 0, 0 },
24794  { 'x', 16, 0, etRADIX, 16, 1 },
24795  { 'X', 16, 0, etRADIX, 0, 4 },
24796 #ifndef SQLITE_OMIT_FLOATING_POINT
24797  { 'f', 0, 1, etFLOAT, 0, 0 },
24798  { 'e', 0, 1, etEXP, 30, 0 },
24799  { 'E', 0, 1, etEXP, 14, 0 },
24800  { 'G', 0, 1, etGENERIC, 14, 0 },
24801 #endif
24802  { 'i', 10, 1, etRADIX, 0, 0 },
24803  { 'n', 0, 0, etSIZE, 0, 0 },
24804  { '%', 0, 0, etPERCENT, 0, 0 },
24805  { 'p', 16, 0, etPOINTER, 0, 1 },
24806 
24807 /* All the rest have the FLAG_INTERN bit set and are thus for internal
24808 ** use only */
24809  { 'T', 0, 2, etTOKEN, 0, 0 },
24810  { 'S', 0, 2, etSRCLIST, 0, 0 },
24811  { 'r', 10, 3, etORDINAL, 0, 0 },
24812 };
24813 
24814 /*
24815 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
24816 ** conversions will work.
24817 */
24818 #ifndef SQLITE_OMIT_FLOATING_POINT
24819 /*
24820 ** "*val" is a double such that 0.1 <= *val < 10.0
24821 ** Return the ascii code for the leading digit of *val, then
24822 ** multiply "*val" by 10.0 to renormalize.
24823 **
24824 ** Example:
24825 ** input: *val = 3.14159
24826 ** output: *val = 1.4159 function return = '3'
24827 **
24828 ** The counter *cnt is incremented each time. After counter exceeds
24829 ** 16 (the number of significant digits in a 64-bit float) '0' is
24830 ** always returned.
24831 */
24832 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
24833  int digit;
24835  if( (*cnt)<=0 ) return '0';
24836  (*cnt)--;
24837  digit = (int)*val;
24838  d = digit;
24839  digit += '0';
24840  *val = (*val - d)*10.0;
24841  return (char)digit;
24842 }
24843 #endif /* SQLITE_OMIT_FLOATING_POINT */
24844 
24845 /*
24846 ** Set the StrAccum object to an error mode.
24847 */
24848 static void setStrAccumError(StrAccum *p, u8 eError){
24849  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
24850  p->accError = eError;
24851  p->nAlloc = 0;
24852 }
24853 
24854 /*
24855 ** Extra argument values from a PrintfArguments object
24856 */
24857 static sqlite3_int64 getIntArg(PrintfArguments *p){
24858  if( p->nArg<=p->nUsed ) return 0;
24859  return sqlite3_value_int64(p->apArg[p->nUsed++]);
24860 }
24861 static double getDoubleArg(PrintfArguments *p){
24862  if( p->nArg<=p->nUsed ) return 0.0;
24863  return sqlite3_value_double(p->apArg[p->nUsed++]);
24864 }
24865 static char *getTextArg(PrintfArguments *p){
24866  if( p->nArg<=p->nUsed ) return 0;
24867  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
24868 }
24869 
24870 
24871 /*
24872 ** On machines with a small stack size, you can redefine the
24873 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
24874 */
24875 #ifndef SQLITE_PRINT_BUF_SIZE
24876 # define SQLITE_PRINT_BUF_SIZE 70
24877 #endif
24878 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
24879 
24880 /*
24881 ** Render a string given by "fmt" into the StrAccum object.
24882 */
24884  StrAccum *pAccum, /* Accumulate results here */
24885  const char *fmt, /* Format string */
24886  va_list ap /* arguments */
24887 ){
24888  int c; /* Next character in the format string */
24889  char *bufpt; /* Pointer to the conversion buffer */
24890  int precision; /* Precision of the current field */
24891  int length; /* Length of the field */
24892  int idx; /* A general purpose loop counter */
24893  int width; /* Width of the current field */
24894  etByte flag_leftjustify; /* True if "-" flag is present */
24895  etByte flag_plussign; /* True if "+" flag is present */
24896  etByte flag_blanksign; /* True if " " flag is present */
24897  etByte flag_alternateform; /* True if "#" flag is present */
24898  etByte flag_altform2; /* True if "!" flag is present */
24899  etByte flag_zeropad; /* True if field width constant starts with zero */
24900  etByte flag_long; /* True if "l" flag is present */
24901  etByte flag_longlong; /* True if the "ll" flag is present */
24902  etByte done; /* Loop termination flag */
24903  etByte xtype = etINVALID; /* Conversion paradigm */
24904  u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
24905  u8 useIntern; /* Ok to use internal conversions (ex: %T) */
24906  char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
24907  sqlite_uint64 longvalue; /* Value for integer types */
24908  LONGDOUBLE_TYPE realvalue; /* Value for real types */
24909  const et_info *infop; /* Pointer to the appropriate info structure */
24910  char *zOut; /* Rendering buffer */
24911  int nOut; /* Size of the rendering buffer */
24912  char *zExtra = 0; /* Malloced memory used by some conversion */
24913 #ifndef SQLITE_OMIT_FLOATING_POINT
24914  int exp, e2; /* exponent of real numbers */
24915  int nsd; /* Number of significant digits returned */
24916  double rounder; /* Used for rounding floating point values */
24917  etByte flag_dp; /* True if decimal point should be shown */
24918  etByte flag_rtz; /* True if trailing zeros should be removed */
24919 #endif
24920  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
24921  char buf[etBUFSIZE]; /* Conversion buffer */
24922 
24923  bufpt = 0;
24924  if( pAccum->printfFlags ){
24925  if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
24926  pArgList = va_arg(ap, PrintfArguments*);
24927  }
24928  useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL;
24929  }else{
24930  bArgList = useIntern = 0;
24931  }
24932  for(; (c=(*fmt))!=0; ++fmt){
24933  if( c!='%' ){
24934  bufpt = (char *)fmt;
24935 #if HAVE_STRCHRNUL
24936  fmt = strchrnul(fmt, '%');
24937 #else
24938  do{ fmt++; }while( *fmt && *fmt != '%' );
24939 #endif
24940  sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
24941  if( *fmt==0 ) break;
24942  }
24943  if( (c=(*++fmt))==0 ){
24944  sqlite3StrAccumAppend(pAccum, "%", 1);
24945  break;
24946  }
24947  /* Find out what flags are present */
24948  flag_leftjustify = flag_plussign = flag_blanksign =
24949  flag_alternateform = flag_altform2 = flag_zeropad = 0;
24950  done = 0;
24951  do{
24952  switch( c ){
24953  case '-': flag_leftjustify = 1; break;
24954  case '+': flag_plussign = 1; break;
24955  case ' ': flag_blanksign = 1; break;
24956  case '#': flag_alternateform = 1; break;
24957  case '!': flag_altform2 = 1; break;
24958  case '0': flag_zeropad = 1; break;
24959  default: done = 1; break;
24960  }
24961  }while( !done && (c=(*++fmt))!=0 );
24962  /* Get the field width */
24963  if( c=='*' ){
24964  if( bArgList ){
24965  width = (int)getIntArg(pArgList);
24966  }else{
24967  width = va_arg(ap,int);
24968  }
24969  if( width<0 ){
24970  flag_leftjustify = 1;
24971  width = width >= -2147483647 ? -width : 0;
24972  }
24973  c = *++fmt;
24974  }else{
24975  unsigned wx = 0;
24976  while( c>='0' && c<='9' ){
24977  wx = wx*10 + c - '0';
24978  c = *++fmt;
24979  }
24980  testcase( wx>0x7fffffff );
24981  width = wx & 0x7fffffff;
24982  }
24983  assert( width>=0 );
24984 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
24985  if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
24986  width = SQLITE_PRINTF_PRECISION_LIMIT;
24987  }
24988 #endif
24989 
24990  /* Get the precision */
24991  if( c=='.' ){
24992  c = *++fmt;
24993  if( c=='*' ){
24994  if( bArgList ){
24995  precision = (int)getIntArg(pArgList);
24996  }else{
24997  precision = va_arg(ap,int);
24998  }
24999  c = *++fmt;
25000  if( precision<0 ){
25001  precision = precision >= -2147483647 ? -precision : -1;
25002  }
25003  }else{
25004  unsigned px = 0;
25005  while( c>='0' && c<='9' ){
25006  px = px*10 + c - '0';
25007  c = *++fmt;
25008  }
25009  testcase( px>0x7fffffff );
25010  precision = px & 0x7fffffff;
25011  }
25012  }else{
25013  precision = -1;
25014  }
25015  assert( precision>=(-1) );
25016 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
25017  if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
25018  precision = SQLITE_PRINTF_PRECISION_LIMIT;
25019  }
25020 #endif
25021 
25022 
25023  /* Get the conversion type modifier */
25024  if( c=='l' ){
25025  flag_long = 1;
25026  c = *++fmt;
25027  if( c=='l' ){
25028  flag_longlong = 1;
25029  c = *++fmt;
25030  }else{
25031  flag_longlong = 0;
25032  }
25033  }else{
25034  flag_long = flag_longlong = 0;
25035  }
25036  /* Fetch the info entry for the field */
25037  infop = &fmtinfo[0];
25038  xtype = etINVALID;
25039  for(idx=0; idx<ArraySize(fmtinfo); idx++){
25040  if( c==fmtinfo[idx].fmttype ){
25041  infop = &fmtinfo[idx];
25042  if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
25043  xtype = infop->type;
25044  }else{
25045  return;
25046  }
25047  break;
25048  }
25049  }
25050 
25051  /*
25052  ** At this point, variables are initialized as follows:
25053  **
25054  ** flag_alternateform TRUE if a '#' is present.
25055  ** flag_altform2 TRUE if a '!' is present.
25056  ** flag_plussign TRUE if a '+' is present.
25057  ** flag_leftjustify TRUE if a '-' is present or if the
25058  ** field width was negative.
25059  ** flag_zeropad TRUE if the width began with 0.
25060  ** flag_long TRUE if the letter 'l' (ell) prefixed
25061  ** the conversion character.
25062  ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
25063  ** the conversion character.
25064  ** flag_blanksign TRUE if a ' ' is present.
25065  ** width The specified field width. This is
25066  ** always non-negative. Zero is the default.
25067  ** precision The specified precision. The default
25068  ** is -1.
25069  ** xtype The class of the conversion.
25070  ** infop Pointer to the appropriate info struct.
25071  */
25072  switch( xtype ){
25073  case etPOINTER:
25074  flag_longlong = sizeof(char*)==sizeof(i64);
25075  flag_long = sizeof(char*)==sizeof(long int);
25076  /* Fall through into the next case */
25077  case etORDINAL:
25078  case etRADIX:
25079  if( infop->flags & FLAG_SIGNED ){
25080  i64 v;
25081  if( bArgList ){
25082  v = getIntArg(pArgList);
25083  }else if( flag_longlong ){
25084  v = va_arg(ap,i64);
25085  }else if( flag_long ){
25086  v = va_arg(ap,long int);
25087  }else{
25088  v = va_arg(ap,int);
25089  }
25090  if( v<0 ){
25091  if( v==SMALLEST_INT64 ){
25092  longvalue = ((u64)1)<<63;
25093  }else{
25094  longvalue = -v;
25095  }
25096  prefix = '-';
25097  }else{
25098  longvalue = v;
25099  if( flag_plussign ) prefix = '+';
25100  else if( flag_blanksign ) prefix = ' ';
25101  else prefix = 0;
25102  }
25103  }else{
25104  if( bArgList ){
25105  longvalue = (u64)getIntArg(pArgList);
25106  }else if( flag_longlong ){
25107  longvalue = va_arg(ap,u64);
25108  }else if( flag_long ){
25109  longvalue = va_arg(ap,unsigned long int);
25110  }else{
25111  longvalue = va_arg(ap,unsigned int);
25112  }
25113  prefix = 0;
25114  }
25115  if( longvalue==0 ) flag_alternateform = 0;
25116  if( flag_zeropad && precision<width-(prefix!=0) ){
25117  precision = width-(prefix!=0);
25118  }
25119  if( precision<etBUFSIZE-10 ){
25120  nOut = etBUFSIZE;
25121  zOut = buf;
25122  }else{
25123  nOut = precision + 10;
25124  zOut = zExtra = sqlite3Malloc( nOut );
25125  if( zOut==0 ){
25127  return;
25128  }
25129  }
25130  bufpt = &zOut[nOut-1];
25131  if( xtype==etORDINAL ){
25132  static const char zOrd[] = "thstndrd";
25133  int x = (int)(longvalue % 10);
25134  if( x>=4 || (longvalue/10)%10==1 ){
25135  x = 0;
25136  }
25137  *(--bufpt) = zOrd[x*2+1];
25138  *(--bufpt) = zOrd[x*2];
25139  }
25140  {
25141  const char *cset = &aDigits[infop->charset];
25142  u8 base = infop->base;
25143  do{ /* Convert to ascii */
25144  *(--bufpt) = cset[longvalue%base];
25145  longvalue = longvalue/base;
25146  }while( longvalue>0 );
25147  }
25148  length = (int)(&zOut[nOut-1]-bufpt);
25149  for(idx=precision-length; idx>0; idx--){
25150  *(--bufpt) = '0'; /* Zero pad */
25151  }
25152  if( prefix ) *(--bufpt) = prefix; /* Add sign */
25153  if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
25154  const char *pre;
25155  char x;
25156  pre = &aPrefix[infop->prefix];
25157  for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25158  }
25159  length = (int)(&zOut[nOut-1]-bufpt);
25160  break;
25161  case etFLOAT:
25162  case etEXP:
25163  case etGENERIC:
25164  if( bArgList ){
25165  realvalue = getDoubleArg(pArgList);
25166  }else{
25167  realvalue = va_arg(ap,double);
25168  }
25169 #ifdef SQLITE_OMIT_FLOATING_POINT
25170  length = 0;
25171 #else
25172  if( precision<0 ) precision = 6; /* Set default precision */
25173  if( realvalue<0.0 ){
25174  realvalue = -realvalue;
25175  prefix = '-';
25176  }else{
25177  if( flag_plussign ) prefix = '+';
25178  else if( flag_blanksign ) prefix = ' ';
25179  else prefix = 0;
25180  }
25181  if( xtype==etGENERIC && precision>0 ) precision--;
25182  testcase( precision>0xfff );
25183  for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
25184  if( xtype==etFLOAT ) realvalue += rounder;
25185  /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
25186  exp = 0;
25187  if( sqlite3IsNaN((double)realvalue) ){
25188  bufpt = "NaN";
25189  length = 3;
25190  break;
25191  }
25192  if( realvalue>0.0 ){
25193  LONGDOUBLE_TYPE scale = 1.0;
25194  while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
25195  while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
25196  while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
25197  realvalue /= scale;
25198  while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
25199  while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
25200  if( exp>350 ){
25201  bufpt = buf;
25202  buf[0] = prefix;
25203  memcpy(buf+(prefix!=0),"Inf",4);
25204  length = 3+(prefix!=0);
25205  break;
25206  }
25207  }
25208  bufpt = buf;
25209  /*
25210  ** If the field type is etGENERIC, then convert to either etEXP
25211  ** or etFLOAT, as appropriate.
25212  */
25213  if( xtype!=etFLOAT ){
25214  realvalue += rounder;
25215  if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
25216  }
25217  if( xtype==etGENERIC ){
25218  flag_rtz = !flag_alternateform;
25219  if( exp<-4 || exp>precision ){
25220  xtype = etEXP;
25221  }else{
25222  precision = precision - exp;
25223  xtype = etFLOAT;
25224  }
25225  }else{
25226  flag_rtz = flag_altform2;
25227  }
25228  if( xtype==etEXP ){
25229  e2 = 0;
25230  }else{
25231  e2 = exp;
25232  }
25233  if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
25234  bufpt = zExtra
25235  = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
25236  if( bufpt==0 ){
25238  return;
25239  }
25240  }
25241  zOut = bufpt;
25242  nsd = 16 + flag_altform2*10;
25243  flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
25244  /* The sign in front of the number */
25245  if( prefix ){
25246  *(bufpt++) = prefix;
25247  }
25248  /* Digits prior to the decimal point */
25249  if( e2<0 ){
25250  *(bufpt++) = '0';
25251  }else{
25252  for(; e2>=0; e2--){
25253  *(bufpt++) = et_getdigit(&realvalue,&nsd);
25254  }
25255  }
25256  /* The decimal point */
25257  if( flag_dp ){
25258  *(bufpt++) = '.';
25259  }
25260  /* "0" digits after the decimal point but before the first
25261  ** significant digit of the number */
25262  for(e2++; e2<0; precision--, e2++){
25263  assert( precision>0 );
25264  *(bufpt++) = '0';
25265  }
25266  /* Significant digits after the decimal point */
25267  while( (precision--)>0 ){
25268  *(bufpt++) = et_getdigit(&realvalue,&nsd);
25269  }
25270  /* Remove trailing zeros and the "." if no digits follow the "." */
25271  if( flag_rtz && flag_dp ){
25272  while( bufpt[-1]=='0' ) *(--bufpt) = 0;
25273  assert( bufpt>zOut );
25274  if( bufpt[-1]=='.' ){
25275  if( flag_altform2 ){
25276  *(bufpt++) = '0';
25277  }else{
25278  *(--bufpt) = 0;
25279  }
25280  }
25281  }
25282  /* Add the "eNNN" suffix */
25283  if( xtype==etEXP ){
25284  *(bufpt++) = aDigits[infop->charset];
25285  if( exp<0 ){
25286  *(bufpt++) = '-'; exp = -exp;
25287  }else{
25288  *(bufpt++) = '+';
25289  }
25290  if( exp>=100 ){
25291  *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
25292  exp %= 100;
25293  }
25294  *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
25295  *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
25296  }
25297  *bufpt = 0;
25298 
25299  /* The converted number is in buf[] and zero terminated. Output it.
25300  ** Note that the number is in the usual order, not reversed as with
25301  ** integer conversions. */
25302  length = (int)(bufpt-zOut);
25303  bufpt = zOut;
25304 
25305  /* Special case: Add leading zeros if the flag_zeropad flag is
25306  ** set and we are not left justified */
25307  if( flag_zeropad && !flag_leftjustify && length < width){
25308  int i;
25309  int nPad = width - length;
25310  for(i=width; i>=nPad; i--){
25311  bufpt[i] = bufpt[i-nPad];
25312  }
25313  i = prefix!=0;
25314  while( nPad-- ) bufpt[i++] = '0';
25315  length = width;
25316  }
25317 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
25318  break;
25319  case etSIZE:
25320  if( !bArgList ){
25321  *(va_arg(ap,int*)) = pAccum->nChar;
25322  }
25323  length = width = 0;
25324  break;
25325  case etPERCENT:
25326  buf[0] = '%';
25327  bufpt = buf;
25328  length = 1;
25329  break;
25330  case etCHARX:
25331  if( bArgList ){
25332  bufpt = getTextArg(pArgList);
25333  c = bufpt ? bufpt[0] : 0;
25334  }else{
25335  c = va_arg(ap,int);
25336  }
25337  if( precision>1 ){
25338  width -= precision-1;
25339  if( width>1 && !flag_leftjustify ){
25340  sqlite3AppendChar(pAccum, width-1, ' ');
25341  width = 0;
25342  }
25343  sqlite3AppendChar(pAccum, precision-1, c);
25344  }
25345  length = 1;
25346  buf[0] = c;
25347  bufpt = buf;
25348  break;
25349  case etSTRING:
25350  case etDYNSTRING:
25351  if( bArgList ){
25352  bufpt = getTextArg(pArgList);
25353  xtype = etSTRING;
25354  }else{
25355  bufpt = va_arg(ap,char*);
25356  }
25357  if( bufpt==0 ){
25358  bufpt = "";
25359  }else if( xtype==etDYNSTRING ){
25360  zExtra = bufpt;
25361  }
25362  if( precision>=0 ){
25363  for(length=0; length<precision && bufpt[length]; length++){}
25364  }else{
25365  length = sqlite3Strlen30(bufpt);
25366  }
25367  break;
25368  case etSQLESCAPE: /* Escape ' characters */
25369  case etSQLESCAPE2: /* Escape ' and enclose in '...' */
25370  case etSQLESCAPE3: { /* Escape " characters */
25371  int i, j, k, n, isnull;
25372  int needQuote;
25373  char ch;
25374  char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
25375  char *escarg;
25376 
25377  if( bArgList ){
25378  escarg = getTextArg(pArgList);
25379  }else{
25380  escarg = va_arg(ap,char*);
25381  }
25382  isnull = escarg==0;
25383  if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25384  k = precision;
25385  for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
25386  if( ch==q ) n++;
25387  }
25388  needQuote = !isnull && xtype==etSQLESCAPE2;
25389  n += i + 3;
25390  if( n>etBUFSIZE ){
25391  bufpt = zExtra = sqlite3Malloc( n );
25392  if( bufpt==0 ){
25394  return;
25395  }
25396  }else{
25397  bufpt = buf;
25398  }
25399  j = 0;
25400  if( needQuote ) bufpt[j++] = q;
25401  k = i;
25402  for(i=0; i<k; i++){
25403  bufpt[j++] = ch = escarg[i];
25404  if( ch==q ) bufpt[j++] = ch;
25405  }
25406  if( needQuote ) bufpt[j++] = q;
25407  bufpt[j] = 0;
25408  length = j;
25409  /* The precision in %q and %Q means how many input characters to
25410  ** consume, not the length of the output...
25411  ** if( precision>=0 && precision<length ) length = precision; */
25412  break;
25413  }
25414  case etTOKEN: {
25415  Token *pToken = va_arg(ap, Token*);
25416  assert( bArgList==0 );
25417  if( pToken && pToken->n ){
25418  sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
25419  }
25420  length = width = 0;
25421  break;
25422  }
25423  case etSRCLIST: {
25424  SrcList *pSrc = va_arg(ap, SrcList*);
25425  int k = va_arg(ap, int);
25426  struct SrcList_item *pItem = &pSrc->a[k];
25427  assert( bArgList==0 );
25428  assert( k>=0 && k<pSrc->nSrc );
25429  if( pItem->zDatabase ){
25430  sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
25431  sqlite3StrAccumAppend(pAccum, ".", 1);
25432  }
25433  sqlite3StrAccumAppendAll(pAccum, pItem->zName);
25434  length = width = 0;
25435  break;
25436  }
25437  default: {
25438  assert( xtype==etINVALID );
25439  return;
25440  }
25441  }/* End switch over the format type */
25442  /*
25443  ** The text of the conversion is pointed to by "bufpt" and is
25444  ** "length" characters long. The field width is "width". Do
25445  ** the output.
25446  */
25447  width -= length;
25448  if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25449  sqlite3StrAccumAppend(pAccum, bufpt, length);
25450  if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25451 
25452  if( zExtra ){
25453  sqlite3DbFree(pAccum->db, zExtra);
25454  zExtra = 0;
25455  }
25456  }/* End for loop over the format string */
25457 } /* End of function */
25458 
25459 /*
25460 ** Enlarge the memory allocation on a StrAccum object so that it is
25461 ** able to accept at least N more bytes of text.
25462 **
25463 ** Return the number of bytes of text that StrAccum is able to accept
25464 ** after the attempted enlargement. The value returned might be zero.
25465 */
25466 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
25467  char *zNew;
25468  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
25469  if( p->accError ){
25472  return 0;
25473  }
25474  if( p->mxAlloc==0 ){
25475  N = p->nAlloc - p->nChar - 1;
25477  return N;
25478  }else{
25479  char *zOld = isMalloced(p) ? p->zText : 0;
25480  i64 szNew = p->nChar;
25481  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25482  szNew += N + 1;
25483  if( szNew+p->nChar<=p->mxAlloc ){
25484  /* Force exponential buffer size growth as long as it does not overflow,
25485  ** to avoid having to call this routine too often */
25486  szNew += p->nChar;
25487  }
25488  if( szNew > p->mxAlloc ){
25491  return 0;
25492  }else{
25493  p->nAlloc = (int)szNew;
25494  }
25495  if( p->db ){
25496  zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
25497  }else{
25498  zNew = sqlite3_realloc64(zOld, p->nAlloc);
25499  }
25500  if( zNew ){
25501  assert( p->zText!=0 || p->nChar==0 );
25502  if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
25503  p->zText = zNew;
25504  p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
25506  }else{
25509  return 0;
25510  }
25511  }
25512  return N;
25513 }
25514 
25515 /*
25516 ** Append N copies of character c to the given string buffer.
25517 */
25519  testcase( p->nChar + (i64)N > 0x7fffffff );
25520  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
25521  return;
25522  }
25523  assert( (p->zText==p->zBase)==!isMalloced(p) );
25524  while( (N--)>0 ) p->zText[p->nChar++] = c;
25525 }
25526 
25527 /*
25528 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
25529 ** So enlarge if first, then do the append.
25530 **
25531 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
25532 ** work (enlarging the buffer) using tail recursion, so that the
25533 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
25534 */
25535 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
25536  N = sqlite3StrAccumEnlarge(p, N);
25537  if( N>0 ){
25538  memcpy(&p->zText[p->nChar], z, N);
25539  p->nChar += N;
25540  }
25541  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25542 }
25543 
25544 /*
25545 ** Append N bytes of text from z to the StrAccum object. Increase the
25546 ** size of the memory allocation for StrAccum if necessary.
25547 */
25548 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
25549  assert( z!=0 || N==0 );
25550  assert( p->zText!=0 || p->nChar==0 || p->accError );
25551  assert( N>=0 );
25552  assert( p->accError==0 || p->nAlloc==0 );
25553  if( p->nChar+N >= p->nAlloc ){
25554  enlargeAndAppend(p,z,N);
25555  }else{
25556  assert( p->zText );
25557  p->nChar += N;
25558  memcpy(&p->zText[p->nChar-N], z, N);
25559  }
25560 }
25561 
25562 /*
25563 ** Append the complete text of zero-terminated string z[] to the p string.
25564 */
25567 }
25568 
25569 
25570 /*
25571 ** Finish off a string by making sure it is zero-terminated.
25572 ** Return a pointer to the resulting string. Return a NULL
25573 ** pointer if any kind of error was encountered.
25574 */
25576  if( p->zText ){
25577  assert( (p->zText==p->zBase)==!isMalloced(p) );
25578  p->zText[p->nChar] = 0;
25579  if( p->mxAlloc>0 && !isMalloced(p) ){
25580  p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
25581  if( p->zText ){
25582  memcpy(p->zText, p->zBase, p->nChar+1);
25584  }else{
25586  }
25587  }
25588  }
25589  return p->zText;
25590 }
25591 
25592 /*
25593 ** Reset an StrAccum string. Reclaim all malloced memory.
25594 */
25596  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25597  if( isMalloced(p) ){
25598  sqlite3DbFree(p->db, p->zText);
25600  }
25601  p->zText = 0;
25602 }
25603 
25604 /*
25605 ** Initialize a string accumulator.
25606 **
25607 ** p: The accumulator to be initialized.
25608 ** db: Pointer to a database connection. May be NULL. Lookaside
25609 ** memory is used if not NULL. db->mallocFailed is set appropriately
25610 ** when not NULL.
25611 ** zBase: An initial buffer. May be NULL in which case the initial buffer
25612 ** is malloced.
25613 ** n: Size of zBase in bytes. If total space requirements never exceed
25614 ** n then no memory allocations ever occur.
25615 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
25616 ** allocations will ever occur.
25617 */
25618 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
25619  p->zText = p->zBase = zBase;
25620  p->db = db;
25621  p->nChar = 0;
25622  p->nAlloc = n;
25623  p->mxAlloc = mx;
25624  p->accError = 0;
25625  p->printfFlags = 0;
25626 }
25627 
25628 /*
25629 ** Print into memory obtained from sqliteMalloc(). Use the internal
25630 ** %-conversion extensions.
25631 */
25632 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
25633  char *z;
25634  char zBase[SQLITE_PRINT_BUF_SIZE];
25635  StrAccum acc;
25636  assert( db!=0 );
25637  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
25640  sqlite3VXPrintf(&acc, zFormat, ap);
25641  z = sqlite3StrAccumFinish(&acc);
25642  if( acc.accError==STRACCUM_NOMEM ){
25643  sqlite3OomFault(db);
25644  }
25645  return z;
25646 }
25647 
25648 /*
25649 ** Print into memory obtained from sqliteMalloc(). Use the internal
25650 ** %-conversion extensions.
25651 */
25652 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
25653  va_list ap;
25654  char *z;
25655  va_start(ap, zFormat);
25656  z = sqlite3VMPrintf(db, zFormat, ap);
25657  va_end(ap);
25658  return z;
25659 }
25660 
25661 /*
25662 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
25663 ** %-conversion extensions.
25664 */
25665 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
25666  char *z;
25667  char zBase[SQLITE_PRINT_BUF_SIZE];
25668  StrAccum acc;
25669 
25670 #ifdef SQLITE_ENABLE_API_ARMOR
25671  if( zFormat==0 ){
25672  (void)SQLITE_MISUSE_BKPT;
25673  return 0;
25674  }
25675 #endif
25676 #ifndef SQLITE_OMIT_AUTOINIT
25677  if( sqlite3_initialize() ) return 0;
25678 #endif
25679  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
25680  sqlite3VXPrintf(&acc, zFormat, ap);
25681  z = sqlite3StrAccumFinish(&acc);
25682  return z;
25683 }
25684 
25685 /*
25686 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
25687 ** %-conversion extensions.
25688 */
25689 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
25690  va_list ap;
25691  char *z;
25692 #ifndef SQLITE_OMIT_AUTOINIT
25693  if( sqlite3_initialize() ) return 0;
25694 #endif
25695  va_start(ap, zFormat);
25696  z = sqlite3_vmprintf(zFormat, ap);
25697  va_end(ap);
25698  return z;
25699 }
25700 
25701 /*
25702 ** sqlite3_snprintf() works like snprintf() except that it ignores the
25703 ** current locale settings. This is important for SQLite because we
25704 ** are not able to use a "," as the decimal point in place of "." as
25705 ** specified by some locales.
25706 **
25707 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
25708 ** from the snprintf() standard. Unfortunately, it is too late to change
25709 ** this without breaking compatibility, so we just have to live with the
25710 ** mistake.
25711 **
25712 ** sqlite3_vsnprintf() is the varargs version.
25713 */
25714 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
25715  StrAccum acc;
25716  if( n<=0 ) return zBuf;
25717 #ifdef SQLITE_ENABLE_API_ARMOR
25718  if( zBuf==0 || zFormat==0 ) {
25719  (void)SQLITE_MISUSE_BKPT;
25720  if( zBuf ) zBuf[0] = 0;
25721  return zBuf;
25722  }
25723 #endif
25724  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
25725  sqlite3VXPrintf(&acc, zFormat, ap);
25726  return sqlite3StrAccumFinish(&acc);
25727 }
25728 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
25729  char *z;
25730  va_list ap;
25731  va_start(ap,zFormat);
25732  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
25733  va_end(ap);
25734  return z;
25735 }
25736 
25737 /*
25738 ** This is the routine that actually formats the sqlite3_log() message.
25739 ** We house it in a separate routine from sqlite3_log() to avoid using
25740 ** stack space on small-stack systems when logging is disabled.
25741 **
25742 ** sqlite3_log() must render into a static buffer. It cannot dynamically
25743 ** allocate memory because it might be called while the memory allocator
25744 ** mutex is held.
25745 **
25746 ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
25747 ** certain format characters (%q) or for very large precisions or widths.
25748 ** Care must be taken that any sqlite3_log() calls that occur while the
25749 ** memory mutex is held do not use these mechanisms.
25750 */
25751 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
25752  StrAccum acc; /* String accumulator */
25753  char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
25754 
25755  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
25756  sqlite3VXPrintf(&acc, zFormat, ap);
25757  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
25758  sqlite3StrAccumFinish(&acc));
25759 }
25760 
25761 /*
25762 ** Format and write a message to the log if logging is enabled.
25763 */
25764 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
25765  va_list ap; /* Vararg list */
25766  if( sqlite3GlobalConfig.xLog ){
25767  va_start(ap, zFormat);
25768  renderLogMsg(iErrCode, zFormat, ap);
25769  va_end(ap);
25770  }
25771 }
25772 
25773 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
25774 /*
25775 ** A version of printf() that understands %lld. Used for debugging.
25776 ** The printf() built into some versions of windows does not understand %lld
25777 ** and segfaults if you give it a long long int.
25778 */
25779 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
25780  va_list ap;
25781  StrAccum acc;
25782  char zBuf[500];
25783  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25784  va_start(ap,zFormat);
25785  sqlite3VXPrintf(&acc, zFormat, ap);
25786  va_end(ap);
25787  sqlite3StrAccumFinish(&acc);
25788  fprintf(stdout,"%s", zBuf);
25789  fflush(stdout);
25790 }
25791 #endif
25792 
25793 
25794 /*
25795 ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
25796 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
25797 */
25798 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
25799  va_list ap;
25800  va_start(ap,zFormat);
25801  sqlite3VXPrintf(p, zFormat, ap);
25802  va_end(ap);
25803 }
25804 
25805 /************** End of printf.c **********************************************/
25806 /************** Begin file treeview.c ****************************************/
25807 /*
25808 ** 2015-06-08
25809 **
25810 ** The author disclaims copyright to this source code. In place of
25811 ** a legal notice, here is a blessing:
25812 **
25813 ** May you do good and not evil.
25814 ** May you find forgiveness for yourself and forgive others.
25815 ** May you share freely, never taking more than you give.
25816 **
25817 *************************************************************************
25818 **
25819 ** This file contains C code to implement the TreeView debugging routines.
25820 ** These routines print a parse tree to standard output for debugging and
25821 ** analysis.
25822 **
25823 ** The interfaces in this file is only available when compiling
25824 ** with SQLITE_DEBUG.
25825 */
25826 /* #include "sqliteInt.h" */
25827 #ifdef SQLITE_DEBUG
25828 
25829 /*
25830 ** Add a new subitem to the tree. The moreToFollow flag indicates that this
25831 ** is not the last item in the tree.
25832 */
25833 static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
25834  if( p==0 ){
25835  p = sqlite3_malloc64( sizeof(*p) );
25836  if( p==0 ) return 0;
25837  memset(p, 0, sizeof(*p));
25838  }else{
25839  p->iLevel++;
25840  }
25841  assert( moreToFollow==0 || moreToFollow==1 );
25842  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
25843  return p;
25844 }
25845 
25846 /*
25847 ** Finished with one layer of the tree
25848 */
25849 static void sqlite3TreeViewPop(TreeView *p){
25850  if( p==0 ) return;
25851  p->iLevel--;
25852  if( p->iLevel<0 ) sqlite3_free(p);
25853 }
25854 
25855 /*
25856 ** Generate a single line of output for the tree, with a prefix that contains
25857 ** all the appropriate tree lines
25858 */
25859 static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
25860  va_list ap;
25861  int i;
25862  StrAccum acc;
25863  char zBuf[500];
25864  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25865  if( p ){
25866  for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
25867  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
25868  }
25869  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
25870  }
25871  va_start(ap, zFormat);
25872  sqlite3VXPrintf(&acc, zFormat, ap);
25873  va_end(ap);
25874  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
25875  sqlite3StrAccumFinish(&acc);
25876  fprintf(stdout,"%s", zBuf);
25877  fflush(stdout);
25878 }
25879 
25880 /*
25881 ** Shorthand for starting a new tree item that consists of a single label
25882 */
25883 static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
25884  p = sqlite3TreeViewPush(p, moreFollows);
25885  sqlite3TreeViewLine(p, "%s", zLabel);
25886 }
25887 
25888 /*
25889 ** Generate a human-readable description of a WITH clause.
25890 */
25891 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
25892  int i;
25893  if( pWith==0 ) return;
25894  if( pWith->nCte==0 ) return;
25895  if( pWith->pOuter ){
25896  sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
25897  }else{
25898  sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
25899  }
25900  if( pWith->nCte>0 ){
25901  pView = sqlite3TreeViewPush(pView, 1);
25902  for(i=0; i<pWith->nCte; i++){
25903  StrAccum x;
25904  char zLine[1000];
25905  const struct Cte *pCte = &pWith->a[i];
25906  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25907  sqlite3XPrintf(&x, "%s", pCte->zName);
25908  if( pCte->pCols && pCte->pCols->nExpr>0 ){
25909  char cSep = '(';
25910  int j;
25911  for(j=0; j<pCte->pCols->nExpr; j++){
25912  sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
25913  cSep = ',';
25914  }
25915  sqlite3XPrintf(&x, ")");
25916  }
25917  sqlite3XPrintf(&x, " AS");
25919  sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
25920  sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
25921  sqlite3TreeViewPop(pView);
25922  }
25923  sqlite3TreeViewPop(pView);
25924  }
25925 }
25926 
25927 
25928 /*
25929 ** Generate a human-readable description of a Select object.
25930 */
25931 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
25932  int n = 0;
25933  int cnt = 0;
25934  pView = sqlite3TreeViewPush(pView, moreToFollow);
25935  if( p->pWith ){
25936  sqlite3TreeViewWith(pView, p->pWith, 1);
25937  cnt = 1;
25938  sqlite3TreeViewPush(pView, 1);
25939  }
25940  do{
25941  sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
25942  ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
25943  ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
25944  (int)p->nSelectRow
25945  );
25946  if( cnt++ ) sqlite3TreeViewPop(pView);
25947  if( p->pPrior ){
25948  n = 1000;
25949  }else{
25950  n = 0;
25951  if( p->pSrc && p->pSrc->nSrc ) n++;
25952  if( p->pWhere ) n++;
25953  if( p->pGroupBy ) n++;
25954  if( p->pHaving ) n++;
25955  if( p->pOrderBy ) n++;
25956  if( p->pLimit ) n++;
25957  if( p->pOffset ) n++;
25958  }
25959  sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
25960  if( p->pSrc && p->pSrc->nSrc ){
25961  int i;
25962  pView = sqlite3TreeViewPush(pView, (n--)>0);
25963  sqlite3TreeViewLine(pView, "FROM");
25964  for(i=0; i<p->pSrc->nSrc; i++){
25965  struct SrcList_item *pItem = &p->pSrc->a[i];
25966  StrAccum x;
25967  char zLine[100];
25968  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25969  sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
25970  if( pItem->zDatabase ){
25971  sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
25972  }else if( pItem->zName ){
25973  sqlite3XPrintf(&x, " %s", pItem->zName);
25974  }
25975  if( pItem->pTab ){
25976  sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
25977  }
25978  if( pItem->zAlias ){
25979  sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
25980  }
25981  if( pItem->fg.jointype & JT_LEFT ){
25982  sqlite3XPrintf(&x, " LEFT-JOIN");
25983  }
25985  sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
25986  if( pItem->pSelect ){
25987  sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
25988  }
25989  if( pItem->fg.isTabFunc ){
25990  sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
25991  }
25992  sqlite3TreeViewPop(pView);
25993  }
25994  sqlite3TreeViewPop(pView);
25995  }
25996  if( p->pWhere ){
25997  sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
25998  sqlite3TreeViewExpr(pView, p->pWhere, 0);
25999  sqlite3TreeViewPop(pView);
26000  }
26001  if( p->pGroupBy ){
26002  sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
26003  }
26004  if( p->pHaving ){
26005  sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
26006  sqlite3TreeViewExpr(pView, p->pHaving, 0);
26007  sqlite3TreeViewPop(pView);
26008  }
26009  if( p->pOrderBy ){
26010  sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
26011  }
26012  if( p->pLimit ){
26013  sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
26014  sqlite3TreeViewExpr(pView, p->pLimit, 0);
26015  sqlite3TreeViewPop(pView);
26016  }
26017  if( p->pOffset ){
26018  sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
26019  sqlite3TreeViewExpr(pView, p->pOffset, 0);
26020  sqlite3TreeViewPop(pView);
26021  }
26022  if( p->pPrior ){
26023  const char *zOp = "UNION";
26024  switch( p->op ){
26025  case TK_ALL: zOp = "UNION ALL"; break;
26026  case TK_INTERSECT: zOp = "INTERSECT"; break;
26027  case TK_EXCEPT: zOp = "EXCEPT"; break;
26028  }
26029  sqlite3TreeViewItem(pView, zOp, 1);
26030  }
26031  p = p->pPrior;
26032  }while( p!=0 );
26033  sqlite3TreeViewPop(pView);
26034 }
26035 
26036 /*
26037 ** Generate a human-readable explanation of an expression tree.
26038 */
26039 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
26040  const char *zBinOp = 0; /* Binary operator */
26041  const char *zUniOp = 0; /* Unary operator */
26042  char zFlgs[30];
26043  pView = sqlite3TreeViewPush(pView, moreToFollow);
26044  if( pExpr==0 ){
26045  sqlite3TreeViewLine(pView, "nil");
26046  sqlite3TreeViewPop(pView);
26047  return;
26048  }
26049  if( pExpr->flags ){
26050  sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
26051  }else{
26052  zFlgs[0] = 0;
26053  }
26054  switch( pExpr->op ){
26055  case TK_AGG_COLUMN: {
26056  sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26057  pExpr->iTable, pExpr->iColumn, zFlgs);
26058  break;
26059  }
26060  case TK_COLUMN: {
26061  if( pExpr->iTable<0 ){
26062  /* This only happens when coding check constraints */
26063  sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26064  }else{
26065  sqlite3TreeViewLine(pView, "{%d:%d}%s",
26066  pExpr->iTable, pExpr->iColumn, zFlgs);
26067  }
26068  break;
26069  }
26070  case TK_INTEGER: {
26071  if( pExpr->flags & EP_IntValue ){
26072  sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26073  }else{
26074  sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26075  }
26076  break;
26077  }
26078 #ifndef SQLITE_OMIT_FLOATING_POINT
26079  case TK_FLOAT: {
26080  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26081  break;
26082  }
26083 #endif
26084  case TK_STRING: {
26085  sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26086  break;
26087  }
26088  case TK_NULL: {
26089  sqlite3TreeViewLine(pView,"NULL");
26090  break;
26091  }
26092 #ifndef SQLITE_OMIT_BLOB_LITERAL
26093  case TK_BLOB: {
26094  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26095  break;
26096  }
26097 #endif
26098  case TK_VARIABLE: {
26099  sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
26100  pExpr->u.zToken, pExpr->iColumn);
26101  break;
26102  }
26103  case TK_REGISTER: {
26104  sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
26105  break;
26106  }
26107  case TK_ID: {
26108  sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
26109  break;
26110  }
26111 #ifndef SQLITE_OMIT_CAST
26112  case TK_CAST: {
26113  /* Expressions of the form: CAST(pLeft AS token) */
26114  sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
26115  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26116  break;
26117  }
26118 #endif /* SQLITE_OMIT_CAST */
26119  case TK_LT: zBinOp = "LT"; break;
26120  case TK_LE: zBinOp = "LE"; break;
26121  case TK_GT: zBinOp = "GT"; break;
26122  case TK_GE: zBinOp = "GE"; break;
26123  case TK_NE: zBinOp = "NE"; break;
26124  case TK_EQ: zBinOp = "EQ"; break;
26125  case TK_IS: zBinOp = "IS"; break;
26126  case TK_ISNOT: zBinOp = "ISNOT"; break;
26127  case TK_AND: zBinOp = "AND"; break;
26128  case TK_OR: zBinOp = "OR"; break;
26129  case TK_PLUS: zBinOp = "ADD"; break;
26130  case TK_STAR: zBinOp = "MUL"; break;
26131  case TK_MINUS: zBinOp = "SUB"; break;
26132  case TK_REM: zBinOp = "REM"; break;
26133  case TK_BITAND: zBinOp = "BITAND"; break;
26134  case TK_BITOR: zBinOp = "BITOR"; break;
26135  case TK_SLASH: zBinOp = "DIV"; break;
26136  case TK_LSHIFT: zBinOp = "LSHIFT"; break;
26137  case TK_RSHIFT: zBinOp = "RSHIFT"; break;
26138  case TK_CONCAT: zBinOp = "CONCAT"; break;
26139  case TK_DOT: zBinOp = "DOT"; break;
26140 
26141  case TK_UMINUS: zUniOp = "UMINUS"; break;
26142  case TK_UPLUS: zUniOp = "UPLUS"; break;
26143  case TK_BITNOT: zUniOp = "BITNOT"; break;
26144  case TK_NOT: zUniOp = "NOT"; break;
26145  case TK_ISNULL: zUniOp = "ISNULL"; break;
26146  case TK_NOTNULL: zUniOp = "NOTNULL"; break;
26147 
26148  case TK_SPAN: {
26149  sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
26150  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26151  break;
26152  }
26153 
26154  case TK_COLLATE: {
26155  sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
26156  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26157  break;
26158  }
26159 
26160  case TK_AGG_FUNCTION:
26161  case TK_FUNCTION: {
26162  ExprList *pFarg; /* List of function arguments */
26163  if( ExprHasProperty(pExpr, EP_TokenOnly) ){
26164  pFarg = 0;
26165  }else{
26166  pFarg = pExpr->x.pList;
26167  }
26168  if( pExpr->op==TK_AGG_FUNCTION ){
26169  sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
26170  pExpr->op2, pExpr->u.zToken);
26171  }else{
26172  sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
26173  }
26174  if( pFarg ){
26175  sqlite3TreeViewExprList(pView, pFarg, 0, 0);
26176  }
26177  break;
26178  }
26179 #ifndef SQLITE_OMIT_SUBQUERY
26180  case TK_EXISTS: {
26181  sqlite3TreeViewLine(pView, "EXISTS-expr");
26182  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26183  break;
26184  }
26185  case TK_SELECT: {
26186  sqlite3TreeViewLine(pView, "SELECT-expr");
26187  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26188  break;
26189  }
26190  case TK_IN: {
26191  sqlite3TreeViewLine(pView, "IN");
26192  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26193  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26194  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26195  }else{
26196  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26197  }
26198  break;
26199  }
26200 #endif /* SQLITE_OMIT_SUBQUERY */
26201 
26202  /*
26203  ** x BETWEEN y AND z
26204  **
26205  ** This is equivalent to
26206  **
26207  ** x>=y AND x<=z
26208  **
26209  ** X is stored in pExpr->pLeft.
26210  ** Y is stored in pExpr->pList->a[0].pExpr.
26211  ** Z is stored in pExpr->pList->a[1].pExpr.
26212  */
26213  case TK_BETWEEN: {
26214  Expr *pX = pExpr->pLeft;
26215  Expr *pY = pExpr->x.pList->a[0].pExpr;
26216  Expr *pZ = pExpr->x.pList->a[1].pExpr;
26217  sqlite3TreeViewLine(pView, "BETWEEN");
26218  sqlite3TreeViewExpr(pView, pX, 1);
26219  sqlite3TreeViewExpr(pView, pY, 1);
26220  sqlite3TreeViewExpr(pView, pZ, 0);
26221  break;
26222  }
26223  case TK_TRIGGER: {
26224  /* If the opcode is TK_TRIGGER, then the expression is a reference
26225  ** to a column in the new.* or old.* pseudo-tables available to
26226  ** trigger programs. In this case Expr.iTable is set to 1 for the
26227  ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
26228  ** is set to the column of the pseudo-table to read, or to -1 to
26229  ** read the rowid field.
26230  */
26231  sqlite3TreeViewLine(pView, "%s(%d)",
26232  pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
26233  break;
26234  }
26235  case TK_CASE: {
26236  sqlite3TreeViewLine(pView, "CASE");
26237  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26238  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26239  break;
26240  }
26241 #ifndef SQLITE_OMIT_TRIGGER
26242  case TK_RAISE: {
26243  const char *zType = "unk";
26244  switch( pExpr->affinity ){
26245  case OE_Rollback: zType = "rollback"; break;
26246  case OE_Abort: zType = "abort"; break;
26247  case OE_Fail: zType = "fail"; break;
26248  case OE_Ignore: zType = "ignore"; break;
26249  }
26250  sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
26251  break;
26252  }
26253 #endif
26254  case TK_MATCH: {
26255  sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
26256  pExpr->iTable, pExpr->iColumn, zFlgs);
26257  sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26258  break;
26259  }
26260  case TK_VECTOR: {
26261  sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
26262  break;
26263  }
26264  case TK_SELECT_COLUMN: {
26265  sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
26266  sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
26267  break;
26268  }
26269  default: {
26270  sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
26271  break;
26272  }
26273  }
26274  if( zBinOp ){
26275  sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
26276  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26277  sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26278  }else if( zUniOp ){
26279  sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
26280  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26281  }
26282  sqlite3TreeViewPop(pView);
26283 }
26284 
26285 
26286 /*
26287 ** Generate a human-readable explanation of an expression list.
26288 */
26289 SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
26290  TreeView *pView,
26291  const ExprList *pList,
26292  const char *zLabel
26293 ){
26294  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
26295  if( pList==0 ){
26296  sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
26297  }else{
26298  int i;
26299  sqlite3TreeViewLine(pView, "%s", zLabel);
26300  for(i=0; i<pList->nExpr; i++){
26301  int j = pList->a[i].u.x.iOrderByCol;
26302  if( j ){
26303  sqlite3TreeViewPush(pView, 0);
26304  sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
26305  }
26306  sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
26307  if( j ) sqlite3TreeViewPop(pView);
26308  }
26309  }
26310 }
26311 SQLITE_PRIVATE void sqlite3TreeViewExprList(
26312  TreeView *pView,
26313  const ExprList *pList,
26314  u8 moreToFollow,
26315  const char *zLabel
26316 ){
26317  pView = sqlite3TreeViewPush(pView, moreToFollow);
26318  sqlite3TreeViewBareExprList(pView, pList, zLabel);
26319  sqlite3TreeViewPop(pView);
26320 }
26321 
26322 #endif /* SQLITE_DEBUG */
26323 
26324 /************** End of treeview.c ********************************************/
26325 /************** Begin file random.c ******************************************/
26326 /*
26327 ** 2001 September 15
26328 **
26329 ** The author disclaims copyright to this source code. In place of
26330 ** a legal notice, here is a blessing:
26331 **
26332 ** May you do good and not evil.
26333 ** May you find forgiveness for yourself and forgive others.
26334 ** May you share freely, never taking more than you give.
26335 **
26336 *************************************************************************
26337 ** This file contains code to implement a pseudo-random number
26338 ** generator (PRNG) for SQLite.
26339 **
26340 ** Random numbers are used by some of the database backends in order
26341 ** to generate random integer keys for tables or random filenames.
26342 */
26343 /* #include "sqliteInt.h" */
26344 
26345 
26346 /* All threads share a single random number generator.
26347 ** This structure is the current state of the generator.
26348 */
26350  unsigned char isInit; /* True if initialized */
26351  unsigned char i, j; /* State variables */
26352  unsigned char s[256]; /* State variables */
26353 } sqlite3Prng;
26354 
26355 /*
26356 ** Return N random bytes.
26357 */
26358 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
26359  unsigned char t;
26360  unsigned char *zBuf = pBuf;
26361 
26362  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
26363  ** state vector. If writable static data is unsupported on the target,
26364  ** we have to locate the state vector at run-time. In the more common
26365  ** case where writable static data is supported, wsdPrng can refer directly
26366  ** to the "sqlite3Prng" state vector declared above.
26367  */
26368 #ifdef SQLITE_OMIT_WSD
26369  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
26370 # define wsdPrng p[0]
26371 #else
26372 # define wsdPrng sqlite3Prng
26373 #endif
26374 
26375 #if SQLITE_THREADSAFE
26376  sqlite3_mutex *mutex;
26377 #endif
26378 
26379 #ifndef SQLITE_OMIT_AUTOINIT
26380  if( sqlite3_initialize() ) return;
26381 #endif
26382 
26383 #if SQLITE_THREADSAFE
26385 #endif
26386 
26387  sqlite3_mutex_enter(mutex);
26388  if( N<=0 || pBuf==0 ){
26389  wsdPrng.isInit = 0;
26390  sqlite3_mutex_leave(mutex);
26391  return;
26392  }
26393 
26394  /* Initialize the state of the random number generator once,
26395  ** the first time this routine is called. The seed value does
26396  ** not need to contain a lot of randomness since we are not
26397  ** trying to do secure encryption or anything like that...
26398  **
26399  ** Nothing in this file or anywhere else in SQLite does any kind of
26400  ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
26401  ** number generator) not as an encryption device.
26402  */
26403  if( !wsdPrng.isInit ){
26404  int i;
26405  char k[256];
26406  wsdPrng.j = 0;
26407  wsdPrng.i = 0;
26409  for(i=0; i<256; i++){
26410  wsdPrng.s[i] = (u8)i;
26411  }
26412  for(i=0; i<256; i++){
26413  wsdPrng.j += wsdPrng.s[i] + k[i];
26414  t = wsdPrng.s[wsdPrng.j];
26415  wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
26416  wsdPrng.s[i] = t;
26417  }
26418  wsdPrng.isInit = 1;
26419  }
26420 
26421  assert( N>0 );
26422  do{
26423  wsdPrng.i++;
26424  t = wsdPrng.s[wsdPrng.i];
26425  wsdPrng.j += t;
26426  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
26427  wsdPrng.s[wsdPrng.j] = t;
26428  t += wsdPrng.s[wsdPrng.i];
26429  *(zBuf++) = wsdPrng.s[t];
26430  }while( --N );
26431  sqlite3_mutex_leave(mutex);
26432 }
26433 
26434 #ifndef SQLITE_OMIT_BUILTIN_TEST
26435 /*
26436 ** For testing purposes, we sometimes want to preserve the state of
26437 ** PRNG and restore the PRNG to its saved state at a later time, or
26438 ** to reset the PRNG to its initial state. These routines accomplish
26439 ** those tasks.
26440 **
26441 ** The sqlite3_test_control() interface calls these routines to
26442 ** control the PRNG.
26443 */
26446  memcpy(
26449  sizeof(sqlite3Prng)
26450  );
26451 }
26453  memcpy(
26456  sizeof(sqlite3Prng)
26457  );
26458 }
26459 #endif /* SQLITE_OMIT_BUILTIN_TEST */
26460 
26461 /************** End of random.c **********************************************/
26462 /************** Begin file threads.c *****************************************/
26463 /*
26464 ** 2012 July 21
26465 **
26466 ** The author disclaims copyright to this source code. In place of
26467 ** a legal notice, here is a blessing:
26468 **
26469 ** May you do good and not evil.
26470 ** May you find forgiveness for yourself and forgive others.
26471 ** May you share freely, never taking more than you give.
26472 **
26473 ******************************************************************************
26474 **
26475 ** This file presents a simple cross-platform threading interface for
26476 ** use internally by SQLite.
26477 **
26478 ** A "thread" can be created using sqlite3ThreadCreate(). This thread
26479 ** runs independently of its creator until it is joined using
26480 ** sqlite3ThreadJoin(), at which point it terminates.
26481 **
26482 ** Threads do not have to be real. It could be that the work of the
26483 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
26484 ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
26485 ** single threaded systems. Nothing in SQLite requires multiple threads.
26486 ** This interface exists so that applications that want to take advantage
26487 ** of multiple cores can do so, while also allowing applications to stay
26488 ** single-threaded if desired.
26489 */
26490 /* #include "sqliteInt.h" */
26491 #if SQLITE_OS_WIN
26492 /* # include "os_win.h" */
26493 #endif
26494 
26495 #if SQLITE_MAX_WORKER_THREADS>0
26496 
26497 /********************************* Unix Pthreads ****************************/
26498 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
26499 
26500 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26501 /* #include <pthread.h> */
26502 
26503 /* A running thread */
26505  pthread_t tid; /* Thread ID */
26506  int done; /* Set to true when thread finishes */
26507  void *pOut; /* Result returned by the thread */
26508  void *(*xTask)(void*); /* The thread routine */
26509  void *pIn; /* Argument to the thread */
26510 };
26511 
26512 /* Create a new thread */
26514  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26515  void *(*xTask)(void*), /* Routine to run in a separate thread */
26516  void *pIn /* Argument passed into xTask() */
26517 ){
26518  SQLiteThread *p;
26519  int rc;
26520 
26521  assert( ppThread!=0 );
26522  assert( xTask!=0 );
26523  /* This routine is never used in single-threaded mode */
26524  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
26525 
26526  *ppThread = 0;
26527  p = sqlite3Malloc(sizeof(*p));
26528  if( p==0 ) return SQLITE_NOMEM_BKPT;
26529  memset(p, 0, sizeof(*p));
26530  p->xTask = xTask;
26531  p->pIn = pIn;
26532  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26533  ** function that returns SQLITE_ERROR when passed the argument 200, that
26534  ** forces worker threads to run sequentially and deterministically
26535  ** for testing purposes. */
26536  if( sqlite3FaultSim(200) ){
26537  rc = 1;
26538  }else{
26539  rc = pthread_create(&p->tid, 0, xTask, pIn);
26540  }
26541  if( rc ){
26542  p->done = 1;
26543  p->pOut = xTask(pIn);
26544  }
26545  *ppThread = p;
26546  return SQLITE_OK;
26547 }
26548 
26549 /* Get the results of the thread */
26551  int rc;
26552 
26553  assert( ppOut!=0 );
26554  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26555  if( p->done ){
26556  *ppOut = p->pOut;
26557  rc = SQLITE_OK;
26558  }else{
26559  rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
26560  }
26561  sqlite3_free(p);
26562  return rc;
26563 }
26564 
26565 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
26566 /******************************** End Unix Pthreads *************************/
26567 
26568 
26569 /********************************* Win32 Threads ****************************/
26570 #if SQLITE_OS_WIN_THREADS
26571 
26572 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26573 #include <process.h>
26574 
26575 /* A running thread */
26576 struct SQLiteThread {
26577  void *tid; /* The thread handle */
26578  unsigned id; /* The thread identifier */
26579  void *(*xTask)(void*); /* The routine to run as a thread */
26580  void *pIn; /* Argument to xTask */
26581  void *pResult; /* Result of xTask */
26582 };
26583 
26584 /* Thread procedure Win32 compatibility shim */
26585 static unsigned __stdcall sqlite3ThreadProc(
26586  void *pArg /* IN: Pointer to the SQLiteThread structure */
26587 ){
26588  SQLiteThread *p = (SQLiteThread *)pArg;
26589 
26590  assert( p!=0 );
26591 #if 0
26592  /*
26593  ** This assert appears to trigger spuriously on certain
26594  ** versions of Windows, possibly due to _beginthreadex()
26595  ** and/or CreateThread() not fully setting their thread
26596  ** ID parameter before starting the thread.
26597  */
26598  assert( p->id==GetCurrentThreadId() );
26599 #endif
26600  assert( p->xTask!=0 );
26601  p->pResult = p->xTask(p->pIn);
26602 
26603  _endthreadex(0);
26604  return 0; /* NOT REACHED */
26605 }
26606 
26607 /* Create a new thread */
26609  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26610  void *(*xTask)(void*), /* Routine to run in a separate thread */
26611  void *pIn /* Argument passed into xTask() */
26612 ){
26613  SQLiteThread *p;
26614 
26615  assert( ppThread!=0 );
26616  assert( xTask!=0 );
26617  *ppThread = 0;
26618  p = sqlite3Malloc(sizeof(*p));
26619  if( p==0 ) return SQLITE_NOMEM_BKPT;
26620  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26621  ** function that returns SQLITE_ERROR when passed the argument 200, that
26622  ** forces worker threads to run sequentially and deterministically
26623  ** (via the sqlite3FaultSim() term of the conditional) for testing
26624  ** purposes. */
26625  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
26626  memset(p, 0, sizeof(*p));
26627  }else{
26628  p->xTask = xTask;
26629  p->pIn = pIn;
26630  p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
26631  if( p->tid==0 ){
26632  memset(p, 0, sizeof(*p));
26633  }
26634  }
26635  if( p->xTask==0 ){
26636  p->id = GetCurrentThreadId();
26637  p->pResult = xTask(pIn);
26638  }
26639  *ppThread = p;
26640  return SQLITE_OK;
26641 }
26642 
26643 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
26644 
26645 /* Get the results of the thread */
26646 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26647  DWORD rc;
26648  BOOL bRc;
26649 
26650  assert( ppOut!=0 );
26651  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26652  if( p->xTask==0 ){
26653  /* assert( p->id==GetCurrentThreadId() ); */
26654  rc = WAIT_OBJECT_0;
26655  assert( p->tid==0 );
26656  }else{
26657  assert( p->id!=0 && p->id!=GetCurrentThreadId() );
26658  rc = sqlite3Win32Wait((HANDLE)p->tid);
26659  assert( rc!=WAIT_IO_COMPLETION );
26660  bRc = CloseHandle((HANDLE)p->tid);
26661  assert( bRc );
26662  }
26663  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
26664  sqlite3_free(p);
26665  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
26666 }
26667 
26668 #endif /* SQLITE_OS_WIN_THREADS */
26669 /******************************** End Win32 Threads *************************/
26670 
26671 
26672 /********************************* Single-Threaded **************************/
26673 #ifndef SQLITE_THREADS_IMPLEMENTED
26674 /*
26675 ** This implementation does not actually create a new thread. It does the
26676 ** work of the thread in the main thread, when either the thread is created
26677 ** or when it is joined
26678 */
26679 
26680 /* A running thread */
26681 struct SQLiteThread {
26682  void *(*xTask)(void*); /* The routine to run as a thread */
26683  void *pIn; /* Argument to xTask */
26684  void *pResult; /* Result of xTask */
26685 };
26686 
26687 /* Create a new thread */
26689  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26690  void *(*xTask)(void*), /* Routine to run in a separate thread */
26691  void *pIn /* Argument passed into xTask() */
26692 ){
26693  SQLiteThread *p;
26694 
26695  assert( ppThread!=0 );
26696  assert( xTask!=0 );
26697  *ppThread = 0;
26698  p = sqlite3Malloc(sizeof(*p));
26699  if( p==0 ) return SQLITE_NOMEM_BKPT;
26700  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
26701  p->xTask = xTask;
26702  p->pIn = pIn;
26703  }else{
26704  p->xTask = 0;
26705  p->pResult = xTask(pIn);
26706  }
26707  *ppThread = p;
26708  return SQLITE_OK;
26709 }
26710 
26711 /* Get the results of the thread */
26712 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26713 
26714  assert( ppOut!=0 );
26715  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26716  if( p->xTask ){
26717  *ppOut = p->xTask(p->pIn);
26718  }else{
26719  *ppOut = p->pResult;
26720  }
26721  sqlite3_free(p);
26722 
26723 #if defined(SQLITE_TEST)
26724  {
26725  void *pTstAlloc = sqlite3Malloc(10);
26726  if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
26727  sqlite3_free(pTstAlloc);
26728  }
26729 #endif
26730 
26731  return SQLITE_OK;
26732 }
26733 
26734 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
26735 /****************************** End Single-Threaded *************************/
26736 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
26737 
26738 /************** End of threads.c *********************************************/
26739 /************** Begin file utf.c *********************************************/
26740 /*
26741 ** 2004 April 13
26742 **
26743 ** The author disclaims copyright to this source code. In place of
26744 ** a legal notice, here is a blessing:
26745 **
26746 ** May you do good and not evil.
26747 ** May you find forgiveness for yourself and forgive others.
26748 ** May you share freely, never taking more than you give.
26749 **
26750 *************************************************************************
26751 ** This file contains routines used to translate between UTF-8,
26752 ** UTF-16, UTF-16BE, and UTF-16LE.
26753 **
26754 ** Notes on UTF-8:
26755 **
26756 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
26757 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
26758 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
26759 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
26760 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26761 **
26762 **
26763 ** Notes on UTF-16: (with wwww+1==uuuuu)
26764 **
26765 ** Word-0 Word-1 Value
26766 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26767 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
26768 **
26769 **
26770 ** BOM or Byte Order Mark:
26771 ** 0xff 0xfe little-endian utf-16 follows
26772 ** 0xfe 0xff big-endian utf-16 follows
26773 **
26774 */
26775 /* #include "sqliteInt.h" */
26776 /* #include <assert.h> */
26777 /* #include "vdbeInt.h" */
26778 
26779 #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
26780 /*
26781 ** The following constant value is used by the SQLITE_BIGENDIAN and
26782 ** SQLITE_LITTLEENDIAN macros.
26783 */
26784 SQLITE_PRIVATE const int sqlite3one = 1;
26785 #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
26786 
26787 /*
26788 ** This lookup table is used to help decode the first byte of
26789 ** a multi-byte UTF8 character.
26790 */
26791 static const unsigned char sqlite3Utf8Trans1[] = {
26792  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26793  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26794  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
26795  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
26796  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26797  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26798  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26799  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
26800 };
26801 
26802 
26803 #define WRITE_UTF8(zOut, c) { \
26804  if( c<0x00080 ){ \
26805  *zOut++ = (u8)(c&0xFF); \
26806  } \
26807  else if( c<0x00800 ){ \
26808  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
26809  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26810  } \
26811  else if( c<0x10000 ){ \
26812  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
26813  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26814  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26815  }else{ \
26816  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
26817  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
26818  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26819  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26820  } \
26821 }
26822 
26823 #define WRITE_UTF16LE(zOut, c) { \
26824  if( c<=0xFFFF ){ \
26825  *zOut++ = (u8)(c&0x00FF); \
26826  *zOut++ = (u8)((c>>8)&0x00FF); \
26827  }else{ \
26828  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26829  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26830  *zOut++ = (u8)(c&0x00FF); \
26831  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26832  } \
26833 }
26834 
26835 #define WRITE_UTF16BE(zOut, c) { \
26836  if( c<=0xFFFF ){ \
26837  *zOut++ = (u8)((c>>8)&0x00FF); \
26838  *zOut++ = (u8)(c&0x00FF); \
26839  }else{ \
26840  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26841  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26842  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26843  *zOut++ = (u8)(c&0x00FF); \
26844  } \
26845 }
26846 
26847 #define READ_UTF16LE(zIn, TERM, c){ \
26848  c = (*zIn++); \
26849  c += ((*zIn++)<<8); \
26850  if( c>=0xD800 && c<0xE000 && TERM ){ \
26851  int c2 = (*zIn++); \
26852  c2 += ((*zIn++)<<8); \
26853  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26854  } \
26855 }
26856 
26857 #define READ_UTF16BE(zIn, TERM, c){ \
26858  c = ((*zIn++)<<8); \
26859  c += (*zIn++); \
26860  if( c>=0xD800 && c<0xE000 && TERM ){ \
26861  int c2 = ((*zIn++)<<8); \
26862  c2 += (*zIn++); \
26863  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26864  } \
26865 }
26866 
26867 /*
26868 ** Translate a single UTF-8 character. Return the unicode value.
26869 **
26870 ** During translation, assume that the byte that zTerm points
26871 ** is a 0x00.
26872 **
26873 ** Write a pointer to the next unread byte back into *pzNext.
26874 **
26875 ** Notes On Invalid UTF-8:
26876 **
26877 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
26878 ** be encoded as a multi-byte character. Any multi-byte character that
26879 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
26880 **
26881 ** * This routine never allows a UTF16 surrogate value to be encoded.
26882 ** If a multi-byte character attempts to encode a value between
26883 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
26884 **
26885 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
26886 ** byte of a character are interpreted as single-byte characters
26887 ** and rendered as themselves even though they are technically
26888 ** invalid characters.
26889 **
26890 ** * This routine accepts over-length UTF8 encodings
26891 ** for unicode values 0x80 and greater. It does not change over-length
26892 ** encodings to 0xfffd as some systems recommend.
26893 */
26894 #define READ_UTF8(zIn, zTerm, c) \
26895  c = *(zIn++); \
26896  if( c>=0xc0 ){ \
26897  c = sqlite3Utf8Trans1[c-0xc0]; \
26898  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
26899  c = (c<<6) + (0x3f & *(zIn++)); \
26900  } \
26901  if( c<0x80 \
26902  || (c&0xFFFFF800)==0xD800 \
26903  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
26904  }
26906  const unsigned char **pz /* Pointer to string from which to read char */
26907 ){
26908  unsigned int c;
26909 
26910  /* Same as READ_UTF8() above but without the zTerm parameter.
26911  ** For this routine, we assume the UTF8 string is always zero-terminated.
26912  */
26913  c = *((*pz)++);
26914  if( c>=0xc0 ){
26915  c = sqlite3Utf8Trans1[c-0xc0];
26916  while( (*(*pz) & 0xc0)==0x80 ){
26917  c = (c<<6) + (0x3f & *((*pz)++));
26918  }
26919  if( c<0x80
26920  || (c&0xFFFFF800)==0xD800
26921  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
26922  }
26923  return c;
26924 }
26925 
26926 
26927 
26928 
26929 /*
26930 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
26931 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
26932 */
26933 /* #define TRANSLATE_TRACE 1 */
26934 
26935 #ifndef SQLITE_OMIT_UTF16
26936 /*
26937 ** This routine transforms the internal text encoding used by pMem to
26938 ** desiredEnc. It is an error if the string is already of the desired
26939 ** encoding, or if *pMem does not contain a string value.
26940 */
26942  int len; /* Maximum length of output string in bytes */
26943  unsigned char *zOut; /* Output buffer */
26944  unsigned char *zIn; /* Input iterator */
26945  unsigned char *zTerm; /* End of input */
26946  unsigned char *z; /* Output iterator */
26947  unsigned int c;
26948 
26949  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
26950  assert( pMem->flags&MEM_Str );
26951  assert( pMem->enc!=desiredEnc );
26952  assert( pMem->enc!=0 );
26953  assert( pMem->n>=0 );
26954 
26955 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26956  {
26957  char zBuf[100];
26958  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
26959  fprintf(stderr, "INPUT: %s\n", zBuf);
26960  }
26961 #endif
26962 
26963  /* If the translation is between UTF-16 little and big endian, then
26964  ** all that is required is to swap the byte order. This case is handled
26965  ** differently from the others.
26966  */
26967  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
26968  u8 temp;
26969  int rc;
26970  rc = sqlite3VdbeMemMakeWriteable(pMem);
26971  if( rc!=SQLITE_OK ){
26972  assert( rc==SQLITE_NOMEM );
26973  return SQLITE_NOMEM_BKPT;
26974  }
26975  zIn = (u8*)pMem->z;
26976  zTerm = &zIn[pMem->n&~1];
26977  while( zIn<zTerm ){
26978  temp = *zIn;
26979  *zIn = *(zIn+1);
26980  zIn++;
26981  *zIn++ = temp;
26982  }
26983  pMem->enc = desiredEnc;
26984  goto translate_out;
26985  }
26986 
26987  /* Set len to the maximum number of bytes required in the output buffer. */
26988  if( desiredEnc==SQLITE_UTF8 ){
26989  /* When converting from UTF-16, the maximum growth results from
26990  ** translating a 2-byte character to a 4-byte UTF-8 character.
26991  ** A single byte is required for the output string
26992  ** nul-terminator.
26993  */
26994  pMem->n &= ~1;
26995  len = pMem->n * 2 + 1;
26996  }else{
26997  /* When converting from UTF-8 to UTF-16 the maximum growth is caused
26998  ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
26999  ** character. Two bytes are required in the output buffer for the
27000  ** nul-terminator.
27001  */
27002  len = pMem->n * 2 + 2;
27003  }
27004 
27005  /* Set zIn to point at the start of the input buffer and zTerm to point 1
27006  ** byte past the end.
27007  **
27008  ** Variable zOut is set to point at the output buffer, space obtained
27009  ** from sqlite3_malloc().
27010  */
27011  zIn = (u8*)pMem->z;
27012  zTerm = &zIn[pMem->n];
27013  zOut = sqlite3DbMallocRaw(pMem->db, len);
27014  if( !zOut ){
27015  return SQLITE_NOMEM_BKPT;
27016  }
27017  z = zOut;
27018 
27019  if( pMem->enc==SQLITE_UTF8 ){
27020  if( desiredEnc==SQLITE_UTF16LE ){
27021  /* UTF-8 -> UTF-16 Little-endian */
27022  while( zIn<zTerm ){
27023  READ_UTF8(zIn, zTerm, c);
27024  WRITE_UTF16LE(z, c);
27025  }
27026  }else{
27027  assert( desiredEnc==SQLITE_UTF16BE );
27028  /* UTF-8 -> UTF-16 Big-endian */
27029  while( zIn<zTerm ){
27030  READ_UTF8(zIn, zTerm, c);
27031  WRITE_UTF16BE(z, c);
27032  }
27033  }
27034  pMem->n = (int)(z - zOut);
27035  *z++ = 0;
27036  }else{
27037  assert( desiredEnc==SQLITE_UTF8 );
27038  if( pMem->enc==SQLITE_UTF16LE ){
27039  /* UTF-16 Little-endian -> UTF-8 */
27040  while( zIn<zTerm ){
27041  READ_UTF16LE(zIn, zIn<zTerm, c);
27042  WRITE_UTF8(z, c);
27043  }
27044  }else{
27045  /* UTF-16 Big-endian -> UTF-8 */
27046  while( zIn<zTerm ){
27047  READ_UTF16BE(zIn, zIn<zTerm, c);
27048  WRITE_UTF8(z, c);
27049  }
27050  }
27051  pMem->n = (int)(z - zOut);
27052  }
27053  *z = 0;
27054  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
27055 
27056  c = pMem->flags;
27057  sqlite3VdbeMemRelease(pMem);
27059  pMem->enc = desiredEnc;
27060  pMem->z = (char*)zOut;
27061  pMem->zMalloc = pMem->z;
27062  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
27063 
27064 translate_out:
27065 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
27066  {
27067  char zBuf[100];
27068  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27069  fprintf(stderr, "OUTPUT: %s\n", zBuf);
27070  }
27071 #endif
27072  return SQLITE_OK;
27073 }
27074 
27075 /*
27076 ** This routine checks for a byte-order mark at the beginning of the
27077 ** UTF-16 string stored in *pMem. If one is present, it is removed and
27078 ** the encoding of the Mem adjusted. This routine does not do any
27079 ** byte-swapping, it just sets Mem.enc appropriately.
27080 **
27081 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
27082 ** changed by this function.
27083 */
27085  int rc = SQLITE_OK;
27086  u8 bom = 0;
27087 
27088  assert( pMem->n>=0 );
27089  if( pMem->n>1 ){
27090  u8 b1 = *(u8 *)pMem->z;
27091  u8 b2 = *(((u8 *)pMem->z) + 1);
27092  if( b1==0xFE && b2==0xFF ){
27093  bom = SQLITE_UTF16BE;
27094  }
27095  if( b1==0xFF && b2==0xFE ){
27096  bom = SQLITE_UTF16LE;
27097  }
27098  }
27099 
27100  if( bom ){
27101  rc = sqlite3VdbeMemMakeWriteable(pMem);
27102  if( rc==SQLITE_OK ){
27103  pMem->n -= 2;
27104  memmove(pMem->z, &pMem->z[2], pMem->n);
27105  pMem->z[pMem->n] = '\0';
27106  pMem->z[pMem->n+1] = '\0';
27107  pMem->flags |= MEM_Term;
27108  pMem->enc = bom;
27109  }
27110  }
27111  return rc;
27112 }
27113 #endif /* SQLITE_OMIT_UTF16 */
27114 
27115 /*
27116 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
27117 ** return the number of unicode characters in pZ up to (but not including)
27118 ** the first 0x00 byte. If nByte is not less than zero, return the
27119 ** number of unicode characters in the first nByte of pZ (or up to
27120 ** the first 0x00, whichever comes first).
27121 */
27122 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
27123  int r = 0;
27124  const u8 *z = (const u8*)zIn;
27125  const u8 *zTerm;
27126  if( nByte>=0 ){
27127  zTerm = &z[nByte];
27128  }else{
27129  zTerm = (const u8*)(-1);
27130  }
27131  assert( z<=zTerm );
27132  while( *z!=0 && z<zTerm ){
27133  SQLITE_SKIP_UTF8(z);
27134  r++;
27135  }
27136  return r;
27137 }
27138 
27139 /* This test function is not currently used by the automated test-suite.
27140 ** Hence it is only available in debug builds.
27141 */
27142 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
27143 /*
27144 ** Translate UTF-8 to UTF-8.
27145 **
27146 ** This has the effect of making sure that the string is well-formed
27147 ** UTF-8. Miscoded characters are removed.
27148 **
27149 ** The translation is done in-place and aborted if the output
27150 ** overruns the input.
27151 */
27152 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
27153  unsigned char *zOut = zIn;
27154  unsigned char *zStart = zIn;
27155  u32 c;
27156 
27157  while( zIn[0] && zOut<=zIn ){
27158  c = sqlite3Utf8Read((const u8**)&zIn);
27159  if( c!=0xfffd ){
27160  WRITE_UTF8(zOut, c);
27161  }
27162  }
27163  *zOut = 0;
27164  return (int)(zOut - zStart);
27165 }
27166 #endif
27167 
27168 #ifndef SQLITE_OMIT_UTF16
27169 /*
27170 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
27171 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
27172 ** be freed by the calling function.
27173 **
27174 ** NULL is returned if there is an allocation error.
27175 */
27176 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
27177  Mem m;
27178  memset(&m, 0, sizeof(m));
27179  m.db = db;
27180  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
27182  if( db->mallocFailed ){
27184  m.z = 0;
27185  }
27186  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
27187  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
27188  assert( m.z || db->mallocFailed );
27189  return m.z;
27190 }
27191 
27192 /*
27193 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
27194 ** Return the number of bytes in the first nChar unicode characters
27195 ** in pZ. nChar must be non-negative.
27196 */
27197 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
27198  int c;
27199  unsigned char const *z = zIn;
27200  int n = 0;
27201 
27203  while( n<nChar ){
27204  READ_UTF16BE(z, 1, c);
27205  n++;
27206  }
27207  }else{
27208  while( n<nChar ){
27209  READ_UTF16LE(z, 1, c);
27210  n++;
27211  }
27212  }
27213  return (int)(z-(unsigned char const *)zIn);
27214 }
27215 
27216 #if defined(SQLITE_TEST)
27217 /*
27218 ** This routine is called from the TCL test function "translate_selftest".
27219 ** It checks that the primitives for serializing and deserializing
27220 ** characters in each encoding are inverses of each other.
27221 */
27222 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
27223  unsigned int i, t;
27224  unsigned char zBuf[20];
27225  unsigned char *z;
27226  int n;
27227  unsigned int c;
27228 
27229  for(i=0; i<0x00110000; i++){
27230  z = zBuf;
27231  WRITE_UTF8(z, i);
27232  n = (int)(z-zBuf);
27233  assert( n>0 && n<=4 );
27234  z[0] = 0;
27235  z = zBuf;
27236  c = sqlite3Utf8Read((const u8**)&z);
27237  t = i;
27238  if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
27239  if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
27240  assert( c==t );
27241  assert( (z-zBuf)==n );
27242  }
27243  for(i=0; i<0x00110000; i++){
27244  if( i>=0xD800 && i<0xE000 ) continue;
27245  z = zBuf;
27246  WRITE_UTF16LE(z, i);
27247  n = (int)(z-zBuf);
27248  assert( n>0 && n<=4 );
27249  z[0] = 0;
27250  z = zBuf;
27251  READ_UTF16LE(z, 1, c);
27252  assert( c==i );
27253  assert( (z-zBuf)==n );
27254  }
27255  for(i=0; i<0x00110000; i++){
27256  if( i>=0xD800 && i<0xE000 ) continue;
27257  z = zBuf;
27258  WRITE_UTF16BE(z, i);
27259  n = (int)(z-zBuf);
27260  assert( n>0 && n<=4 );
27261  z[0] = 0;
27262  z = zBuf;
27263  READ_UTF16BE(z, 1, c);
27264  assert( c==i );
27265  assert( (z-zBuf)==n );
27266  }
27267 }
27268 #endif /* SQLITE_TEST */
27269 #endif /* SQLITE_OMIT_UTF16 */
27270 
27271 /************** End of utf.c *************************************************/
27272 /************** Begin file util.c ********************************************/
27273 /*
27274 ** 2001 September 15
27275 **
27276 ** The author disclaims copyright to this source code. In place of
27277 ** a legal notice, here is a blessing:
27278 **
27279 ** May you do good and not evil.
27280 ** May you find forgiveness for yourself and forgive others.
27281 ** May you share freely, never taking more than you give.
27282 **
27283 *************************************************************************
27284 ** Utility functions used throughout sqlite.
27285 **
27286 ** This file contains functions for allocating memory, comparing
27287 ** strings, and stuff like that.
27288 **
27289 */
27290 /* #include "sqliteInt.h" */
27291 /* #include <stdarg.h> */
27292 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
27293 # include <math.h>
27294 #endif
27295 
27296 /*
27297 ** Routine needed to support the testcase() macro.
27298 */
27299 #ifdef SQLITE_COVERAGE_TEST
27300 SQLITE_PRIVATE void sqlite3Coverage(int x){
27301  static unsigned dummy = 0;
27302  dummy += (unsigned)x;
27303 }
27304 #endif
27305 
27306 /*
27307 ** Give a callback to the test harness that can be used to simulate faults
27308 ** in places where it is difficult or expensive to do so purely by means
27309 ** of inputs.
27310 **
27311 ** The intent of the integer argument is to let the fault simulator know
27312 ** which of multiple sqlite3FaultSim() calls has been hit.
27313 **
27314 ** Return whatever integer value the test callback returns, or return
27315 ** SQLITE_OK if no test callback is installed.
27316 */
27317 #ifndef SQLITE_OMIT_BUILTIN_TEST
27319  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
27320  return xCallback ? xCallback(iTest) : SQLITE_OK;
27321 }
27322 #endif
27323 
27324 #ifndef SQLITE_OMIT_FLOATING_POINT
27325 /*
27326 ** Return true if the floating point value is Not a Number (NaN).
27327 **
27328 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
27329 ** Otherwise, we have our own implementation that works on most systems.
27330 */
27332  int rc; /* The value return */
27333 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
27334  /*
27335  ** Systems that support the isnan() library function should probably
27336  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
27337  ** found that many systems do not have a working isnan() function so
27338  ** this implementation is provided as an alternative.
27339  **
27340  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
27341  ** On the other hand, the use of -ffast-math comes with the following
27342  ** warning:
27343  **
27344  ** This option [-ffast-math] should never be turned on by any
27345  ** -O option since it can result in incorrect output for programs
27346  ** which depend on an exact implementation of IEEE or ISO
27347  ** rules/specifications for math functions.
27348  **
27349  ** Under MSVC, this NaN test may fail if compiled with a floating-
27350  ** point precision mode other than /fp:precise. From the MSDN
27351  ** documentation:
27352  **
27353  ** The compiler [with /fp:precise] will properly handle comparisons
27354  ** involving NaN. For example, x != x evaluates to true if x is NaN
27355  ** ...
27356  */
27357 #ifdef __FAST_MATH__
27358 # error SQLite will not work correctly with the -ffast-math option of GCC.
27359 #endif
27360  volatile double y = x;
27361  volatile double z = y;
27362  rc = (y!=z);
27363 #else /* if HAVE_ISNAN */
27364  rc = isnan(x);
27365 #endif /* HAVE_ISNAN */
27366  testcase( rc );
27367  return rc;
27368 }
27369 #endif /* SQLITE_OMIT_FLOATING_POINT */
27370 
27371 /*
27372 ** Compute a string length that is limited to what can be stored in
27373 ** lower 30 bits of a 32-bit signed integer.
27374 **
27375 ** The value returned will never be negative. Nor will it ever be greater
27376 ** than the actual length of the string. For very long strings (greater
27377 ** than 1GiB) the value returned might be less than the true string length.
27378 */
27379 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
27380  if( z==0 ) return 0;
27381  return 0x3fffffff & (int)strlen(z);
27382 }
27383 
27384 /*
27385 ** Return the declared type of a column. Or return zDflt if the column
27386 ** has no declared type.
27387 **
27388 ** The column type is an extra string stored after the zero-terminator on
27389 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
27390 */
27391 SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
27392  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
27393  return pCol->zName + strlen(pCol->zName) + 1;
27394 }
27395 
27396 /*
27397 ** Helper function for sqlite3Error() - called rarely. Broken out into
27398 ** a separate routine to avoid unnecessary register saves on entry to
27399 ** sqlite3Error().
27400 */
27401 static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
27402  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
27403  sqlite3SystemError(db, err_code);
27404 }
27405 
27406 /*
27407 ** Set the current error code to err_code and clear any prior error message.
27408 ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
27409 ** that would be appropriate.
27410 */
27411 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
27412  assert( db!=0 );
27413  db->errCode = err_code;
27414  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
27415 }
27416 
27417 /*
27418 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
27419 ** to do based on the SQLite error code in rc.
27420 */
27422  if( rc==SQLITE_IOERR_NOMEM ) return;
27423  rc &= 0xff;
27424  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
27426  }
27427 }
27428 
27429 /*
27430 ** Set the most recent error code and error string for the sqlite
27431 ** handle "db". The error code is set to "err_code".
27432 **
27433 ** If it is not NULL, string zFormat specifies the format of the
27434 ** error string in the style of the printf functions: The following
27435 ** format characters are allowed:
27436 **
27437 ** %s Insert a string
27438 ** %z A string that should be freed after use
27439 ** %d Insert an integer
27440 ** %T Insert a token
27441 ** %S Insert the first element of a SrcList
27442 **
27443 ** zFormat and any string tokens that follow it are assumed to be
27444 ** encoded in UTF-8.
27445 **
27446 ** To clear the most recent error for sqlite handle "db", sqlite3Error
27447 ** should be called with err_code set to SQLITE_OK and zFormat set
27448 ** to NULL.
27449 */
27450 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
27451  assert( db!=0 );
27452  db->errCode = err_code;
27453  sqlite3SystemError(db, err_code);
27454  if( zFormat==0 ){
27455  sqlite3Error(db, err_code);
27456  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
27457  char *z;
27458  va_list ap;
27459  va_start(ap, zFormat);
27460  z = sqlite3VMPrintf(db, zFormat, ap);
27461  va_end(ap);
27463  }
27464 }
27465 
27466 /*
27467 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
27468 ** The following formatting characters are allowed:
27469 **
27470 ** %s Insert a string
27471 ** %z A string that should be freed after use
27472 ** %d Insert an integer
27473 ** %T Insert a token
27474 ** %S Insert the first element of a SrcList
27475 **
27476 ** This function should be used to report any error that occurs while
27477 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
27478 ** last thing the sqlite3_prepare() function does is copy the error
27479 ** stored by this function into the database handle using sqlite3Error().
27480 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
27481 ** during statement execution (sqlite3_step() etc.).
27482 */
27483 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
27484  char *zMsg;
27485  va_list ap;
27486  sqlite3 *db = pParse->db;
27487  va_start(ap, zFormat);
27488  zMsg = sqlite3VMPrintf(db, zFormat, ap);
27489  va_end(ap);
27490  if( db->suppressErr ){
27491  sqlite3DbFree(db, zMsg);
27492  }else{
27493  pParse->nErr++;
27494  sqlite3DbFree(db, pParse->zErrMsg);
27495  pParse->zErrMsg = zMsg;
27496  pParse->rc = SQLITE_ERROR;
27497  }
27498 }
27499 
27500 /*
27501 ** Convert an SQL-style quoted string into a normal string by removing
27502 ** the quote characters. The conversion is done in-place. If the
27503 ** input does not begin with a quote character, then this routine
27504 ** is a no-op.
27505 **
27506 ** The input string must be zero-terminated. A new zero-terminator
27507 ** is added to the dequoted string.
27508 **
27509 ** The return value is -1 if no dequoting occurs or the length of the
27510 ** dequoted string, exclusive of the zero terminator, if dequoting does
27511 ** occur.
27512 **
27513 ** 2002-Feb-14: This routine is extended to remove MS-Access style
27514 ** brackets from around identifiers. For example: "[a-b-c]" becomes
27515 ** "a-b-c".
27516 */
27518  char quote;
27519  int i, j;
27520  if( z==0 ) return;
27521  quote = z[0];
27522  if( !sqlite3Isquote(quote) ) return;
27523  if( quote=='[' ) quote = ']';
27524  for(i=1, j=0;; i++){
27525  assert( z[i] );
27526  if( z[i]==quote ){
27527  if( z[i+1]==quote ){
27528  z[j++] = quote;
27529  i++;
27530  }else{
27531  break;
27532  }
27533  }else{
27534  z[j++] = z[i];
27535  }
27536  }
27537  z[j] = 0;
27538 }
27539 
27540 /*
27541 ** Generate a Token object from a string
27542 */
27544  p->z = z;
27545  p->n = sqlite3Strlen30(z);
27546 }
27547 
27548 /* Convenient short-hand */
27549 #define UpperToLower sqlite3UpperToLower
27550 
27551 /*
27552 ** Some systems have stricmp(). Others have strcasecmp(). Because
27553 ** there is no consistency, we will define our own.
27554 **
27555 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
27556 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
27557 ** the contents of two buffers containing UTF-8 strings in a
27558 ** case-independent fashion, using the same definition of "case
27559 ** independence" that SQLite uses internally when comparing identifiers.
27560 */
27561 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
27562  if( zLeft==0 ){
27563  return zRight ? -1 : 0;
27564  }else if( zRight==0 ){
27565  return 1;
27566  }
27567  return sqlite3StrICmp(zLeft, zRight);
27568 }
27569 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
27570  unsigned char *a, *b;
27571  int c;
27572  a = (unsigned char *)zLeft;
27573  b = (unsigned char *)zRight;
27574  for(;;){
27575  c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
27576  if( c || *a==0 ) break;
27577  a++;
27578  b++;
27579  }
27580  return c;
27581 }
27582 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
27583  register unsigned char *a, *b;
27584  if( zLeft==0 ){
27585  return zRight ? -1 : 0;
27586  }else if( zRight==0 ){
27587  return 1;
27588  }
27589  a = (unsigned char *)zLeft;
27590  b = (unsigned char *)zRight;
27591  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
27592  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
27593 }
27594 
27595 /*
27596 ** The string z[] is an text representation of a real number.
27597 ** Convert this string to a double and write it into *pResult.
27598 **
27599 ** The string z[] is length bytes in length (bytes, not characters) and
27600 ** uses the encoding enc. The string is not necessarily zero-terminated.
27601 **
27602 ** Return TRUE if the result is a valid real number (or integer) and FALSE
27603 ** if the string is empty or contains extraneous text. Valid numbers
27604 ** are in one of these formats:
27605 **
27606 ** [+-]digits[E[+-]digits]
27607 ** [+-]digits.[digits][E[+-]digits]
27608 ** [+-].digits[E[+-]digits]
27609 **
27610 ** Leading and trailing whitespace is ignored for the purpose of determining
27611 ** validity.
27612 **
27613 ** If some prefix of the input string is a valid number, this routine
27614 ** returns FALSE but it still converts the prefix and writes the result
27615 ** into *pResult.
27616 */
27617 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
27618 #ifndef SQLITE_OMIT_FLOATING_POINT
27619  int incr;
27620  const char *zEnd = z + length;
27621  /* sign * significand * (10 ^ (esign * exponent)) */
27622  int sign = 1; /* sign of significand */
27623  i64 s = 0; /* significand */
27624  int d = 0; /* adjust exponent for shifting decimal point */
27625  int esign = 1; /* sign of exponent */
27626  int e = 0; /* exponent */
27627  int eValid = 1; /* True exponent is either not used or is well-formed */
27628  double result;
27629  int nDigits = 0;
27630  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27631 
27632  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27633  *pResult = 0.0; /* Default return value, in case of an error */
27634 
27635  if( enc==SQLITE_UTF8 ){
27636  incr = 1;
27637  }else{
27638  int i;
27639  incr = 2;
27640  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27641  for(i=3-enc; i<length && z[i]==0; i+=2){}
27642  nonNum = i<length;
27643  zEnd = &z[i^1];
27644  z += (enc&1);
27645  }
27646 
27647  /* skip leading spaces */
27648  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27649  if( z>=zEnd ) return 0;
27650 
27651  /* get sign of significand */
27652  if( *z=='-' ){
27653  sign = -1;
27654  z+=incr;
27655  }else if( *z=='+' ){
27656  z+=incr;
27657  }
27658 
27659  /* copy max significant digits to significand */
27660  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
27661  s = s*10 + (*z - '0');
27662  z+=incr, nDigits++;
27663  }
27664 
27665  /* skip non-significant significand digits
27666  ** (increase exponent by d to shift decimal left) */
27667  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
27668  if( z>=zEnd ) goto do_atof_calc;
27669 
27670  /* if decimal point is present */
27671  if( *z=='.' ){
27672  z+=incr;
27673  /* copy digits from after decimal to significand
27674  ** (decrease exponent by d to shift decimal right) */
27675  while( z<zEnd && sqlite3Isdigit(*z) ){
27676  if( s<((LARGEST_INT64-9)/10) ){
27677  s = s*10 + (*z - '0');
27678  d--;
27679  }
27680  z+=incr, nDigits++;
27681  }
27682  }
27683  if( z>=zEnd ) goto do_atof_calc;
27684 
27685  /* if exponent is present */
27686  if( *z=='e' || *z=='E' ){
27687  z+=incr;
27688  eValid = 0;
27689 
27690  /* This branch is needed to avoid a (harmless) buffer overread. The
27691  ** special comment alerts the mutation tester that the correct answer
27692  ** is obtained even if the branch is omitted */
27693  if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
27694 
27695  /* get sign of exponent */
27696  if( *z=='-' ){
27697  esign = -1;
27698  z+=incr;
27699  }else if( *z=='+' ){
27700  z+=incr;
27701  }
27702  /* copy digits to exponent */
27703  while( z<zEnd && sqlite3Isdigit(*z) ){
27704  e = e<10000 ? (e*10 + (*z - '0')) : 10000;
27705  z+=incr;
27706  eValid = 1;
27707  }
27708  }
27709 
27710  /* skip trailing spaces */
27711  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27712 
27713 do_atof_calc:
27714  /* adjust exponent by d, and update sign */
27715  e = (e*esign) + d;
27716  if( e<0 ) {
27717  esign = -1;
27718  e *= -1;
27719  } else {
27720  esign = 1;
27721  }
27722 
27723  if( s==0 ) {
27724  /* In the IEEE 754 standard, zero is signed. */
27725  result = sign<0 ? -(double)0 : (double)0;
27726  } else {
27727  /* Attempt to reduce exponent.
27728  **
27729  ** Branches that are not required for the correct answer but which only
27730  ** help to obtain the correct answer faster are marked with special
27731  ** comments, as a hint to the mutation tester.
27732  */
27733  while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
27734  if( esign>0 ){
27735  if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
27736  s *= 10;
27737  }else{
27738  if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
27739  s /= 10;
27740  }
27741  e--;
27742  }
27743 
27744  /* adjust the sign of significand */
27745  s = sign<0 ? -s : s;
27746 
27747  if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
27748  result = (double)s;
27749  }else{
27750  LONGDOUBLE_TYPE scale = 1.0;
27751  /* attempt to handle extremely small/large numbers better */
27752  if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
27753  if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
27754  while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27755  if( esign<0 ){
27756  result = s / scale;
27757  result /= 1.0e+308;
27758  }else{
27759  result = s * scale;
27760  result *= 1.0e+308;
27761  }
27762  }else{ assert( e>=342 );
27763  if( esign<0 ){
27764  result = 0.0*s;
27765  }else{
27766  result = 1e308*1e308*s; /* Infinity */
27767  }
27768  }
27769  }else{
27770  /* 1.0e+22 is the largest power of 10 than can be
27771  ** represented exactly. */
27772  while( e%22 ) { scale *= 1.0e+1; e -= 1; }
27773  while( e>0 ) { scale *= 1.0e+22; e -= 22; }
27774  if( esign<0 ){
27775  result = s / scale;
27776  }else{
27777  result = s * scale;
27778  }
27779  }
27780  }
27781  }
27782 
27783  /* store the result */
27784  *pResult = result;
27785 
27786  /* return true if number and no extra non-whitespace chracters after */
27787  return z==zEnd && nDigits>0 && eValid && nonNum==0;
27788 #else
27789  return !sqlite3Atoi64(z, pResult, length, enc);
27790 #endif /* SQLITE_OMIT_FLOATING_POINT */
27791 }
27792 
27793 /*
27794 ** Compare the 19-character string zNum against the text representation
27795 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
27796 ** if zNum is less than, equal to, or greater than the string.
27797 ** Note that zNum must contain exactly 19 characters.
27798 **
27799 ** Unlike memcmp() this routine is guaranteed to return the difference
27800 ** in the values of the last digit if the only difference is in the
27801 ** last digit. So, for example,
27802 **
27803 ** compare2pow63("9223372036854775800", 1)
27804 **
27805 ** will return -8.
27806 */
27807 static int compare2pow63(const char *zNum, int incr){
27808  int c = 0;
27809  int i;
27810  /* 012345678901234567 */
27811  const char *pow63 = "922337203685477580";
27812  for(i=0; c==0 && i<18; i++){
27813  c = (zNum[i*incr]-pow63[i])*10;
27814  }
27815  if( c==0 ){
27816  c = zNum[18*incr] - '8';
27817  testcase( c==(-1) );
27818  testcase( c==0 );
27819  testcase( c==(+1) );
27820  }
27821  return c;
27822 }
27823 
27824 /*
27825 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
27826 ** routine does *not* accept hexadecimal notation.
27827 **
27828 ** If the zNum value is representable as a 64-bit twos-complement
27829 ** integer, then write that value into *pNum and return 0.
27830 **
27831 ** If zNum is exactly 9223372036854775808, return 2. This special
27832 ** case is broken out because while 9223372036854775808 cannot be a
27833 ** signed 64-bit integer, its negative -9223372036854775808 can be.
27834 **
27835 ** If zNum is too big for a 64-bit integer and is not
27836 ** 9223372036854775808 or if zNum contains any non-numeric text,
27837 ** then return 1.
27838 **
27839 ** length is the number of bytes in the string (bytes, not characters).
27840 ** The string is not necessarily zero-terminated. The encoding is
27841 ** given by enc.
27842 */
27843 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
27844  int incr;
27845  u64 u = 0;
27846  int neg = 0; /* assume positive */
27847  int i;
27848  int c = 0;
27849  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27850  const char *zStart;
27851  const char *zEnd = zNum + length;
27852  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27853  if( enc==SQLITE_UTF8 ){
27854  incr = 1;
27855  }else{
27856  incr = 2;
27857  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27858  for(i=3-enc; i<length && zNum[i]==0; i+=2){}
27859  nonNum = i<length;
27860  zEnd = &zNum[i^1];
27861  zNum += (enc&1);
27862  }
27863  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
27864  if( zNum<zEnd ){
27865  if( *zNum=='-' ){
27866  neg = 1;
27867  zNum+=incr;
27868  }else if( *zNum=='+' ){
27869  zNum+=incr;
27870  }
27871  }
27872  zStart = zNum;
27873  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
27874  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
27875  u = u*10 + c - '0';
27876  }
27877  if( u>LARGEST_INT64 ){
27878  *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
27879  }else if( neg ){
27880  *pNum = -(i64)u;
27881  }else{
27882  *pNum = (i64)u;
27883  }
27884  testcase( i==18 );
27885  testcase( i==19 );
27886  testcase( i==20 );
27887  if( &zNum[i]<zEnd /* Extra bytes at the end */
27888  || (i==0 && zStart==zNum) /* No digits */
27889  || i>19*incr /* Too many digits */
27890  || nonNum /* UTF16 with high-order bytes non-zero */
27891  ){
27892  /* zNum is empty or contains non-numeric text or is longer
27893  ** than 19 digits (thus guaranteeing that it is too large) */
27894  return 1;
27895  }else if( i<19*incr ){
27896  /* Less than 19 digits, so we know that it fits in 64 bits */
27897  assert( u<=LARGEST_INT64 );
27898  return 0;
27899  }else{
27900  /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
27901  c = compare2pow63(zNum, incr);
27902  if( c<0 ){
27903  /* zNum is less than 9223372036854775808 so it fits */
27904  assert( u<=LARGEST_INT64 );
27905  return 0;
27906  }else if( c>0 ){
27907  /* zNum is greater than 9223372036854775808 so it overflows */
27908  return 1;
27909  }else{
27910  /* zNum is exactly 9223372036854775808. Fits if negative. The
27911  ** special case 2 overflow if positive */
27912  assert( u-1==LARGEST_INT64 );
27913  return neg ? 0 : 2;
27914  }
27915  }
27916 }
27917 
27918 /*
27919 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
27920 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
27921 ** whereas sqlite3Atoi64() does not.
27922 **
27923 ** Returns:
27924 **
27925 ** 0 Successful transformation. Fits in a 64-bit signed integer.
27926 ** 1 Integer too large for a 64-bit signed integer or is malformed
27927 ** 2 Special case of 9223372036854775808
27928 */
27929 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
27930 #ifndef SQLITE_OMIT_HEX_INTEGER
27931  if( z[0]=='0'
27932  && (z[1]=='x' || z[1]=='X')
27933  ){
27934  u64 u = 0;
27935  int i, k;
27936  for(i=2; z[i]=='0'; i++){}
27937  for(k=i; sqlite3Isxdigit(z[k]); k++){
27938  u = u*16 + sqlite3HexToInt(z[k]);
27939  }
27940  memcpy(pOut, &u, 8);
27941  return (z[k]==0 && k-i<=16) ? 0 : 1;
27942  }else
27943 #endif /* SQLITE_OMIT_HEX_INTEGER */
27944  {
27945  return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
27946  }
27947 }
27948 
27949 /*
27950 ** If zNum represents an integer that will fit in 32-bits, then set
27951 ** *pValue to that integer and return true. Otherwise return false.
27952 **
27953 ** This routine accepts both decimal and hexadecimal notation for integers.
27954 **
27955 ** Any non-numeric characters that following zNum are ignored.
27956 ** This is different from sqlite3Atoi64() which requires the
27957 ** input number to be zero-terminated.
27958 */
27959 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
27960  sqlite_int64 v = 0;
27961  int i, c;
27962  int neg = 0;
27963  if( zNum[0]=='-' ){
27964  neg = 1;
27965  zNum++;
27966  }else if( zNum[0]=='+' ){
27967  zNum++;
27968  }
27969 #ifndef SQLITE_OMIT_HEX_INTEGER
27970  else if( zNum[0]=='0'
27971  && (zNum[1]=='x' || zNum[1]=='X')
27972  && sqlite3Isxdigit(zNum[2])
27973  ){
27974  u32 u = 0;
27975  zNum += 2;
27976  while( zNum[0]=='0' ) zNum++;
27977  for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
27978  u = u*16 + sqlite3HexToInt(zNum[i]);
27979  }
27980  if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
27981  memcpy(pValue, &u, 4);
27982  return 1;
27983  }else{
27984  return 0;
27985  }
27986  }
27987 #endif
27988  while( zNum[0]=='0' ) zNum++;
27989  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
27990  v = v*10 + c;
27991  }
27992 
27993  /* The longest decimal representation of a 32 bit integer is 10 digits:
27994  **
27995  ** 1234567890
27996  ** 2^31 -> 2147483648
27997  */
27998  testcase( i==10 );
27999  if( i>10 ){
28000  return 0;
28001  }
28002  testcase( v-neg==2147483647 );
28003  if( v-neg>2147483647 ){
28004  return 0;
28005  }
28006  if( neg ){
28007  v = -v;
28008  }
28009  *pValue = (int)v;
28010  return 1;
28011 }
28012 
28013 /*
28014 ** Return a 32-bit integer value extracted from a string. If the
28015 ** string is not an integer, just return 0.
28016 */
28017 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
28018  int x = 0;
28019  if( z ) sqlite3GetInt32(z, &x);
28020  return x;
28021 }
28022 
28023 /*
28024 ** The variable-length integer encoding is as follows:
28025 **
28026 ** KEY:
28027 ** A = 0xxxxxxx 7 bits of data and one flag bit
28028 ** B = 1xxxxxxx 7 bits of data and one flag bit
28029 ** C = xxxxxxxx 8 bits of data
28030 **
28031 ** 7 bits - A
28032 ** 14 bits - BA
28033 ** 21 bits - BBA
28034 ** 28 bits - BBBA
28035 ** 35 bits - BBBBA
28036 ** 42 bits - BBBBBA
28037 ** 49 bits - BBBBBBA
28038 ** 56 bits - BBBBBBBA
28039 ** 64 bits - BBBBBBBBC
28040 */
28041 
28042 /*
28043 ** Write a 64-bit variable-length integer to memory starting at p[0].
28044 ** The length of data write will be between 1 and 9 bytes. The number
28045 ** of bytes written is returned.
28046 **
28047 ** A variable-length integer consists of the lower 7 bits of each byte
28048 ** for all bytes that have the 8th bit set and one byte with the 8th
28049 ** bit clear. Except, if we get to the 9th byte, it stores the full
28050 ** 8 bits and is the last byte.
28051 */
28052 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
28053  int i, j, n;
28054  u8 buf[10];
28055  if( v & (((u64)0xff000000)<<32) ){
28056  p[8] = (u8)v;
28057  v >>= 8;
28058  for(i=7; i>=0; i--){
28059  p[i] = (u8)((v & 0x7f) | 0x80);
28060  v >>= 7;
28061  }
28062  return 9;
28063  }
28064  n = 0;
28065  do{
28066  buf[n++] = (u8)((v & 0x7f) | 0x80);
28067  v >>= 7;
28068  }while( v!=0 );
28069  buf[0] &= 0x7f;
28070  assert( n<=9 );
28071  for(i=0, j=n-1; j>=0; j--, i++){
28072  p[i] = buf[j];
28073  }
28074  return n;
28075 }
28076 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28077  if( v<=0x7f ){
28078  p[0] = v&0x7f;
28079  return 1;
28080  }
28081  if( v<=0x3fff ){
28082  p[0] = ((v>>7)&0x7f)|0x80;
28083  p[1] = v&0x7f;
28084  return 2;
28085  }
28086  return putVarint64(p,v);
28087 }
28088 
28089 /*
28090 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
28091 ** are defined here rather than simply putting the constant expressions
28092 ** inline in order to work around bugs in the RVT compiler.
28093 **
28094 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
28095 **
28096 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
28097 */
28098 #define SLOT_2_0 0x001fc07f
28099 #define SLOT_4_2_0 0xf01fc07f
28100 
28101 
28102 /*
28103 ** Read a 64-bit variable-length integer from memory starting at p[0].
28104 ** Return the number of bytes read. The value is stored in *v.
28105 */
28106 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
28107  u32 a,b,s;
28108 
28109  a = *p;
28110  /* a: p0 (unmasked) */
28111  if (!(a&0x80))
28112  {
28113  *v = a;
28114  return 1;
28115  }
28116 
28117  p++;
28118  b = *p;
28119  /* b: p1 (unmasked) */
28120  if (!(b&0x80))
28121  {
28122  a &= 0x7f;
28123  a = a<<7;
28124  a |= b;
28125  *v = a;
28126  return 2;
28127  }
28128 
28129  /* Verify that constants are precomputed correctly */
28130  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
28131  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
28132 
28133  p++;
28134  a = a<<14;
28135  a |= *p;
28136  /* a: p0<<14 | p2 (unmasked) */
28137  if (!(a&0x80))
28138  {
28139  a &= SLOT_2_0;
28140  b &= 0x7f;
28141  b = b<<7;
28142  a |= b;
28143  *v = a;
28144  return 3;
28145  }
28146 
28147  /* CSE1 from below */
28148  a &= SLOT_2_0;
28149  p++;
28150  b = b<<14;
28151  b |= *p;
28152  /* b: p1<<14 | p3 (unmasked) */
28153  if (!(b&0x80))
28154  {
28155  b &= SLOT_2_0;
28156  /* moved CSE1 up */
28157  /* a &= (0x7f<<14)|(0x7f); */
28158  a = a<<7;
28159  a |= b;
28160  *v = a;
28161  return 4;
28162  }
28163 
28164  /* a: p0<<14 | p2 (masked) */
28165  /* b: p1<<14 | p3 (unmasked) */
28166  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28167  /* moved CSE1 up */
28168  /* a &= (0x7f<<14)|(0x7f); */
28169  b &= SLOT_2_0;
28170  s = a;
28171  /* s: p0<<14 | p2 (masked) */
28172 
28173  p++;
28174  a = a<<14;
28175  a |= *p;
28176  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28177  if (!(a&0x80))
28178  {
28179  /* we can skip these cause they were (effectively) done above
28180  ** while calculating s */
28181  /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28182  /* b &= (0x7f<<14)|(0x7f); */
28183  b = b<<7;
28184  a |= b;
28185  s = s>>18;
28186  *v = ((u64)s)<<32 | a;
28187  return 5;
28188  }
28189 
28190  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28191  s = s<<7;
28192  s |= b;
28193  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28194 
28195  p++;
28196  b = b<<14;
28197  b |= *p;
28198  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
28199  if (!(b&0x80))
28200  {
28201  /* we can skip this cause it was (effectively) done above in calc'ing s */
28202  /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28203  a &= SLOT_2_0;
28204  a = a<<7;
28205  a |= b;
28206  s = s>>18;
28207  *v = ((u64)s)<<32 | a;
28208  return 6;
28209  }
28210 
28211  p++;
28212  a = a<<14;
28213  a |= *p;
28214  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
28215  if (!(a&0x80))
28216  {
28217  a &= SLOT_4_2_0;
28218  b &= SLOT_2_0;
28219  b = b<<7;
28220  a |= b;
28221  s = s>>11;
28222  *v = ((u64)s)<<32 | a;
28223  return 7;
28224  }
28225 
28226  /* CSE2 from below */
28227  a &= SLOT_2_0;
28228  p++;
28229  b = b<<14;
28230  b |= *p;
28231  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
28232  if (!(b&0x80))
28233  {
28234  b &= SLOT_4_2_0;
28235  /* moved CSE2 up */
28236  /* a &= (0x7f<<14)|(0x7f); */
28237  a = a<<7;
28238  a |= b;
28239  s = s>>4;
28240  *v = ((u64)s)<<32 | a;
28241  return 8;
28242  }
28243 
28244  p++;
28245  a = a<<15;
28246  a |= *p;
28247  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
28248 
28249  /* moved CSE2 up */
28250  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
28251  b &= SLOT_2_0;
28252  b = b<<8;
28253  a |= b;
28254 
28255  s = s<<4;
28256  b = p[-4];
28257  b &= 0x7f;
28258  b = b>>3;
28259  s |= b;
28260 
28261  *v = ((u64)s)<<32 | a;
28262 
28263  return 9;
28264 }
28265 
28266 /*
28267 ** Read a 32-bit variable-length integer from memory starting at p[0].
28268 ** Return the number of bytes read. The value is stored in *v.
28269 **
28270 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
28271 ** integer, then set *v to 0xffffffff.
28272 **
28273 ** A MACRO version, getVarint32, is provided which inlines the
28274 ** single-byte case. All code should use the MACRO version as
28275 ** this function assumes the single-byte case has already been handled.
28276 */
28277 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
28278  u32 a,b;
28279 
28280  /* The 1-byte case. Overwhelmingly the most common. Handled inline
28281  ** by the getVarin32() macro */
28282  a = *p;
28283  /* a: p0 (unmasked) */
28284 #ifndef getVarint32
28285  if (!(a&0x80))
28286  {
28287  /* Values between 0 and 127 */
28288  *v = a;
28289  return 1;
28290  }
28291 #endif
28292 
28293  /* The 2-byte case */
28294  p++;
28295  b = *p;
28296  /* b: p1 (unmasked) */
28297  if (!(b&0x80))
28298  {
28299  /* Values between 128 and 16383 */
28300  a &= 0x7f;
28301  a = a<<7;
28302  *v = a | b;
28303  return 2;
28304  }
28305 
28306  /* The 3-byte case */
28307  p++;
28308  a = a<<14;
28309  a |= *p;
28310  /* a: p0<<14 | p2 (unmasked) */
28311  if (!(a&0x80))
28312  {
28313  /* Values between 16384 and 2097151 */
28314  a &= (0x7f<<14)|(0x7f);
28315  b &= 0x7f;
28316  b = b<<7;
28317  *v = a | b;
28318  return 3;
28319  }
28320 
28321  /* A 32-bit varint is used to store size information in btrees.
28322  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
28323  ** A 3-byte varint is sufficient, for example, to record the size
28324  ** of a 1048569-byte BLOB or string.
28325  **
28326  ** We only unroll the first 1-, 2-, and 3- byte cases. The very
28327  ** rare larger cases can be handled by the slower 64-bit varint
28328  ** routine.
28329  */
28330 #if 1
28331  {
28332  u64 v64;
28333  u8 n;
28334 
28335  p -= 2;
28336  n = sqlite3GetVarint(p, &v64);
28337  assert( n>3 && n<=9 );
28338  if( (v64 & SQLITE_MAX_U32)!=v64 ){
28339  *v = 0xffffffff;
28340  }else{
28341  *v = (u32)v64;
28342  }
28343  return n;
28344  }
28345 
28346 #else
28347  /* For following code (kept for historical record only) shows an
28348  ** unrolling for the 3- and 4-byte varint cases. This code is
28349  ** slightly faster, but it is also larger and much harder to test.
28350  */
28351  p++;
28352  b = b<<14;
28353  b |= *p;
28354  /* b: p1<<14 | p3 (unmasked) */
28355  if (!(b&0x80))
28356  {
28357  /* Values between 2097152 and 268435455 */
28358  b &= (0x7f<<14)|(0x7f);
28359  a &= (0x7f<<14)|(0x7f);
28360  a = a<<7;
28361  *v = a | b;
28362  return 4;
28363  }
28364 
28365  p++;
28366  a = a<<14;
28367  a |= *p;
28368  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28369  if (!(a&0x80))
28370  {
28371  /* Values between 268435456 and 34359738367 */
28372  a &= SLOT_4_2_0;
28373  b &= SLOT_4_2_0;
28374  b = b<<7;
28375  *v = a | b;
28376  return 5;
28377  }
28378 
28379  /* We can only reach this point when reading a corrupt database
28380  ** file. In that case we are not in any hurry. Use the (relatively
28381  ** slow) general-purpose sqlite3GetVarint() routine to extract the
28382  ** value. */
28383  {
28384  u64 v64;
28385  u8 n;
28386 
28387  p -= 4;
28388  n = sqlite3GetVarint(p, &v64);
28389  assert( n>5 && n<=9 );
28390  *v = (u32)v64;
28391  return n;
28392  }
28393 #endif
28394 }
28395 
28396 /*
28397 ** Return the number of bytes that will be needed to store the given
28398 ** 64-bit integer.
28399 */
28401  int i;
28402  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
28403  return i;
28404 }
28405 
28406 
28407 /*
28408 ** Read or write a four-byte big-endian integer value.
28409 */
28411 #if SQLITE_BYTEORDER==4321
28412  u32 x;
28413  memcpy(&x,p,4);
28414  return x;
28415 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28416  && defined(__GNUC__) && GCC_VERSION>=4003000
28417  u32 x;
28418  memcpy(&x,p,4);
28419  return __builtin_bswap32(x);
28420 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28421  && defined(_MSC_VER) && _MSC_VER>=1300
28422  u32 x;
28423  memcpy(&x,p,4);
28424  return _byteswap_ulong(x);
28425 #else
28426  testcase( p[0]&0x80 );
28427  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
28428 #endif
28429 }
28430 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
28431 #if SQLITE_BYTEORDER==4321
28432  memcpy(p,&v,4);
28433 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28434  && defined(__GNUC__) && GCC_VERSION>=4003000
28435  u32 x = __builtin_bswap32(v);
28436  memcpy(p,&x,4);
28437 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28438  && defined(_MSC_VER) && _MSC_VER>=1300
28439  u32 x = _byteswap_ulong(v);
28440  memcpy(p,&x,4);
28441 #else
28442  p[0] = (u8)(v>>24);
28443  p[1] = (u8)(v>>16);
28444  p[2] = (u8)(v>>8);
28445  p[3] = (u8)v;
28446 #endif
28447 }
28448 
28449 
28450 
28451 /*
28452 ** Translate a single byte of Hex into an integer.
28453 ** This routine only works if h really is a valid hexadecimal
28454 ** character: 0..9a..fA..F
28455 */
28457  assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
28458 #ifdef SQLITE_ASCII
28459  h += 9*(1&(h>>6));
28460 #endif
28461 #ifdef SQLITE_EBCDIC
28462  h += 9*(1&~(h>>4));
28463 #endif
28464  return (u8)(h & 0xf);
28465 }
28466 
28467 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
28468 /*
28469 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
28470 ** value. Return a pointer to its binary value. Space to hold the
28471 ** binary value has been obtained from malloc and must be freed by
28472 ** the calling routine.
28473 */
28474 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
28475  char *zBlob;
28476  int i;
28477 
28478  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
28479  n--;
28480  if( zBlob ){
28481  for(i=0; i<n; i+=2){
28482  zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
28483  }
28484  zBlob[i/2] = 0;
28485  }
28486  return zBlob;
28487 }
28488 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
28489 
28490 /*
28491 ** Log an error that is an API call on a connection pointer that should
28492 ** not have been used. The "type" of connection pointer is given as the
28493 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
28494 */
28495 static void logBadConnection(const char *zType){
28497  "API call with %s database connection pointer",
28498  zType
28499  );
28500 }
28501 
28502 /*
28503 ** Check to make sure we have a valid db pointer. This test is not
28504 ** foolproof but it does provide some measure of protection against
28505 ** misuse of the interface such as passing in db pointers that are
28506 ** NULL or which have been previously closed. If this routine returns
28507 ** 1 it means that the db pointer is valid and 0 if it should not be
28508 ** dereferenced for any reason. The calling function should invoke
28509 ** SQLITE_MISUSE immediately.
28510 **
28511 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
28512 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
28513 ** open properly and is not fit for general use but which can be
28514 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
28515 */
28517  u32 magic;
28518  if( db==0 ){
28519  logBadConnection("NULL");
28520  return 0;
28521  }
28522  magic = db->magic;
28523  if( magic!=SQLITE_MAGIC_OPEN ){
28524  if( sqlite3SafetyCheckSickOrOk(db) ){
28525  testcase( sqlite3GlobalConfig.xLog!=0 );
28526  logBadConnection("unopened");
28527  }
28528  return 0;
28529  }else{
28530  return 1;
28531  }
28532 }
28534  u32 magic;
28535  magic = db->magic;
28536  if( magic!=SQLITE_MAGIC_SICK &&
28537  magic!=SQLITE_MAGIC_OPEN &&
28538  magic!=SQLITE_MAGIC_BUSY ){
28539  testcase( sqlite3GlobalConfig.xLog!=0 );
28540  logBadConnection("invalid");
28541  return 0;
28542  }else{
28543  return 1;
28544  }
28545 }
28546 
28547 /*
28548 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
28549 ** the other 64-bit signed integer at *pA and store the result in *pA.
28550 ** Return 0 on success. Or if the operation would have resulted in an
28551 ** overflow, leave *pA unchanged and return 1.
28552 */
28553 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
28554  i64 iA = *pA;
28555  testcase( iA==0 ); testcase( iA==1 );
28556  testcase( iB==-1 ); testcase( iB==0 );
28557  if( iB>=0 ){
28558  testcase( iA>0 && LARGEST_INT64 - iA == iB );
28559  testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
28560  if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
28561  }else{
28562  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
28563  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
28564  if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
28565  }
28566  *pA += iB;
28567  return 0;
28568 }
28569 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
28570  testcase( iB==SMALLEST_INT64+1 );
28571  if( iB==SMALLEST_INT64 ){
28572  testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
28573  if( (*pA)>=0 ) return 1;
28574  *pA -= iB;
28575  return 0;
28576  }else{
28577  return sqlite3AddInt64(pA, -iB);
28578  }
28579 }
28580 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
28581  i64 iA = *pA;
28582  if( iB>0 ){
28583  if( iA>LARGEST_INT64/iB ) return 1;
28584  if( iA<SMALLEST_INT64/iB ) return 1;
28585  }else if( iB<0 ){
28586  if( iA>0 ){
28587  if( iB<SMALLEST_INT64/iA ) return 1;
28588  }else if( iA<0 ){
28589  if( iB==SMALLEST_INT64 ) return 1;
28590  if( iA==SMALLEST_INT64 ) return 1;
28591  if( -iA>LARGEST_INT64/-iB ) return 1;
28592  }
28593  }
28594  *pA = iA*iB;
28595  return 0;
28596 }
28597 
28598 /*
28599 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
28600 ** if the integer has a value of -2147483648, return +2147483647
28601 */
28603  if( x>=0 ) return x;
28604  if( x==(int)0x80000000 ) return 0x7fffffff;
28605  return -x;
28606 }
28607 
28608 #ifdef SQLITE_ENABLE_8_3_NAMES
28609 /*
28610 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
28611 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
28612 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
28613 ** three characters, then shorten the suffix on z[] to be the last three
28614 ** characters of the original suffix.
28615 **
28616 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
28617 ** do the suffix shortening regardless of URI parameter.
28618 **
28619 ** Examples:
28620 **
28621 ** test.db-journal => test.nal
28622 ** test.db-wal => test.wal
28623 ** test.db-shm => test.shm
28624 ** test.db-mj7f3319fa => test.9fa
28625 */
28626 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
28627 #if SQLITE_ENABLE_8_3_NAMES<2
28628  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
28629 #endif
28630  {
28631  int i, sz;
28632  sz = sqlite3Strlen30(z);
28633  for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
28634  if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
28635  }
28636 }
28637 #endif
28638 
28639 /*
28640 ** Find (an approximate) sum of two LogEst values. This computation is
28641 ** not a simple "+" operator because LogEst is stored as a logarithmic
28642 ** value.
28643 **
28644 */
28645 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
28646  static const unsigned char x[] = {
28647  10, 10, /* 0,1 */
28648  9, 9, /* 2,3 */
28649  8, 8, /* 4,5 */
28650  7, 7, 7, /* 6,7,8 */
28651  6, 6, 6, /* 9,10,11 */
28652  5, 5, 5, /* 12-14 */
28653  4, 4, 4, 4, /* 15-18 */
28654  3, 3, 3, 3, 3, 3, /* 19-24 */
28655  2, 2, 2, 2, 2, 2, 2, /* 25-31 */
28656  };
28657  if( a>=b ){
28658  if( a>b+49 ) return a;
28659  if( a>b+31 ) return a+1;
28660  return a+x[a-b];
28661  }else{
28662  if( b>a+49 ) return b;
28663  if( b>a+31 ) return b+1;
28664  return b+x[b-a];
28665  }
28666 }
28667 
28668 /*
28669 ** Convert an integer into a LogEst. In other words, compute an
28670 ** approximation for 10*log2(x).
28671 */
28673  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
28674  LogEst y = 40;
28675  if( x<8 ){
28676  if( x<2 ) return 0;
28677  while( x<8 ){ y -= 10; x <<= 1; }
28678  }else{
28679  while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
28680  while( x>15 ){ y += 10; x >>= 1; }
28681  }
28682  return a[x&7] + y - 10;
28683 }
28684 
28685 #ifndef SQLITE_OMIT_VIRTUALTABLE
28686 /*
28687 ** Convert a double into a LogEst
28688 ** In other words, compute an approximation for 10*log2(x).
28689 */
28691  u64 a;
28692  LogEst e;
28693  assert( sizeof(x)==8 && sizeof(a)==8 );
28694  if( x<=1 ) return 0;
28695  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
28696  memcpy(&a, &x, 8);
28697  e = (a>>52) - 1022;
28698  return e*10;
28699 }
28700 #endif /* SQLITE_OMIT_VIRTUALTABLE */
28701 
28702 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28703  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
28704  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28705 /*
28706 ** Convert a LogEst into an integer.
28707 **
28708 ** Note that this routine is only used when one or more of various
28709 ** non-standard compile-time options is enabled.
28710 */
28711 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
28712  u64 n;
28713  n = x%10;
28714  x /= 10;
28715  if( n>=5 ) n -= 2;
28716  else if( n>=1 ) n -= 1;
28717 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28718  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28719  if( x>60 ) return (u64)LARGEST_INT64;
28720 #else
28721  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
28722  ** possible to this routine is 310, resulting in a maximum x of 31 */
28723  assert( x<=60 );
28724 #endif
28725  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
28726 }
28727 #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
28728 
28729 /************** End of util.c ************************************************/
28730 /************** Begin file hash.c ********************************************/
28731 /*
28732 ** 2001 September 22
28733 **
28734 ** The author disclaims copyright to this source code. In place of
28735 ** a legal notice, here is a blessing:
28736 **
28737 ** May you do good and not evil.
28738 ** May you find forgiveness for yourself and forgive others.
28739 ** May you share freely, never taking more than you give.
28740 **
28741 *************************************************************************
28742 ** This is the implementation of generic hash-tables
28743 ** used in SQLite.
28744 */
28745 /* #include "sqliteInt.h" */
28746 /* #include <assert.h> */
28747 
28748 /* Turn bulk memory into a hash table object by initializing the
28749 ** fields of the Hash structure.
28750 **
28751 ** "pNew" is a pointer to the hash table that is to be initialized.
28752 */
28754  assert( pNew!=0 );
28755  pNew->first = 0;
28756  pNew->count = 0;
28757  pNew->htsize = 0;
28758  pNew->ht = 0;
28759 }
28760 
28761 /* Remove all entries from a hash table. Reclaim all memory.
28762 ** Call this routine to delete a hash table or to reset a hash table
28763 ** to the empty state.
28764 */
28766  HashElem *elem; /* For looping over all elements of the table */
28767 
28768  assert( pH!=0 );
28769  elem = pH->first;
28770  pH->first = 0;
28771  sqlite3_free(pH->ht);
28772  pH->ht = 0;
28773  pH->htsize = 0;
28774  while( elem ){
28775  HashElem *next_elem = elem->next;
28776  sqlite3_free(elem);
28777  elem = next_elem;
28778  }
28779  pH->count = 0;
28780 }
28781 
28782 /*
28783 ** The hashing function.
28784 */
28785 static unsigned int strHash(const char *z){
28786  unsigned int h = 0;
28787  unsigned char c;
28788  while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
28789  /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
28790  ** 0x9e3779b1 is 2654435761 which is the closest prime number to
28791  ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
28792  h += sqlite3UpperToLower[c];
28793  h *= 0x9e3779b1;
28794  }
28795  return h;
28796 }
28797 
28798 
28799 /* Link pNew element into the hash table pH. If pEntry!=0 then also
28800 ** insert pNew into the pEntry hash bucket.
28801 */
28802 static void insertElement(
28803  Hash *pH, /* The complete hash table */
28804  struct _ht *pEntry, /* The entry into which pNew is inserted */
28805  HashElem *pNew /* The element to be inserted */
28806 ){
28807  HashElem *pHead; /* First element already in pEntry */
28808  if( pEntry ){
28809  pHead = pEntry->count ? pEntry->chain : 0;
28810  pEntry->count++;
28811  pEntry->chain = pNew;
28812  }else{
28813  pHead = 0;
28814  }
28815  if( pHead ){
28816  pNew->next = pHead;
28817  pNew->prev = pHead->prev;
28818  if( pHead->prev ){ pHead->prev->next = pNew; }
28819  else { pH->first = pNew; }
28820  pHead->prev = pNew;
28821  }else{
28822  pNew->next = pH->first;
28823  if( pH->first ){ pH->first->prev = pNew; }
28824  pNew->prev = 0;
28825  pH->first = pNew;
28826  }
28827 }
28828 
28829 
28830 /* Resize the hash table so that it cantains "new_size" buckets.
28831 **
28832 ** The hash table might fail to resize if sqlite3_malloc() fails or
28833 ** if the new size is the same as the prior size.
28834 ** Return TRUE if the resize occurs and false if not.
28835 */
28836 static int rehash(Hash *pH, unsigned int new_size){
28837  struct _ht *new_ht; /* The new hash table */
28838  HashElem *elem, *next_elem; /* For looping over existing elements */
28839 
28840 #if SQLITE_MALLOC_SOFT_LIMIT>0
28841  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
28842  new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
28843  }
28844  if( new_size==pH->htsize ) return 0;
28845 #endif
28846 
28847  /* The inability to allocates space for a larger hash table is
28848  ** a performance hit but it is not a fatal error. So mark the
28849  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
28850  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
28851  ** only zeroes the requested number of bytes whereas this module will
28852  ** use the actual amount of space allocated for the hash table (which
28853  ** may be larger than the requested amount).
28854  */
28856  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
28858 
28859  if( new_ht==0 ) return 0;
28860  sqlite3_free(pH->ht);
28861  pH->ht = new_ht;
28862  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
28863  memset(new_ht, 0, new_size*sizeof(struct _ht));
28864  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
28865  unsigned int h = strHash(elem->pKey) % new_size;
28866  next_elem = elem->next;
28867  insertElement(pH, &new_ht[h], elem);
28868  }
28869  return 1;
28870 }
28871 
28872 /* This function (for internal use only) locates an element in an
28873 ** hash table that matches the given key. The hash for this key is
28874 ** also computed and returned in the *pH parameter.
28875 */
28877  const Hash *pH, /* The pH to be searched */
28878  const char *pKey, /* The key we are searching for */
28879  unsigned int *pHash /* Write the hash value here */
28880 ){
28881  HashElem *elem; /* Used to loop thru the element list */
28882  int count; /* Number of elements left to test */
28883  unsigned int h; /* The computed hash */
28884 
28885  if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
28886  struct _ht *pEntry;
28887  h = strHash(pKey) % pH->htsize;
28888  pEntry = &pH->ht[h];
28889  elem = pEntry->chain;
28890  count = pEntry->count;
28891  }else{
28892  h = 0;
28893  elem = pH->first;
28894  count = pH->count;
28895  }
28896  *pHash = h;
28897  while( count-- ){
28898  assert( elem!=0 );
28899  if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
28900  return elem;
28901  }
28902  elem = elem->next;
28903  }
28904  return 0;
28905 }
28906 
28907 /* Remove a single entry from the hash table given a pointer to that
28908 ** element and a hash on the element's key.
28909 */
28911  Hash *pH, /* The pH containing "elem" */
28912  HashElem* elem, /* The element to be removed from the pH */
28913  unsigned int h /* Hash value for the element */
28914 ){
28915  struct _ht *pEntry;
28916  if( elem->prev ){
28917  elem->prev->next = elem->next;
28918  }else{
28919  pH->first = elem->next;
28920  }
28921  if( elem->next ){
28922  elem->next->prev = elem->prev;
28923  }
28924  if( pH->ht ){
28925  pEntry = &pH->ht[h];
28926  if( pEntry->chain==elem ){
28927  pEntry->chain = elem->next;
28928  }
28929  pEntry->count--;
28930  assert( pEntry->count>=0 );
28931  }
28932  sqlite3_free( elem );
28933  pH->count--;
28934  if( pH->count==0 ){
28935  assert( pH->first==0 );
28936  assert( pH->count==0 );
28937  sqlite3HashClear(pH);
28938  }
28939 }
28940 
28941 /* Attempt to locate an element of the hash table pH with a key
28942 ** that matches pKey. Return the data for this element if it is
28943 ** found, or NULL if there is no match.
28944 */
28945 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
28946  HashElem *elem; /* The element that matches key */
28947  unsigned int h; /* A hash on key */
28948 
28949  assert( pH!=0 );
28950  assert( pKey!=0 );
28951  elem = findElementWithHash(pH, pKey, &h);
28952  return elem ? elem->data : 0;
28953 }
28954 
28955 /* Insert an element into the hash table pH. The key is pKey
28956 ** and the data is "data".
28957 **
28958 ** If no element exists with a matching key, then a new
28959 ** element is created and NULL is returned.
28960 **
28961 ** If another element already exists with the same key, then the
28962 ** new data replaces the old data and the old data is returned.
28963 ** The key is not copied in this instance. If a malloc fails, then
28964 ** the new data is returned and the hash table is unchanged.
28965 **
28966 ** If the "data" parameter to this function is NULL, then the
28967 ** element corresponding to "key" is removed from the hash table.
28968 */
28969 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
28970  unsigned int h; /* the hash of the key modulo hash table size */
28971  HashElem *elem; /* Used to loop thru the element list */
28972  HashElem *new_elem; /* New element added to the pH */
28973 
28974  assert( pH!=0 );
28975  assert( pKey!=0 );
28976  elem = findElementWithHash(pH,pKey,&h);
28977  if( elem ){
28978  void *old_data = elem->data;
28979  if( data==0 ){
28980  removeElementGivenHash(pH,elem,h);
28981  }else{
28982  elem->data = data;
28983  elem->pKey = pKey;
28984  }
28985  return old_data;
28986  }
28987  if( data==0 ) return 0;
28988  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
28989  if( new_elem==0 ) return data;
28990  new_elem->pKey = pKey;
28991  new_elem->data = data;
28992  pH->count++;
28993  if( pH->count>=10 && pH->count > 2*pH->htsize ){
28994  if( rehash(pH, pH->count*2) ){
28995  assert( pH->htsize>0 );
28996  h = strHash(pKey) % pH->htsize;
28997  }
28998  }
28999  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
29000  return 0;
29001 }
29002 
29003 /************** End of hash.c ************************************************/
29004 /************** Begin file opcodes.c *****************************************/
29005 /* Automatically generated. Do not edit */
29006 /* See the tool/mkopcodec.tcl script for details. */
29007 #if !defined(SQLITE_OMIT_EXPLAIN) \
29008  || defined(VDBE_PROFILE) \
29009  || defined(SQLITE_DEBUG)
29010 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
29011 # define OpHelp(X) "\0" X
29012 #else
29013 # define OpHelp(X)
29014 #endif
29016  static const char *const azName[] = {
29017  /* 0 */ "Savepoint" OpHelp(""),
29018  /* 1 */ "AutoCommit" OpHelp(""),
29019  /* 2 */ "Transaction" OpHelp(""),
29020  /* 3 */ "SorterNext" OpHelp(""),
29021  /* 4 */ "PrevIfOpen" OpHelp(""),
29022  /* 5 */ "NextIfOpen" OpHelp(""),
29023  /* 6 */ "Prev" OpHelp(""),
29024  /* 7 */ "Next" OpHelp(""),
29025  /* 8 */ "Checkpoint" OpHelp(""),
29026  /* 9 */ "JournalMode" OpHelp(""),
29027  /* 10 */ "Vacuum" OpHelp(""),
29028  /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
29029  /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
29030  /* 13 */ "Goto" OpHelp(""),
29031  /* 14 */ "Gosub" OpHelp(""),
29032  /* 15 */ "InitCoroutine" OpHelp(""),
29033  /* 16 */ "Yield" OpHelp(""),
29034  /* 17 */ "MustBeInt" OpHelp(""),
29035  /* 18 */ "Jump" OpHelp(""),
29036  /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
29037  /* 20 */ "Once" OpHelp(""),
29038  /* 21 */ "If" OpHelp(""),
29039  /* 22 */ "IfNot" OpHelp(""),
29040  /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"),
29041  /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"),
29042  /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"),
29043  /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"),
29044  /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
29045  /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
29046  /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"),
29047  /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"),
29048  /* 31 */ "Found" OpHelp("key=r[P3@P4]"),
29049  /* 32 */ "SeekRowid" OpHelp("intkey=r[P3]"),
29050  /* 33 */ "NotExists" OpHelp("intkey=r[P3]"),
29051  /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
29052  /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
29053  /* 36 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
29054  /* 37 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
29055  /* 38 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
29056  /* 39 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
29057  /* 40 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
29058  /* 41 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
29059  /* 42 */ "ElseNotEq" OpHelp(""),
29060  /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
29061  /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
29062  /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
29063  /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
29064  /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
29065  /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
29066  /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
29067  /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
29068  /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
29069  /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
29070  /* 53 */ "Last" OpHelp(""),
29071  /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
29072  /* 55 */ "SorterSort" OpHelp(""),
29073  /* 56 */ "Sort" OpHelp(""),
29074  /* 57 */ "Rewind" OpHelp(""),
29075  /* 58 */ "IdxLE" OpHelp("key=r[P3@P4]"),
29076  /* 59 */ "IdxGT" OpHelp("key=r[P3@P4]"),
29077  /* 60 */ "IdxLT" OpHelp("key=r[P3@P4]"),
29078  /* 61 */ "IdxGE" OpHelp("key=r[P3@P4]"),
29079  /* 62 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
29080  /* 63 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
29081  /* 64 */ "Program" OpHelp(""),
29082  /* 65 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
29083  /* 66 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
29084  /* 67 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
29085  /* 68 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
29086  /* 69 */ "IncrVacuum" OpHelp(""),
29087  /* 70 */ "VNext" OpHelp(""),
29088  /* 71 */ "Init" OpHelp("Start at P2"),
29089  /* 72 */ "Return" OpHelp(""),
29090  /* 73 */ "EndCoroutine" OpHelp(""),
29091  /* 74 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
29092  /* 75 */ "Halt" OpHelp(""),
29093  /* 76 */ "Integer" OpHelp("r[P2]=P1"),
29094  /* 77 */ "Int64" OpHelp("r[P2]=P4"),
29095  /* 78 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
29096  /* 79 */ "Null" OpHelp("r[P2..P3]=NULL"),
29097  /* 80 */ "SoftNull" OpHelp("r[P1]=NULL"),
29098  /* 81 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
29099  /* 82 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
29100  /* 83 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
29101  /* 84 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
29102  /* 85 */ "SCopy" OpHelp("r[P2]=r[P1]"),
29103  /* 86 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
29104  /* 87 */ "ResultRow" OpHelp("output=r[P1@P2]"),
29105  /* 88 */ "CollSeq" OpHelp(""),
29106  /* 89 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
29107  /* 90 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
29108  /* 91 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
29109  /* 92 */ "RealAffinity" OpHelp(""),
29110  /* 93 */ "Cast" OpHelp("affinity(r[P1])"),
29111  /* 94 */ "Permutation" OpHelp(""),
29112  /* 95 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
29113  /* 96 */ "Column" OpHelp("r[P3]=PX"),
29114  /* 97 */ "String8" OpHelp("r[P2]='P4'"),
29115  /* 98 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
29116  /* 99 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
29117  /* 100 */ "Count" OpHelp("r[P2]=count()"),
29118  /* 101 */ "ReadCookie" OpHelp(""),
29119  /* 102 */ "SetCookie" OpHelp(""),
29120  /* 103 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
29121  /* 104 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
29122  /* 105 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
29123  /* 106 */ "OpenAutoindex" OpHelp("nColumn=P2"),
29124  /* 107 */ "OpenEphemeral" OpHelp("nColumn=P2"),
29125  /* 108 */ "SorterOpen" OpHelp(""),
29126  /* 109 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
29127  /* 110 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
29128  /* 111 */ "Close" OpHelp(""),
29129  /* 112 */ "ColumnsUsed" OpHelp(""),
29130  /* 113 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
29131  /* 114 */ "NewRowid" OpHelp("r[P2]=rowid"),
29132  /* 115 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
29133  /* 116 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
29134  /* 117 */ "Delete" OpHelp(""),
29135  /* 118 */ "ResetCount" OpHelp(""),
29136  /* 119 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
29137  /* 120 */ "SorterData" OpHelp("r[P2]=data"),
29138  /* 121 */ "RowKey" OpHelp("r[P2]=key"),
29139  /* 122 */ "RowData" OpHelp("r[P2]=data"),
29140  /* 123 */ "Rowid" OpHelp("r[P2]=rowid"),
29141  /* 124 */ "NullRow" OpHelp(""),
29142  /* 125 */ "SorterInsert" OpHelp(""),
29143  /* 126 */ "IdxInsert" OpHelp("key=r[P2]"),
29144  /* 127 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
29145  /* 128 */ "Seek" OpHelp("Move P3 to P1.rowid"),
29146  /* 129 */ "IdxRowid" OpHelp("r[P2]=rowid"),
29147  /* 130 */ "Destroy" OpHelp(""),
29148  /* 131 */ "Clear" OpHelp(""),
29149  /* 132 */ "Real" OpHelp("r[P2]=P4"),
29150  /* 133 */ "ResetSorter" OpHelp(""),
29151  /* 134 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
29152  /* 135 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
29153  /* 136 */ "ParseSchema" OpHelp(""),
29154  /* 137 */ "LoadAnalysis" OpHelp(""),
29155  /* 138 */ "DropTable" OpHelp(""),
29156  /* 139 */ "DropIndex" OpHelp(""),
29157  /* 140 */ "DropTrigger" OpHelp(""),
29158  /* 141 */ "IntegrityCk" OpHelp(""),
29159  /* 142 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
29160  /* 143 */ "Param" OpHelp(""),
29161  /* 144 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
29162  /* 145 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
29163  /* 146 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
29164  /* 147 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
29165  /* 148 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
29166  /* 149 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
29167  /* 150 */ "Expire" OpHelp(""),
29168  /* 151 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
29169  /* 152 */ "VBegin" OpHelp(""),
29170  /* 153 */ "VCreate" OpHelp(""),
29171  /* 154 */ "VDestroy" OpHelp(""),
29172  /* 155 */ "VOpen" OpHelp(""),
29173  /* 156 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
29174  /* 157 */ "VRename" OpHelp(""),
29175  /* 158 */ "Pagecount" OpHelp(""),
29176  /* 159 */ "MaxPgcnt" OpHelp(""),
29177  /* 160 */ "CursorHint" OpHelp(""),
29178  /* 161 */ "Noop" OpHelp(""),
29179  /* 162 */ "Explain" OpHelp(""),
29180  };
29181  return azName[i];
29182 }
29183 #endif
29184 
29185 /************** End of opcodes.c *********************************************/
29186 /************** Begin file os_unix.c *****************************************/
29187 /*
29188 ** 2004 May 22
29189 **
29190 ** The author disclaims copyright to this source code. In place of
29191 ** a legal notice, here is a blessing:
29192 **
29193 ** May you do good and not evil.
29194 ** May you find forgiveness for yourself and forgive others.
29195 ** May you share freely, never taking more than you give.
29196 **
29197 ******************************************************************************
29198 **
29199 ** This file contains the VFS implementation for unix-like operating systems
29200 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
29201 **
29202 ** There are actually several different VFS implementations in this file.
29203 ** The differences are in the way that file locking is done. The default
29204 ** implementation uses Posix Advisory Locks. Alternative implementations
29205 ** use flock(), dot-files, various proprietary locking schemas, or simply
29206 ** skip locking all together.
29207 **
29208 ** This source file is organized into divisions where the logic for various
29209 ** subfunctions is contained within the appropriate division. PLEASE
29210 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
29211 ** in the correct division and should be clearly labeled.
29212 **
29213 ** The layout of divisions is as follows:
29214 **
29215 ** * General-purpose declarations and utility functions.
29216 ** * Unique file ID logic used by VxWorks.
29217 ** * Various locking primitive implementations (all except proxy locking):
29218 ** + for Posix Advisory Locks
29219 ** + for no-op locks
29220 ** + for dot-file locks
29221 ** + for flock() locking
29222 ** + for named semaphore locks (VxWorks only)
29223 ** + for AFP filesystem locks (MacOSX only)
29224 ** * sqlite3_file methods not associated with locking.
29225 ** * Definitions of sqlite3_io_methods objects for all locking
29226 ** methods plus "finder" functions for each locking method.
29227 ** * sqlite3_vfs method implementations.
29228 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
29229 ** * Definitions of sqlite3_vfs objects for all locking methods
29230 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
29231 */
29232 /* #include "sqliteInt.h" */
29233 #if SQLITE_OS_UNIX /* This file is used on unix only */
29234 
29235 /*
29236 ** There are various methods for file locking used for concurrency
29237 ** control:
29238 **
29239 ** 1. POSIX locking (the default),
29240 ** 2. No locking,
29241 ** 3. Dot-file locking,
29242 ** 4. flock() locking,
29243 ** 5. AFP locking (OSX only),
29244 ** 6. Named POSIX semaphores (VXWorks only),
29245 ** 7. proxy locking. (OSX only)
29246 **
29247 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
29248 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
29249 ** selection of the appropriate locking style based on the filesystem
29250 ** where the database is located.
29251 */
29252 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
29253 # if defined(__APPLE__)
29254 # define SQLITE_ENABLE_LOCKING_STYLE 1
29255 # else
29256 # define SQLITE_ENABLE_LOCKING_STYLE 0
29257 # endif
29258 #endif
29259 
29260 /* Use pread() and pwrite() if they are available */
29261 #if defined(__APPLE__)
29262 # define HAVE_PREAD 1
29263 # define HAVE_PWRITE 1
29264 #endif
29265 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
29266 # undef USE_PREAD
29267 # define USE_PREAD64 1
29268 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
29269 # undef USE_PREAD64
29270 # define USE_PREAD 1
29271 #endif
29272 
29273 /*
29274 ** standard include files.
29275 */
29276 #include <sys/types.h>
29277 #include <sys/stat.h>
29278 #include <fcntl.h>
29279 #include <unistd.h>
29280 /* #include <time.h> */
29281 #include <sys/time.h>
29282 #include <errno.h>
29283 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29284 # include <sys/mman.h>
29285 #endif
29286 
29287 #if SQLITE_ENABLE_LOCKING_STYLE
29288 # include <sys/ioctl.h>
29289 # include <sys/file.h>
29290 # include <sys/param.h>
29291 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
29292 
29293 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
29294  (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
29295 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
29296  && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
29297 # define HAVE_GETHOSTUUID 1
29298 # else
29299 # warning "gethostuuid() is disabled."
29300 # endif
29301 #endif
29302 
29303 
29304 #if OS_VXWORKS
29305 /* # include <sys/ioctl.h> */
29306 # include <semaphore.h>
29307 # include <limits.h>
29308 #endif /* OS_VXWORKS */
29309 
29310 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29311 # include <sys/mount.h>
29312 #endif
29313 
29314 #ifdef HAVE_UTIME
29315 # include <utime.h>
29316 #endif
29317 
29318 /*
29319 ** Allowed values of unixFile.fsFlags
29320 */
29321 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
29322 
29323 /*
29324 ** If we are to be thread-safe, include the pthreads header and define
29325 ** the SQLITE_UNIX_THREADS macro.
29326 */
29327 #if SQLITE_THREADSAFE
29328 /* # include <pthread.h> */
29329 # define SQLITE_UNIX_THREADS 1
29330 #endif
29331 
29332 /*
29333 ** Default permissions when creating a new file
29334 */
29335 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
29336 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
29337 #endif
29338 
29339 /*
29340 ** Default permissions when creating auto proxy dir
29341 */
29342 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29343 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
29344 #endif
29345 
29346 /*
29347 ** Maximum supported path-length.
29348 */
29349 #define MAX_PATHNAME 512
29350 
29351 /*
29352 ** Maximum supported symbolic links
29353 */
29354 #define SQLITE_MAX_SYMLINKS 100
29355 
29356 /* Always cast the getpid() return type for compatibility with
29357 ** kernel modules in VxWorks. */
29358 #define osGetpid(X) (pid_t)getpid()
29359 
29360 /*
29361 ** Only set the lastErrno if the error code is a real error and not
29362 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
29363 */
29364 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
29365 
29366 /* Forward references */
29367 typedef struct unixShm unixShm; /* Connection shared memory */
29368 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
29369 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
29370 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
29371 
29372 /*
29373 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
29374 ** cannot be closed immediately. In these cases, instances of the following
29375 ** structure are used to store the file descriptor while waiting for an
29376 ** opportunity to either close or reuse it.
29377 */
29379  int fd; /* File descriptor to close */
29380  int flags; /* Flags this file descriptor was opened with */
29381  UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
29382 };
29383 
29384 /*
29385 ** The unixFile structure is subclass of sqlite3_file specific to the unix
29386 ** VFS implementations.
29387 */
29388 typedef struct unixFile unixFile;
29389 struct unixFile {
29390  sqlite3_io_methods const *pMethod; /* Always the first entry */
29391  sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
29392  unixInodeInfo *pInode; /* Info about locks on this inode */
29393  int h; /* The file descriptor */
29394  unsigned char eFileLock; /* The type of lock held on this fd */
29395  unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
29396  int lastErrno; /* The unix errno from last I/O error */
29397  void *lockingContext; /* Locking style specific state */
29398  UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
29399  const char *zPath; /* Name of the file */
29400  unixShm *pShm; /* Shared memory segment information */
29401  int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
29402 #if SQLITE_MAX_MMAP_SIZE>0
29403  int nFetchOut; /* Number of outstanding xFetch refs */
29404  sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
29405  sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
29406  sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
29407  void *pMapRegion; /* Memory mapped region */
29408 #endif
29409 #ifdef __QNXNTO__
29410  int sectorSize; /* Device sector size */
29411  int deviceCharacteristics; /* Precomputed device characteristics */
29412 #endif
29413 #if SQLITE_ENABLE_LOCKING_STYLE
29414  int openFlags; /* The flags specified at open() */
29415 #endif
29416 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
29417  unsigned fsFlags; /* cached details from statfs() */
29418 #endif
29419 #if OS_VXWORKS
29420  struct vxworksFileId *pId; /* Unique file ID */
29421 #endif
29422 #ifdef SQLITE_DEBUG
29423  /* The next group of variables are used to track whether or not the
29424  ** transaction counter in bytes 24-27 of database files are updated
29425  ** whenever any part of the database changes. An assertion fault will
29426  ** occur if a file is updated without also updating the transaction
29427  ** counter. This test is made to avoid new problems similar to the
29428  ** one described by ticket #3584.
29429  */
29430  unsigned char transCntrChng; /* True if the transaction counter changed */
29431  unsigned char dbUpdate; /* True if any part of database file changed */
29432  unsigned char inNormalWrite; /* True if in a normal write operation */
29433 
29434 #endif
29435 
29436 #ifdef SQLITE_TEST
29437  /* In test mode, increase the size of this structure a bit so that
29438  ** it is larger than the struct CrashFile defined in test6.c.
29439  */
29440  char aPadding[32];
29441 #endif
29442 };
29443 
29444 /* This variable holds the process id (pid) from when the xRandomness()
29445 ** method was called. If xOpen() is called from a different process id,
29446 ** indicating that a fork() has occurred, the PRNG will be reset.
29447 */
29448 static pid_t randomnessPid = 0;
29449 
29450 /*
29451 ** Allowed values for the unixFile.ctrlFlags bitmask:
29452 */
29453 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
29454 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
29455 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
29456 #ifndef SQLITE_DISABLE_DIRSYNC
29457 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
29458 #else
29459 # define UNIXFILE_DIRSYNC 0x00
29460 #endif
29461 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29462 #define UNIXFILE_DELETE 0x20 /* Delete on close */
29463 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
29464 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
29465 
29466 /*
29467 ** Include code that is common to all os_*.c files
29468 */
29469 /************** Include os_common.h in the middle of os_unix.c ***************/
29470 /************** Begin file os_common.h ***************************************/
29471 /*
29472 ** 2004 May 22
29473 **
29474 ** The author disclaims copyright to this source code. In place of
29475 ** a legal notice, here is a blessing:
29476 **
29477 ** May you do good and not evil.
29478 ** May you find forgiveness for yourself and forgive others.
29479 ** May you share freely, never taking more than you give.
29480 **
29481 ******************************************************************************
29482 **
29483 ** This file contains macros and a little bit of code that is common to
29484 ** all of the platform-specific files (os_*.c) and is #included into those
29485 ** files.
29486 **
29487 ** This file should be #included by the os_*.c files only. It is not a
29488 ** general purpose header file.
29489 */
29490 #ifndef _OS_COMMON_H_
29491 #define _OS_COMMON_H_
29492 
29493 /*
29494 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29495 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29496 ** switch. The following code should catch this problem at compile-time.
29497 */
29498 #ifdef MEMORY_DEBUG
29499 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
29500 #endif
29501 
29502 /*
29503 ** Macros for performance tracing. Normally turned off. Only works
29504 ** on i486 hardware.
29505 */
29506 #ifdef SQLITE_PERFORMANCE_TRACE
29507 
29508 /*
29509 ** hwtime.h contains inline assembler code for implementing
29510 ** high-performance timing routines.
29511 */
29512 /************** Include hwtime.h in the middle of os_common.h ****************/
29513 /************** Begin file hwtime.h ******************************************/
29514 /*
29515 ** 2008 May 27
29516 **
29517 ** The author disclaims copyright to this source code. In place of
29518 ** a legal notice, here is a blessing:
29519 **
29520 ** May you do good and not evil.
29521 ** May you find forgiveness for yourself and forgive others.
29522 ** May you share freely, never taking more than you give.
29523 **
29524 ******************************************************************************
29525 **
29526 ** This file contains inline asm code for retrieving "high-performance"
29527 ** counters for x86 class CPUs.
29528 */
29529 #ifndef SQLITE_HWTIME_H
29530 #define SQLITE_HWTIME_H
29531 
29532 /*
29533 ** The following routine only works on pentium-class (or newer) processors.
29534 ** It uses the RDTSC opcode to read the cycle count value out of the
29535 ** processor and returns that value. This can be used for high-res
29536 ** profiling.
29537 */
29538 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29539  (defined(i386) || defined(__i386__) || defined(_M_IX86))
29540 
29541  #if defined(__GNUC__)
29542 
29543  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29544  unsigned int lo, hi;
29545  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29546  return (sqlite_uint64)hi << 32 | lo;
29547  }
29548 
29549  #elif defined(_MSC_VER)
29550 
29551  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29552  __asm {
29553  rdtsc
29554  ret ; return value at EDX:EAX
29555  }
29556  }
29557 
29558  #endif
29559 
29560 #elif (defined(__GNUC__) && defined(__x86_64__))
29561 
29562  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29563  unsigned long val;
29564  __asm__ __volatile__ ("rdtsc" : "=A" (val));
29565  return val;
29566  }
29567 
29568 #elif (defined(__GNUC__) && defined(__ppc__))
29569 
29570  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29571  unsigned long long retval;
29572  unsigned long junk;
29573  __asm__ __volatile__ ("\n\
29574  1: mftbu %1\n\
29575  mftb %L0\n\
29576  mftbu %0\n\
29577  cmpw %0,%1\n\
29578  bne 1b"
29579  : "=r" (retval), "=r" (junk));
29580  return retval;
29581  }
29582 
29583 #else
29584 
29585  #error Need implementation of sqlite3Hwtime() for your platform.
29586 
29587  /*
29588  ** To compile without implementing sqlite3Hwtime() for your platform,
29589  ** you can remove the above #error and use the following
29590  ** stub function. You will lose timing support for many
29591  ** of the debugging and testing utilities, but it should at
29592  ** least compile and run.
29593  */
29594 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29595 
29596 #endif
29597 
29598 #endif /* !defined(SQLITE_HWTIME_H) */
29599 
29600 /************** End of hwtime.h **********************************************/
29601 /************** Continuing where we left off in os_common.h ******************/
29602 
29603 static sqlite_uint64 g_start;
29604 static sqlite_uint64 g_elapsed;
29605 #define TIMER_START g_start=sqlite3Hwtime()
29606 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
29607 #define TIMER_ELAPSED g_elapsed
29608 #else
29609 #define TIMER_START
29610 #define TIMER_END
29611 #define TIMER_ELAPSED ((sqlite_uint64)0)
29612 #endif
29613 
29614 /*
29615 ** If we compile with the SQLITE_TEST macro set, then the following block
29616 ** of code will give us the ability to simulate a disk I/O error. This
29617 ** is used for testing the I/O recovery logic.
29618 */
29619 #if defined(SQLITE_TEST)
29620 SQLITE_API extern int sqlite3_io_error_hit;
29621 SQLITE_API extern int sqlite3_io_error_hardhit;
29622 SQLITE_API extern int sqlite3_io_error_pending;
29623 SQLITE_API extern int sqlite3_io_error_persist;
29624 SQLITE_API extern int sqlite3_io_error_benign;
29625 SQLITE_API extern int sqlite3_diskfull_pending;
29626 SQLITE_API extern int sqlite3_diskfull;
29627 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29628 #define SimulateIOError(CODE) \
29629  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29630  || sqlite3_io_error_pending-- == 1 ) \
29631  { local_ioerr(); CODE; }
29632 static void local_ioerr(){
29633  IOTRACE(("IOERR\n"));
29634  sqlite3_io_error_hit++;
29635  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29636 }
29637 #define SimulateDiskfullError(CODE) \
29638  if( sqlite3_diskfull_pending ){ \
29639  if( sqlite3_diskfull_pending == 1 ){ \
29640  local_ioerr(); \
29641  sqlite3_diskfull = 1; \
29642  sqlite3_io_error_hit = 1; \
29643  CODE; \
29644  }else{ \
29645  sqlite3_diskfull_pending--; \
29646  } \
29647  }
29648 #else
29649 #define SimulateIOErrorBenign(X)
29650 #define SimulateIOError(A)
29651 #define SimulateDiskfullError(A)
29652 #endif /* defined(SQLITE_TEST) */
29653 
29654 /*
29655 ** When testing, keep a count of the number of open files.
29656 */
29657 #if defined(SQLITE_TEST)
29658 SQLITE_API extern int sqlite3_open_file_count;
29659 #define OpenCounter(X) sqlite3_open_file_count+=(X)
29660 #else
29661 #define OpenCounter(X)
29662 #endif /* defined(SQLITE_TEST) */
29663 
29664 #endif /* !defined(_OS_COMMON_H_) */
29665 
29666 /************** End of os_common.h *******************************************/
29667 /************** Continuing where we left off in os_unix.c ********************/
29668 
29669 /*
29670 ** Define various macros that are missing from some systems.
29671 */
29672 #ifndef O_LARGEFILE
29673 # define O_LARGEFILE 0
29674 #endif
29675 #ifdef SQLITE_DISABLE_LFS
29676 # undef O_LARGEFILE
29677 # define O_LARGEFILE 0
29678 #endif
29679 #ifndef O_NOFOLLOW
29680 # define O_NOFOLLOW 0
29681 #endif
29682 #ifndef O_BINARY
29683 # define O_BINARY 0
29684 #endif
29685 
29686 /*
29687 ** The threadid macro resolves to the thread-id or to 0. Used for
29688 ** testing and debugging only.
29689 */
29690 #if SQLITE_THREADSAFE
29691 #define threadid pthread_self()
29692 #else
29693 #define threadid 0
29694 #endif
29695 
29696 /*
29697 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
29698 */
29699 #if !defined(HAVE_MREMAP)
29700 # if defined(__linux__) && defined(_GNU_SOURCE)
29701 # define HAVE_MREMAP 1
29702 # else
29703 # define HAVE_MREMAP 0
29704 # endif
29705 #endif
29706 
29707 /*
29708 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
29709 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
29710 */
29711 #ifdef __ANDROID__
29712 # define lseek lseek64
29713 #endif
29714 
29715 /*
29716 ** Different Unix systems declare open() in different ways. Same use
29717 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
29718 ** The difference is important when using a pointer to the function.
29719 **
29720 ** The safest way to deal with the problem is to always use this wrapper
29721 ** which always has the same well-defined interface.
29722 */
29723 static int posixOpen(const char *zFile, int flags, int mode){
29724  return open(zFile, flags, mode);
29725 }
29726 
29727 /* Forward reference */
29728 static int openDirectory(const char*, int*);
29729 static int unixGetpagesize(void);
29730 
29731 /*
29732 ** Many system calls are accessed through pointer-to-functions so that
29733 ** they may be overridden at runtime to facilitate fault injection during
29734 ** testing and sandboxing. The following array holds the names and pointers
29735 ** to all overrideable system calls.
29736 */
29737 static struct unix_syscall {
29738  const char *zName; /* Name of the system call */
29739  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
29740  sqlite3_syscall_ptr pDefault; /* Default value */
29741 } aSyscall[] = {
29742  { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
29743 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
29744 
29745  { "close", (sqlite3_syscall_ptr)close, 0 },
29746 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
29747 
29748  { "access", (sqlite3_syscall_ptr)access, 0 },
29749 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
29750 
29751  { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
29752 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
29753 
29754  { "stat", (sqlite3_syscall_ptr)stat, 0 },
29755 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
29756 
29757 /*
29758 ** The DJGPP compiler environment looks mostly like Unix, but it
29759 ** lacks the fcntl() system call. So redefine fcntl() to be something
29760 ** that always succeeds. This means that locking does not occur under
29761 ** DJGPP. But it is DOS - what did you expect?
29762 */
29763 #ifdef __DJGPP__
29764  { "fstat", 0, 0 },
29765 #define osFstat(a,b,c) 0
29766 #else
29767  { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
29768 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
29769 #endif
29770 
29771  { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
29772 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
29773 
29774  { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
29775 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
29776 
29777  { "read", (sqlite3_syscall_ptr)read, 0 },
29778 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
29779 
29780 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29781  { "pread", (sqlite3_syscall_ptr)pread, 0 },
29782 #else
29783  { "pread", (sqlite3_syscall_ptr)0, 0 },
29784 #endif
29785 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
29786 
29787 #if defined(USE_PREAD64)
29788  { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
29789 #else
29790  { "pread64", (sqlite3_syscall_ptr)0, 0 },
29791 #endif
29792 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
29793 
29794  { "write", (sqlite3_syscall_ptr)write, 0 },
29795 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
29796 
29797 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29798  { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
29799 #else
29800  { "pwrite", (sqlite3_syscall_ptr)0, 0 },
29801 #endif
29802 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
29803  aSyscall[12].pCurrent)
29804 
29805 #if defined(USE_PREAD64)
29806  { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
29807 #else
29808  { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
29809 #endif
29810 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
29811  aSyscall[13].pCurrent)
29812 
29813  { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
29814 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
29815 
29816 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29817  { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
29818 #else
29819  { "fallocate", (sqlite3_syscall_ptr)0, 0 },
29820 #endif
29821 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
29822 
29823  { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
29824 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
29825 
29826  { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
29827 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
29828 
29829  { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
29830 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
29831 
29832  { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
29833 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
29834 
29835 #if defined(HAVE_FCHOWN)
29836  { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
29837 #else
29838  { "fchown", (sqlite3_syscall_ptr)0, 0 },
29839 #endif
29840 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
29841 
29842  { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
29843 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
29844 
29845 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29846  { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
29847 #else
29848  { "mmap", (sqlite3_syscall_ptr)0, 0 },
29849 #endif
29850 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
29851 
29852 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29853  { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
29854 #else
29855  { "munmap", (sqlite3_syscall_ptr)0, 0 },
29856 #endif
29857 #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
29858 
29859 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
29860  { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
29861 #else
29862  { "mremap", (sqlite3_syscall_ptr)0, 0 },
29863 #endif
29864 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
29865 
29866 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29867  { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
29868 #else
29869  { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
29870 #endif
29871 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
29872 
29873 #if defined(HAVE_READLINK)
29874  { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
29875 #else
29876  { "readlink", (sqlite3_syscall_ptr)0, 0 },
29877 #endif
29878 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
29879 
29880 #if defined(HAVE_LSTAT)
29881  { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
29882 #else
29883  { "lstat", (sqlite3_syscall_ptr)0, 0 },
29884 #endif
29885 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
29886 
29887 }; /* End of the overrideable system calls */
29888 
29889 
29890 /*
29891 ** On some systems, calls to fchown() will trigger a message in a security
29892 ** log if they come from non-root processes. So avoid calling fchown() if
29893 ** we are not running as root.
29894 */
29895 static int robustFchown(int fd, uid_t uid, gid_t gid){
29896 #if defined(HAVE_FCHOWN)
29897  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
29898 #else
29899  return 0;
29900 #endif
29901 }
29902 
29903 /*
29904 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
29905 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
29906 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
29907 ** system call named zName.
29908 */
29910  sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
29911  const char *zName, /* Name of system call to override */
29912  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
29913 ){
29914  unsigned int i;
29915  int rc = SQLITE_NOTFOUND;
29916 
29917  UNUSED_PARAMETER(pNotUsed);
29918  if( zName==0 ){
29919  /* If no zName is given, restore all system calls to their default
29920  ** settings and return NULL
29921  */
29922  rc = SQLITE_OK;
29923  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29924  if( aSyscall[i].pDefault ){
29926  }
29927  }
29928  }else{
29929  /* If zName is specified, operate on only the one system call
29930  ** specified.
29931  */
29932  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29933  if( strcmp(zName, aSyscall[i].zName)==0 ){
29934  if( aSyscall[i].pDefault==0 ){
29936  }
29937  rc = SQLITE_OK;
29938  if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
29939  aSyscall[i].pCurrent = pNewFunc;
29940  break;
29941  }
29942  }
29943  }
29944  return rc;
29945 }
29946 
29947 /*
29948 ** Return the value of a system call. Return NULL if zName is not a
29949 ** recognized system call name. NULL is also returned if the system call
29950 ** is currently undefined.
29951 */
29953  sqlite3_vfs *pNotUsed,
29954  const char *zName
29955 ){
29956  unsigned int i;
29957 
29958  UNUSED_PARAMETER(pNotUsed);
29959  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29960  if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
29961  }
29962  return 0;
29963 }
29964 
29965 /*
29966 ** Return the name of the first system call after zName. If zName==NULL
29967 ** then return the name of the first system call. Return NULL if zName
29968 ** is the last system call or if zName is not the name of a valid
29969 ** system call.
29970 */
29971 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
29972  int i = -1;
29973 
29974  UNUSED_PARAMETER(p);
29975  if( zName ){
29976  for(i=0; i<ArraySize(aSyscall)-1; i++){
29977  if( strcmp(zName, aSyscall[i].zName)==0 ) break;
29978  }
29979  }
29980  for(i++; i<ArraySize(aSyscall); i++){
29981  if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
29982  }
29983  return 0;
29984 }
29985 
29986 /*
29987 ** Do not accept any file descriptor less than this value, in order to avoid
29988 ** opening database file using file descriptors that are commonly used for
29989 ** standard input, output, and error.
29990 */
29991 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
29992 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
29993 #endif
29994 
29995 /*
29996 ** Invoke open(). Do so multiple times, until it either succeeds or
29997 ** fails for some reason other than EINTR.
29998 **
29999 ** If the file creation mode "m" is 0 then set it to the default for
30000 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
30001 ** 0644) as modified by the system umask. If m is not 0, then
30002 ** make the file creation mode be exactly m ignoring the umask.
30003 **
30004 ** The m parameter will be non-zero only when creating -wal, -journal,
30005 ** and -shm files. We want those files to have *exactly* the same
30006 ** permissions as their original database, unadulterated by the umask.
30007 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
30008 ** transaction crashes and leaves behind hot journals, then any
30009 ** process that is able to write to the database will also be able to
30010 ** recover the hot journals.
30011 */
30012 static int robust_open(const char *z, int f, mode_t m){
30013  int fd;
30014  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
30015  while(1){
30016 #if defined(O_CLOEXEC)
30017  fd = osOpen(z,f|O_CLOEXEC,m2);
30018 #else
30019  fd = osOpen(z,f,m2);
30020 #endif
30021  if( fd<0 ){
30022  if( errno==EINTR ) continue;
30023  break;
30024  }
30025  if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
30026  osClose(fd);
30028  "attempt to open \"%s\" as file descriptor %d", z, fd);
30029  fd = -1;
30030  if( osOpen("/dev/null", f, m)<0 ) break;
30031  }
30032  if( fd>=0 ){
30033  if( m!=0 ){
30034  struct stat statbuf;
30035  if( osFstat(fd, &statbuf)==0
30036  && statbuf.st_size==0
30037  && (statbuf.st_mode&0777)!=m
30038  ){
30039  osFchmod(fd, m);
30040  }
30041  }
30042 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
30043  osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
30044 #endif
30045  }
30046  return fd;
30047 }
30048 
30049 /*
30050 ** Helper functions to obtain and relinquish the global mutex. The
30051 ** global mutex is used to protect the unixInodeInfo and
30052 ** vxworksFileId objects used by this file, all of which may be
30053 ** shared by multiple threads.
30054 **
30055 ** Function unixMutexHeld() is used to assert() that the global mutex
30056 ** is held when required. This function is only used as part of assert()
30057 ** statements. e.g.
30058 **
30059 ** unixEnterMutex()
30060 ** assert( unixMutexHeld() );
30061 ** unixEnterLeave()
30062 */
30063 static void unixEnterMutex(void){
30065 }
30066 static void unixLeaveMutex(void){
30068 }
30069 #ifdef SQLITE_DEBUG
30070 static int unixMutexHeld(void) {
30072 }
30073 #endif
30074 
30075 
30076 #ifdef SQLITE_HAVE_OS_TRACE
30077 /*
30078 ** Helper function for printing out trace information from debugging
30079 ** binaries. This returns the string representation of the supplied
30080 ** integer lock-type.
30081 */
30082 static const char *azFileLock(int eFileLock){
30083  switch( eFileLock ){
30084  case NO_LOCK: return "NONE";
30085  case SHARED_LOCK: return "SHARED";
30086  case RESERVED_LOCK: return "RESERVED";
30087  case PENDING_LOCK: return "PENDING";
30088  case EXCLUSIVE_LOCK: return "EXCLUSIVE";
30089  }
30090  return "ERROR";
30091 }
30092 #endif
30093 
30094 #ifdef SQLITE_LOCK_TRACE
30095 /*
30096 ** Print out information about all locking operations.
30097 **
30098 ** This routine is used for troubleshooting locks on multithreaded
30099 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
30100 ** command-line option on the compiler. This code is normally
30101 ** turned off.
30102 */
30103 static int lockTrace(int fd, int op, struct flock *p){
30104  char *zOpName, *zType;
30105  int s;
30106  int savedErrno;
30107  if( op==F_GETLK ){
30108  zOpName = "GETLK";
30109  }else if( op==F_SETLK ){
30110  zOpName = "SETLK";
30111  }else{
30112  s = osFcntl(fd, op, p);
30113  sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
30114  return s;
30115  }
30116  if( p->l_type==F_RDLCK ){
30117  zType = "RDLCK";
30118  }else if( p->l_type==F_WRLCK ){
30119  zType = "WRLCK";
30120  }else if( p->l_type==F_UNLCK ){
30121  zType = "UNLCK";
30122  }else{
30123  assert( 0 );
30124  }
30125  assert( p->l_whence==SEEK_SET );
30126  s = osFcntl(fd, op, p);
30127  savedErrno = errno;
30128  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
30129  threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
30130  (int)p->l_pid, s);
30131  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
30132  struct flock l2;
30133  l2 = *p;
30134  osFcntl(fd, F_GETLK, &l2);
30135  if( l2.l_type==F_RDLCK ){
30136  zType = "RDLCK";
30137  }else if( l2.l_type==F_WRLCK ){
30138  zType = "WRLCK";
30139  }else if( l2.l_type==F_UNLCK ){
30140  zType = "UNLCK";
30141  }else{
30142  assert( 0 );
30143  }
30144  sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
30145  zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
30146  }
30147  errno = savedErrno;
30148  return s;
30149 }
30150 #undef osFcntl
30151 #define osFcntl lockTrace
30152 #endif /* SQLITE_LOCK_TRACE */
30153 
30154 /*
30155 ** Retry ftruncate() calls that fail due to EINTR
30156 **
30157 ** All calls to ftruncate() within this file should be made through
30158 ** this wrapper. On the Android platform, bypassing the logic below
30159 ** could lead to a corrupt database.
30160 */
30161 static int robust_ftruncate(int h, sqlite3_int64 sz){
30162  int rc;
30163 #ifdef __ANDROID__
30164  /* On Android, ftruncate() always uses 32-bit offsets, even if
30165  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
30166  ** truncate a file to any size larger than 2GiB. Silently ignore any
30167  ** such attempts. */
30168  if( sz>(sqlite3_int64)0x7FFFFFFF ){
30169  rc = SQLITE_OK;
30170  }else
30171 #endif
30172  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
30173  return rc;
30174 }
30175 
30176 /*
30177 ** This routine translates a standard POSIX errno code into something
30178 ** useful to the clients of the sqlite3 functions. Specifically, it is
30179 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
30180 ** and a variety of "please close the file descriptor NOW" errors into
30181 ** SQLITE_IOERR
30182 **
30183 ** Errors during initialization of locks, or file system support for locks,
30184 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
30185 */
30186 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
30187  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
30188  (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
30189  (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
30190  (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
30191  switch (posixError) {
30192  case EACCES:
30193  case EAGAIN:
30194  case ETIMEDOUT:
30195  case EBUSY:
30196  case EINTR:
30197  case ENOLCK:
30198  /* random NFS retry error, unless during file system support
30199  * introspection, in which it actually means what it says */
30200  return SQLITE_BUSY;
30201 
30202  case EPERM:
30203  return SQLITE_PERM;
30204 
30205  default:
30206  return sqliteIOErr;
30207  }
30208 }
30209 
30210 
30211 /******************************************************************************
30212 ****************** Begin Unique File ID Utility Used By VxWorks ***************
30213 **
30214 ** On most versions of unix, we can get a unique ID for a file by concatenating
30215 ** the device number and the inode number. But this does not work on VxWorks.
30216 ** On VxWorks, a unique file id must be based on the canonical filename.
30217 **
30218 ** A pointer to an instance of the following structure can be used as a
30219 ** unique file ID in VxWorks. Each instance of this structure contains
30220 ** a copy of the canonical filename. There is also a reference count.
30221 ** The structure is reclaimed when the number of pointers to it drops to
30222 ** zero.
30223 **
30224 ** There are never very many files open at one time and lookups are not
30225 ** a performance-critical path, so it is sufficient to put these
30226 ** structures on a linked list.
30227 */
30229  struct vxworksFileId *pNext; /* Next in a list of them all */
30230  int nRef; /* Number of references to this one */
30231  int nName; /* Length of the zCanonicalName[] string */
30232  char *zCanonicalName; /* Canonical filename */
30233 };
30234 
30235 #if OS_VXWORKS
30236 /*
30237 ** All unique filenames are held on a linked list headed by this
30238 ** variable:
30239 */
30240 static struct vxworksFileId *vxworksFileList = 0;
30241 
30242 /*
30243 ** Simplify a filename into its canonical form
30244 ** by making the following changes:
30245 **
30246 ** * removing any trailing and duplicate /
30247 ** * convert /./ into just /
30248 ** * convert /A/../ where A is any simple name into just /
30249 **
30250 ** Changes are made in-place. Return the new name length.
30251 **
30252 ** The original filename is in z[0..n-1]. Return the number of
30253 ** characters in the simplified name.
30254 */
30255 static int vxworksSimplifyName(char *z, int n){
30256  int i, j;
30257  while( n>1 && z[n-1]=='/' ){ n--; }
30258  for(i=j=0; i<n; i++){
30259  if( z[i]=='/' ){
30260  if( z[i+1]=='/' ) continue;
30261  if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
30262  i += 1;
30263  continue;
30264  }
30265  if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
30266  while( j>0 && z[j-1]!='/' ){ j--; }
30267  if( j>0 ){ j--; }
30268  i += 2;
30269  continue;
30270  }
30271  }
30272  z[j++] = z[i];
30273  }
30274  z[j] = 0;
30275  return j;
30276 }
30277 
30278 /*
30279 ** Find a unique file ID for the given absolute pathname. Return
30280 ** a pointer to the vxworksFileId object. This pointer is the unique
30281 ** file ID.
30282 **
30283 ** The nRef field of the vxworksFileId object is incremented before
30284 ** the object is returned. A new vxworksFileId object is created
30285 ** and added to the global list if necessary.
30286 **
30287 ** If a memory allocation error occurs, return NULL.
30288 */
30289 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
30290  struct vxworksFileId *pNew; /* search key and new file ID */
30291  struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
30292  int n; /* Length of zAbsoluteName string */
30293 
30294  assert( zAbsoluteName[0]=='/' );
30295  n = (int)strlen(zAbsoluteName);
30296  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
30297  if( pNew==0 ) return 0;
30298  pNew->zCanonicalName = (char*)&pNew[1];
30299  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
30300  n = vxworksSimplifyName(pNew->zCanonicalName, n);
30301 
30302  /* Search for an existing entry that matching the canonical name.
30303  ** If found, increment the reference count and return a pointer to
30304  ** the existing file ID.
30305  */
30306  unixEnterMutex();
30307  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
30308  if( pCandidate->nName==n
30309  && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
30310  ){
30311  sqlite3_free(pNew);
30312  pCandidate->nRef++;
30313  unixLeaveMutex();
30314  return pCandidate;
30315  }
30316  }
30317 
30318  /* No match was found. We will make a new file ID */
30319  pNew->nRef = 1;
30320  pNew->nName = n;
30321  pNew->pNext = vxworksFileList;
30322  vxworksFileList = pNew;
30323  unixLeaveMutex();
30324  return pNew;
30325 }
30326 
30327 /*
30328 ** Decrement the reference count on a vxworksFileId object. Free
30329 ** the object when the reference count reaches zero.
30330 */
30331 static void vxworksReleaseFileId(struct vxworksFileId *pId){
30332  unixEnterMutex();
30333  assert( pId->nRef>0 );
30334  pId->nRef--;
30335  if( pId->nRef==0 ){
30336  struct vxworksFileId **pp;
30337  for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
30338  assert( *pp==pId );
30339  *pp = pId->pNext;
30340  sqlite3_free(pId);
30341  }
30342  unixLeaveMutex();
30343 }
30344 #endif /* OS_VXWORKS */
30345 /*************** End of Unique File ID Utility Used By VxWorks ****************
30346 ******************************************************************************/
30347 
30348 
30349 /******************************************************************************
30350 *************************** Posix Advisory Locking ****************************
30351 **
30352 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
30353 ** section 6.5.2.2 lines 483 through 490 specify that when a process
30354 ** sets or clears a lock, that operation overrides any prior locks set
30355 ** by the same process. It does not explicitly say so, but this implies
30356 ** that it overrides locks set by the same process using a different
30357 ** file descriptor. Consider this test case:
30358 **
30359 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
30360 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
30361 **
30362 ** Suppose ./file1 and ./file2 are really the same file (because
30363 ** one is a hard or symbolic link to the other) then if you set
30364 ** an exclusive lock on fd1, then try to get an exclusive lock
30365 ** on fd2, it works. I would have expected the second lock to
30366 ** fail since there was already a lock on the file due to fd1.
30367 ** But not so. Since both locks came from the same process, the
30368 ** second overrides the first, even though they were on different
30369 ** file descriptors opened on different file names.
30370 **
30371 ** This means that we cannot use POSIX locks to synchronize file access
30372 ** among competing threads of the same process. POSIX locks will work fine
30373 ** to synchronize access for threads in separate processes, but not
30374 ** threads within the same process.
30375 **
30376 ** To work around the problem, SQLite has to manage file locks internally
30377 ** on its own. Whenever a new database is opened, we have to find the
30378 ** specific inode of the database file (the inode is determined by the
30379 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
30380 ** and check for locks already existing on that inode. When locks are
30381 ** created or removed, we have to look at our own internal record of the
30382 ** locks to see if another thread has previously set a lock on that same
30383 ** inode.
30384 **
30385 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
30386 ** For VxWorks, we have to use the alternative unique ID system based on
30387 ** canonical filename and implemented in the previous division.)
30388 **
30389 ** The sqlite3_file structure for POSIX is no longer just an integer file
30390 ** descriptor. It is now a structure that holds the integer file
30391 ** descriptor and a pointer to a structure that describes the internal
30392 ** locks on the corresponding inode. There is one locking structure
30393 ** per inode, so if the same inode is opened twice, both unixFile structures
30394 ** point to the same locking structure. The locking structure keeps
30395 ** a reference count (so we will know when to delete it) and a "cnt"
30396 ** field that tells us its internal lock status. cnt==0 means the
30397 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
30398 ** cnt>0 means there are cnt shared locks on the file.
30399 **
30400 ** Any attempt to lock or unlock a file first checks the locking
30401 ** structure. The fcntl() system call is only invoked to set a
30402 ** POSIX lock if the internal lock structure transitions between
30403 ** a locked and an unlocked state.
30404 **
30405 ** But wait: there are yet more problems with POSIX advisory locks.
30406 **
30407 ** If you close a file descriptor that points to a file that has locks,
30408 ** all locks on that file that are owned by the current process are
30409 ** released. To work around this problem, each unixInodeInfo object
30410 ** maintains a count of the number of pending locks on tha inode.
30411 ** When an attempt is made to close an unixFile, if there are
30412 ** other unixFile open on the same inode that are holding locks, the call
30413 ** to close() the file descriptor is deferred until all of the locks clear.
30414 ** The unixInodeInfo structure keeps a list of file descriptors that need to
30415 ** be closed and that list is walked (and cleared) when the last lock
30416 ** clears.
30417 **
30418 ** Yet another problem: LinuxThreads do not play well with posix locks.
30419 **
30420 ** Many older versions of linux use the LinuxThreads library which is
30421 ** not posix compliant. Under LinuxThreads, a lock created by thread
30422 ** A cannot be modified or overridden by a different thread B.
30423 ** Only thread A can modify the lock. Locking behavior is correct
30424 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
30425 ** on linux - with NPTL a lock created by thread A can override locks
30426 ** in thread B. But there is no way to know at compile-time which
30427 ** threading library is being used. So there is no way to know at
30428 ** compile-time whether or not thread A can override locks on thread B.
30429 ** One has to do a run-time check to discover the behavior of the
30430 ** current process.
30431 **
30432 ** SQLite used to support LinuxThreads. But support for LinuxThreads
30433 ** was dropped beginning with version 3.7.0. SQLite will still work with
30434 ** LinuxThreads provided that (1) there is no more than one connection
30435 ** per database file in the same process and (2) database connections
30436 ** do not move across threads.
30437 */
30438 
30439 /*
30440 ** An instance of the following structure serves as the key used
30441 ** to locate a particular unixInodeInfo object.
30442 */
30443 struct unixFileId {
30444  dev_t dev; /* Device number */
30445 #if OS_VXWORKS
30446  struct vxworksFileId *pId; /* Unique file ID for vxworks. */
30447 #else
30448  ino_t ino; /* Inode number */
30449 #endif
30450 };
30451 
30452 /*
30453 ** An instance of the following structure is allocated for each open
30454 ** inode. Or, on LinuxThreads, there is one of these structures for
30455 ** each inode opened by each thread.
30456 **
30457 ** A single inode can have multiple file descriptors, so each unixFile
30458 ** structure contains a pointer to an instance of this object and this
30459 ** object keeps a count of the number of unixFile pointing to it.
30460 */
30462  struct unixFileId fileId; /* The lookup key */
30463  int nShared; /* Number of SHARED locks held */
30464  unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
30465  unsigned char bProcessLock; /* An exclusive process lock is held */
30466  int nRef; /* Number of pointers to this structure */
30467  unixShmNode *pShmNode; /* Shared memory associated with this inode */
30468  int nLock; /* Number of outstanding file locks */
30469  UnixUnusedFd *pUnused; /* Unused file descriptors to close */
30470  unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
30471  unixInodeInfo *pPrev; /* .... doubly linked */
30472 #if SQLITE_ENABLE_LOCKING_STYLE
30473  unsigned long long sharedByte; /* for AFP simulated shared lock */
30474 #endif
30475 #if OS_VXWORKS
30476  sem_t *pSem; /* Named POSIX semaphore */
30477  char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
30478 #endif
30479 };
30480 
30481 /*
30482 ** A lists of all unixInodeInfo objects.
30483 */
30485 
30486 /*
30487 **
30488 ** This function - unixLogErrorAtLine(), is only ever called via the macro
30489 ** unixLogError().
30490 **
30491 ** It is invoked after an error occurs in an OS function and errno has been
30492 ** set. It logs a message using sqlite3_log() containing the current value of
30493 ** errno and, if possible, the human-readable equivalent from strerror() or
30494 ** strerror_r().
30495 **
30496 ** The first argument passed to the macro should be the error code that
30497 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
30498 ** The two subsequent arguments should be the name of the OS function that
30499 ** failed (e.g. "unlink", "open") and the associated file-system path,
30500 ** if any.
30501 */
30502 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
30504  int errcode, /* SQLite error code */
30505  const char *zFunc, /* Name of OS function that failed */
30506  const char *zPath, /* File path associated with error */
30507  int iLine /* Source line number where error occurred */
30508 ){
30509  char *zErr; /* Message from strerror() or equivalent */
30510  int iErrno = errno; /* Saved syscall error number */
30511 
30512  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
30513  ** the strerror() function to obtain the human-readable error message
30514  ** equivalent to errno. Otherwise, use strerror_r().
30515  */
30516 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
30517  char aErr[80];
30518  memset(aErr, 0, sizeof(aErr));
30519  zErr = aErr;
30520 
30521  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
30522  ** assume that the system provides the GNU version of strerror_r() that
30523  ** returns a pointer to a buffer containing the error message. That pointer
30524  ** may point to aErr[], or it may point to some static storage somewhere.
30525  ** Otherwise, assume that the system provides the POSIX version of
30526  ** strerror_r(), which always writes an error message into aErr[].
30527  **
30528  ** If the code incorrectly assumes that it is the POSIX version that is
30529  ** available, the error message will often be an empty string. Not a
30530  ** huge problem. Incorrectly concluding that the GNU version is available
30531  ** could lead to a segfault though.
30532  */
30533 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
30534  zErr =
30535 # endif
30536  strerror_r(iErrno, aErr, sizeof(aErr)-1);
30537 
30538 #elif SQLITE_THREADSAFE
30539  /* This is a threadsafe build, but strerror_r() is not available. */
30540  zErr = "";
30541 #else
30542  /* Non-threadsafe build, use strerror(). */
30543  zErr = strerror(iErrno);
30544 #endif
30545 
30546  if( zPath==0 ) zPath = "";
30547  sqlite3_log(errcode,
30548  "os_unix.c:%d: (%d) %s(%s) - %s",
30549  iLine, iErrno, zFunc, zPath, zErr
30550  );
30551 
30552  return errcode;
30553 }
30554 
30555 /*
30556 ** Close a file descriptor.
30557 **
30558 ** We assume that close() almost always works, since it is only in a
30559 ** very sick application or on a very sick platform that it might fail.
30560 ** If it does fail, simply leak the file descriptor, but do log the
30561 ** error.
30562 **
30563 ** Note that it is not safe to retry close() after EINTR since the
30564 ** file descriptor might have already been reused by another thread.
30565 ** So we don't even try to recover from an EINTR. Just log the error
30566 ** and move on.
30567 */
30568 static void robust_close(unixFile *pFile, int h, int lineno){
30569  if( osClose(h) ){
30571  pFile ? pFile->zPath : 0, lineno);
30572  }
30573 }
30574 
30575 /*
30576 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
30577 ** a convenient place to set a breakpoint.
30578 */
30579 static void storeLastErrno(unixFile *pFile, int error){
30580  pFile->lastErrno = error;
30581 }
30582 
30583 /*
30584 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
30585 */
30586 static void closePendingFds(unixFile *pFile){
30587  unixInodeInfo *pInode = pFile->pInode;
30588  UnixUnusedFd *p;
30589  UnixUnusedFd *pNext;
30590  for(p=pInode->pUnused; p; p=pNext){
30591  pNext = p->pNext;
30592  robust_close(pFile, p->fd, __LINE__);
30593  sqlite3_free(p);
30594  }
30595  pInode->pUnused = 0;
30596 }
30597 
30598 /*
30599 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
30600 **
30601 ** The mutex entered using the unixEnterMutex() function must be held
30602 ** when this function is called.
30603 */
30604 static void releaseInodeInfo(unixFile *pFile){
30605  unixInodeInfo *pInode = pFile->pInode;
30606  assert( unixMutexHeld() );
30607  if( ALWAYS(pInode) ){
30608  pInode->nRef--;
30609  if( pInode->nRef==0 ){
30610  assert( pInode->pShmNode==0 );
30611  closePendingFds(pFile);
30612  if( pInode->pPrev ){
30613  assert( pInode->pPrev->pNext==pInode );
30614  pInode->pPrev->pNext = pInode->pNext;
30615  }else{
30616  assert( inodeList==pInode );
30617  inodeList = pInode->pNext;
30618  }
30619  if( pInode->pNext ){
30620  assert( pInode->pNext->pPrev==pInode );
30621  pInode->pNext->pPrev = pInode->pPrev;
30622  }
30623  sqlite3_free(pInode);
30624  }
30625  }
30626 }
30627 
30628 /*
30629 ** Given a file descriptor, locate the unixInodeInfo object that
30630 ** describes that file descriptor. Create a new one if necessary. The
30631 ** return value might be uninitialized if an error occurs.
30632 **
30633 ** The mutex entered using the unixEnterMutex() function must be held
30634 ** when this function is called.
30635 **
30636 ** Return an appropriate error code.
30637 */
30638 static int findInodeInfo(
30639  unixFile *pFile, /* Unix file with file desc used in the key */
30640  unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
30641 ){
30642  int rc; /* System call return code */
30643  int fd; /* The file descriptor for pFile */
30644  struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
30645  struct stat statbuf; /* Low-level file information */
30646  unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
30647 
30648  assert( unixMutexHeld() );
30649 
30650  /* Get low-level information about the file that we can used to
30651  ** create a unique name for the file.
30652  */
30653  fd = pFile->h;
30654  rc = osFstat(fd, &statbuf);
30655  if( rc!=0 ){
30656  storeLastErrno(pFile, errno);
30657 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
30658  if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
30659 #endif
30660  return SQLITE_IOERR;
30661  }
30662 
30663 #ifdef __APPLE__
30664  /* On OS X on an msdos filesystem, the inode number is reported
30665  ** incorrectly for zero-size files. See ticket #3260. To work
30666  ** around this problem (we consider it a bug in OS X, not SQLite)
30667  ** we always increase the file size to 1 by writing a single byte
30668  ** prior to accessing the inode number. The one byte written is
30669  ** an ASCII 'S' character which also happens to be the first byte
30670  ** in the header of every SQLite database. In this way, if there
30671  ** is a race condition such that another thread has already populated
30672  ** the first page of the database, no damage is done.
30673  */
30674  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
30675  do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
30676  if( rc!=1 ){
30677  storeLastErrno(pFile, errno);
30678  return SQLITE_IOERR;
30679  }
30680  rc = osFstat(fd, &statbuf);
30681  if( rc!=0 ){
30682  storeLastErrno(pFile, errno);
30683  return SQLITE_IOERR;
30684  }
30685  }
30686 #endif
30687 
30688  memset(&fileId, 0, sizeof(fileId));
30689  fileId.dev = statbuf.st_dev;
30690 #if OS_VXWORKS
30691  fileId.pId = pFile->pId;
30692 #else
30693  fileId.ino = statbuf.st_ino;
30694 #endif
30695  pInode = inodeList;
30696  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
30697  pInode = pInode->pNext;
30698  }
30699  if( pInode==0 ){
30700  pInode = sqlite3_malloc64( sizeof(*pInode) );
30701  if( pInode==0 ){
30702  return SQLITE_NOMEM_BKPT;
30703  }
30704  memset(pInode, 0, sizeof(*pInode));
30705  memcpy(&pInode->fileId, &fileId, sizeof(fileId));
30706  pInode->nRef = 1;
30707  pInode->pNext = inodeList;
30708  pInode->pPrev = 0;
30709  if( inodeList ) inodeList->pPrev = pInode;
30710  inodeList = pInode;
30711  }else{
30712  pInode->nRef++;
30713  }
30714  *ppInode = pInode;
30715  return SQLITE_OK;
30716 }
30717 
30718 /*
30719 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
30720 */
30721 static int fileHasMoved(unixFile *pFile){
30722 #if OS_VXWORKS
30723  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
30724 #else
30725  struct stat buf;
30726  return pFile->pInode!=0 &&
30727  (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
30728 #endif
30729 }
30730 
30731 
30732 /*
30733 ** Check a unixFile that is a database. Verify the following:
30734 **
30735 ** (1) There is exactly one hard link on the file
30736 ** (2) The file is not a symbolic link
30737 ** (3) The file has not been renamed or unlinked
30738 **
30739 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
30740 */
30741 static void verifyDbFile(unixFile *pFile){
30742  struct stat buf;
30743  int rc;
30744 
30745  /* These verifications occurs for the main database only */
30746  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
30747 
30748  rc = osFstat(pFile->h, &buf);
30749  if( rc!=0 ){
30750  sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
30751  return;
30752  }
30753  if( buf.st_nlink==0 ){
30754  sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
30755  return;
30756  }
30757  if( buf.st_nlink>1 ){
30758  sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
30759  return;
30760  }
30761  if( fileHasMoved(pFile) ){
30762  sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
30763  return;
30764  }
30765 }
30766 
30767 
30768 /*
30769 ** This routine checks if there is a RESERVED lock held on the specified
30770 ** file by this or any other process. If such a lock is held, set *pResOut
30771 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30772 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30773 */
30774 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
30775  int rc = SQLITE_OK;
30776  int reserved = 0;
30777  unixFile *pFile = (unixFile*)id;
30778 
30780 
30781  assert( pFile );
30782  assert( pFile->eFileLock<=SHARED_LOCK );
30783  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
30784 
30785  /* Check if a thread in this process holds such a lock */
30786  if( pFile->pInode->eFileLock>SHARED_LOCK ){
30787  reserved = 1;
30788  }
30789 
30790  /* Otherwise see if some other process holds it.
30791  */
30792 #ifndef __DJGPP__
30793  if( !reserved && !pFile->pInode->bProcessLock ){
30794  struct flock lock;
30795  lock.l_whence = SEEK_SET;
30796  lock.l_start = RESERVED_BYTE;
30797  lock.l_len = 1;
30798  lock.l_type = F_WRLCK;
30799  if( osFcntl(pFile->h, F_GETLK, &lock) ){
30801  storeLastErrno(pFile, errno);
30802  } else if( lock.l_type!=F_UNLCK ){
30803  reserved = 1;
30804  }
30805  }
30806 #endif
30807 
30808  unixLeaveMutex();
30809  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
30810 
30811  *pResOut = reserved;
30812  return rc;
30813 }
30814 
30815 /*
30816 ** Attempt to set a system-lock on the file pFile. The lock is
30817 ** described by pLock.
30818 **
30819 ** If the pFile was opened read/write from unix-excl, then the only lock
30820 ** ever obtained is an exclusive lock, and it is obtained exactly once
30821 ** the first time any lock is attempted. All subsequent system locking
30822 ** operations become no-ops. Locking operations still happen internally,
30823 ** in order to coordinate access between separate database connections
30824 ** within this process, but all of that is handled in memory and the
30825 ** operating system does not participate.
30826 **
30827 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
30828 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
30829 ** and is read-only.
30830 **
30831 ** Zero is returned if the call completes successfully, or -1 if a call
30832 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
30833 */
30834 static int unixFileLock(unixFile *pFile, struct flock *pLock){
30835  int rc;
30836  unixInodeInfo *pInode = pFile->pInode;
30837  assert( unixMutexHeld() );
30838  assert( pInode!=0 );
30840  if( pInode->bProcessLock==0 ){
30841  struct flock lock;
30842  assert( pInode->nLock==0 );
30843  lock.l_whence = SEEK_SET;
30844  lock.l_start = SHARED_FIRST;
30845  lock.l_len = SHARED_SIZE;
30846  lock.l_type = F_WRLCK;
30847  rc = osFcntl(pFile->h, F_SETLK, &lock);
30848  if( rc<0 ) return rc;
30849  pInode->bProcessLock = 1;
30850  pInode->nLock++;
30851  }else{
30852  rc = 0;
30853  }
30854  }else{
30855  rc = osFcntl(pFile->h, F_SETLK, pLock);
30856  }
30857  return rc;
30858 }
30859 
30860 /*
30861 ** Lock the file with the lock specified by parameter eFileLock - one
30862 ** of the following:
30863 **
30864 ** (1) SHARED_LOCK
30865 ** (2) RESERVED_LOCK
30866 ** (3) PENDING_LOCK
30867 ** (4) EXCLUSIVE_LOCK
30868 **
30869 ** Sometimes when requesting one lock state, additional lock states
30870 ** are inserted in between. The locking might fail on one of the later
30871 ** transitions leaving the lock state different from what it started but
30872 ** still short of its goal. The following chart shows the allowed
30873 ** transitions and the inserted intermediate states:
30874 **
30875 ** UNLOCKED -> SHARED
30876 ** SHARED -> RESERVED
30877 ** SHARED -> (PENDING) -> EXCLUSIVE
30878 ** RESERVED -> (PENDING) -> EXCLUSIVE
30879 ** PENDING -> EXCLUSIVE
30880 **
30881 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30882 ** routine to lower a locking level.
30883 */
30884 static int unixLock(sqlite3_file *id, int eFileLock){
30885  /* The following describes the implementation of the various locks and
30886  ** lock transitions in terms of the POSIX advisory shared and exclusive
30887  ** lock primitives (called read-locks and write-locks below, to avoid
30888  ** confusion with SQLite lock names). The algorithms are complicated
30889  ** slightly in order to be compatible with Windows95 systems simultaneously
30890  ** accessing the same database file, in case that is ever required.
30891  **
30892  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
30893  ** byte', each single bytes at well known offsets, and the 'shared byte
30894  ** range', a range of 510 bytes at a well known offset.
30895  **
30896  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
30897  ** byte'. If this is successful, 'shared byte range' is read-locked
30898  ** and the lock on the 'pending byte' released. (Legacy note: When
30899  ** SQLite was first developed, Windows95 systems were still very common,
30900  ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
30901  ** single randomly selected by from the 'shared byte range' is locked.
30902  ** Windows95 is now pretty much extinct, but this work-around for the
30903  ** lack of shared-locks on Windows95 lives on, for backwards
30904  ** compatibility.)
30905  **
30906  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
30907  ** A RESERVED lock is implemented by grabbing a write-lock on the
30908  ** 'reserved byte'.
30909  **
30910  ** A process may only obtain a PENDING lock after it has obtained a
30911  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
30912  ** on the 'pending byte'. This ensures that no new SHARED locks can be
30913  ** obtained, but existing SHARED locks are allowed to persist. A process
30914  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
30915  ** This property is used by the algorithm for rolling back a journal file
30916  ** after a crash.
30917  **
30918  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
30919  ** implemented by obtaining a write-lock on the entire 'shared byte
30920  ** range'. Since all other locks require a read-lock on one of the bytes
30921  ** within this range, this ensures that no other locks are held on the
30922  ** database.
30923  */
30924  int rc = SQLITE_OK;
30925  unixFile *pFile = (unixFile*)id;
30926  unixInodeInfo *pInode;
30927  struct flock lock;
30928  int tErrno = 0;
30929 
30930  assert( pFile );
30931  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
30932  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
30933  azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
30934  osGetpid(0)));
30935 
30936  /* If there is already a lock of this type or more restrictive on the
30937  ** unixFile, do nothing. Don't use the end_lock: exit path, as
30938  ** unixEnterMutex() hasn't been called yet.
30939  */
30940  if( pFile->eFileLock>=eFileLock ){
30941  OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
30942  azFileLock(eFileLock)));
30943  return SQLITE_OK;
30944  }
30945 
30946  /* Make sure the locking sequence is correct.
30947  ** (1) We never move from unlocked to anything higher than shared lock.
30948  ** (2) SQLite never explicitly requests a pendig lock.
30949  ** (3) A shared lock is always held when a reserve lock is requested.
30950  */
30951  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
30952  assert( eFileLock!=PENDING_LOCK );
30953  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
30954 
30955  /* This mutex is needed because pFile->pInode is shared across threads
30956  */
30957  unixEnterMutex();
30958  pInode = pFile->pInode;
30959 
30960  /* If some thread using this PID has a lock via a different unixFile*
30961  ** handle that precludes the requested lock, return BUSY.
30962  */
30963  if( (pFile->eFileLock!=pInode->eFileLock &&
30964  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
30965  ){
30966  rc = SQLITE_BUSY;
30967  goto end_lock;
30968  }
30969 
30970  /* If a SHARED lock is requested, and some thread using this PID already
30971  ** has a SHARED or RESERVED lock, then increment reference counts and
30972  ** return SQLITE_OK.
30973  */
30974  if( eFileLock==SHARED_LOCK &&
30975  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
30976  assert( eFileLock==SHARED_LOCK );
30977  assert( pFile->eFileLock==0 );
30978  assert( pInode->nShared>0 );
30979  pFile->eFileLock = SHARED_LOCK;
30980  pInode->nShared++;
30981  pInode->nLock++;
30982  goto end_lock;
30983  }
30984 
30985 
30986  /* A PENDING lock is needed before acquiring a SHARED lock and before
30987  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
30988  ** be released.
30989  */
30990  lock.l_len = 1L;
30991  lock.l_whence = SEEK_SET;
30992  if( eFileLock==SHARED_LOCK
30993  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
30994  ){
30995  lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
30996  lock.l_start = PENDING_BYTE;
30997  if( unixFileLock(pFile, &lock) ){
30998  tErrno = errno;
31000  if( rc!=SQLITE_BUSY ){
31001  storeLastErrno(pFile, tErrno);
31002  }
31003  goto end_lock;
31004  }
31005  }
31006 
31007 
31008  /* If control gets to this point, then actually go ahead and make
31009  ** operating system calls for the specified lock.
31010  */
31011  if( eFileLock==SHARED_LOCK ){
31012  assert( pInode->nShared==0 );
31013  assert( pInode->eFileLock==0 );
31014  assert( rc==SQLITE_OK );
31015 
31016  /* Now get the read-lock */
31017  lock.l_start = SHARED_FIRST;
31018  lock.l_len = SHARED_SIZE;
31019  if( unixFileLock(pFile, &lock) ){
31020  tErrno = errno;
31022  }
31023 
31024  /* Drop the temporary PENDING lock */
31025  lock.l_start = PENDING_BYTE;
31026  lock.l_len = 1L;
31027  lock.l_type = F_UNLCK;
31028  if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
31029  /* This could happen with a network mount */
31030  tErrno = errno;
31031  rc = SQLITE_IOERR_UNLOCK;
31032  }
31033 
31034  if( rc ){
31035  if( rc!=SQLITE_BUSY ){
31036  storeLastErrno(pFile, tErrno);
31037  }
31038  goto end_lock;
31039  }else{
31040  pFile->eFileLock = SHARED_LOCK;
31041  pInode->nLock++;
31042  pInode->nShared = 1;
31043  }
31044  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
31045  /* We are trying for an exclusive lock but another thread in this
31046  ** same process is still holding a shared lock. */
31047  rc = SQLITE_BUSY;
31048  }else{
31049  /* The request was for a RESERVED or EXCLUSIVE lock. It is
31050  ** assumed that there is a SHARED or greater lock on the file
31051  ** already.
31052  */
31053  assert( 0!=pFile->eFileLock );
31054  lock.l_type = F_WRLCK;
31055 
31056  assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
31057  if( eFileLock==RESERVED_LOCK ){
31058  lock.l_start = RESERVED_BYTE;
31059  lock.l_len = 1L;
31060  }else{
31061  lock.l_start = SHARED_FIRST;
31062  lock.l_len = SHARED_SIZE;
31063  }
31064 
31065  if( unixFileLock(pFile, &lock) ){
31066  tErrno = errno;
31068  if( rc!=SQLITE_BUSY ){
31069  storeLastErrno(pFile, tErrno);
31070  }
31071  }
31072  }
31073 
31074 
31075 #ifdef SQLITE_DEBUG
31076  /* Set up the transaction-counter change checking flags when
31077  ** transitioning from a SHARED to a RESERVED lock. The change
31078  ** from SHARED to RESERVED marks the beginning of a normal
31079  ** write operation (not a hot journal rollback).
31080  */
31081  if( rc==SQLITE_OK
31082  && pFile->eFileLock<=SHARED_LOCK
31083  && eFileLock==RESERVED_LOCK
31084  ){
31085  pFile->transCntrChng = 0;
31086  pFile->dbUpdate = 0;
31087  pFile->inNormalWrite = 1;
31088  }
31089 #endif
31090 
31091 
31092  if( rc==SQLITE_OK ){
31093  pFile->eFileLock = eFileLock;
31094  pInode->eFileLock = eFileLock;
31095  }else if( eFileLock==EXCLUSIVE_LOCK ){
31096  pFile->eFileLock = PENDING_LOCK;
31097  pInode->eFileLock = PENDING_LOCK;
31098  }
31099 
31100 end_lock:
31101  unixLeaveMutex();
31102  OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
31103  rc==SQLITE_OK ? "ok" : "failed"));
31104  return rc;
31105 }
31106 
31107 /*
31108 ** Add the file descriptor used by file handle pFile to the corresponding
31109 ** pUnused list.
31110 */
31111 static void setPendingFd(unixFile *pFile){
31112  unixInodeInfo *pInode = pFile->pInode;
31113  UnixUnusedFd *p = pFile->pUnused;
31114  p->pNext = pInode->pUnused;
31115  pInode->pUnused = p;
31116  pFile->h = -1;
31117  pFile->pUnused = 0;
31118 }
31119 
31120 /*
31121 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31122 ** must be either NO_LOCK or SHARED_LOCK.
31123 **
31124 ** If the locking level of the file descriptor is already at or below
31125 ** the requested locking level, this routine is a no-op.
31126 **
31127 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
31128 ** the byte range is divided into 2 parts and the first part is unlocked then
31129 ** set to a read lock, then the other part is simply unlocked. This works
31130 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
31131 ** remove the write lock on a region when a read lock is set.
31132 */
31133 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
31134  unixFile *pFile = (unixFile*)id;
31135  unixInodeInfo *pInode;
31136  struct flock lock;
31137  int rc = SQLITE_OK;
31138 
31139  assert( pFile );
31140  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
31141  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
31142  osGetpid(0)));
31143 
31144  assert( eFileLock<=SHARED_LOCK );
31145  if( pFile->eFileLock<=eFileLock ){
31146  return SQLITE_OK;
31147  }
31148  unixEnterMutex();
31149  pInode = pFile->pInode;
31150  assert( pInode->nShared!=0 );
31151  if( pFile->eFileLock>SHARED_LOCK ){
31152  assert( pInode->eFileLock==pFile->eFileLock );
31153 
31154 #ifdef SQLITE_DEBUG
31155  /* When reducing a lock such that other processes can start
31156  ** reading the database file again, make sure that the
31157  ** transaction counter was updated if any part of the database
31158  ** file changed. If the transaction counter is not updated,
31159  ** other connections to the same file might not realize that
31160  ** the file has changed and hence might not know to flush their
31161  ** cache. The use of a stale cache can lead to database corruption.
31162  */
31163  pFile->inNormalWrite = 0;
31164 #endif
31165 
31166  /* downgrading to a shared lock on NFS involves clearing the write lock
31167  ** before establishing the readlock - to avoid a race condition we downgrade
31168  ** the lock in 2 blocks, so that part of the range will be covered by a
31169  ** write lock until the rest is covered by a read lock:
31170  ** 1: [WWWWW]
31171  ** 2: [....W]
31172  ** 3: [RRRRW]
31173  ** 4: [RRRR.]
31174  */
31175  if( eFileLock==SHARED_LOCK ){
31176 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
31177  (void)handleNFSUnlock;
31178  assert( handleNFSUnlock==0 );
31179 #endif
31180 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31181  if( handleNFSUnlock ){
31182  int tErrno; /* Error code from system call errors */
31183  off_t divSize = SHARED_SIZE - 1;
31184 
31185  lock.l_type = F_UNLCK;
31186  lock.l_whence = SEEK_SET;
31187  lock.l_start = SHARED_FIRST;
31188  lock.l_len = divSize;
31189  if( unixFileLock(pFile, &lock)==(-1) ){
31190  tErrno = errno;
31191  rc = SQLITE_IOERR_UNLOCK;
31192  storeLastErrno(pFile, tErrno);
31193  goto end_unlock;
31194  }
31195  lock.l_type = F_RDLCK;
31196  lock.l_whence = SEEK_SET;
31197  lock.l_start = SHARED_FIRST;
31198  lock.l_len = divSize;
31199  if( unixFileLock(pFile, &lock)==(-1) ){
31200  tErrno = errno;
31202  if( IS_LOCK_ERROR(rc) ){
31203  storeLastErrno(pFile, tErrno);
31204  }
31205  goto end_unlock;
31206  }
31207  lock.l_type = F_UNLCK;
31208  lock.l_whence = SEEK_SET;
31209  lock.l_start = SHARED_FIRST+divSize;
31210  lock.l_len = SHARED_SIZE-divSize;
31211  if( unixFileLock(pFile, &lock)==(-1) ){
31212  tErrno = errno;
31213  rc = SQLITE_IOERR_UNLOCK;
31214  storeLastErrno(pFile, tErrno);
31215  goto end_unlock;
31216  }
31217  }else
31218 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31219  {
31220  lock.l_type = F_RDLCK;
31221  lock.l_whence = SEEK_SET;
31222  lock.l_start = SHARED_FIRST;
31223  lock.l_len = SHARED_SIZE;
31224  if( unixFileLock(pFile, &lock) ){
31225  /* In theory, the call to unixFileLock() cannot fail because another
31226  ** process is holding an incompatible lock. If it does, this
31227  ** indicates that the other process is not following the locking
31228  ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
31229  ** SQLITE_BUSY would confuse the upper layer (in practice it causes
31230  ** an assert to fail). */
31231  rc = SQLITE_IOERR_RDLOCK;
31232  storeLastErrno(pFile, errno);
31233  goto end_unlock;
31234  }
31235  }
31236  }
31237  lock.l_type = F_UNLCK;
31238  lock.l_whence = SEEK_SET;
31239  lock.l_start = PENDING_BYTE;
31240  lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
31241  if( unixFileLock(pFile, &lock)==0 ){
31242  pInode->eFileLock = SHARED_LOCK;
31243  }else{
31244  rc = SQLITE_IOERR_UNLOCK;
31245  storeLastErrno(pFile, errno);
31246  goto end_unlock;
31247  }
31248  }
31249  if( eFileLock==NO_LOCK ){
31250  /* Decrement the shared lock counter. Release the lock using an
31251  ** OS call only when all threads in this same process have released
31252  ** the lock.
31253  */
31254  pInode->nShared--;
31255  if( pInode->nShared==0 ){
31256  lock.l_type = F_UNLCK;
31257  lock.l_whence = SEEK_SET;
31258  lock.l_start = lock.l_len = 0L;
31259  if( unixFileLock(pFile, &lock)==0 ){
31260  pInode->eFileLock = NO_LOCK;
31261  }else{
31262  rc = SQLITE_IOERR_UNLOCK;
31263  storeLastErrno(pFile, errno);
31264  pInode->eFileLock = NO_LOCK;
31265  pFile->eFileLock = NO_LOCK;
31266  }
31267  }
31268 
31269  /* Decrement the count of locks against this same file. When the
31270  ** count reaches zero, close any other file descriptors whose close
31271  ** was deferred because of outstanding locks.
31272  */
31273  pInode->nLock--;
31274  assert( pInode->nLock>=0 );
31275  if( pInode->nLock==0 ){
31276  closePendingFds(pFile);
31277  }
31278  }
31279 
31280 end_unlock:
31281  unixLeaveMutex();
31282  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
31283  return rc;
31284 }
31285 
31286 /*
31287 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31288 ** must be either NO_LOCK or SHARED_LOCK.
31289 **
31290 ** If the locking level of the file descriptor is already at or below
31291 ** the requested locking level, this routine is a no-op.
31292 */
31293 static int unixUnlock(sqlite3_file *id, int eFileLock){
31294 #if SQLITE_MAX_MMAP_SIZE>0
31295  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
31296 #endif
31297  return posixUnlock(id, eFileLock, 0);
31298 }
31299 
31300 #if SQLITE_MAX_MMAP_SIZE>0
31301 static int unixMapfile(unixFile *pFd, i64 nByte);
31302 static void unixUnmapfile(unixFile *pFd);
31303 #endif
31304 
31305 /*
31306 ** This function performs the parts of the "close file" operation
31307 ** common to all locking schemes. It closes the directory and file
31308 ** handles, if they are valid, and sets all fields of the unixFile
31309 ** structure to 0.
31310 **
31311 ** It is *not* necessary to hold the mutex when this routine is called,
31312 ** even on VxWorks. A mutex will be acquired on VxWorks by the
31313 ** vxworksReleaseFileId() routine.
31314 */
31315 static int closeUnixFile(sqlite3_file *id){
31316  unixFile *pFile = (unixFile*)id;
31317 #if SQLITE_MAX_MMAP_SIZE>0
31318  unixUnmapfile(pFile);
31319 #endif
31320  if( pFile->h>=0 ){
31321  robust_close(pFile, pFile->h, __LINE__);
31322  pFile->h = -1;
31323  }
31324 #if OS_VXWORKS
31325  if( pFile->pId ){
31326  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31327  osUnlink(pFile->pId->zCanonicalName);
31328  }
31329  vxworksReleaseFileId(pFile->pId);
31330  pFile->pId = 0;
31331  }
31332 #endif
31333 #ifdef SQLITE_UNLINK_AFTER_CLOSE
31334  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31335  osUnlink(pFile->zPath);
31336  sqlite3_free(*(char**)&pFile->zPath);
31337  pFile->zPath = 0;
31338  }
31339 #endif
31340  OSTRACE(("CLOSE %-3d\n", pFile->h));
31341  OpenCounter(-1);
31342  sqlite3_free(pFile->pUnused);
31343  memset(pFile, 0, sizeof(unixFile));
31344  return SQLITE_OK;
31345 }
31346 
31347 /*
31348 ** Close a file.
31349 */
31350 static int unixClose(sqlite3_file *id){
31351  int rc = SQLITE_OK;
31352  unixFile *pFile = (unixFile *)id;
31353  verifyDbFile(pFile);
31354  unixUnlock(id, NO_LOCK);
31355  unixEnterMutex();
31356 
31357  /* unixFile.pInode is always valid here. Otherwise, a different close
31358  ** routine (e.g. nolockClose()) would be called instead.
31359  */
31360  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
31361  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
31362  /* If there are outstanding locks, do not actually close the file just
31363  ** yet because that would clear those locks. Instead, add the file
31364  ** descriptor to pInode->pUnused list. It will be automatically closed
31365  ** when the last lock is cleared.
31366  */
31367  setPendingFd(pFile);
31368  }
31369  releaseInodeInfo(pFile);
31370  rc = closeUnixFile(id);
31371  unixLeaveMutex();
31372  return rc;
31373 }
31374 
31375 /************** End of the posix advisory lock implementation *****************
31376 ******************************************************************************/
31377 
31378 /******************************************************************************
31379 ****************************** No-op Locking **********************************
31380 **
31381 ** Of the various locking implementations available, this is by far the
31382 ** simplest: locking is ignored. No attempt is made to lock the database
31383 ** file for reading or writing.
31384 **
31385 ** This locking mode is appropriate for use on read-only databases
31386 ** (ex: databases that are burned into CD-ROM, for example.) It can
31387 ** also be used if the application employs some external mechanism to
31388 ** prevent simultaneous access of the same database by two or more
31389 ** database connections. But there is a serious risk of database
31390 ** corruption if this locking mode is used in situations where multiple
31391 ** database connections are accessing the same database file at the same
31392 ** time and one or more of those connections are writing.
31393 */
31394 
31395 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
31396  UNUSED_PARAMETER(NotUsed);
31397  *pResOut = 0;
31398  return SQLITE_OK;
31399 }
31400 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
31401  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31402  return SQLITE_OK;
31403 }
31404 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
31405  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31406  return SQLITE_OK;
31407 }
31408 
31409 /*
31410 ** Close the file.
31411 */
31412 static int nolockClose(sqlite3_file *id) {
31413  return closeUnixFile(id);
31414 }
31415 
31416 /******************* End of the no-op lock implementation *********************
31417 ******************************************************************************/
31418 
31419 /******************************************************************************
31420 ************************* Begin dot-file Locking ******************************
31421 **
31422 ** The dotfile locking implementation uses the existence of separate lock
31423 ** files (really a directory) to control access to the database. This works
31424 ** on just about every filesystem imaginable. But there are serious downsides:
31425 **
31426 ** (1) There is zero concurrency. A single reader blocks all other
31427 ** connections from reading or writing the database.
31428 **
31429 ** (2) An application crash or power loss can leave stale lock files
31430 ** sitting around that need to be cleared manually.
31431 **
31432 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
31433 ** other locking strategy is available.
31434 **
31435 ** Dotfile locking works by creating a subdirectory in the same directory as
31436 ** the database and with the same name but with a ".lock" extension added.
31437 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
31438 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
31439 */
31440 
31441 /*
31442 ** The file suffix added to the data base filename in order to create the
31443 ** lock directory.
31444 */
31445 #define DOTLOCK_SUFFIX ".lock"
31446 
31447 /*
31448 ** This routine checks if there is a RESERVED lock held on the specified
31449 ** file by this or any other process. If such a lock is held, set *pResOut
31450 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31451 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31452 **
31453 ** In dotfile locking, either a lock exists or it does not. So in this
31454 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
31455 ** is held on the file and false if the file is unlocked.
31456 */
31457 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
31458  int rc = SQLITE_OK;
31459  int reserved = 0;
31460  unixFile *pFile = (unixFile*)id;
31461 
31463 
31464  assert( pFile );
31465  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
31466  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
31467  *pResOut = reserved;
31468  return rc;
31469 }
31470 
31471 /*
31472 ** Lock the file with the lock specified by parameter eFileLock - one
31473 ** of the following:
31474 **
31475 ** (1) SHARED_LOCK
31476 ** (2) RESERVED_LOCK
31477 ** (3) PENDING_LOCK
31478 ** (4) EXCLUSIVE_LOCK
31479 **
31480 ** Sometimes when requesting one lock state, additional lock states
31481 ** are inserted in between. The locking might fail on one of the later
31482 ** transitions leaving the lock state different from what it started but
31483 ** still short of its goal. The following chart shows the allowed
31484 ** transitions and the inserted intermediate states:
31485 **
31486 ** UNLOCKED -> SHARED
31487 ** SHARED -> RESERVED
31488 ** SHARED -> (PENDING) -> EXCLUSIVE
31489 ** RESERVED -> (PENDING) -> EXCLUSIVE
31490 ** PENDING -> EXCLUSIVE
31491 **
31492 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31493 ** routine to lower a locking level.
31494 **
31495 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
31496 ** But we track the other locking levels internally.
31497 */
31498 static int dotlockLock(sqlite3_file *id, int eFileLock) {
31499  unixFile *pFile = (unixFile*)id;
31500  char *zLockFile = (char *)pFile->lockingContext;
31501  int rc = SQLITE_OK;
31502 
31503 
31504  /* If we have any lock, then the lock file already exists. All we have
31505  ** to do is adjust our internal record of the lock level.
31506  */
31507  if( pFile->eFileLock > NO_LOCK ){
31508  pFile->eFileLock = eFileLock;
31509  /* Always update the timestamp on the old file */
31510 #ifdef HAVE_UTIME
31511  utime(zLockFile, NULL);
31512 #else
31513  utimes(zLockFile, NULL);
31514 #endif
31515  return SQLITE_OK;
31516  }
31517 
31518  /* grab an exclusive lock */
31519  rc = osMkdir(zLockFile, 0777);
31520  if( rc<0 ){
31521  /* failed to open/create the lock directory */
31522  int tErrno = errno;
31523  if( EEXIST == tErrno ){
31524  rc = SQLITE_BUSY;
31525  } else {
31527  if( rc!=SQLITE_BUSY ){
31528  storeLastErrno(pFile, tErrno);
31529  }
31530  }
31531  return rc;
31532  }
31533 
31534  /* got it, set the type and return ok */
31535  pFile->eFileLock = eFileLock;
31536  return rc;
31537 }
31538 
31539 /*
31540 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31541 ** must be either NO_LOCK or SHARED_LOCK.
31542 **
31543 ** If the locking level of the file descriptor is already at or below
31544 ** the requested locking level, this routine is a no-op.
31545 **
31546 ** When the locking level reaches NO_LOCK, delete the lock file.
31547 */
31548 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
31549  unixFile *pFile = (unixFile*)id;
31550  char *zLockFile = (char *)pFile->lockingContext;
31551  int rc;
31552 
31553  assert( pFile );
31554  OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
31555  pFile->eFileLock, osGetpid(0)));
31556  assert( eFileLock<=SHARED_LOCK );
31557 
31558  /* no-op if possible */
31559  if( pFile->eFileLock==eFileLock ){
31560  return SQLITE_OK;
31561  }
31562 
31563  /* To downgrade to shared, simply update our internal notion of the
31564  ** lock state. No need to mess with the file on disk.
31565  */
31566  if( eFileLock==SHARED_LOCK ){
31567  pFile->eFileLock = SHARED_LOCK;
31568  return SQLITE_OK;
31569  }
31570 
31571  /* To fully unlock the database, delete the lock file */
31572  assert( eFileLock==NO_LOCK );
31573  rc = osRmdir(zLockFile);
31574  if( rc<0 ){
31575  int tErrno = errno;
31576  if( tErrno==ENOENT ){
31577  rc = SQLITE_OK;
31578  }else{
31579  rc = SQLITE_IOERR_UNLOCK;
31580  storeLastErrno(pFile, tErrno);
31581  }
31582  return rc;
31583  }
31584  pFile->eFileLock = NO_LOCK;
31585  return SQLITE_OK;
31586 }
31587 
31588 /*
31589 ** Close a file. Make sure the lock has been released before closing.
31590 */
31591 static int dotlockClose(sqlite3_file *id) {
31592  unixFile *pFile = (unixFile*)id;
31593  assert( id!=0 );
31594  dotlockUnlock(id, NO_LOCK);
31595  sqlite3_free(pFile->lockingContext);
31596  return closeUnixFile(id);
31597 }
31598 /****************** End of the dot-file lock implementation *******************
31599 ******************************************************************************/
31600 
31601 /******************************************************************************
31602 ************************** Begin flock Locking ********************************
31603 **
31604 ** Use the flock() system call to do file locking.
31605 **
31606 ** flock() locking is like dot-file locking in that the various
31607 ** fine-grain locking levels supported by SQLite are collapsed into
31608 ** a single exclusive lock. In other words, SHARED, RESERVED, and
31609 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
31610 ** still works when you do this, but concurrency is reduced since
31611 ** only a single process can be reading the database at a time.
31612 **
31613 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
31614 */
31615 #if SQLITE_ENABLE_LOCKING_STYLE
31616 
31617 /*
31618 ** Retry flock() calls that fail with EINTR
31619 */
31620 #ifdef EINTR
31621 static int robust_flock(int fd, int op){
31622  int rc;
31623  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
31624  return rc;
31625 }
31626 #else
31627 # define robust_flock(a,b) flock(a,b)
31628 #endif
31629 
31630 
31631 /*
31632 ** This routine checks if there is a RESERVED lock held on the specified
31633 ** file by this or any other process. If such a lock is held, set *pResOut
31634 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31635 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31636 */
31637 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
31638  int rc = SQLITE_OK;
31639  int reserved = 0;
31640  unixFile *pFile = (unixFile*)id;
31641 
31643 
31644  assert( pFile );
31645 
31646  /* Check if a thread in this process holds such a lock */
31647  if( pFile->eFileLock>SHARED_LOCK ){
31648  reserved = 1;
31649  }
31650 
31651  /* Otherwise see if some other process holds it. */
31652  if( !reserved ){
31653  /* attempt to get the lock */
31654  int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
31655  if( !lrc ){
31656  /* got the lock, unlock it */
31657  lrc = robust_flock(pFile->h, LOCK_UN);
31658  if ( lrc ) {
31659  int tErrno = errno;
31660  /* unlock failed with an error */
31661  lrc = SQLITE_IOERR_UNLOCK;
31662  storeLastErrno(pFile, tErrno);
31663  rc = lrc;
31664  }
31665  } else {
31666  int tErrno = errno;
31667  reserved = 1;
31668  /* someone else might have it reserved */
31670  if( IS_LOCK_ERROR(lrc) ){
31671  storeLastErrno(pFile, tErrno);
31672  rc = lrc;
31673  }
31674  }
31675  }
31676  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
31677 
31678 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31679  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31680  rc = SQLITE_OK;
31681  reserved=1;
31682  }
31683 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31684  *pResOut = reserved;
31685  return rc;
31686 }
31687 
31688 /*
31689 ** Lock the file with the lock specified by parameter eFileLock - one
31690 ** of the following:
31691 **
31692 ** (1) SHARED_LOCK
31693 ** (2) RESERVED_LOCK
31694 ** (3) PENDING_LOCK
31695 ** (4) EXCLUSIVE_LOCK
31696 **
31697 ** Sometimes when requesting one lock state, additional lock states
31698 ** are inserted in between. The locking might fail on one of the later
31699 ** transitions leaving the lock state different from what it started but
31700 ** still short of its goal. The following chart shows the allowed
31701 ** transitions and the inserted intermediate states:
31702 **
31703 ** UNLOCKED -> SHARED
31704 ** SHARED -> RESERVED
31705 ** SHARED -> (PENDING) -> EXCLUSIVE
31706 ** RESERVED -> (PENDING) -> EXCLUSIVE
31707 ** PENDING -> EXCLUSIVE
31708 **
31709 ** flock() only really support EXCLUSIVE locks. We track intermediate
31710 ** lock states in the sqlite3_file structure, but all locks SHARED or
31711 ** above are really EXCLUSIVE locks and exclude all other processes from
31712 ** access the file.
31713 **
31714 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31715 ** routine to lower a locking level.
31716 */
31717 static int flockLock(sqlite3_file *id, int eFileLock) {
31718  int rc = SQLITE_OK;
31719  unixFile *pFile = (unixFile*)id;
31720 
31721  assert( pFile );
31722 
31723  /* if we already have a lock, it is exclusive.
31724  ** Just adjust level and punt on outta here. */
31725  if (pFile->eFileLock > NO_LOCK) {
31726  pFile->eFileLock = eFileLock;
31727  return SQLITE_OK;
31728  }
31729 
31730  /* grab an exclusive lock */
31731 
31732  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
31733  int tErrno = errno;
31734  /* didn't get, must be busy */
31736  if( IS_LOCK_ERROR(rc) ){
31737  storeLastErrno(pFile, tErrno);
31738  }
31739  } else {
31740  /* got it, set the type and return ok */
31741  pFile->eFileLock = eFileLock;
31742  }
31743  OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
31744  rc==SQLITE_OK ? "ok" : "failed"));
31745 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31746  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31747  rc = SQLITE_BUSY;
31748  }
31749 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31750  return rc;
31751 }
31752 
31753 
31754 /*
31755 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31756 ** must be either NO_LOCK or SHARED_LOCK.
31757 **
31758 ** If the locking level of the file descriptor is already at or below
31759 ** the requested locking level, this routine is a no-op.
31760 */
31761 static int flockUnlock(sqlite3_file *id, int eFileLock) {
31762  unixFile *pFile = (unixFile*)id;
31763 
31764  assert( pFile );
31765  OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
31766  pFile->eFileLock, osGetpid(0)));
31767  assert( eFileLock<=SHARED_LOCK );
31768 
31769  /* no-op if possible */
31770  if( pFile->eFileLock==eFileLock ){
31771  return SQLITE_OK;
31772  }
31773 
31774  /* shared can just be set because we always have an exclusive */
31775  if (eFileLock==SHARED_LOCK) {
31776  pFile->eFileLock = eFileLock;
31777  return SQLITE_OK;
31778  }
31779 
31780  /* no, really, unlock. */
31781  if( robust_flock(pFile->h, LOCK_UN) ){
31782 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31783  return SQLITE_OK;
31784 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31785  return SQLITE_IOERR_UNLOCK;
31786  }else{
31787  pFile->eFileLock = NO_LOCK;
31788  return SQLITE_OK;
31789  }
31790 }
31791 
31792 /*
31793 ** Close a file.
31794 */
31795 static int flockClose(sqlite3_file *id) {
31796  assert( id!=0 );
31797  flockUnlock(id, NO_LOCK);
31798  return closeUnixFile(id);
31799 }
31800 
31801 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
31802 
31803 /******************* End of the flock lock implementation *********************
31804 ******************************************************************************/
31805 
31806 /******************************************************************************
31807 ************************ Begin Named Semaphore Locking ************************
31808 **
31809 ** Named semaphore locking is only supported on VxWorks.
31810 **
31811 ** Semaphore locking is like dot-lock and flock in that it really only
31812 ** supports EXCLUSIVE locking. Only a single process can read or write
31813 ** the database file at a time. This reduces potential concurrency, but
31814 ** makes the lock implementation much easier.
31815 */
31816 #if OS_VXWORKS
31817 
31818 /*
31819 ** This routine checks if there is a RESERVED lock held on the specified
31820 ** file by this or any other process. If such a lock is held, set *pResOut
31821 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31822 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31823 */
31824 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
31825  int rc = SQLITE_OK;
31826  int reserved = 0;
31827  unixFile *pFile = (unixFile*)id;
31828 
31830 
31831  assert( pFile );
31832 
31833  /* Check if a thread in this process holds such a lock */
31834  if( pFile->eFileLock>SHARED_LOCK ){
31835  reserved = 1;
31836  }
31837 
31838  /* Otherwise see if some other process holds it. */
31839  if( !reserved ){
31840  sem_t *pSem = pFile->pInode->pSem;
31841 
31842  if( sem_trywait(pSem)==-1 ){
31843  int tErrno = errno;
31844  if( EAGAIN != tErrno ){
31846  storeLastErrno(pFile, tErrno);
31847  } else {
31848  /* someone else has the lock when we are in NO_LOCK */
31849  reserved = (pFile->eFileLock < SHARED_LOCK);
31850  }
31851  }else{
31852  /* we could have it if we want it */
31853  sem_post(pSem);
31854  }
31855  }
31856  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
31857 
31858  *pResOut = reserved;
31859  return rc;
31860 }
31861 
31862 /*
31863 ** Lock the file with the lock specified by parameter eFileLock - one
31864 ** of the following:
31865 **
31866 ** (1) SHARED_LOCK
31867 ** (2) RESERVED_LOCK
31868 ** (3) PENDING_LOCK
31869 ** (4) EXCLUSIVE_LOCK
31870 **
31871 ** Sometimes when requesting one lock state, additional lock states
31872 ** are inserted in between. The locking might fail on one of the later
31873 ** transitions leaving the lock state different from what it started but
31874 ** still short of its goal. The following chart shows the allowed
31875 ** transitions and the inserted intermediate states:
31876 **
31877 ** UNLOCKED -> SHARED
31878 ** SHARED -> RESERVED
31879 ** SHARED -> (PENDING) -> EXCLUSIVE
31880 ** RESERVED -> (PENDING) -> EXCLUSIVE
31881 ** PENDING -> EXCLUSIVE
31882 **
31883 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
31884 ** lock states in the sqlite3_file structure, but all locks SHARED or
31885 ** above are really EXCLUSIVE locks and exclude all other processes from
31886 ** access the file.
31887 **
31888 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31889 ** routine to lower a locking level.
31890 */
31891 static int semXLock(sqlite3_file *id, int eFileLock) {
31892  unixFile *pFile = (unixFile*)id;
31893  sem_t *pSem = pFile->pInode->pSem;
31894  int rc = SQLITE_OK;
31895 
31896  /* if we already have a lock, it is exclusive.
31897  ** Just adjust level and punt on outta here. */
31898  if (pFile->eFileLock > NO_LOCK) {
31899  pFile->eFileLock = eFileLock;
31900  rc = SQLITE_OK;
31901  goto sem_end_lock;
31902  }
31903 
31904  /* lock semaphore now but bail out when already locked. */
31905  if( sem_trywait(pSem)==-1 ){
31906  rc = SQLITE_BUSY;
31907  goto sem_end_lock;
31908  }
31909 
31910  /* got it, set the type and return ok */
31911  pFile->eFileLock = eFileLock;
31912 
31913  sem_end_lock:
31914  return rc;
31915 }
31916 
31917 /*
31918 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31919 ** must be either NO_LOCK or SHARED_LOCK.
31920 **
31921 ** If the locking level of the file descriptor is already at or below
31922 ** the requested locking level, this routine is a no-op.
31923 */
31924 static int semXUnlock(sqlite3_file *id, int eFileLock) {
31925  unixFile *pFile = (unixFile*)id;
31926  sem_t *pSem = pFile->pInode->pSem;
31927 
31928  assert( pFile );
31929  assert( pSem );
31930  OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
31931  pFile->eFileLock, osGetpid(0)));
31932  assert( eFileLock<=SHARED_LOCK );
31933 
31934  /* no-op if possible */
31935  if( pFile->eFileLock==eFileLock ){
31936  return SQLITE_OK;
31937  }
31938 
31939  /* shared can just be set because we always have an exclusive */
31940  if (eFileLock==SHARED_LOCK) {
31941  pFile->eFileLock = eFileLock;
31942  return SQLITE_OK;
31943  }
31944 
31945  /* no, really unlock. */
31946  if ( sem_post(pSem)==-1 ) {
31947  int rc, tErrno = errno;
31949  if( IS_LOCK_ERROR(rc) ){
31950  storeLastErrno(pFile, tErrno);
31951  }
31952  return rc;
31953  }
31954  pFile->eFileLock = NO_LOCK;
31955  return SQLITE_OK;
31956 }
31957 
31958 /*
31959  ** Close a file.
31960  */
31961 static int semXClose(sqlite3_file *id) {
31962  if( id ){
31963  unixFile *pFile = (unixFile*)id;
31964  semXUnlock(id, NO_LOCK);
31965  assert( pFile );
31966  unixEnterMutex();
31967  releaseInodeInfo(pFile);
31968  unixLeaveMutex();
31969  closeUnixFile(id);
31970  }
31971  return SQLITE_OK;
31972 }
31973 
31974 #endif /* OS_VXWORKS */
31975 /*
31976 ** Named semaphore locking is only available on VxWorks.
31977 **
31978 *************** End of the named semaphore lock implementation ****************
31979 ******************************************************************************/
31980 
31981 
31982 /******************************************************************************
31983 *************************** Begin AFP Locking *********************************
31984 **
31985 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
31986 ** on Apple Macintosh computers - both OS9 and OSX.
31987 **
31988 ** Third-party implementations of AFP are available. But this code here
31989 ** only works on OSX.
31990 */
31991 
31992 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31993 /*
31994 ** The afpLockingContext structure contains all afp lock specific state
31995 */
31996 typedef struct afpLockingContext afpLockingContext;
31997 struct afpLockingContext {
31998  int reserved;
31999  const char *dbPath; /* Name of the open file */
32000 };
32001 
32002 struct ByteRangeLockPB2
32003 {
32004  unsigned long long offset; /* offset to first byte to lock */
32005  unsigned long long length; /* nbr of bytes to lock */
32006  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
32007  unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
32008  unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
32009  int fd; /* file desc to assoc this lock with */
32010 };
32011 
32012 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
32013 
32014 /*
32015 ** This is a utility for setting or clearing a bit-range lock on an
32016 ** AFP filesystem.
32017 **
32018 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
32019 */
32020 static int afpSetLock(
32021  const char *path, /* Name of the file to be locked or unlocked */
32022  unixFile *pFile, /* Open file descriptor on path */
32023  unsigned long long offset, /* First byte to be locked */
32024  unsigned long long length, /* Number of bytes to lock */
32025  int setLockFlag /* True to set lock. False to clear lock */
32026 ){
32027  struct ByteRangeLockPB2 pb;
32028  int err;
32029 
32030  pb.unLockFlag = setLockFlag ? 0 : 1;
32031  pb.startEndFlag = 0;
32032  pb.offset = offset;
32033  pb.length = length;
32034  pb.fd = pFile->h;
32035 
32036  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
32037  (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
32038  offset, length));
32039  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
32040  if ( err==-1 ) {
32041  int rc;
32042  int tErrno = errno;
32043  OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
32044  path, tErrno, strerror(tErrno)));
32045 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
32046  rc = SQLITE_BUSY;
32047 #else
32048  rc = sqliteErrorFromPosixError(tErrno,
32049  setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
32050 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
32051  if( IS_LOCK_ERROR(rc) ){
32052  storeLastErrno(pFile, tErrno);
32053  }
32054  return rc;
32055  } else {
32056  return SQLITE_OK;
32057  }
32058 }
32059 
32060 /*
32061 ** This routine checks if there is a RESERVED lock held on the specified
32062 ** file by this or any other process. If such a lock is held, set *pResOut
32063 ** to a non-zero value otherwise *pResOut is set to zero. The return value
32064 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32065 */
32066 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
32067  int rc = SQLITE_OK;
32068  int reserved = 0;
32069  unixFile *pFile = (unixFile*)id;
32070  afpLockingContext *context;
32071 
32073 
32074  assert( pFile );
32075  context = (afpLockingContext *) pFile->lockingContext;
32076  if( context->reserved ){
32077  *pResOut = 1;
32078  return SQLITE_OK;
32079  }
32080  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
32081 
32082  /* Check if a thread in this process holds such a lock */
32083  if( pFile->pInode->eFileLock>SHARED_LOCK ){
32084  reserved = 1;
32085  }
32086 
32087  /* Otherwise see if some other process holds it.
32088  */
32089  if( !reserved ){
32090  /* lock the RESERVED byte */
32091  int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32092  if( SQLITE_OK==lrc ){
32093  /* if we succeeded in taking the reserved lock, unlock it to restore
32094  ** the original state */
32095  lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32096  } else {
32097  /* if we failed to get the lock then someone else must have it */
32098  reserved = 1;
32099  }
32100  if( IS_LOCK_ERROR(lrc) ){
32101  rc=lrc;
32102  }
32103  }
32104 
32105  unixLeaveMutex();
32106  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
32107 
32108  *pResOut = reserved;
32109  return rc;
32110 }
32111 
32112 /*
32113 ** Lock the file with the lock specified by parameter eFileLock - one
32114 ** of the following:
32115 **
32116 ** (1) SHARED_LOCK
32117 ** (2) RESERVED_LOCK
32118 ** (3) PENDING_LOCK
32119 ** (4) EXCLUSIVE_LOCK
32120 **
32121 ** Sometimes when requesting one lock state, additional lock states
32122 ** are inserted in between. The locking might fail on one of the later
32123 ** transitions leaving the lock state different from what it started but
32124 ** still short of its goal. The following chart shows the allowed
32125 ** transitions and the inserted intermediate states:
32126 **
32127 ** UNLOCKED -> SHARED
32128 ** SHARED -> RESERVED
32129 ** SHARED -> (PENDING) -> EXCLUSIVE
32130 ** RESERVED -> (PENDING) -> EXCLUSIVE
32131 ** PENDING -> EXCLUSIVE
32132 **
32133 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
32134 ** routine to lower a locking level.
32135 */
32136 static int afpLock(sqlite3_file *id, int eFileLock){
32137  int rc = SQLITE_OK;
32138  unixFile *pFile = (unixFile*)id;
32139  unixInodeInfo *pInode = pFile->pInode;
32140  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32141 
32142  assert( pFile );
32143  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
32144  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
32145  azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
32146 
32147  /* If there is already a lock of this type or more restrictive on the
32148  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
32149  ** unixEnterMutex() hasn't been called yet.
32150  */
32151  if( pFile->eFileLock>=eFileLock ){
32152  OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
32153  azFileLock(eFileLock)));
32154  return SQLITE_OK;
32155  }
32156 
32157  /* Make sure the locking sequence is correct
32158  ** (1) We never move from unlocked to anything higher than shared lock.
32159  ** (2) SQLite never explicitly requests a pendig lock.
32160  ** (3) A shared lock is always held when a reserve lock is requested.
32161  */
32162  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
32163  assert( eFileLock!=PENDING_LOCK );
32164  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
32165 
32166  /* This mutex is needed because pFile->pInode is shared across threads
32167  */
32168  unixEnterMutex();
32169  pInode = pFile->pInode;
32170 
32171  /* If some thread using this PID has a lock via a different unixFile*
32172  ** handle that precludes the requested lock, return BUSY.
32173  */
32174  if( (pFile->eFileLock!=pInode->eFileLock &&
32175  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
32176  ){
32177  rc = SQLITE_BUSY;
32178  goto afp_end_lock;
32179  }
32180 
32181  /* If a SHARED lock is requested, and some thread using this PID already
32182  ** has a SHARED or RESERVED lock, then increment reference counts and
32183  ** return SQLITE_OK.
32184  */
32185  if( eFileLock==SHARED_LOCK &&
32186  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
32187  assert( eFileLock==SHARED_LOCK );
32188  assert( pFile->eFileLock==0 );
32189  assert( pInode->nShared>0 );
32190  pFile->eFileLock = SHARED_LOCK;
32191  pInode->nShared++;
32192  pInode->nLock++;
32193  goto afp_end_lock;
32194  }
32195 
32196  /* A PENDING lock is needed before acquiring a SHARED lock and before
32197  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
32198  ** be released.
32199  */
32200  if( eFileLock==SHARED_LOCK
32201  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32202  ){
32203  int failed;
32204  failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
32205  if (failed) {
32206  rc = failed;
32207  goto afp_end_lock;
32208  }
32209  }
32210 
32211  /* If control gets to this point, then actually go ahead and make
32212  ** operating system calls for the specified lock.
32213  */
32214  if( eFileLock==SHARED_LOCK ){
32215  int lrc1, lrc2, lrc1Errno = 0;
32216  long lk, mask;
32217 
32218  assert( pInode->nShared==0 );
32219  assert( pInode->eFileLock==0 );
32220 
32221  mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
32222  /* Now get the read-lock SHARED_LOCK */
32223  /* note that the quality of the randomness doesn't matter that much */
32224  lk = random();
32225  pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
32226  lrc1 = afpSetLock(context->dbPath, pFile,
32227  SHARED_FIRST+pInode->sharedByte, 1, 1);
32228  if( IS_LOCK_ERROR(lrc1) ){
32229  lrc1Errno = pFile->lastErrno;
32230  }
32231  /* Drop the temporary PENDING lock */
32232  lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32233 
32234  if( IS_LOCK_ERROR(lrc1) ) {
32235  storeLastErrno(pFile, lrc1Errno);
32236  rc = lrc1;
32237  goto afp_end_lock;
32238  } else if( IS_LOCK_ERROR(lrc2) ){
32239  rc = lrc2;
32240  goto afp_end_lock;
32241  } else if( lrc1 != SQLITE_OK ) {
32242  rc = lrc1;
32243  } else {
32244  pFile->eFileLock = SHARED_LOCK;
32245  pInode->nLock++;
32246  pInode->nShared = 1;
32247  }
32248  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32249  /* We are trying for an exclusive lock but another thread in this
32250  ** same process is still holding a shared lock. */
32251  rc = SQLITE_BUSY;
32252  }else{
32253  /* The request was for a RESERVED or EXCLUSIVE lock. It is
32254  ** assumed that there is a SHARED or greater lock on the file
32255  ** already.
32256  */
32257  int failed = 0;
32258  assert( 0!=pFile->eFileLock );
32259  if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
32260  /* Acquire a RESERVED lock */
32261  failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32262  if( !failed ){
32263  context->reserved = 1;
32264  }
32265  }
32266  if (!failed && eFileLock == EXCLUSIVE_LOCK) {
32267  /* Acquire an EXCLUSIVE lock */
32268 
32269  /* Remove the shared lock before trying the range. we'll need to
32270  ** reestablish the shared lock if we can't get the afpUnlock
32271  */
32272  if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
32273  pInode->sharedByte, 1, 0)) ){
32274  int failed2 = SQLITE_OK;
32275  /* now attemmpt to get the exclusive lock range */
32276  failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
32277  SHARED_SIZE, 1);
32278  if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
32279  SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
32280  /* Can't reestablish the shared lock. Sqlite can't deal, this is
32281  ** a critical I/O error
32282  */
32283  rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
32285  goto afp_end_lock;
32286  }
32287  }else{
32288  rc = failed;
32289  }
32290  }
32291  if( failed ){
32292  rc = failed;
32293  }
32294  }
32295 
32296  if( rc==SQLITE_OK ){
32297  pFile->eFileLock = eFileLock;
32298  pInode->eFileLock = eFileLock;
32299  }else if( eFileLock==EXCLUSIVE_LOCK ){
32300  pFile->eFileLock = PENDING_LOCK;
32301  pInode->eFileLock = PENDING_LOCK;
32302  }
32303 
32304 afp_end_lock:
32305  unixLeaveMutex();
32306  OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
32307  rc==SQLITE_OK ? "ok" : "failed"));
32308  return rc;
32309 }
32310 
32311 /*
32312 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32313 ** must be either NO_LOCK or SHARED_LOCK.
32314 **
32315 ** If the locking level of the file descriptor is already at or below
32316 ** the requested locking level, this routine is a no-op.
32317 */
32318 static int afpUnlock(sqlite3_file *id, int eFileLock) {
32319  int rc = SQLITE_OK;
32320  unixFile *pFile = (unixFile*)id;
32321  unixInodeInfo *pInode;
32322  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32323  int skipShared = 0;
32324 #ifdef SQLITE_TEST
32325  int h = pFile->h;
32326 #endif
32327 
32328  assert( pFile );
32329  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
32330  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32331  osGetpid(0)));
32332 
32333  assert( eFileLock<=SHARED_LOCK );
32334  if( pFile->eFileLock<=eFileLock ){
32335  return SQLITE_OK;
32336  }
32337  unixEnterMutex();
32338  pInode = pFile->pInode;
32339  assert( pInode->nShared!=0 );
32340  if( pFile->eFileLock>SHARED_LOCK ){
32341  assert( pInode->eFileLock==pFile->eFileLock );
32343  SimulateIOError( h=(-1) )
32345 
32346 #ifdef SQLITE_DEBUG
32347  /* When reducing a lock such that other processes can start
32348  ** reading the database file again, make sure that the
32349  ** transaction counter was updated if any part of the database
32350  ** file changed. If the transaction counter is not updated,
32351  ** other connections to the same file might not realize that
32352  ** the file has changed and hence might not know to flush their
32353  ** cache. The use of a stale cache can lead to database corruption.
32354  */
32355  assert( pFile->inNormalWrite==0
32356  || pFile->dbUpdate==0
32357  || pFile->transCntrChng==1 );
32358  pFile->inNormalWrite = 0;
32359 #endif
32360 
32361  if( pFile->eFileLock==EXCLUSIVE_LOCK ){
32362  rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
32363  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
32364  /* only re-establish the shared lock if necessary */
32365  int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32366  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
32367  } else {
32368  skipShared = 1;
32369  }
32370  }
32371  if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
32372  rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32373  }
32374  if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
32375  rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32376  if( !rc ){
32377  context->reserved = 0;
32378  }
32379  }
32380  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
32381  pInode->eFileLock = SHARED_LOCK;
32382  }
32383  }
32384  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
32385 
32386  /* Decrement the shared lock counter. Release the lock using an
32387  ** OS call only when all threads in this same process have released
32388  ** the lock.
32389  */
32390  unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32391  pInode->nShared--;
32392  if( pInode->nShared==0 ){
32394  SimulateIOError( h=(-1) )
32396  if( !skipShared ){
32397  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
32398  }
32399  if( !rc ){
32400  pInode->eFileLock = NO_LOCK;
32401  pFile->eFileLock = NO_LOCK;
32402  }
32403  }
32404  if( rc==SQLITE_OK ){
32405  pInode->nLock--;
32406  assert( pInode->nLock>=0 );
32407  if( pInode->nLock==0 ){
32408  closePendingFds(pFile);
32409  }
32410  }
32411  }
32412 
32413  unixLeaveMutex();
32414  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32415  return rc;
32416 }
32417 
32418 /*
32419 ** Close a file & cleanup AFP specific locking context
32420 */
32421 static int afpClose(sqlite3_file *id) {
32422  int rc = SQLITE_OK;
32423  unixFile *pFile = (unixFile*)id;
32424  assert( id!=0 );
32425  afpUnlock(id, NO_LOCK);
32426  unixEnterMutex();
32427  if( pFile->pInode && pFile->pInode->nLock ){
32428  /* If there are outstanding locks, do not actually close the file just
32429  ** yet because that would clear those locks. Instead, add the file
32430  ** descriptor to pInode->aPending. It will be automatically closed when
32431  ** the last lock is cleared.
32432  */
32433  setPendingFd(pFile);
32434  }
32435  releaseInodeInfo(pFile);
32436  sqlite3_free(pFile->lockingContext);
32437  rc = closeUnixFile(id);
32438  unixLeaveMutex();
32439  return rc;
32440 }
32441 
32442 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32443 /*
32444 ** The code above is the AFP lock implementation. The code is specific
32445 ** to MacOSX and does not work on other unix platforms. No alternative
32446 ** is available. If you don't compile for a mac, then the "unix-afp"
32447 ** VFS is not available.
32448 **
32449 ********************* End of the AFP lock implementation **********************
32450 ******************************************************************************/
32451 
32452 /******************************************************************************
32453 *************************** Begin NFS Locking ********************************/
32454 
32455 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32456 /*
32457  ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32458  ** must be either NO_LOCK or SHARED_LOCK.
32459  **
32460  ** If the locking level of the file descriptor is already at or below
32461  ** the requested locking level, this routine is a no-op.
32462  */
32463 static int nfsUnlock(sqlite3_file *id, int eFileLock){
32464  return posixUnlock(id, eFileLock, 1);
32465 }
32466 
32467 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32468 /*
32469 ** The code above is the NFS lock implementation. The code is specific
32470 ** to MacOSX and does not work on other unix platforms. No alternative
32471 ** is available.
32472 **
32473 ********************* End of the NFS lock implementation **********************
32474 ******************************************************************************/
32475 
32476 /******************************************************************************
32477 **************** Non-locking sqlite3_file methods *****************************
32478 **
32479 ** The next division contains implementations for all methods of the
32480 ** sqlite3_file object other than the locking methods. The locking
32481 ** methods were defined in divisions above (one locking method per
32482 ** division). Those methods that are common to all locking modes
32483 ** are gather together into this division.
32484 */
32485 
32486 /*
32487 ** Seek to the offset passed as the second argument, then read cnt
32488 ** bytes into pBuf. Return the number of bytes actually read.
32489 **
32490 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
32491 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
32492 ** one system to another. Since SQLite does not define USE_PREAD
32493 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
32494 ** See tickets #2741 and #2681.
32495 **
32496 ** To avoid stomping the errno value on a failed read the lastErrno value
32497 ** is set before returning.
32498 */
32499 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
32500  int got;
32501  int prior = 0;
32502 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
32503  i64 newOffset;
32504 #endif
32505  TIMER_START;
32506  assert( cnt==(cnt&0x1ffff) );
32507  assert( id->h>2 );
32508  do{
32509 #if defined(USE_PREAD)
32510  got = osPread(id->h, pBuf, cnt, offset);
32511  SimulateIOError( got = -1 );
32512 #elif defined(USE_PREAD64)
32513  got = osPread64(id->h, pBuf, cnt, offset);
32514  SimulateIOError( got = -1 );
32515 #else
32516  newOffset = lseek(id->h, offset, SEEK_SET);
32517  SimulateIOError( newOffset = -1 );
32518  if( newOffset<0 ){
32519  storeLastErrno((unixFile*)id, errno);
32520  return -1;
32521  }
32522  got = osRead(id->h, pBuf, cnt);
32523 #endif
32524  if( got==cnt ) break;
32525  if( got<0 ){
32526  if( errno==EINTR ){ got = 1; continue; }
32527  prior = 0;
32528  storeLastErrno((unixFile*)id, errno);
32529  break;
32530  }else if( got>0 ){
32531  cnt -= got;
32532  offset += got;
32533  prior += got;
32534  pBuf = (void*)(got + (char*)pBuf);
32535  }
32536  }while( got>0 );
32537  TIMER_END;
32538  OSTRACE(("READ %-3d %5d %7lld %llu\n",
32539  id->h, got+prior, offset-prior, TIMER_ELAPSED));
32540  return got+prior;
32541 }
32542 
32543 /*
32544 ** Read data from a file into a buffer. Return SQLITE_OK if all
32545 ** bytes were read successfully and SQLITE_IOERR if anything goes
32546 ** wrong.
32547 */
32548 static int unixRead(
32549  sqlite3_file *id,
32550  void *pBuf,
32551  int amt,
32552  sqlite3_int64 offset
32553 ){
32554  unixFile *pFile = (unixFile *)id;
32555  int got;
32556  assert( id );
32557  assert( offset>=0 );
32558  assert( amt>0 );
32559 
32560  /* If this is a database file (not a journal, master-journal or temp
32561  ** file), the bytes in the locking range should never be read or written. */
32562 #if 0
32563  assert( pFile->pUnused==0
32564  || offset>=PENDING_BYTE+512
32565  || offset+amt<=PENDING_BYTE
32566  );
32567 #endif
32568 
32569 #if SQLITE_MAX_MMAP_SIZE>0
32570  /* Deal with as much of this read request as possible by transfering
32571  ** data from the memory mapping using memcpy(). */
32572  if( offset<pFile->mmapSize ){
32573  if( offset+amt <= pFile->mmapSize ){
32574  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32575  return SQLITE_OK;
32576  }else{
32577  int nCopy = pFile->mmapSize - offset;
32578  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32579  pBuf = &((u8 *)pBuf)[nCopy];
32580  amt -= nCopy;
32581  offset += nCopy;
32582  }
32583  }
32584 #endif
32585 
32586  got = seekAndRead(pFile, offset, pBuf, amt);
32587  if( got==amt ){
32588  return SQLITE_OK;
32589  }else if( got<0 ){
32590  /* lastErrno set by seekAndRead */
32591  return SQLITE_IOERR_READ;
32592  }else{
32593  storeLastErrno(pFile, 0); /* not a system error */
32594  /* Unread parts of the buffer must be zero-filled */
32595  memset(&((char*)pBuf)[got], 0, amt-got);
32596  return SQLITE_IOERR_SHORT_READ;
32597  }
32598 }
32599 
32600 /*
32601 ** Attempt to seek the file-descriptor passed as the first argument to
32602 ** absolute offset iOff, then attempt to write nBuf bytes of data from
32603 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
32604 ** return the actual number of bytes written (which may be less than
32605 ** nBuf).
32606 */
32607 static int seekAndWriteFd(
32608  int fd, /* File descriptor to write to */
32609  i64 iOff, /* File offset to begin writing at */
32610  const void *pBuf, /* Copy data from this buffer to the file */
32611  int nBuf, /* Size of buffer pBuf in bytes */
32612  int *piErrno /* OUT: Error number if error occurs */
32613 ){
32614  int rc = 0; /* Value returned by system call */
32615 
32616  assert( nBuf==(nBuf&0x1ffff) );
32617  assert( fd>2 );
32618  assert( piErrno!=0 );
32619  nBuf &= 0x1ffff;
32620  TIMER_START;
32621 
32622 #if defined(USE_PREAD)
32623  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
32624 #elif defined(USE_PREAD64)
32625  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
32626 #else
32627  do{
32628  i64 iSeek = lseek(fd, iOff, SEEK_SET);
32629  SimulateIOError( iSeek = -1 );
32630  if( iSeek<0 ){
32631  rc = -1;
32632  break;
32633  }
32634  rc = osWrite(fd, pBuf, nBuf);
32635  }while( rc<0 && errno==EINTR );
32636 #endif
32637 
32638  TIMER_END;
32639  OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
32640 
32641  if( rc<0 ) *piErrno = errno;
32642  return rc;
32643 }
32644 
32645 
32646 /*
32647 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
32648 ** Return the number of bytes actually read. Update the offset.
32649 **
32650 ** To avoid stomping the errno value on a failed write the lastErrno value
32651 ** is set before returning.
32652 */
32653 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
32654  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
32655 }
32656 
32657 
32658 /*
32659 ** Write data from a buffer into a file. Return SQLITE_OK on success
32660 ** or some other error code on failure.
32661 */
32662 static int unixWrite(
32663  sqlite3_file *id,
32664  const void *pBuf,
32665  int amt,
32666  sqlite3_int64 offset
32667 ){
32668  unixFile *pFile = (unixFile*)id;
32669  int wrote = 0;
32670  assert( id );
32671  assert( amt>0 );
32672 
32673  /* If this is a database file (not a journal, master-journal or temp
32674  ** file), the bytes in the locking range should never be read or written. */
32675 #if 0
32676  assert( pFile->pUnused==0
32677  || offset>=PENDING_BYTE+512
32678  || offset+amt<=PENDING_BYTE
32679  );
32680 #endif
32681 
32682 #ifdef SQLITE_DEBUG
32683  /* If we are doing a normal write to a database file (as opposed to
32684  ** doing a hot-journal rollback or a write to some file other than a
32685  ** normal database file) then record the fact that the database
32686  ** has changed. If the transaction counter is modified, record that
32687  ** fact too.
32688  */
32689  if( pFile->inNormalWrite ){
32690  pFile->dbUpdate = 1; /* The database has been modified */
32691  if( offset<=24 && offset+amt>=27 ){
32692  int rc;
32693  char oldCntr[4];
32695  rc = seekAndRead(pFile, 24, oldCntr, 4);
32697  if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
32698  pFile->transCntrChng = 1; /* The transaction counter has changed */
32699  }
32700  }
32701  }
32702 #endif
32703 
32704 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
32705  /* Deal with as much of this write request as possible by transfering
32706  ** data from the memory mapping using memcpy(). */
32707  if( offset<pFile->mmapSize ){
32708  if( offset+amt <= pFile->mmapSize ){
32709  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32710  return SQLITE_OK;
32711  }else{
32712  int nCopy = pFile->mmapSize - offset;
32713  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32714  pBuf = &((u8 *)pBuf)[nCopy];
32715  amt -= nCopy;
32716  offset += nCopy;
32717  }
32718  }
32719 #endif
32720 
32721  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
32722  amt -= wrote;
32723  offset += wrote;
32724  pBuf = &((char*)pBuf)[wrote];
32725  }
32726  SimulateIOError(( wrote=(-1), amt=1 ));
32727  SimulateDiskfullError(( wrote=0, amt=1 ));
32728 
32729  if( amt>wrote ){
32730  if( wrote<0 && pFile->lastErrno!=ENOSPC ){
32731  /* lastErrno set by seekAndWrite */
32732  return SQLITE_IOERR_WRITE;
32733  }else{
32734  storeLastErrno(pFile, 0); /* not a system error */
32735  return SQLITE_FULL;
32736  }
32737  }
32738 
32739  return SQLITE_OK;
32740 }
32741 
32742 #ifdef SQLITE_TEST
32743 /*
32744 ** Count the number of fullsyncs and normal syncs. This is used to test
32745 ** that syncs and fullsyncs are occurring at the right times.
32746 */
32747 SQLITE_API int sqlite3_sync_count = 0;
32748 SQLITE_API int sqlite3_fullsync_count = 0;
32749 #endif
32750 
32751 /*
32752 ** We do not trust systems to provide a working fdatasync(). Some do.
32753 ** Others do no. To be safe, we will stick with the (slightly slower)
32754 ** fsync(). If you know that your system does support fdatasync() correctly,
32755 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
32756 */
32757 #if !defined(fdatasync) && !HAVE_FDATASYNC
32758 # define fdatasync fsync
32759 #endif
32760 
32761 /*
32762 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
32763 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
32764 ** only available on Mac OS X. But that could change.
32765 */
32766 #ifdef F_FULLFSYNC
32767 # define HAVE_FULLFSYNC 1
32768 #else
32769 # define HAVE_FULLFSYNC 0
32770 #endif
32771 
32772 
32773 /*
32774 ** The fsync() system call does not work as advertised on many
32775 ** unix systems. The following procedure is an attempt to make
32776 ** it work better.
32777 **
32778 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
32779 ** for testing when we want to run through the test suite quickly.
32780 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
32781 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
32782 ** or power failure will likely corrupt the database file.
32783 **
32784 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
32785 ** The idea behind dataOnly is that it should only write the file content
32786 ** to disk, not the inode. We only set dataOnly if the file size is
32787 ** unchanged since the file size is part of the inode. However,
32788 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
32789 ** file size has changed. The only real difference between fdatasync()
32790 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
32791 ** inode if the mtime or owner or other inode attributes have changed.
32792 ** We only care about the file size, not the other file attributes, so
32793 ** as far as SQLite is concerned, an fdatasync() is always adequate.
32794 ** So, we always use fdatasync() if it is available, regardless of
32795 ** the value of the dataOnly flag.
32796 */
32797 static int full_fsync(int fd, int fullSync, int dataOnly){
32798  int rc;
32799 
32800  /* The following "ifdef/elif/else/" block has the same structure as
32801  ** the one below. It is replicated here solely to avoid cluttering
32802  ** up the real code with the UNUSED_PARAMETER() macros.
32803  */
32804 #ifdef SQLITE_NO_SYNC
32805  UNUSED_PARAMETER(fd);
32806  UNUSED_PARAMETER(fullSync);
32807  UNUSED_PARAMETER(dataOnly);
32808 #elif HAVE_FULLFSYNC
32809  UNUSED_PARAMETER(dataOnly);
32810 #else
32811  UNUSED_PARAMETER(fullSync);
32812  UNUSED_PARAMETER(dataOnly);
32813 #endif
32814 
32815  /* Record the number of times that we do a normal fsync() and
32816  ** FULLSYNC. This is used during testing to verify that this procedure
32817  ** gets called with the correct arguments.
32818  */
32819 #ifdef SQLITE_TEST
32820  if( fullSync ) sqlite3_fullsync_count++;
32821  sqlite3_sync_count++;
32822 #endif
32823 
32824  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32825  ** no-op. But go ahead and call fstat() to validate the file
32826  ** descriptor as we need a method to provoke a failure during
32827  ** coverate testing.
32828  */
32829 #ifdef SQLITE_NO_SYNC
32830  {
32831  struct stat buf;
32832  rc = osFstat(fd, &buf);
32833  }
32834 #elif HAVE_FULLFSYNC
32835  if( fullSync ){
32836  rc = osFcntl(fd, F_FULLFSYNC, 0);
32837  }else{
32838  rc = 1;
32839  }
32840  /* If the FULLFSYNC failed, fall back to attempting an fsync().
32841  ** It shouldn't be possible for fullfsync to fail on the local
32842  ** file system (on OSX), so failure indicates that FULLFSYNC
32843  ** isn't supported for this file system. So, attempt an fsync
32844  ** and (for now) ignore the overhead of a superfluous fcntl call.
32845  ** It'd be better to detect fullfsync support once and avoid
32846  ** the fcntl call every time sync is called.
32847  */
32848  if( rc ) rc = fsync(fd);
32849 
32850 #elif defined(__APPLE__)
32851  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
32852  ** so currently we default to the macro that redefines fdatasync to fsync
32853  */
32854  rc = fsync(fd);
32855 #else
32856  rc = fdatasync(fd);
32857 #if OS_VXWORKS
32858  if( rc==-1 && errno==ENOTSUP ){
32859  rc = fsync(fd);
32860  }
32861 #endif /* OS_VXWORKS */
32862 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
32863 
32864  if( OS_VXWORKS && rc!= -1 ){
32865  rc = 0;
32866  }
32867  return rc;
32868 }
32869 
32870 /*
32871 ** Open a file descriptor to the directory containing file zFilename.
32872 ** If successful, *pFd is set to the opened file descriptor and
32873 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
32874 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
32875 ** value.
32876 **
32877 ** The directory file descriptor is used for only one thing - to
32878 ** fsync() a directory to make sure file creation and deletion events
32879 ** are flushed to disk. Such fsyncs are not needed on newer
32880 ** journaling filesystems, but are required on older filesystems.
32881 **
32882 ** This routine can be overridden using the xSetSysCall interface.
32883 ** The ability to override this routine was added in support of the
32884 ** chromium sandbox. Opening a directory is a security risk (we are
32885 ** told) so making it overrideable allows the chromium sandbox to
32886 ** replace this routine with a harmless no-op. To make this routine
32887 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
32888 ** *pFd set to a negative number.
32889 **
32890 ** If SQLITE_OK is returned, the caller is responsible for closing
32891 ** the file descriptor *pFd using close().
32892 */
32893 static int openDirectory(const char *zFilename, int *pFd){
32894  int ii;
32895  int fd = -1;
32896  char zDirname[MAX_PATHNAME+1];
32897 
32898  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
32899  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
32900  if( ii>0 ){
32901  zDirname[ii] = '\0';
32902  }else{
32903  if( zDirname[0]!='/' ) zDirname[0] = '.';
32904  zDirname[1] = 0;
32905  }
32906  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
32907  if( fd>=0 ){
32908  OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
32909  }
32910  *pFd = fd;
32911  if( fd>=0 ) return SQLITE_OK;
32912  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
32913 }
32914 
32915 /*
32916 ** Make sure all writes to a particular file are committed to disk.
32917 **
32918 ** If dataOnly==0 then both the file itself and its metadata (file
32919 ** size, access time, etc) are synced. If dataOnly!=0 then only the
32920 ** file data is synced.
32921 **
32922 ** Under Unix, also make sure that the directory entry for the file
32923 ** has been created by fsync-ing the directory that contains the file.
32924 ** If we do not do this and we encounter a power failure, the directory
32925 ** entry for the journal might not exist after we reboot. The next
32926 ** SQLite to access the file will not know that the journal exists (because
32927 ** the directory entry for the journal was never created) and the transaction
32928 ** will not roll back - possibly leading to database corruption.
32929 */
32930 static int unixSync(sqlite3_file *id, int flags){
32931  int rc;
32932  unixFile *pFile = (unixFile*)id;
32933 
32934  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
32935  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
32936 
32937  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32938  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32939  || (flags&0x0F)==SQLITE_SYNC_FULL
32940  );
32941 
32942  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32943  ** line is to test that doing so does not cause any problems.
32944  */
32946 
32947  assert( pFile );
32948  OSTRACE(("SYNC %-3d\n", pFile->h));
32949  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
32950  SimulateIOError( rc=1 );
32951  if( rc ){
32952  storeLastErrno(pFile, errno);
32953  return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
32954  }
32955 
32956  /* Also fsync the directory containing the file if the DIRSYNC flag
32957  ** is set. This is a one-time occurrence. Many systems (examples: AIX)
32958  ** are unable to fsync a directory, so ignore errors on the fsync.
32959  */
32960  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
32961  int dirfd;
32962  OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
32963  HAVE_FULLFSYNC, isFullsync));
32964  rc = osOpenDirectory(pFile->zPath, &dirfd);
32965  if( rc==SQLITE_OK ){
32966  full_fsync(dirfd, 0, 0);
32967  robust_close(pFile, dirfd, __LINE__);
32968  }else{
32969  assert( rc==SQLITE_CANTOPEN );
32970  rc = SQLITE_OK;
32971  }
32972  pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
32973  }
32974  return rc;
32975 }
32976 
32977 /*
32978 ** Truncate an open file to a specified size
32979 */
32980 static int unixTruncate(sqlite3_file *id, i64 nByte){
32981  unixFile *pFile = (unixFile *)id;
32982  int rc;
32983  assert( pFile );
32985 
32986  /* If the user has configured a chunk-size for this file, truncate the
32987  ** file so that it consists of an integer number of chunks (i.e. the
32988  ** actual file size after the operation may be larger than the requested
32989  ** size).
32990  */
32991  if( pFile->szChunk>0 ){
32992  nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32993  }
32994 
32995  rc = robust_ftruncate(pFile->h, nByte);
32996  if( rc ){
32997  storeLastErrno(pFile, errno);
32998  return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
32999  }else{
33000 #ifdef SQLITE_DEBUG
33001  /* If we are doing a normal write to a database file (as opposed to
33002  ** doing a hot-journal rollback or a write to some file other than a
33003  ** normal database file) and we truncate the file to zero length,
33004  ** that effectively updates the change counter. This might happen
33005  ** when restoring a database using the backup API from a zero-length
33006  ** source.
33007  */
33008  if( pFile->inNormalWrite && nByte==0 ){
33009  pFile->transCntrChng = 1;
33010  }
33011 #endif
33012 
33013 #if SQLITE_MAX_MMAP_SIZE>0
33014  /* If the file was just truncated to a size smaller than the currently
33015  ** mapped region, reduce the effective mapping size as well. SQLite will
33016  ** use read() and write() to access data beyond this point from now on.
33017  */
33018  if( nByte<pFile->mmapSize ){
33019  pFile->mmapSize = nByte;
33020  }
33021 #endif
33022 
33023  return SQLITE_OK;
33024  }
33025 }
33026 
33027 /*
33028 ** Determine the current size of a file in bytes
33029 */
33030 static int unixFileSize(sqlite3_file *id, i64 *pSize){
33031  int rc;
33032  struct stat buf;
33033  assert( id );
33034  rc = osFstat(((unixFile*)id)->h, &buf);
33035  SimulateIOError( rc=1 );
33036  if( rc!=0 ){
33037  storeLastErrno((unixFile*)id, errno);
33038  return SQLITE_IOERR_FSTAT;
33039  }
33040  *pSize = buf.st_size;
33041 
33042  /* When opening a zero-size database, the findInodeInfo() procedure
33043  ** writes a single byte into that file in order to work around a bug
33044  ** in the OS-X msdos filesystem. In order to avoid problems with upper
33045  ** layers, we need to report this file size as zero even though it is
33046  ** really 1. Ticket #3260.
33047  */
33048  if( *pSize==1 ) *pSize = 0;
33049 
33050 
33051  return SQLITE_OK;
33052 }
33053 
33054 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33055 /*
33056 ** Handler for proxy-locking file-control verbs. Defined below in the
33057 ** proxying locking division.
33058 */
33059 static int proxyFileControl(sqlite3_file*,int,void*);
33060 #endif
33061 
33062 /*
33063 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
33064 ** file-control operation. Enlarge the database to nBytes in size
33065 ** (rounded up to the next chunk-size). If the database is already
33066 ** nBytes or larger, this routine is a no-op.
33067 */
33068 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
33069  if( pFile->szChunk>0 ){
33070  i64 nSize; /* Required file size */
33071  struct stat buf; /* Used to hold return values of fstat() */
33072 
33073  if( osFstat(pFile->h, &buf) ){
33074  return SQLITE_IOERR_FSTAT;
33075  }
33076 
33077  nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
33078  if( nSize>(i64)buf.st_size ){
33079 
33080 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
33081  /* The code below is handling the return value of osFallocate()
33082  ** correctly. posix_fallocate() is defined to "returns zero on success,
33083  ** or an error number on failure". See the manpage for details. */
33084  int err;
33085  do{
33086  err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
33087  }while( err==EINTR );
33088  if( err ) return SQLITE_IOERR_WRITE;
33089 #else
33090  /* If the OS does not have posix_fallocate(), fake it. Write a
33091  ** single byte to the last byte in each block that falls entirely
33092  ** within the extended region. Then, if required, a single byte
33093  ** at offset (nSize-1), to set the size of the file correctly.
33094  ** This is a similar technique to that used by glibc on systems
33095  ** that do not have a real fallocate() call.
33096  */
33097  int nBlk = buf.st_blksize; /* File-system block size */
33098  int nWrite = 0; /* Number of bytes written by seekAndWrite */
33099  i64 iWrite; /* Next offset to write to */
33100 
33101  iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
33102  assert( iWrite>=buf.st_size );
33103  assert( ((iWrite+1)%nBlk)==0 );
33104  for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
33105  if( iWrite>=nSize ) iWrite = nSize - 1;
33106  nWrite = seekAndWrite(pFile, iWrite, "", 1);
33107  if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
33108  }
33109 #endif
33110  }
33111  }
33112 
33113 #if SQLITE_MAX_MMAP_SIZE>0
33114  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
33115  int rc;
33116  if( pFile->szChunk<=0 ){
33117  if( robust_ftruncate(pFile->h, nByte) ){
33118  storeLastErrno(pFile, errno);
33119  return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
33120  }
33121  }
33122 
33123  rc = unixMapfile(pFile, nByte);
33124  return rc;
33125  }
33126 #endif
33127 
33128  return SQLITE_OK;
33129 }
33130 
33131 /*
33132 ** If *pArg is initially negative then this is a query. Set *pArg to
33133 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33134 **
33135 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33136 */
33137 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
33138  if( *pArg<0 ){
33139  *pArg = (pFile->ctrlFlags & mask)!=0;
33140  }else if( (*pArg)==0 ){
33141  pFile->ctrlFlags &= ~mask;
33142  }else{
33143  pFile->ctrlFlags |= mask;
33144  }
33145 }
33146 
33147 /* Forward declaration */
33148 static int unixGetTempname(int nBuf, char *zBuf);
33149 
33150 /*
33151 ** Information and control of an open file handle.
33152 */
33153 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
33154  unixFile *pFile = (unixFile*)id;
33155  switch( op ){
33156  case SQLITE_FCNTL_LOCKSTATE: {
33157  *(int*)pArg = pFile->eFileLock;
33158  return SQLITE_OK;
33159  }
33160  case SQLITE_FCNTL_LAST_ERRNO: {
33161  *(int*)pArg = pFile->lastErrno;
33162  return SQLITE_OK;
33163  }
33164  case SQLITE_FCNTL_CHUNK_SIZE: {
33165  pFile->szChunk = *(int *)pArg;
33166  return SQLITE_OK;
33167  }
33168  case SQLITE_FCNTL_SIZE_HINT: {
33169  int rc;
33171  rc = fcntlSizeHint(pFile, *(i64 *)pArg);
33173  return rc;
33174  }
33175  case SQLITE_FCNTL_PERSIST_WAL: {
33176  unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
33177  return SQLITE_OK;
33178  }
33180  unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
33181  return SQLITE_OK;
33182  }
33183  case SQLITE_FCNTL_VFSNAME: {
33184  *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
33185  return SQLITE_OK;
33186  }
33188  char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
33189  if( zTFile ){
33190  unixGetTempname(pFile->pVfs->mxPathname, zTFile);
33191  *(char**)pArg = zTFile;
33192  }
33193  return SQLITE_OK;
33194  }
33195  case SQLITE_FCNTL_HAS_MOVED: {
33196  *(int*)pArg = fileHasMoved(pFile);
33197  return SQLITE_OK;
33198  }
33199 #if SQLITE_MAX_MMAP_SIZE>0
33200  case SQLITE_FCNTL_MMAP_SIZE: {
33201  i64 newLimit = *(i64*)pArg;
33202  int rc = SQLITE_OK;
33203  if( newLimit>sqlite3GlobalConfig.mxMmap ){
33204  newLimit = sqlite3GlobalConfig.mxMmap;
33205  }
33206  *(i64*)pArg = pFile->mmapSizeMax;
33207  if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33208  pFile->mmapSizeMax = newLimit;
33209  if( pFile->mmapSize>0 ){
33210  unixUnmapfile(pFile);
33211  rc = unixMapfile(pFile, -1);
33212  }
33213  }
33214  return rc;
33215  }
33216 #endif
33217 #ifdef SQLITE_DEBUG
33218  /* The pager calls this method to signal that it has done
33219  ** a rollback and that the database is therefore unchanged and
33220  ** it hence it is OK for the transaction change counter to be
33221  ** unchanged.
33222  */
33224  ((unixFile*)id)->dbUpdate = 0;
33225  return SQLITE_OK;
33226  }
33227 #endif
33228 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33231  return proxyFileControl(id,op,pArg);
33232  }
33233 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
33234  }
33235  return SQLITE_NOTFOUND;
33236 }
33237 
33238 /*
33239 ** Return the sector size in bytes of the underlying block device for
33240 ** the specified file. This is almost always 512 bytes, but may be
33241 ** larger for some devices.
33242 **
33243 ** SQLite code assumes this function cannot fail. It also assumes that
33244 ** if two files are created in the same file-system directory (i.e.
33245 ** a database and its journal file) that the sector size will be the
33246 ** same for both.
33247 */
33248 #ifndef __QNXNTO__
33249 static int unixSectorSize(sqlite3_file *NotUsed){
33250  UNUSED_PARAMETER(NotUsed);
33252 }
33253 #endif
33254 
33255 /*
33256 ** The following version of unixSectorSize() is optimized for QNX.
33257 */
33258 #ifdef __QNXNTO__
33259 #include <sys/dcmd_blk.h>
33260 #include <sys/statvfs.h>
33261 static int unixSectorSize(sqlite3_file *id){
33262  unixFile *pFile = (unixFile*)id;
33263  if( pFile->sectorSize == 0 ){
33264  struct statvfs fsInfo;
33265 
33266  /* Set defaults for non-supported filesystems */
33267  pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33268  pFile->deviceCharacteristics = 0;
33269  if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
33270  return pFile->sectorSize;
33271  }
33272 
33273  if( !strcmp(fsInfo.f_basetype, "tmp") ) {
33274  pFile->sectorSize = fsInfo.f_bsize;
33275  pFile->deviceCharacteristics =
33276  SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
33277  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33278  ** the write succeeds */
33279  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33280  ** so it is ordered */
33281  0;
33282  }else if( strstr(fsInfo.f_basetype, "etfs") ){
33283  pFile->sectorSize = fsInfo.f_bsize;
33284  pFile->deviceCharacteristics =
33285  /* etfs cluster size writes are atomic */
33286  (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
33287  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33288  ** the write succeeds */
33289  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33290  ** so it is ordered */
33291  0;
33292  }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
33293  pFile->sectorSize = fsInfo.f_bsize;
33294  pFile->deviceCharacteristics =
33295  SQLITE_IOCAP_ATOMIC | /* All 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( !strcmp(fsInfo.f_basetype, "qnx4") ){
33302  pFile->sectorSize = fsInfo.f_bsize;
33303  pFile->deviceCharacteristics =
33304  /* full bitset of atomics from max sector size and smaller */
33305  ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33306  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33307  ** so it is ordered */
33308  0;
33309  }else if( strstr(fsInfo.f_basetype, "dos") ){
33310  pFile->sectorSize = fsInfo.f_bsize;
33311  pFile->deviceCharacteristics =
33312  /* full bitset of atomics from max sector size and smaller */
33313  ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33314  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33315  ** so it is ordered */
33316  0;
33317  }else{
33318  pFile->deviceCharacteristics =
33319  SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
33320  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33321  ** the write succeeds */
33322  0;
33323  }
33324  }
33325  /* Last chance verification. If the sector size isn't a multiple of 512
33326  ** then it isn't valid.*/
33327  if( pFile->sectorSize % 512 != 0 ){
33328  pFile->deviceCharacteristics = 0;
33329  pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33330  }
33331  return pFile->sectorSize;
33332 }
33333 #endif /* __QNXNTO__ */
33334 
33335 /*
33336 ** Return the device characteristics for the file.
33337 **
33338 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
33339 ** However, that choice is controversial since technically the underlying
33340 ** file system does not always provide powersafe overwrites. (In other
33341 ** words, after a power-loss event, parts of the file that were never
33342 ** written might end up being altered.) However, non-PSOW behavior is very,
33343 ** very rare. And asserting PSOW makes a large reduction in the amount
33344 ** of required I/O for journaling, since a lot of padding is eliminated.
33345 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
33346 ** available to turn it off and URI query parameter available to turn it off.
33347 */
33348 static int unixDeviceCharacteristics(sqlite3_file *id){
33349  unixFile *p = (unixFile*)id;
33350  int rc = 0;
33351 #ifdef __QNXNTO__
33352  if( p->sectorSize==0 ) unixSectorSize(id);
33353  rc = p->deviceCharacteristics;
33354 #endif
33355  if( p->ctrlFlags & UNIXFILE_PSOW ){
33357  }
33358  return rc;
33359 }
33360 
33361 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
33362 
33363 /*
33364 ** Return the system page size.
33365 **
33366 ** This function should not be called directly by other code in this file.
33367 ** Instead, it should be called via macro osGetpagesize().
33368 */
33369 static int unixGetpagesize(void){
33370 #if OS_VXWORKS
33371  return 1024;
33372 #elif defined(_BSD_SOURCE)
33373  return getpagesize();
33374 #else
33375  return (int)sysconf(_SC_PAGESIZE);
33376 #endif
33377 }
33378 
33379 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
33380 
33381 #ifndef SQLITE_OMIT_WAL
33382 
33383 /*
33384 ** Object used to represent an shared memory buffer.
33385 **
33386 ** When multiple threads all reference the same wal-index, each thread
33387 ** has its own unixShm object, but they all point to a single instance
33388 ** of this unixShmNode object. In other words, each wal-index is opened
33389 ** only once per process.
33390 **
33391 ** Each unixShmNode object is connected to a single unixInodeInfo object.
33392 ** We could coalesce this object into unixInodeInfo, but that would mean
33393 ** every open file that does not use shared memory (in other words, most
33394 ** open files) would have to carry around this extra information. So
33395 ** the unixInodeInfo object contains a pointer to this unixShmNode object
33396 ** and the unixShmNode object is created only when needed.
33397 **
33398 ** unixMutexHeld() must be true when creating or destroying
33399 ** this object or while reading or writing the following fields:
33400 **
33401 ** nRef
33402 **
33403 ** The following fields are read-only after the object is created:
33404 **
33405 ** fid
33406 ** zFilename
33407 **
33408 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
33409 ** unixMutexHeld() is true when reading or writing any other field
33410 ** in this structure.
33411 */
33412 struct unixShmNode {
33413  unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
33414  sqlite3_mutex *mutex; /* Mutex to access this object */
33415  char *zFilename; /* Name of the mmapped file */
33416  int h; /* Open file descriptor */
33417  int szRegion; /* Size of shared-memory regions */
33418  u16 nRegion; /* Size of array apRegion */
33419  u8 isReadonly; /* True if read-only */
33420  char **apRegion; /* Array of mapped shared-memory regions */
33421  int nRef; /* Number of unixShm objects pointing to this */
33422  unixShm *pFirst; /* All unixShm objects pointing to this */
33423 #ifdef SQLITE_DEBUG
33424  u8 exclMask; /* Mask of exclusive locks held */
33425  u8 sharedMask; /* Mask of shared locks held */
33426  u8 nextShmId; /* Next available unixShm.id value */
33427 #endif
33428 };
33429 
33430 /*
33431 ** Structure used internally by this VFS to record the state of an
33432 ** open shared memory connection.
33433 **
33434 ** The following fields are initialized when this object is created and
33435 ** are read-only thereafter:
33436 **
33437 ** unixShm.pFile
33438 ** unixShm.id
33439 **
33440 ** All other fields are read/write. The unixShm.pFile->mutex must be held
33441 ** while accessing any read/write fields.
33442 */
33443 struct unixShm {
33444  unixShmNode *pShmNode; /* The underlying unixShmNode object */
33445  unixShm *pNext; /* Next unixShm with the same unixShmNode */
33446  u8 hasMutex; /* True if holding the unixShmNode mutex */
33447  u8 id; /* Id of this connection within its unixShmNode */
33448  u16 sharedMask; /* Mask of shared locks held */
33449  u16 exclMask; /* Mask of exclusive locks held */
33450 };
33451 
33452 /*
33453 ** Constants used for locking
33454 */
33455 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
33456 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
33457 
33458 /*
33459 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
33460 **
33461 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
33462 ** otherwise.
33463 */
33465  unixFile *pFile, /* Open connection to the WAL file */
33466  int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
33467  int ofst, /* First byte of the locking range */
33468  int n /* Number of bytes to lock */
33469 ){
33470  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
33471  struct flock f; /* The posix advisory locking structure */
33472  int rc = SQLITE_OK; /* Result code form fcntl() */
33473 
33474  /* Access to the unixShmNode object is serialized by the caller */
33475  pShmNode = pFile->pInode->pShmNode;
33476  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
33477 
33478  /* Shared locks never span more than one byte */
33479  assert( n==1 || lockType!=F_RDLCK );
33480 
33481  /* Locks are within range */
33482  assert( n>=1 && n<=SQLITE_SHM_NLOCK );
33483 
33484  if( pShmNode->h>=0 ){
33485  /* Initialize the locking parameters */
33486  memset(&f, 0, sizeof(f));
33487  f.l_type = lockType;
33488  f.l_whence = SEEK_SET;
33489  f.l_start = ofst;
33490  f.l_len = n;
33491 
33492  rc = osFcntl(pShmNode->h, F_SETLK, &f);
33493  rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
33494  }
33495 
33496  /* Update the global lock state and do debug tracing */
33497 #ifdef SQLITE_DEBUG
33498  { u16 mask;
33499  OSTRACE(("SHM-LOCK "));
33500  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
33501  if( rc==SQLITE_OK ){
33502  if( lockType==F_UNLCK ){
33503  OSTRACE(("unlock %d ok", ofst));
33504  pShmNode->exclMask &= ~mask;
33505  pShmNode->sharedMask &= ~mask;
33506  }else if( lockType==F_RDLCK ){
33507  OSTRACE(("read-lock %d ok", ofst));
33508  pShmNode->exclMask &= ~mask;
33509  pShmNode->sharedMask |= mask;
33510  }else{
33511  assert( lockType==F_WRLCK );
33512  OSTRACE(("write-lock %d ok", ofst));
33513  pShmNode->exclMask |= mask;
33514  pShmNode->sharedMask &= ~mask;
33515  }
33516  }else{
33517  if( lockType==F_UNLCK ){
33518  OSTRACE(("unlock %d failed", ofst));
33519  }else if( lockType==F_RDLCK ){
33520  OSTRACE(("read-lock failed"));
33521  }else{
33522  assert( lockType==F_WRLCK );
33523  OSTRACE(("write-lock %d failed", ofst));
33524  }
33525  }
33526  OSTRACE((" - afterwards %03x,%03x\n",
33527  pShmNode->sharedMask, pShmNode->exclMask));
33528  }
33529 #endif
33530 
33531  return rc;
33532 }
33533 
33534 /*
33535 ** Return the minimum number of 32KB shm regions that should be mapped at
33536 ** a time, assuming that each mapping must be an integer multiple of the
33537 ** current system page-size.
33538 **
33539 ** Usually, this is 1. The exception seems to be systems that are configured
33540 ** to use 64KB pages - in this case each mapping must cover at least two
33541 ** shm regions.
33542 */
33543 static int unixShmRegionPerMap(void){
33544  int shmsz = 32*1024; /* SHM region size */
33545  int pgsz = osGetpagesize(); /* System page size */
33546  assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
33547  if( pgsz<shmsz ) return 1;
33548  return pgsz/shmsz;
33549 }
33550 
33551 /*
33552 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
33553 **
33554 ** This is not a VFS shared-memory method; it is a utility function called
33555 ** by VFS shared-memory methods.
33556 */
33557 static void unixShmPurge(unixFile *pFd){
33558  unixShmNode *p = pFd->pInode->pShmNode;
33559  assert( unixMutexHeld() );
33560  if( p && ALWAYS(p->nRef==0) ){
33561  int nShmPerMap = unixShmRegionPerMap();
33562  int i;
33563  assert( p->pInode==pFd->pInode );
33565  for(i=0; i<p->nRegion; i+=nShmPerMap){
33566  if( p->h>=0 ){
33567  osMunmap(p->apRegion[i], p->szRegion);
33568  }else{
33569  sqlite3_free(p->apRegion[i]);
33570  }
33571  }
33572  sqlite3_free(p->apRegion);
33573  if( p->h>=0 ){
33574  robust_close(pFd, p->h, __LINE__);
33575  p->h = -1;
33576  }
33577  p->pInode->pShmNode = 0;
33578  sqlite3_free(p);
33579  }
33580 }
33581 
33582 /*
33583 ** Open a shared-memory area associated with open database file pDbFd.
33584 ** This particular implementation uses mmapped files.
33585 **
33586 ** The file used to implement shared-memory is in the same directory
33587 ** as the open database file and has the same name as the open database
33588 ** file with the "-shm" suffix added. For example, if the database file
33589 ** is "/home/user1/config.db" then the file that is created and mmapped
33590 ** for shared memory will be called "/home/user1/config.db-shm".
33591 **
33592 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
33593 ** some other tmpfs mount. But if a file in a different directory
33594 ** from the database file is used, then differing access permissions
33595 ** or a chroot() might cause two different processes on the same
33596 ** database to end up using different files for shared memory -
33597 ** meaning that their memory would not really be shared - resulting
33598 ** in database corruption. Nevertheless, this tmpfs file usage
33599 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
33600 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
33601 ** option results in an incompatible build of SQLite; builds of SQLite
33602 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
33603 ** same database file at the same time, database corruption will likely
33604 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
33605 ** "unsupported" and may go away in a future SQLite release.
33606 **
33607 ** When opening a new shared-memory file, if no other instances of that
33608 ** file are currently open, in this process or in other processes, then
33609 ** the file must be truncated to zero length or have its header cleared.
33610 **
33611 ** If the original database file (pDbFd) is using the "unix-excl" VFS
33612 ** that means that an exclusive lock is held on the database file and
33613 ** that no other processes are able to read or write the database. In
33614 ** that case, we do not really need shared memory. No shared memory
33615 ** file is created. The shared memory will be simulated with heap memory.
33616 */
33617 static int unixOpenSharedMemory(unixFile *pDbFd){
33618  struct unixShm *p = 0; /* The connection to be opened */
33619  struct unixShmNode *pShmNode; /* The underlying mmapped file */
33620  int rc; /* Result code */
33621  unixInodeInfo *pInode; /* The inode of fd */
33622  char *zShmFilename; /* Name of the file used for SHM */
33623  int nShmFilename; /* Size of the SHM filename in bytes */
33624 
33625  /* Allocate space for the new unixShm object. */
33626  p = sqlite3_malloc64( sizeof(*p) );
33627  if( p==0 ) return SQLITE_NOMEM_BKPT;
33628  memset(p, 0, sizeof(*p));
33629  assert( pDbFd->pShm==0 );
33630 
33631  /* Check to see if a unixShmNode object already exists. Reuse an existing
33632  ** one if present. Create a new one if necessary.
33633  */
33634  unixEnterMutex();
33635  pInode = pDbFd->pInode;
33636  pShmNode = pInode->pShmNode;
33637  if( pShmNode==0 ){
33638  struct stat sStat; /* fstat() info for database file */
33639 #ifndef SQLITE_SHM_DIRECTORY
33640  const char *zBasePath = pDbFd->zPath;
33641 #endif
33642 
33643  /* Call fstat() to figure out the permissions on the database file. If
33644  ** a new *-shm file is created, an attempt will be made to create it
33645  ** with the same permissions.
33646  */
33647  if( osFstat(pDbFd->h, &sStat) ){
33648  rc = SQLITE_IOERR_FSTAT;
33649  goto shm_open_err;
33650  }
33651 
33652 #ifdef SQLITE_SHM_DIRECTORY
33653  nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
33654 #else
33655  nShmFilename = 6 + (int)strlen(zBasePath);
33656 #endif
33657  pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
33658  if( pShmNode==0 ){
33659  rc = SQLITE_NOMEM_BKPT;
33660  goto shm_open_err;
33661  }
33662  memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
33663  zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
33664 #ifdef SQLITE_SHM_DIRECTORY
33665  sqlite3_snprintf(nShmFilename, zShmFilename,
33666  SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
33667  (u32)sStat.st_ino, (u32)sStat.st_dev);
33668 #else
33669  sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
33670  sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
33671 #endif
33672  pShmNode->h = -1;
33673  pDbFd->pInode->pShmNode = pShmNode;
33674  pShmNode->pInode = pDbFd->pInode;
33675  if( sqlite3GlobalConfig.bCoreMutex ){
33677  if( pShmNode->mutex==0 ){
33678  rc = SQLITE_NOMEM_BKPT;
33679  goto shm_open_err;
33680  }
33681  }
33682 
33683  if( pInode->bProcessLock==0 ){
33684  int openFlags = O_RDWR | O_CREAT;
33685  if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
33686  openFlags = O_RDONLY;
33687  pShmNode->isReadonly = 1;
33688  }
33689  pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
33690  if( pShmNode->h<0 ){
33691  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
33692  goto shm_open_err;
33693  }
33694 
33695  /* If this process is running as root, make sure that the SHM file
33696  ** is owned by the same user that owns the original database. Otherwise,
33697  ** the original owner will not be able to connect.
33698  */
33699  robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
33700 
33701  /* Check to see if another process is holding the dead-man switch.
33702  ** If not, truncate the file to zero length.
33703  */
33704  rc = SQLITE_OK;
33705  if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
33706  if( robust_ftruncate(pShmNode->h, 0) ){
33707  rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
33708  }
33709  }
33710  if( rc==SQLITE_OK ){
33711  rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
33712  }
33713  if( rc ) goto shm_open_err;
33714  }
33715  }
33716 
33717  /* Make the new connection a child of the unixShmNode */
33718  p->pShmNode = pShmNode;
33719 #ifdef SQLITE_DEBUG
33720  p->id = pShmNode->nextShmId++;
33721 #endif
33722  pShmNode->nRef++;
33723  pDbFd->pShm = p;
33724  unixLeaveMutex();
33725 
33726  /* The reference count on pShmNode has already been incremented under
33727  ** the cover of the unixEnterMutex() mutex and the pointer from the
33728  ** new (struct unixShm) object to the pShmNode has been set. All that is
33729  ** left to do is to link the new object into the linked list starting
33730  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33731  ** mutex.
33732  */
33733  sqlite3_mutex_enter(pShmNode->mutex);
33734  p->pNext = pShmNode->pFirst;
33735  pShmNode->pFirst = p;
33736  sqlite3_mutex_leave(pShmNode->mutex);
33737  return SQLITE_OK;
33738 
33739  /* Jump here on any error */
33740 shm_open_err:
33741  unixShmPurge(pDbFd); /* This call frees pShmNode if required */
33742  sqlite3_free(p);
33743  unixLeaveMutex();
33744  return rc;
33745 }
33746 
33747 /*
33748 ** This function is called to obtain a pointer to region iRegion of the
33749 ** shared-memory associated with the database file fd. Shared-memory regions
33750 ** are numbered starting from zero. Each shared-memory region is szRegion
33751 ** bytes in size.
33752 **
33753 ** If an error occurs, an error code is returned and *pp is set to NULL.
33754 **
33755 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
33756 ** region has not been allocated (by any client, including one running in a
33757 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
33758 ** bExtend is non-zero and the requested shared-memory region has not yet
33759 ** been allocated, it is allocated by this function.
33760 **
33761 ** If the shared-memory region has already been allocated or is allocated by
33762 ** this call as described above, then it is mapped into this processes
33763 ** address space (if it is not already), *pp is set to point to the mapped
33764 ** memory and SQLITE_OK returned.
33765 */
33766 static int unixShmMap(
33767  sqlite3_file *fd, /* Handle open on database file */
33768  int iRegion, /* Region to retrieve */
33769  int szRegion, /* Size of regions */
33770  int bExtend, /* True to extend file if necessary */
33771  void volatile **pp /* OUT: Mapped memory */
33772 ){
33773  unixFile *pDbFd = (unixFile*)fd;
33774  unixShm *p;
33775  unixShmNode *pShmNode;
33776  int rc = SQLITE_OK;
33777  int nShmPerMap = unixShmRegionPerMap();
33778  int nReqRegion;
33779 
33780  /* If the shared-memory file has not yet been opened, open it now. */
33781  if( pDbFd->pShm==0 ){
33782  rc = unixOpenSharedMemory(pDbFd);
33783  if( rc!=SQLITE_OK ) return rc;
33784  }
33785 
33786  p = pDbFd->pShm;
33787  pShmNode = p->pShmNode;
33788  sqlite3_mutex_enter(pShmNode->mutex);
33789  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33790  assert( pShmNode->pInode==pDbFd->pInode );
33791  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33792  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33793 
33794  /* Minimum number of regions required to be mapped. */
33795  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
33796 
33797  if( pShmNode->nRegion<nReqRegion ){
33798  char **apNew; /* New apRegion[] array */
33799  int nByte = nReqRegion*szRegion; /* Minimum required file size */
33800  struct stat sStat; /* Used by fstat() */
33801 
33802  pShmNode->szRegion = szRegion;
33803 
33804  if( pShmNode->h>=0 ){
33805  /* The requested region is not mapped into this processes address space.
33806  ** Check to see if it has been allocated (i.e. if the wal-index file is
33807  ** large enough to contain the requested region).
33808  */
33809  if( osFstat(pShmNode->h, &sStat) ){
33810  rc = SQLITE_IOERR_SHMSIZE;
33811  goto shmpage_out;
33812  }
33813 
33814  if( sStat.st_size<nByte ){
33815  /* The requested memory region does not exist. If bExtend is set to
33816  ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
33817  */
33818  if( !bExtend ){
33819  goto shmpage_out;
33820  }
33821 
33822  /* Alternatively, if bExtend is true, extend the file. Do this by
33823  ** writing a single byte to the end of each (OS) page being
33824  ** allocated or extended. Technically, we need only write to the
33825  ** last page in order to extend the file. But writing to all new
33826  ** pages forces the OS to allocate them immediately, which reduces
33827  ** the chances of SIGBUS while accessing the mapped region later on.
33828  */
33829  else{
33830  static const int pgsz = 4096;
33831  int iPg;
33832 
33833  /* Write to the last byte of each newly allocated or extended page */
33834  assert( (nByte % pgsz)==0 );
33835  for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
33836  int x = 0;
33837  if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
33838  const char *zFile = pShmNode->zFilename;
33839  rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
33840  goto shmpage_out;
33841  }
33842  }
33843  }
33844  }
33845  }
33846 
33847  /* Map the requested memory region into this processes address space. */
33848  apNew = (char **)sqlite3_realloc(
33849  pShmNode->apRegion, nReqRegion*sizeof(char *)
33850  );
33851  if( !apNew ){
33853  goto shmpage_out;
33854  }
33855  pShmNode->apRegion = apNew;
33856  while( pShmNode->nRegion<nReqRegion ){
33857  int nMap = szRegion*nShmPerMap;
33858  int i;
33859  void *pMem;
33860  if( pShmNode->h>=0 ){
33861  pMem = osMmap(0, nMap,
33862  pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
33863  MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
33864  );
33865  if( pMem==MAP_FAILED ){
33866  rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
33867  goto shmpage_out;
33868  }
33869  }else{
33870  pMem = sqlite3_malloc64(szRegion);
33871  if( pMem==0 ){
33872  rc = SQLITE_NOMEM_BKPT;
33873  goto shmpage_out;
33874  }
33875  memset(pMem, 0, szRegion);
33876  }
33877 
33878  for(i=0; i<nShmPerMap; i++){
33879  pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
33880  }
33881  pShmNode->nRegion += nShmPerMap;
33882  }
33883  }
33884 
33885 shmpage_out:
33886  if( pShmNode->nRegion>iRegion ){
33887  *pp = pShmNode->apRegion[iRegion];
33888  }else{
33889  *pp = 0;
33890  }
33891  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
33892  sqlite3_mutex_leave(pShmNode->mutex);
33893  return rc;
33894 }
33895 
33896 /*
33897 ** Change the lock state for a shared-memory segment.
33898 **
33899 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
33900 ** different here than in posix. In xShmLock(), one can go from unlocked
33901 ** to shared and back or from unlocked to exclusive and back. But one may
33902 ** not go from shared to exclusive or from exclusive to shared.
33903 */
33904 static int unixShmLock(
33905  sqlite3_file *fd, /* Database file holding the shared memory */
33906  int ofst, /* First lock to acquire or release */
33907  int n, /* Number of locks to acquire or release */
33908  int flags /* What to do with the lock */
33909 ){
33910  unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
33911  unixShm *p = pDbFd->pShm; /* The shared memory being locked */
33912  unixShm *pX; /* For looping over all siblings */
33913  unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
33914  int rc = SQLITE_OK; /* Result code */
33915  u16 mask; /* Mask of locks to take or release */
33916 
33917  assert( pShmNode==pDbFd->pInode->pShmNode );
33918  assert( pShmNode->pInode==pDbFd->pInode );
33919  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33920  assert( n>=1 );
33921  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33923  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33924  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33925  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33926  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33927  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33928 
33929  mask = (1<<(ofst+n)) - (1<<ofst);
33930  assert( n>1 || mask==(1<<ofst) );
33931  sqlite3_mutex_enter(pShmNode->mutex);
33932  if( flags & SQLITE_SHM_UNLOCK ){
33933  u16 allMask = 0; /* Mask of locks held by siblings */
33934 
33935  /* See if any siblings hold this same lock */
33936  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33937  if( pX==p ) continue;
33938  assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33939  allMask |= pX->sharedMask;
33940  }
33941 
33942  /* Unlock the system-level locks */
33943  if( (mask & allMask)==0 ){
33944  rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
33945  }else{
33946  rc = SQLITE_OK;
33947  }
33948 
33949  /* Undo the local locks */
33950  if( rc==SQLITE_OK ){
33951  p->exclMask &= ~mask;
33952  p->sharedMask &= ~mask;
33953  }
33954  }else if( flags & SQLITE_SHM_SHARED ){
33955  u16 allShared = 0; /* Union of locks held by connections other than "p" */
33956 
33957  /* Find out which shared locks are already held by sibling connections.
33958  ** If any sibling already holds an exclusive lock, go ahead and return
33959  ** SQLITE_BUSY.
33960  */
33961  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33962  if( (pX->exclMask & mask)!=0 ){
33963  rc = SQLITE_BUSY;
33964  break;
33965  }
33966  allShared |= pX->sharedMask;
33967  }
33968 
33969  /* Get shared locks at the system level, if necessary */
33970  if( rc==SQLITE_OK ){
33971  if( (allShared & mask)==0 ){
33972  rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
33973  }else{
33974  rc = SQLITE_OK;
33975  }
33976  }
33977 
33978  /* Get the local shared locks */
33979  if( rc==SQLITE_OK ){
33980  p->sharedMask |= mask;
33981  }
33982  }else{
33983  /* Make sure no sibling connections hold locks that will block this
33984  ** lock. If any do, return SQLITE_BUSY right away.
33985  */
33986  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33987  if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33988  rc = SQLITE_BUSY;
33989  break;
33990  }
33991  }
33992 
33993  /* Get the exclusive locks at the system level. Then if successful
33994  ** also mark the local connection as being locked.
33995  */
33996  if( rc==SQLITE_OK ){
33997  rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
33998  if( rc==SQLITE_OK ){
33999  assert( (p->sharedMask & mask)==0 );
34000  p->exclMask |= mask;
34001  }
34002  }
34003  }
34004  sqlite3_mutex_leave(pShmNode->mutex);
34005  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
34006  p->id, osGetpid(0), p->sharedMask, p->exclMask));
34007  return rc;
34008 }
34009 
34010 /*
34011 ** Implement a memory barrier or memory fence on shared memory.
34012 **
34013 ** All loads and stores begun before the barrier must complete before
34014 ** any load or store begun after the barrier.
34015 */
34016 static void unixShmBarrier(
34017  sqlite3_file *fd /* Database file holding the shared memory */
34018 ){
34019  UNUSED_PARAMETER(fd);
34020  sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
34021  unixEnterMutex(); /* Also mutex, for redundancy */
34022  unixLeaveMutex();
34023 }
34024 
34025 /*
34026 ** Close a connection to shared-memory. Delete the underlying
34027 ** storage if deleteFlag is true.
34028 **
34029 ** If there is no shared memory associated with the connection then this
34030 ** routine is a harmless no-op.
34031 */
34032 static int unixShmUnmap(
34033  sqlite3_file *fd, /* The underlying database file */
34034  int deleteFlag /* Delete shared-memory if true */
34035 ){
34036  unixShm *p; /* The connection to be closed */
34037  unixShmNode *pShmNode; /* The underlying shared-memory file */
34038  unixShm **pp; /* For looping over sibling connections */
34039  unixFile *pDbFd; /* The underlying database file */
34040 
34041  pDbFd = (unixFile*)fd;
34042  p = pDbFd->pShm;
34043  if( p==0 ) return SQLITE_OK;
34044  pShmNode = p->pShmNode;
34045 
34046  assert( pShmNode==pDbFd->pInode->pShmNode );
34047  assert( pShmNode->pInode==pDbFd->pInode );
34048 
34049  /* Remove connection p from the set of connections associated
34050  ** with pShmNode */
34051  sqlite3_mutex_enter(pShmNode->mutex);
34052  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34053  *pp = p->pNext;
34054 
34055  /* Free the connection p */
34056  sqlite3_free(p);
34057  pDbFd->pShm = 0;
34058  sqlite3_mutex_leave(pShmNode->mutex);
34059 
34060  /* If pShmNode->nRef has reached 0, then close the underlying
34061  ** shared-memory file, too */
34062  unixEnterMutex();
34063  assert( pShmNode->nRef>0 );
34064  pShmNode->nRef--;
34065  if( pShmNode->nRef==0 ){
34066  if( deleteFlag && pShmNode->h>=0 ){
34067  osUnlink(pShmNode->zFilename);
34068  }
34069  unixShmPurge(pDbFd);
34070  }
34071  unixLeaveMutex();
34072 
34073  return SQLITE_OK;
34074 }
34075 
34076 
34077 #else
34078 # define unixShmMap 0
34079 # define unixShmLock 0
34080 # define unixShmBarrier 0
34081 # define unixShmUnmap 0
34082 #endif /* #ifndef SQLITE_OMIT_WAL */
34083 
34084 #if SQLITE_MAX_MMAP_SIZE>0
34085 /*
34086 ** If it is currently memory mapped, unmap file pFd.
34087 */
34088 static void unixUnmapfile(unixFile *pFd){
34089  assert( pFd->nFetchOut==0 );
34090  if( pFd->pMapRegion ){
34091  osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
34092  pFd->pMapRegion = 0;
34093  pFd->mmapSize = 0;
34094  pFd->mmapSizeActual = 0;
34095  }
34096 }
34097 
34098 /*
34099 ** Attempt to set the size of the memory mapping maintained by file
34100 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
34101 **
34102 ** If successful, this function sets the following variables:
34103 **
34104 ** unixFile.pMapRegion
34105 ** unixFile.mmapSize
34106 ** unixFile.mmapSizeActual
34107 **
34108 ** If unsuccessful, an error message is logged via sqlite3_log() and
34109 ** the three variables above are zeroed. In this case SQLite should
34110 ** continue accessing the database using the xRead() and xWrite()
34111 ** methods.
34112 */
34113 static void unixRemapfile(
34114  unixFile *pFd, /* File descriptor object */
34115  i64 nNew /* Required mapping size */
34116 ){
34117  const char *zErr = "mmap";
34118  int h = pFd->h; /* File descriptor open on db file */
34119  u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
34120  i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
34121  u8 *pNew = 0; /* Location of new mapping */
34122  int flags = PROT_READ; /* Flags to pass to mmap() */
34123 
34124  assert( pFd->nFetchOut==0 );
34125  assert( nNew>pFd->mmapSize );
34126  assert( nNew<=pFd->mmapSizeMax );
34127  assert( nNew>0 );
34128  assert( pFd->mmapSizeActual>=pFd->mmapSize );
34129  assert( MAP_FAILED!=0 );
34130 
34131 #ifdef SQLITE_MMAP_READWRITE
34132  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
34133 #endif
34134 
34135  if( pOrig ){
34136 #if HAVE_MREMAP
34137  i64 nReuse = pFd->mmapSize;
34138 #else
34139  const int szSyspage = osGetpagesize();
34140  i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
34141 #endif
34142  u8 *pReq = &pOrig[nReuse];
34143 
34144  /* Unmap any pages of the existing mapping that cannot be reused. */
34145  if( nReuse!=nOrig ){
34146  osMunmap(pReq, nOrig-nReuse);
34147  }
34148 
34149 #if HAVE_MREMAP
34150  pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
34151  zErr = "mremap";
34152 #else
34153  pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
34154  if( pNew!=MAP_FAILED ){
34155  if( pNew!=pReq ){
34156  osMunmap(pNew, nNew - nReuse);
34157  pNew = 0;
34158  }else{
34159  pNew = pOrig;
34160  }
34161  }
34162 #endif
34163 
34164  /* The attempt to extend the existing mapping failed. Free it. */
34165  if( pNew==MAP_FAILED || pNew==0 ){
34166  osMunmap(pOrig, nReuse);
34167  }
34168  }
34169 
34170  /* If pNew is still NULL, try to create an entirely new mapping. */
34171  if( pNew==0 ){
34172  pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
34173  }
34174 
34175  if( pNew==MAP_FAILED ){
34176  pNew = 0;
34177  nNew = 0;
34178  unixLogError(SQLITE_OK, zErr, pFd->zPath);
34179 
34180  /* If the mmap() above failed, assume that all subsequent mmap() calls
34181  ** will probably fail too. Fall back to using xRead/xWrite exclusively
34182  ** in this case. */
34183  pFd->mmapSizeMax = 0;
34184  }
34185  pFd->pMapRegion = (void *)pNew;
34186  pFd->mmapSize = pFd->mmapSizeActual = nNew;
34187 }
34188 
34189 /*
34190 ** Memory map or remap the file opened by file-descriptor pFd (if the file
34191 ** is already mapped, the existing mapping is replaced by the new). Or, if
34192 ** there already exists a mapping for this file, and there are still
34193 ** outstanding xFetch() references to it, this function is a no-op.
34194 **
34195 ** If parameter nByte is non-negative, then it is the requested size of
34196 ** the mapping to create. Otherwise, if nByte is less than zero, then the
34197 ** requested size is the size of the file on disk. The actual size of the
34198 ** created mapping is either the requested size or the value configured
34199 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
34200 **
34201 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
34202 ** recreated as a result of outstanding references) or an SQLite error
34203 ** code otherwise.
34204 */
34205 static int unixMapfile(unixFile *pFd, i64 nMap){
34206  assert( nMap>=0 || pFd->nFetchOut==0 );
34207  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34208  if( pFd->nFetchOut>0 ) return SQLITE_OK;
34209 
34210  if( nMap<0 ){
34211  struct stat statbuf; /* Low-level file information */
34212  if( osFstat(pFd->h, &statbuf) ){
34213  return SQLITE_IOERR_FSTAT;
34214  }
34215  nMap = statbuf.st_size;
34216  }
34217  if( nMap>pFd->mmapSizeMax ){
34218  nMap = pFd->mmapSizeMax;
34219  }
34220 
34221  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34222  if( nMap!=pFd->mmapSize ){
34223  unixRemapfile(pFd, nMap);
34224  }
34225 
34226  return SQLITE_OK;
34227 }
34228 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
34229 
34230 /*
34231 ** If possible, return a pointer to a mapping of file fd starting at offset
34232 ** iOff. The mapping must be valid for at least nAmt bytes.
34233 **
34234 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34235 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34236 ** Finally, if an error does occur, return an SQLite error code. The final
34237 ** value of *pp is undefined in this case.
34238 **
34239 ** If this function does return a pointer, the caller must eventually
34240 ** release the reference by calling unixUnfetch().
34241 */
34242 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34243 #if SQLITE_MAX_MMAP_SIZE>0
34244  unixFile *pFd = (unixFile *)fd; /* The underlying database file */
34245 #endif
34246  *pp = 0;
34247 
34248 #if SQLITE_MAX_MMAP_SIZE>0
34249  if( pFd->mmapSizeMax>0 ){
34250  if( pFd->pMapRegion==0 ){
34251  int rc = unixMapfile(pFd, -1);
34252  if( rc!=SQLITE_OK ) return rc;
34253  }
34254  if( pFd->mmapSize >= iOff+nAmt ){
34255  *pp = &((u8 *)pFd->pMapRegion)[iOff];
34256  pFd->nFetchOut++;
34257  }
34258  }
34259 #endif
34260  return SQLITE_OK;
34261 }
34262 
34263 /*
34264 ** If the third argument is non-NULL, then this function releases a
34265 ** reference obtained by an earlier call to unixFetch(). The second
34266 ** argument passed to this function must be the same as the corresponding
34267 ** argument that was passed to the unixFetch() invocation.
34268 **
34269 ** Or, if the third argument is NULL, then this function is being called
34270 ** to inform the VFS layer that, according to POSIX, any existing mapping
34271 ** may now be invalid and should be unmapped.
34272 */
34273 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34274 #if SQLITE_MAX_MMAP_SIZE>0
34275  unixFile *pFd = (unixFile *)fd; /* The underlying database file */
34276  UNUSED_PARAMETER(iOff);
34277 
34278  /* If p==0 (unmap the entire file) then there must be no outstanding
34279  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34280  ** then there must be at least one outstanding. */
34281  assert( (p==0)==(pFd->nFetchOut==0) );
34282 
34283  /* If p!=0, it must match the iOff value. */
34284  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34285 
34286  if( p ){
34287  pFd->nFetchOut--;
34288  }else{
34289  unixUnmapfile(pFd);
34290  }
34291 
34292  assert( pFd->nFetchOut>=0 );
34293 #else
34294  UNUSED_PARAMETER(fd);
34295  UNUSED_PARAMETER(p);
34296  UNUSED_PARAMETER(iOff);
34297 #endif
34298  return SQLITE_OK;
34299 }
34300 
34301 /*
34302 ** Here ends the implementation of all sqlite3_file methods.
34303 **
34304 ********************** End sqlite3_file Methods *******************************
34305 ******************************************************************************/
34306 
34307 /*
34308 ** This division contains definitions of sqlite3_io_methods objects that
34309 ** implement various file locking strategies. It also contains definitions
34310 ** of "finder" functions. A finder-function is used to locate the appropriate
34311 ** sqlite3_io_methods object for a particular database file. The pAppData
34312 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
34313 ** the correct finder-function for that VFS.
34314 **
34315 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
34316 ** object. The only interesting finder-function is autolockIoFinder, which
34317 ** looks at the filesystem type and tries to guess the best locking
34318 ** strategy from that.
34319 **
34320 ** For finder-function F, two objects are created:
34321 **
34322 ** (1) The real finder-function named "FImpt()".
34323 **
34324 ** (2) A constant pointer to this function named just "F".
34325 **
34326 **
34327 ** A pointer to the F pointer is used as the pAppData value for VFS
34328 ** objects. We have to do this instead of letting pAppData point
34329 ** directly at the finder-function since C90 rules prevent a void*
34330 ** from be cast into a function pointer.
34331 **
34332 **
34333 ** Each instance of this macro generates two objects:
34334 **
34335 ** * A constant sqlite3_io_methods object call METHOD that has locking
34336 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
34337 **
34338 ** * An I/O method finder function called FINDER that returns a pointer
34339 ** to the METHOD object in the previous bullet.
34340 */
34341 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
34342 static const sqlite3_io_methods METHOD = { \
34343  VERSION, /* iVersion */ \
34344  CLOSE, /* xClose */ \
34345  unixRead, /* xRead */ \
34346  unixWrite, /* xWrite */ \
34347  unixTruncate, /* xTruncate */ \
34348  unixSync, /* xSync */ \
34349  unixFileSize, /* xFileSize */ \
34350  LOCK, /* xLock */ \
34351  UNLOCK, /* xUnlock */ \
34352  CKLOCK, /* xCheckReservedLock */ \
34353  unixFileControl, /* xFileControl */ \
34354  unixSectorSize, /* xSectorSize */ \
34355  unixDeviceCharacteristics, /* xDeviceCapabilities */ \
34356  SHMMAP, /* xShmMap */ \
34357  unixShmLock, /* xShmLock */ \
34358  unixShmBarrier, /* xShmBarrier */ \
34359  unixShmUnmap, /* xShmUnmap */ \
34360  unixFetch, /* xFetch */ \
34361  unixUnfetch, /* xUnfetch */ \
34362 }; \
34363 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
34364  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
34365  return &METHOD; \
34366 } \
34367 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
34368  = FINDER##Impl;
34369 
34370 /*
34371 ** Here are all of the sqlite3_io_methods objects for each of the
34372 ** locking strategies. Functions that return pointers to these methods
34373 ** are also created.
34374 */
34376  posixIoFinder, /* Finder function name */
34377  posixIoMethods, /* sqlite3_io_methods object name */
34378  3, /* shared memory and mmap are enabled */
34379  unixClose, /* xClose method */
34380  unixLock, /* xLock method */
34381  unixUnlock, /* xUnlock method */
34382  unixCheckReservedLock, /* xCheckReservedLock method */
34383  unixShmMap /* xShmMap method */
34384 )
34385 IOMETHODS(
34386  nolockIoFinder, /* Finder function name */
34387  nolockIoMethods, /* sqlite3_io_methods object name */
34388  3, /* shared memory is disabled */
34389  nolockClose, /* xClose method */
34390  nolockLock, /* xLock method */
34391  nolockUnlock, /* xUnlock method */
34392  nolockCheckReservedLock, /* xCheckReservedLock method */
34393  0 /* xShmMap method */
34394 )
34395 IOMETHODS(
34396  dotlockIoFinder, /* Finder function name */
34397  dotlockIoMethods, /* sqlite3_io_methods object name */
34398  1, /* shared memory is disabled */
34399  dotlockClose, /* xClose method */
34400  dotlockLock, /* xLock method */
34401  dotlockUnlock, /* xUnlock method */
34402  dotlockCheckReservedLock, /* xCheckReservedLock method */
34403  0 /* xShmMap method */
34404 )
34405 
34406 #if SQLITE_ENABLE_LOCKING_STYLE
34407 IOMETHODS(
34408  flockIoFinder, /* Finder function name */
34409  flockIoMethods, /* sqlite3_io_methods object name */
34410  1, /* shared memory is disabled */
34411  flockClose, /* xClose method */
34412  flockLock, /* xLock method */
34413  flockUnlock, /* xUnlock method */
34414  flockCheckReservedLock, /* xCheckReservedLock method */
34415  0 /* xShmMap method */
34416 )
34417 #endif
34418 
34419 #if OS_VXWORKS
34420 IOMETHODS(
34421  semIoFinder, /* Finder function name */
34422  semIoMethods, /* sqlite3_io_methods object name */
34423  1, /* shared memory is disabled */
34424  semXClose, /* xClose method */
34425  semXLock, /* xLock method */
34426  semXUnlock, /* xUnlock method */
34427  semXCheckReservedLock, /* xCheckReservedLock method */
34428  0 /* xShmMap method */
34429 )
34430 #endif
34431 
34432 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34433 IOMETHODS(
34434  afpIoFinder, /* Finder function name */
34435  afpIoMethods, /* sqlite3_io_methods object name */
34436  1, /* shared memory is disabled */
34437  afpClose, /* xClose method */
34438  afpLock, /* xLock method */
34439  afpUnlock, /* xUnlock method */
34440  afpCheckReservedLock, /* xCheckReservedLock method */
34441  0 /* xShmMap method */
34442 )
34443 #endif
34444 
34445 /*
34446 ** The proxy locking method is a "super-method" in the sense that it
34447 ** opens secondary file descriptors for the conch and lock files and
34448 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
34449 ** secondary files. For this reason, the division that implements
34450 ** proxy locking is located much further down in the file. But we need
34451 ** to go ahead and define the sqlite3_io_methods and finder function
34452 ** for proxy locking here. So we forward declare the I/O methods.
34453 */
34454 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34455 static int proxyClose(sqlite3_file*);
34456 static int proxyLock(sqlite3_file*, int);
34457 static int proxyUnlock(sqlite3_file*, int);
34458 static int proxyCheckReservedLock(sqlite3_file*, int*);
34459 IOMETHODS(
34460  proxyIoFinder, /* Finder function name */
34461  proxyIoMethods, /* sqlite3_io_methods object name */
34462  1, /* shared memory is disabled */
34463  proxyClose, /* xClose method */
34464  proxyLock, /* xLock method */
34465  proxyUnlock, /* xUnlock method */
34466  proxyCheckReservedLock, /* xCheckReservedLock method */
34467  0 /* xShmMap method */
34468 )
34469 #endif
34470 
34471 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
34472 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34473 IOMETHODS(
34474  nfsIoFinder, /* Finder function name */
34475  nfsIoMethods, /* sqlite3_io_methods object name */
34476  1, /* shared memory is disabled */
34477  unixClose, /* xClose method */
34478  unixLock, /* xLock method */
34479  nfsUnlock, /* xUnlock method */
34480  unixCheckReservedLock, /* xCheckReservedLock method */
34481  0 /* xShmMap method */
34482 )
34483 #endif
34484 
34485 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34486 /*
34487 ** This "finder" function attempts to determine the best locking strategy
34488 ** for the database file "filePath". It then returns the sqlite3_io_methods
34489 ** object that implements that strategy.
34490 **
34491 ** This is for MacOSX only.
34492 */
34493 static const sqlite3_io_methods *autolockIoFinderImpl(
34494  const char *filePath, /* name of the database file */
34495  unixFile *pNew /* open file object for the database file */
34496 ){
34497  static const struct Mapping {
34498  const char *zFilesystem; /* Filesystem type name */
34499  const sqlite3_io_methods *pMethods; /* Appropriate locking method */
34500  } aMap[] = {
34501  { "hfs", &posixIoMethods },
34502  { "ufs", &posixIoMethods },
34503  { "afpfs", &afpIoMethods },
34504  { "smbfs", &afpIoMethods },
34505  { "webdav", &nolockIoMethods },
34506  { 0, 0 }
34507  };
34508  int i;
34509  struct statfs fsInfo;
34510  struct flock lockInfo;
34511 
34512  if( !filePath ){
34513  /* If filePath==NULL that means we are dealing with a transient file
34514  ** that does not need to be locked. */
34515  return &nolockIoMethods;
34516  }
34517  if( statfs(filePath, &fsInfo) != -1 ){
34518  if( fsInfo.f_flags & MNT_RDONLY ){
34519  return &nolockIoMethods;
34520  }
34521  for(i=0; aMap[i].zFilesystem; i++){
34522  if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
34523  return aMap[i].pMethods;
34524  }
34525  }
34526  }
34527 
34528  /* Default case. Handles, amongst others, "nfs".
34529  ** Test byte-range lock using fcntl(). If the call succeeds,
34530  ** assume that the file-system supports POSIX style locks.
34531  */
34532  lockInfo.l_len = 1;
34533  lockInfo.l_start = 0;
34534  lockInfo.l_whence = SEEK_SET;
34535  lockInfo.l_type = F_RDLCK;
34536  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34537  if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
34538  return &nfsIoMethods;
34539  } else {
34540  return &posixIoMethods;
34541  }
34542  }else{
34543  return &dotlockIoMethods;
34544  }
34545 }
34546 static const sqlite3_io_methods
34547  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
34548 
34549 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
34550 
34551 #if OS_VXWORKS
34552 /*
34553 ** This "finder" function for VxWorks checks to see if posix advisory
34554 ** locking works. If it does, then that is what is used. If it does not
34555 ** work, then fallback to named semaphore locking.
34556 */
34557 static const sqlite3_io_methods *vxworksIoFinderImpl(
34558  const char *filePath, /* name of the database file */
34559  unixFile *pNew /* the open file object */
34560 ){
34561  struct flock lockInfo;
34562 
34563  if( !filePath ){
34564  /* If filePath==NULL that means we are dealing with a transient file
34565  ** that does not need to be locked. */
34566  return &nolockIoMethods;
34567  }
34568 
34569  /* Test if fcntl() is supported and use POSIX style locks.
34570  ** Otherwise fall back to the named semaphore method.
34571  */
34572  lockInfo.l_len = 1;
34573  lockInfo.l_start = 0;
34574  lockInfo.l_whence = SEEK_SET;
34575  lockInfo.l_type = F_RDLCK;
34576  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34577  return &posixIoMethods;
34578  }else{
34579  return &semIoMethods;
34580  }
34581 }
34582 static const sqlite3_io_methods
34583  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
34584 
34585 #endif /* OS_VXWORKS */
34586 
34587 /*
34588 ** An abstract type for a pointer to an IO method finder function:
34589 */
34590 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
34591 
34592 
34593 /****************************************************************************
34594 **************************** sqlite3_vfs methods ****************************
34595 **
34596 ** This division contains the implementation of methods on the
34597 ** sqlite3_vfs object.
34598 */
34599 
34600 /*
34601 ** Initialize the contents of the unixFile structure pointed to by pId.
34602 */
34603 static int fillInUnixFile(
34604  sqlite3_vfs *pVfs, /* Pointer to vfs object */
34605  int h, /* Open file descriptor of file being opened */
34606  sqlite3_file *pId, /* Write to the unixFile structure here */
34607  const char *zFilename, /* Name of the file being opened */
34608  int ctrlFlags /* Zero or more UNIXFILE_* values */
34609 ){
34610  const sqlite3_io_methods *pLockingStyle;
34611  unixFile *pNew = (unixFile *)pId;
34612  int rc = SQLITE_OK;
34613 
34614  assert( pNew->pInode==NULL );
34615 
34616  /* Usually the path zFilename should not be a relative pathname. The
34617  ** exception is when opening the proxy "conch" file in builds that
34618  ** include the special Apple locking styles.
34619  */
34620 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34621  assert( zFilename==0 || zFilename[0]=='/'
34622  || pVfs->pAppData==(void*)&autolockIoFinder );
34623 #else
34624  assert( zFilename==0 || zFilename[0]=='/' );
34625 #endif
34626 
34627  /* No locking occurs in temporary files */
34628  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
34629 
34630  OSTRACE(("OPEN %-3d %s\n", h, zFilename));
34631  pNew->h = h;
34632  pNew->pVfs = pVfs;
34633  pNew->zPath = zFilename;
34634  pNew->ctrlFlags = (u8)ctrlFlags;
34635 #if SQLITE_MAX_MMAP_SIZE>0
34636  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34637 #endif
34638  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
34639  "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34640  pNew->ctrlFlags |= UNIXFILE_PSOW;
34641  }
34642  if( strcmp(pVfs->zName,"unix-excl")==0 ){
34643  pNew->ctrlFlags |= UNIXFILE_EXCL;
34644  }
34645 
34646 #if OS_VXWORKS
34647  pNew->pId = vxworksFindFileId(zFilename);
34648  if( pNew->pId==0 ){
34649  ctrlFlags |= UNIXFILE_NOLOCK;
34650  rc = SQLITE_NOMEM_BKPT;
34651  }
34652 #endif
34653 
34654  if( ctrlFlags & UNIXFILE_NOLOCK ){
34655  pLockingStyle = &nolockIoMethods;
34656  }else{
34657  pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
34658 #if SQLITE_ENABLE_LOCKING_STYLE
34659  /* Cache zFilename in the locking context (AFP and dotlock override) for
34660  ** proxyLock activation is possible (remote proxy is based on db name)
34661  ** zFilename remains valid until file is closed, to support */
34662  pNew->lockingContext = (void*)zFilename;
34663 #endif
34664  }
34665 
34666  if( pLockingStyle == &posixIoMethods
34667 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34668  || pLockingStyle == &nfsIoMethods
34669 #endif
34670  ){
34671  unixEnterMutex();
34672  rc = findInodeInfo(pNew, &pNew->pInode);
34673  if( rc!=SQLITE_OK ){
34674  /* If an error occurred in findInodeInfo(), close the file descriptor
34675  ** immediately, before releasing the mutex. findInodeInfo() may fail
34676  ** in two scenarios:
34677  **
34678  ** (a) A call to fstat() failed.
34679  ** (b) A malloc failed.
34680  **
34681  ** Scenario (b) may only occur if the process is holding no other
34682  ** file descriptors open on the same file. If there were other file
34683  ** descriptors on this file, then no malloc would be required by
34684  ** findInodeInfo(). If this is the case, it is quite safe to close
34685  ** handle h - as it is guaranteed that no posix locks will be released
34686  ** by doing so.
34687  **
34688  ** If scenario (a) caused the error then things are not so safe. The
34689  ** implicit assumption here is that if fstat() fails, things are in
34690  ** such bad shape that dropping a lock or two doesn't matter much.
34691  */
34692  robust_close(pNew, h, __LINE__);
34693  h = -1;
34694  }
34695  unixLeaveMutex();
34696  }
34697 
34698 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34699  else if( pLockingStyle == &afpIoMethods ){
34700  /* AFP locking uses the file path so it needs to be included in
34701  ** the afpLockingContext.
34702  */
34703  afpLockingContext *pCtx;
34704  pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
34705  if( pCtx==0 ){
34706  rc = SQLITE_NOMEM_BKPT;
34707  }else{
34708  /* NB: zFilename exists and remains valid until the file is closed
34709  ** according to requirement F11141. So we do not need to make a
34710  ** copy of the filename. */
34711  pCtx->dbPath = zFilename;
34712  pCtx->reserved = 0;
34713  srandomdev();
34714  unixEnterMutex();
34715  rc = findInodeInfo(pNew, &pNew->pInode);
34716  if( rc!=SQLITE_OK ){
34718  robust_close(pNew, h, __LINE__);
34719  h = -1;
34720  }
34721  unixLeaveMutex();
34722  }
34723  }
34724 #endif
34725 
34726  else if( pLockingStyle == &dotlockIoMethods ){
34727  /* Dotfile locking uses the file path so it needs to be included in
34728  ** the dotlockLockingContext
34729  */
34730  char *zLockFile;
34731  int nFilename;
34732  assert( zFilename!=0 );
34733  nFilename = (int)strlen(zFilename) + 6;
34734  zLockFile = (char *)sqlite3_malloc64(nFilename);
34735  if( zLockFile==0 ){
34736  rc = SQLITE_NOMEM_BKPT;
34737  }else{
34738  sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
34739  }
34740  pNew->lockingContext = zLockFile;
34741  }
34742 
34743 #if OS_VXWORKS
34744  else if( pLockingStyle == &semIoMethods ){
34745  /* Named semaphore locking uses the file path so it needs to be
34746  ** included in the semLockingContext
34747  */
34748  unixEnterMutex();
34749  rc = findInodeInfo(pNew, &pNew->pInode);
34750  if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
34751  char *zSemName = pNew->pInode->aSemName;
34752  int n;
34753  sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
34754  pNew->pId->zCanonicalName);
34755  for( n=1; zSemName[n]; n++ )
34756  if( zSemName[n]=='/' ) zSemName[n] = '_';
34757  pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
34758  if( pNew->pInode->pSem == SEM_FAILED ){
34759  rc = SQLITE_NOMEM_BKPT;
34760  pNew->pInode->aSemName[0] = '\0';
34761  }
34762  }
34763  unixLeaveMutex();
34764  }
34765 #endif
34766 
34767  storeLastErrno(pNew, 0);
34768 #if OS_VXWORKS
34769  if( rc!=SQLITE_OK ){
34770  if( h>=0 ) robust_close(pNew, h, __LINE__);
34771  h = -1;
34772  osUnlink(zFilename);
34773  pNew->ctrlFlags |= UNIXFILE_DELETE;
34774  }
34775 #endif
34776  if( rc!=SQLITE_OK ){
34777  if( h>=0 ) robust_close(pNew, h, __LINE__);
34778  }else{
34779  pNew->pMethod = pLockingStyle;
34780  OpenCounter(+1);
34781  verifyDbFile(pNew);
34782  }
34783  return rc;
34784 }
34785 
34786 /*
34787 ** Return the name of a directory in which to put temporary files.
34788 ** If no suitable temporary file directory can be found, return NULL.
34789 */
34790 static const char *unixTempFileDir(void){
34791  static const char *azDirs[] = {
34792  0,
34793  0,
34794  "/var/tmp",
34795  "/usr/tmp",
34796  "/tmp",
34797  "."
34798  };
34799  unsigned int i = 0;
34800  struct stat buf;
34801  const char *zDir = sqlite3_temp_directory;
34802 
34803  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
34804  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
34805  while(1){
34806  if( zDir!=0
34807  && osStat(zDir, &buf)==0
34808  && S_ISDIR(buf.st_mode)
34809  && osAccess(zDir, 03)==0
34810  ){
34811  return zDir;
34812  }
34813  if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
34814  zDir = azDirs[i++];
34815  }
34816  return 0;
34817 }
34818 
34819 /*
34820 ** Create a temporary file name in zBuf. zBuf must be allocated
34821 ** by the calling process and must be big enough to hold at least
34822 ** pVfs->mxPathname bytes.
34823 */
34824 static int unixGetTempname(int nBuf, char *zBuf){
34825  const char *zDir;
34826  int iLimit = 0;
34827 
34828  /* It's odd to simulate an io-error here, but really this is just
34829  ** using the io-error infrastructure to test that SQLite handles this
34830  ** function failing.
34831  */
34832  zBuf[0] = 0;
34833  SimulateIOError( return SQLITE_IOERR );
34834 
34835  zDir = unixTempFileDir();
34836  if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
34837  do{
34838  u64 r;
34839  sqlite3_randomness(sizeof(r), &r);
34840  assert( nBuf>2 );
34841  zBuf[nBuf-2] = 0;
34842  sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
34843  zDir, r, 0);
34844  if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
34845  }while( osAccess(zBuf,0)==0 );
34846  return SQLITE_OK;
34847 }
34848 
34849 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34850 /*
34851 ** Routine to transform a unixFile into a proxy-locking unixFile.
34852 ** Implementation in the proxy-lock division, but used by unixOpen()
34853 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
34854 */
34855 static int proxyTransformUnixFile(unixFile*, const char*);
34856 #endif
34857 
34858 /*
34859 ** Search for an unused file descriptor that was opened on the database
34860 ** file (not a journal or master-journal file) identified by pathname
34861 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
34862 ** argument to this function.
34863 **
34864 ** Such a file descriptor may exist if a database connection was closed
34865 ** but the associated file descriptor could not be closed because some
34866 ** other file descriptor open on the same file is holding a file-lock.
34867 ** Refer to comments in the unixClose() function and the lengthy comment
34868 ** describing "Posix Advisory Locking" at the start of this file for
34869 ** further details. Also, ticket #4018.
34870 **
34871 ** If a suitable file descriptor is found, then it is returned. If no
34872 ** such file descriptor is located, -1 is returned.
34873 */
34874 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
34875  UnixUnusedFd *pUnused = 0;
34876 
34877  /* Do not search for an unused file descriptor on vxworks. Not because
34878  ** vxworks would not benefit from the change (it might, we're not sure),
34879  ** but because no way to test it is currently available. It is better
34880  ** not to risk breaking vxworks support for the sake of such an obscure
34881  ** feature. */
34882 #if !OS_VXWORKS
34883  struct stat sStat; /* Results of stat() call */
34884 
34885  /* A stat() call may fail for various reasons. If this happens, it is
34886  ** almost certain that an open() call on the same path will also fail.
34887  ** For this reason, if an error occurs in the stat() call here, it is
34888  ** ignored and -1 is returned. The caller will try to open a new file
34889  ** descriptor on the same path, fail, and return an error to SQLite.
34890  **
34891  ** Even if a subsequent open() call does succeed, the consequences of
34892  ** not searching for a reusable file descriptor are not dire. */
34893  if( 0==osStat(zPath, &sStat) ){
34894  unixInodeInfo *pInode;
34895 
34896  unixEnterMutex();
34897  pInode = inodeList;
34898  while( pInode && (pInode->fileId.dev!=sStat.st_dev
34899  || pInode->fileId.ino!=sStat.st_ino) ){
34900  pInode = pInode->pNext;
34901  }
34902  if( pInode ){
34903  UnixUnusedFd **pp;
34904  for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
34905  pUnused = *pp;
34906  if( pUnused ){
34907  *pp = pUnused->pNext;
34908  }
34909  }
34910  unixLeaveMutex();
34911  }
34912 #endif /* if !OS_VXWORKS */
34913  return pUnused;
34914 }
34915 
34916 /*
34917 ** Find the mode, uid and gid of file zFile.
34918 */
34919 static int getFileMode(
34920  const char *zFile, /* File name */
34921  mode_t *pMode, /* OUT: Permissions of zFile */
34922  uid_t *pUid, /* OUT: uid of zFile. */
34923  gid_t *pGid /* OUT: gid of zFile. */
34924 ){
34925  struct stat sStat; /* Output of stat() on database file */
34926  int rc = SQLITE_OK;
34927  if( 0==osStat(zFile, &sStat) ){
34928  *pMode = sStat.st_mode & 0777;
34929  *pUid = sStat.st_uid;
34930  *pGid = sStat.st_gid;
34931  }else{
34932  rc = SQLITE_IOERR_FSTAT;
34933  }
34934  return rc;
34935 }
34936 
34937 /*
34938 ** This function is called by unixOpen() to determine the unix permissions
34939 ** to create new files with. If no error occurs, then SQLITE_OK is returned
34940 ** and a value suitable for passing as the third argument to open(2) is
34941 ** written to *pMode. If an IO error occurs, an SQLite error code is
34942 ** returned and the value of *pMode is not modified.
34943 **
34944 ** In most cases, this routine sets *pMode to 0, which will become
34945 ** an indication to robust_open() to create the file using
34946 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
34947 ** But if the file being opened is a WAL or regular journal file, then
34948 ** this function queries the file-system for the permissions on the
34949 ** corresponding database file and sets *pMode to this value. Whenever
34950 ** possible, WAL and journal files are created using the same permissions
34951 ** as the associated database file.
34952 **
34953 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
34954 ** original filename is unavailable. But 8_3_NAMES is only used for
34955 ** FAT filesystems and permissions do not matter there, so just use
34956 ** the default permissions.
34957 */
34959  const char *zPath, /* Path of file (possibly) being created */
34960  int flags, /* Flags passed as 4th argument to xOpen() */
34961  mode_t *pMode, /* OUT: Permissions to open file with */
34962  uid_t *pUid, /* OUT: uid to set on the file */
34963  gid_t *pGid /* OUT: gid to set on the file */
34964 ){
34965  int rc = SQLITE_OK; /* Return Code */
34966  *pMode = 0;
34967  *pUid = 0;
34968  *pGid = 0;
34969  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
34970  char zDb[MAX_PATHNAME+1]; /* Database file path */
34971  int nDb; /* Number of valid bytes in zDb */
34972 
34973  /* zPath is a path to a WAL or journal file. The following block derives
34974  ** the path to the associated database file from zPath. This block handles
34975  ** the following naming conventions:
34976  **
34977  ** "<path to db>-journal"
34978  ** "<path to db>-wal"
34979  ** "<path to db>-journalNN"
34980  ** "<path to db>-walNN"
34981  **
34982  ** where NN is a decimal number. The NN naming schemes are
34983  ** used by the test_multiplex.c module.
34984  */
34985  nDb = sqlite3Strlen30(zPath) - 1;
34986  while( zPath[nDb]!='-' ){
34987 #ifndef SQLITE_ENABLE_8_3_NAMES
34988  /* In the normal case (8+3 filenames disabled) the journal filename
34989  ** is guaranteed to contain a '-' character. */
34990  assert( nDb>0 );
34991  assert( sqlite3Isalnum(zPath[nDb]) );
34992 #else
34993  /* If 8+3 names are possible, then the journal file might not contain
34994  ** a '-' character. So check for that case and return early. */
34995  if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
34996 #endif
34997  nDb--;
34998  }
34999  memcpy(zDb, zPath, nDb);
35000  zDb[nDb] = '\0';
35001 
35002  rc = getFileMode(zDb, pMode, pUid, pGid);
35003  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
35004  *pMode = 0600;
35005  }else if( flags & SQLITE_OPEN_URI ){
35006  /* If this is a main database file and the file was opened using a URI
35007  ** filename, check for the "modeof" parameter. If present, interpret
35008  ** its value as a filename and try to copy the mode, uid and gid from
35009  ** that file. */
35010  const char *z = sqlite3_uri_parameter(zPath, "modeof");
35011  if( z ){
35012  rc = getFileMode(z, pMode, pUid, pGid);
35013  }
35014  }
35015  return rc;
35016 }
35017 
35018 /*
35019 ** Open the file zPath.
35020 **
35021 ** Previously, the SQLite OS layer used three functions in place of this
35022 ** one:
35023 **
35024 ** sqlite3OsOpenReadWrite();
35025 ** sqlite3OsOpenReadOnly();
35026 ** sqlite3OsOpenExclusive();
35027 **
35028 ** These calls correspond to the following combinations of flags:
35029 **
35030 ** ReadWrite() -> (READWRITE | CREATE)
35031 ** ReadOnly() -> (READONLY)
35032 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
35033 **
35034 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
35035 ** true, the file was configured to be automatically deleted when the
35036 ** file handle closed. To achieve the same effect using this new
35037 ** interface, add the DELETEONCLOSE flag to those specified above for
35038 ** OpenExclusive().
35039 */
35040 static int unixOpen(
35041  sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
35042  const char *zPath, /* Pathname of file to be opened */
35043  sqlite3_file *pFile, /* The file descriptor to be filled in */
35044  int flags, /* Input flags to control the opening */
35045  int *pOutFlags /* Output flags returned to SQLite core */
35046 ){
35047  unixFile *p = (unixFile *)pFile;
35048  int fd = -1; /* File descriptor returned by open() */
35049  int openFlags = 0; /* Flags to pass to open() */
35050  int eType = flags&0xFFFFFF00; /* Type of file to open */
35051  int noLock; /* True to omit locking primitives */
35052  int rc = SQLITE_OK; /* Function Return Code */
35053  int ctrlFlags = 0; /* UNIXFILE_* flags */
35054 
35055  int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
35056  int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
35057  int isCreate = (flags & SQLITE_OPEN_CREATE);
35058  int isReadonly = (flags & SQLITE_OPEN_READONLY);
35059  int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
35060 #if SQLITE_ENABLE_LOCKING_STYLE
35061  int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
35062 #endif
35063 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35064  struct statfs fsInfo;
35065 #endif
35066 
35067  /* If creating a master or main-file journal, this function will open
35068  ** a file-descriptor on the directory too. The first time unixSync()
35069  ** is called the directory file descriptor will be fsync()ed and close()d.
35070  */
35071  int syncDir = (isCreate && (
35073  || eType==SQLITE_OPEN_MAIN_JOURNAL
35074  || eType==SQLITE_OPEN_WAL
35075  ));
35076 
35077  /* If argument zPath is a NULL pointer, this function is required to open
35078  ** a temporary file. Use this buffer to store the file name in.
35079  */
35080  char zTmpname[MAX_PATHNAME+2];
35081  const char *zName = zPath;
35082 
35083  /* Check the following statements are true:
35084  **
35085  ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
35086  ** (b) if CREATE is set, then READWRITE must also be set, and
35087  ** (c) if EXCLUSIVE is set, then CREATE must also be set.
35088  ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
35089  */
35090  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35091  assert(isCreate==0 || isReadWrite);
35092  assert(isExclusive==0 || isCreate);
35093  assert(isDelete==0 || isCreate);
35094 
35095  /* The main DB, main journal, WAL file and master journal are never
35096  ** automatically deleted. Nor are they ever temporary files. */
35097  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35098  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35099  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35100  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35101 
35102  /* Assert that the upper layer has set one of the "file-type" flags. */
35103  assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
35106  || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35107  );
35108 
35109  /* Detect a pid change and reset the PRNG. There is a race condition
35110  ** here such that two or more threads all trying to open databases at
35111  ** the same instant might all reset the PRNG. But multiple resets
35112  ** are harmless.
35113  */
35114  if( randomnessPid!=osGetpid(0) ){
35115  randomnessPid = osGetpid(0);
35116  sqlite3_randomness(0,0);
35117  }
35118 
35119  memset(p, 0, sizeof(unixFile));
35120 
35121  if( eType==SQLITE_OPEN_MAIN_DB ){
35122  UnixUnusedFd *pUnused;
35123  pUnused = findReusableFd(zName, flags);
35124  if( pUnused ){
35125  fd = pUnused->fd;
35126  }else{
35127  pUnused = sqlite3_malloc64(sizeof(*pUnused));
35128  if( !pUnused ){
35129  return SQLITE_NOMEM_BKPT;
35130  }
35131  }
35132  p->pUnused = pUnused;
35133 
35134  /* Database filenames are double-zero terminated if they are not
35135  ** URIs with parameters. Hence, they can always be passed into
35136  ** sqlite3_uri_parameter(). */
35137  assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
35138 
35139  }else if( !zName ){
35140  /* If zName is NULL, the upper layer is requesting a temp file. */
35141  assert(isDelete && !syncDir);
35142  rc = unixGetTempname(pVfs->mxPathname, zTmpname);
35143  if( rc!=SQLITE_OK ){
35144  return rc;
35145  }
35146  zName = zTmpname;
35147 
35148  /* Generated temporary filenames are always double-zero terminated
35149  ** for use by sqlite3_uri_parameter(). */
35150  assert( zName[strlen(zName)+1]==0 );
35151  }
35152 
35153  /* Determine the value of the flags parameter passed to POSIX function
35154  ** open(). These must be calculated even if open() is not called, as
35155  ** they may be stored as part of the file handle and used by the
35156  ** 'conch file' locking functions later on. */
35157  if( isReadonly ) openFlags |= O_RDONLY;
35158  if( isReadWrite ) openFlags |= O_RDWR;
35159  if( isCreate ) openFlags |= O_CREAT;
35160  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
35161  openFlags |= (O_LARGEFILE|O_BINARY);
35162 
35163  if( fd<0 ){
35164  mode_t openMode; /* Permissions to create file with */
35165  uid_t uid; /* Userid for the file */
35166  gid_t gid; /* Groupid for the file */
35167  rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
35168  if( rc!=SQLITE_OK ){
35169  assert( !p->pUnused );
35170  assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
35171  return rc;
35172  }
35173  fd = robust_open(zName, openFlags, openMode);
35174  OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
35175  assert( !isExclusive || (openFlags & O_CREAT)!=0 );
35176  if( fd<0 && errno!=EISDIR && isReadWrite ){
35177  /* Failed to open the file for read/write access. Try read-only. */
35179  openFlags &= ~(O_RDWR|O_CREAT);
35180  flags |= SQLITE_OPEN_READONLY;
35181  openFlags |= O_RDONLY;
35182  isReadonly = 1;
35183  fd = robust_open(zName, openFlags, openMode);
35184  }
35185  if( fd<0 ){
35186  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
35187  goto open_finished;
35188  }
35189 
35190  /* If this process is running as root and if creating a new rollback
35191  ** journal or WAL file, set the ownership of the journal or WAL to be
35192  ** the same as the original database.
35193  */
35194  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
35195  robustFchown(fd, uid, gid);
35196  }
35197  }
35198  assert( fd>=0 );
35199  if( pOutFlags ){
35200  *pOutFlags = flags;
35201  }
35202 
35203  if( p->pUnused ){
35204  p->pUnused->fd = fd;
35205  p->pUnused->flags = flags;
35206  }
35207 
35208  if( isDelete ){
35209 #if OS_VXWORKS
35210  zPath = zName;
35211 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
35212  zPath = sqlite3_mprintf("%s", zName);
35213  if( zPath==0 ){
35214  robust_close(p, fd, __LINE__);
35215  return SQLITE_NOMEM_BKPT;
35216  }
35217 #else
35218  osUnlink(zName);
35219 #endif
35220  }
35221 #if SQLITE_ENABLE_LOCKING_STYLE
35222  else{
35223  p->openFlags = openFlags;
35224  }
35225 #endif
35226 
35227 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35228  if( fstatfs(fd, &fsInfo) == -1 ){
35229  storeLastErrno(p, errno);
35230  robust_close(p, fd, __LINE__);
35231  return SQLITE_IOERR_ACCESS;
35232  }
35233  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
35234  ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35235  }
35236  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
35237  ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35238  }
35239 #endif
35240 
35241  /* Set up appropriate ctrlFlags */
35242  if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
35243  if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
35244  noLock = eType!=SQLITE_OPEN_MAIN_DB;
35245  if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
35246  if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
35247  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
35248 
35249 #if SQLITE_ENABLE_LOCKING_STYLE
35250 #if SQLITE_PREFER_PROXY_LOCKING
35251  isAutoProxy = 1;
35252 #endif
35253  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
35254  char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
35255  int useProxy = 0;
35256 
35257  /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
35258  ** never use proxy, NULL means use proxy for non-local files only. */
35259  if( envforce!=NULL ){
35260  useProxy = atoi(envforce)>0;
35261  }else{
35262  useProxy = !(fsInfo.f_flags&MNT_LOCAL);
35263  }
35264  if( useProxy ){
35265  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35266  if( rc==SQLITE_OK ){
35267  rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
35268  if( rc!=SQLITE_OK ){
35269  /* Use unixClose to clean up the resources added in fillInUnixFile
35270  ** and clear all the structure's references. Specifically,
35271  ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
35272  */
35273  unixClose(pFile);
35274  return rc;
35275  }
35276  }
35277  goto open_finished;
35278  }
35279  }
35280 #endif
35281 
35282  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35283 
35284 open_finished:
35285  if( rc!=SQLITE_OK ){
35286  sqlite3_free(p->pUnused);
35287  }
35288  return rc;
35289 }
35290 
35291 
35292 /*
35293 ** Delete the file at zPath. If the dirSync argument is true, fsync()
35294 ** the directory after deleting the file.
35295 */
35296 static int unixDelete(
35297  sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
35298  const char *zPath, /* Name of file to be deleted */
35299  int dirSync /* If true, fsync() directory after deleting file */
35300 ){
35301  int rc = SQLITE_OK;
35302  UNUSED_PARAMETER(NotUsed);
35304  if( osUnlink(zPath)==(-1) ){
35305  if( errno==ENOENT
35306 #if OS_VXWORKS
35307  || osAccess(zPath,0)!=0
35308 #endif
35309  ){
35311  }else{
35312  rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
35313  }
35314  return rc;
35315  }
35316 #ifndef SQLITE_DISABLE_DIRSYNC
35317  if( (dirSync & 1)!=0 ){
35318  int fd;
35319  rc = osOpenDirectory(zPath, &fd);
35320  if( rc==SQLITE_OK ){
35321  if( full_fsync(fd,0,0) ){
35322  rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
35323  }
35324  robust_close(0, fd, __LINE__);
35325  }else{
35326  assert( rc==SQLITE_CANTOPEN );
35327  rc = SQLITE_OK;
35328  }
35329  }
35330 #endif
35331  return rc;
35332 }
35333 
35334 /*
35335 ** Test the existence of or access permissions of file zPath. The
35336 ** test performed depends on the value of flags:
35337 **
35338 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
35339 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
35340 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
35341 **
35342 ** Otherwise return 0.
35343 */
35344 static int unixAccess(
35345  sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
35346  const char *zPath, /* Path of the file to examine */
35347  int flags, /* What do we want to learn about the zPath file? */
35348  int *pResOut /* Write result boolean here */
35349 ){
35350  UNUSED_PARAMETER(NotUsed);
35352  assert( pResOut!=0 );
35353 
35354  /* The spec says there are three possible values for flags. But only
35355  ** two of them are actually used */
35356  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
35357 
35358  if( flags==SQLITE_ACCESS_EXISTS ){
35359  struct stat buf;
35360  *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
35361  }else{
35362  *pResOut = osAccess(zPath, W_OK|R_OK)==0;
35363  }
35364  return SQLITE_OK;
35365 }
35366 
35367 /*
35368 **
35369 */
35370 static int mkFullPathname(
35371  const char *zPath, /* Input path */
35372  char *zOut, /* Output buffer */
35373  int nOut /* Allocated size of buffer zOut */
35374 ){
35375  int nPath = sqlite3Strlen30(zPath);
35376  int iOff = 0;
35377  if( zPath[0]!='/' ){
35378  if( osGetcwd(zOut, nOut-2)==0 ){
35379  return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
35380  }
35381  iOff = sqlite3Strlen30(zOut);
35382  zOut[iOff++] = '/';
35383  }
35384  if( (iOff+nPath+1)>nOut ){
35385  /* SQLite assumes that xFullPathname() nul-terminates the output buffer
35386  ** even if it returns an error. */
35387  zOut[iOff] = '\0';
35388  return SQLITE_CANTOPEN_BKPT;
35389  }
35390  sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
35391  return SQLITE_OK;
35392 }
35393 
35394 /*
35395 ** Turn a relative pathname into a full pathname. The relative path
35396 ** is stored as a nul-terminated string in the buffer pointed to by
35397 ** zPath.
35398 **
35399 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
35400 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
35401 ** this buffer before returning.
35402 */
35403 static int unixFullPathname(
35404  sqlite3_vfs *pVfs, /* Pointer to vfs object */
35405  const char *zPath, /* Possibly relative input path */
35406  int nOut, /* Size of output buffer in bytes */
35407  char *zOut /* Output buffer */
35408 ){
35409 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
35410  return mkFullPathname(zPath, zOut, nOut);
35411 #else
35412  int rc = SQLITE_OK;
35413  int nByte;
35414  int nLink = 1; /* Number of symbolic links followed so far */
35415  const char *zIn = zPath; /* Input path for each iteration of loop */
35416  char *zDel = 0;
35417 
35418  assert( pVfs->mxPathname==MAX_PATHNAME );
35419  UNUSED_PARAMETER(pVfs);
35420 
35421  /* It's odd to simulate an io-error here, but really this is just
35422  ** using the io-error infrastructure to test that SQLite handles this
35423  ** function failing. This function could fail if, for example, the
35424  ** current working directory has been unlinked.
35425  */
35426  SimulateIOError( return SQLITE_ERROR );
35427 
35428  do {
35429 
35430  /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
35431  ** link, or false otherwise. */
35432  int bLink = 0;
35433  struct stat buf;
35434  if( osLstat(zIn, &buf)!=0 ){
35435  if( errno!=ENOENT ){
35436  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
35437  }
35438  }else{
35439  bLink = S_ISLNK(buf.st_mode);
35440  }
35441 
35442  if( bLink ){
35443  if( zDel==0 ){
35444  zDel = sqlite3_malloc(nOut);
35445  if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
35446  }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
35447  rc = SQLITE_CANTOPEN_BKPT;
35448  }
35449 
35450  if( rc==SQLITE_OK ){
35451  nByte = osReadlink(zIn, zDel, nOut-1);
35452  if( nByte<0 ){
35453  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
35454  }else{
35455  if( zDel[0]!='/' ){
35456  int n;
35457  for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
35458  if( nByte+n+1>nOut ){
35459  rc = SQLITE_CANTOPEN_BKPT;
35460  }else{
35461  memmove(&zDel[n], zDel, nByte+1);
35462  memcpy(zDel, zIn, n);
35463  nByte += n;
35464  }
35465  }
35466  zDel[nByte] = '\0';
35467  }
35468  }
35469 
35470  zIn = zDel;
35471  }
35472 
35473  assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
35474  if( rc==SQLITE_OK && zIn!=zOut ){
35475  rc = mkFullPathname(zIn, zOut, nOut);
35476  }
35477  if( bLink==0 ) break;
35478  zIn = zOut;
35479  }while( rc==SQLITE_OK );
35480 
35481  sqlite3_free(zDel);
35482  return rc;
35483 #endif /* HAVE_READLINK && HAVE_LSTAT */
35484 }
35485 
35486 
35487 #ifndef SQLITE_OMIT_LOAD_EXTENSION
35488 /*
35489 ** Interfaces for opening a shared library, finding entry points
35490 ** within the shared library, and closing the shared library.
35491 */
35492 #include <dlfcn.h>
35493 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
35494  UNUSED_PARAMETER(NotUsed);
35495  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
35496 }
35497 
35498 /*
35499 ** SQLite calls this function immediately after a call to unixDlSym() or
35500 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
35501 ** message is available, it is written to zBufOut. If no error message
35502 ** is available, zBufOut is left unmodified and SQLite uses a default
35503 ** error message.
35504 */
35505 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
35506  const char *zErr;
35507  UNUSED_PARAMETER(NotUsed);
35508  unixEnterMutex();
35509  zErr = dlerror();
35510  if( zErr ){
35511  sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
35512  }
35513  unixLeaveMutex();
35514 }
35515 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
35516  /*
35517  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
35518  ** cast into a pointer to a function. And yet the library dlsym() routine
35519  ** returns a void* which is really a pointer to a function. So how do we
35520  ** use dlsym() with -pedantic-errors?
35521  **
35522  ** Variable x below is defined to be a pointer to a function taking
35523  ** parameters void* and const char* and returning a pointer to a function.
35524  ** We initialize x by assigning it a pointer to the dlsym() function.
35525  ** (That assignment requires a cast.) Then we call the function that
35526  ** x points to.
35527  **
35528  ** This work-around is unlikely to work correctly on any system where
35529  ** you really cannot cast a function pointer into void*. But then, on the
35530  ** other hand, dlsym() will not work on such a system either, so we have
35531  ** not really lost anything.
35532  */
35533  void (*(*x)(void*,const char*))(void);
35534  UNUSED_PARAMETER(NotUsed);
35535  x = (void(*(*)(void*,const char*))(void))dlsym;
35536  return (*x)(p, zSym);
35537 }
35538 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
35539  UNUSED_PARAMETER(NotUsed);
35540  dlclose(pHandle);
35541 }
35542 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35543  #define unixDlOpen 0
35544  #define unixDlError 0
35545  #define unixDlSym 0
35546  #define unixDlClose 0
35547 #endif
35548 
35549 /*
35550 ** Write nBuf bytes of random data to the supplied buffer zBuf.
35551 */
35552 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
35553  UNUSED_PARAMETER(NotUsed);
35554  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
35555 
35556  /* We have to initialize zBuf to prevent valgrind from reporting
35557  ** errors. The reports issued by valgrind are incorrect - we would
35558  ** prefer that the randomness be increased by making use of the
35559  ** uninitialized space in zBuf - but valgrind errors tend to worry
35560  ** some users. Rather than argue, it seems easier just to initialize
35561  ** the whole array and silence valgrind, even if that means less randomness
35562  ** in the random seed.
35563  **
35564  ** When testing, initializing zBuf[] to zero is all we do. That means
35565  ** that we always use the same random number sequence. This makes the
35566  ** tests repeatable.
35567  */
35568  memset(zBuf, 0, nBuf);
35569  randomnessPid = osGetpid(0);
35570 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
35571  {
35572  int fd, got;
35573  fd = robust_open("/dev/urandom", O_RDONLY, 0);
35574  if( fd<0 ){
35575  time_t t;
35576  time(&t);
35577  memcpy(zBuf, &t, sizeof(t));
35578  memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
35579  assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
35580  nBuf = sizeof(t) + sizeof(randomnessPid);
35581  }else{
35582  do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
35583  robust_close(0, fd, __LINE__);
35584  }
35585  }
35586 #endif
35587  return nBuf;
35588 }
35589 
35590 
35591 /*
35592 ** Sleep for a little while. Return the amount of time slept.
35593 ** The argument is the number of microseconds we want to sleep.
35594 ** The return value is the number of microseconds of sleep actually
35595 ** requested from the underlying operating system, a number which
35596 ** might be greater than or equal to the argument, but not less
35597 ** than the argument.
35598 */
35599 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
35600 #if OS_VXWORKS
35601  struct timespec sp;
35602 
35603  sp.tv_sec = microseconds / 1000000;
35604  sp.tv_nsec = (microseconds % 1000000) * 1000;
35605  nanosleep(&sp, NULL);
35606  UNUSED_PARAMETER(NotUsed);
35607  return microseconds;
35608 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
35609  usleep(microseconds);
35610  UNUSED_PARAMETER(NotUsed);
35611  return microseconds;
35612 #else
35613  int seconds = (microseconds+999999)/1000000;
35614  sleep(seconds);
35615  UNUSED_PARAMETER(NotUsed);
35616  return seconds*1000000;
35617 #endif
35618 }
35619 
35620 /*
35621 ** The following variable, if set to a non-zero value, is interpreted as
35622 ** the number of seconds since 1970 and is used to set the result of
35623 ** sqlite3OsCurrentTime() during testing.
35624 */
35625 #ifdef SQLITE_TEST
35626 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
35627 #endif
35628 
35629 /*
35630 ** Find the current time (in Universal Coordinated Time). Write into *piNow
35631 ** the current time and date as a Julian Day number times 86_400_000. In
35632 ** other words, write into *piNow the number of milliseconds since the Julian
35633 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35634 ** proleptic Gregorian calendar.
35635 **
35636 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
35637 ** cannot be found.
35638 */
35639 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
35640  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35641  int rc = SQLITE_OK;
35642 #if defined(NO_GETTOD)
35643  time_t t;
35644  time(&t);
35645  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
35646 #elif OS_VXWORKS
35647  struct timespec sNow;
35648  clock_gettime(CLOCK_REALTIME, &sNow);
35649  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
35650 #else
35651  struct timeval sNow;
35652  (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
35653  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
35654 #endif
35655 
35656 #ifdef SQLITE_TEST
35657  if( sqlite3_current_time ){
35658  *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35659  }
35660 #endif
35661  UNUSED_PARAMETER(NotUsed);
35662  return rc;
35663 }
35664 
35665 #ifndef SQLITE_OMIT_DEPRECATED
35666 /*
35667 ** Find the current time (in Universal Coordinated Time). Write the
35668 ** current time and date as a Julian Day number into *prNow and
35669 ** return 0. Return 1 if the time and date cannot be found.
35670 */
35671 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
35672  sqlite3_int64 i = 0;
35673  int rc;
35674  UNUSED_PARAMETER(NotUsed);
35675  rc = unixCurrentTimeInt64(0, &i);
35676  *prNow = i/86400000.0;
35677  return rc;
35678 }
35679 #else
35680 # define unixCurrentTime 0
35681 #endif
35682 
35683 /*
35684 ** The xGetLastError() method is designed to return a better
35685 ** low-level error message when operating-system problems come up
35686 ** during SQLite operation. Only the integer return code is currently
35687 ** used.
35688 */
35689 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
35690  UNUSED_PARAMETER(NotUsed);
35691  UNUSED_PARAMETER(NotUsed2);
35692  UNUSED_PARAMETER(NotUsed3);
35693  return errno;
35694 }
35695 
35696 
35697 /*
35698 ************************ End of sqlite3_vfs methods ***************************
35699 ******************************************************************************/
35700 
35701 /******************************************************************************
35702 ************************** Begin Proxy Locking ********************************
35703 **
35704 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
35705 ** other locking methods on secondary lock files. Proxy locking is a
35706 ** meta-layer over top of the primitive locking implemented above. For
35707 ** this reason, the division that implements of proxy locking is deferred
35708 ** until late in the file (here) after all of the other I/O methods have
35709 ** been defined - so that the primitive locking methods are available
35710 ** as services to help with the implementation of proxy locking.
35711 **
35712 ****
35713 **
35714 ** The default locking schemes in SQLite use byte-range locks on the
35715 ** database file to coordinate safe, concurrent access by multiple readers
35716 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
35717 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
35718 ** as POSIX read & write locks over fixed set of locations (via fsctl),
35719 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
35720 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
35721 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
35722 ** address in the shared range is taken for a SHARED lock, the entire
35723 ** shared range is taken for an EXCLUSIVE lock):
35724 **
35725 ** PENDING_BYTE 0x40000000
35726 ** RESERVED_BYTE 0x40000001
35727 ** SHARED_RANGE 0x40000002 -> 0x40000200
35728 **
35729 ** This works well on the local file system, but shows a nearly 100x
35730 ** slowdown in read performance on AFP because the AFP client disables
35731 ** the read cache when byte-range locks are present. Enabling the read
35732 ** cache exposes a cache coherency problem that is present on all OS X
35733 ** supported network file systems. NFS and AFP both observe the
35734 ** close-to-open semantics for ensuring cache coherency
35735 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
35736 ** address the requirements for concurrent database access by multiple
35737 ** readers and writers
35738 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
35739 **
35740 ** To address the performance and cache coherency issues, proxy file locking
35741 ** changes the way database access is controlled by limiting access to a
35742 ** single host at a time and moving file locks off of the database file
35743 ** and onto a proxy file on the local file system.
35744 **
35745 **
35746 ** Using proxy locks
35747 ** -----------------
35748 **
35749 ** C APIs
35750 **
35751 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
35752 ** <proxy_path> | ":auto:");
35753 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
35754 ** &<proxy_path>);
35755 **
35756 **
35757 ** SQL pragmas
35758 **
35759 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
35760 ** PRAGMA [database.]lock_proxy_file
35761 **
35762 ** Specifying ":auto:" means that if there is a conch file with a matching
35763 ** host ID in it, the proxy path in the conch file will be used, otherwise
35764 ** a proxy path based on the user's temp dir
35765 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
35766 ** actual proxy file name is generated from the name and path of the
35767 ** database file. For example:
35768 **
35769 ** For database path "/Users/me/foo.db"
35770 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
35771 **
35772 ** Once a lock proxy is configured for a database connection, it can not
35773 ** be removed, however it may be switched to a different proxy path via
35774 ** the above APIs (assuming the conch file is not being held by another
35775 ** connection or process).
35776 **
35777 **
35778 ** How proxy locking works
35779 ** -----------------------
35780 **
35781 ** Proxy file locking relies primarily on two new supporting files:
35782 **
35783 ** * conch file to limit access to the database file to a single host
35784 ** at a time
35785 **
35786 ** * proxy file to act as a proxy for the advisory locks normally
35787 ** taken on the database
35788 **
35789 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
35790 ** by taking an sqlite-style shared lock on the conch file, reading the
35791 ** contents and comparing the host's unique host ID (see below) and lock
35792 ** proxy path against the values stored in the conch. The conch file is
35793 ** stored in the same directory as the database file and the file name
35794 ** is patterned after the database file name as ".<databasename>-conch".
35795 ** If the conch file does not exist, or its contents do not match the
35796 ** host ID and/or proxy path, then the lock is escalated to an exclusive
35797 ** lock and the conch file contents is updated with the host ID and proxy
35798 ** path and the lock is downgraded to a shared lock again. If the conch
35799 ** is held by another process (with a shared lock), the exclusive lock
35800 ** will fail and SQLITE_BUSY is returned.
35801 **
35802 ** The proxy file - a single-byte file used for all advisory file locks
35803 ** normally taken on the database file. This allows for safe sharing
35804 ** of the database file for multiple readers and writers on the same
35805 ** host (the conch ensures that they all use the same local lock file).
35806 **
35807 ** Requesting the lock proxy does not immediately take the conch, it is
35808 ** only taken when the first request to lock database file is made.
35809 ** This matches the semantics of the traditional locking behavior, where
35810 ** opening a connection to a database file does not take a lock on it.
35811 ** The shared lock and an open file descriptor are maintained until
35812 ** the connection to the database is closed.
35813 **
35814 ** The proxy file and the lock file are never deleted so they only need
35815 ** to be created the first time they are used.
35816 **
35817 ** Configuration options
35818 ** ---------------------
35819 **
35820 ** SQLITE_PREFER_PROXY_LOCKING
35821 **
35822 ** Database files accessed on non-local file systems are
35823 ** automatically configured for proxy locking, lock files are
35824 ** named automatically using the same logic as
35825 ** PRAGMA lock_proxy_file=":auto:"
35826 **
35827 ** SQLITE_PROXY_DEBUG
35828 **
35829 ** Enables the logging of error messages during host id file
35830 ** retrieval and creation
35831 **
35832 ** LOCKPROXYDIR
35833 **
35834 ** Overrides the default directory used for lock proxy files that
35835 ** are named automatically via the ":auto:" setting
35836 **
35837 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
35838 **
35839 ** Permissions to use when creating a directory for storing the
35840 ** lock proxy files, only used when LOCKPROXYDIR is not set.
35841 **
35842 **
35843 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
35844 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
35845 ** force proxy locking to be used for every database file opened, and 0
35846 ** will force automatic proxy locking to be disabled for all database
35847 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
35848 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
35849 */
35850 
35851 /*
35852 ** Proxy locking is only available on MacOSX
35853 */
35854 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35855 
35856 /*
35857 ** The proxyLockingContext has the path and file structures for the remote
35858 ** and local proxy files in it
35859 */
35860 typedef struct proxyLockingContext proxyLockingContext;
35861 struct proxyLockingContext {
35862  unixFile *conchFile; /* Open conch file */
35863  char *conchFilePath; /* Name of the conch file */
35864  unixFile *lockProxy; /* Open proxy lock file */
35865  char *lockProxyPath; /* Name of the proxy lock file */
35866  char *dbPath; /* Name of the open file */
35867  int conchHeld; /* 1 if the conch is held, -1 if lockless */
35868  int nFails; /* Number of conch taking failures */
35869  void *oldLockingContext; /* Original lockingcontext to restore on close */
35870  sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
35871 };
35872 
35873 /*
35874 ** The proxy lock file path for the database at dbPath is written into lPath,
35875 ** which must point to valid, writable memory large enough for a maxLen length
35876 ** file path.
35877 */
35878 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
35879  int len;
35880  int dbLen;
35881  int i;
35882 
35883 #ifdef LOCKPROXYDIR
35884  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
35885 #else
35886 # ifdef _CS_DARWIN_USER_TEMP_DIR
35887  {
35888  if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
35889  OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
35890  lPath, errno, osGetpid(0)));
35891  return SQLITE_IOERR_LOCK;
35892  }
35893  len = strlcat(lPath, "sqliteplocks", maxLen);
35894  }
35895 # else
35896  len = strlcpy(lPath, "/tmp/", maxLen);
35897 # endif
35898 #endif
35899 
35900  if( lPath[len-1]!='/' ){
35901  len = strlcat(lPath, "/", maxLen);
35902  }
35903 
35904  /* transform the db path to a unique cache name */
35905  dbLen = (int)strlen(dbPath);
35906  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
35907  char c = dbPath[i];
35908  lPath[i+len] = (c=='/')?'_':c;
35909  }
35910  lPath[i+len]='\0';
35911  strlcat(lPath, ":auto:", maxLen);
35912  OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
35913  return SQLITE_OK;
35914 }
35915 
35916 /*
35917  ** Creates the lock file and any missing directories in lockPath
35918  */
35919 static int proxyCreateLockPath(const char *lockPath){
35920  int i, len;
35921  char buf[MAXPATHLEN];
35922  int start = 0;
35923 
35924  assert(lockPath!=NULL);
35925  /* try to create all the intermediate directories */
35926  len = (int)strlen(lockPath);
35927  buf[0] = lockPath[0];
35928  for( i=1; i<len; i++ ){
35929  if( lockPath[i] == '/' && (i - start > 0) ){
35930  /* only mkdir if leaf dir != "." or "/" or ".." */
35931  if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
35932  || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
35933  buf[i]='\0';
35935  int err=errno;
35936  if( err!=EEXIST ) {
35937  OSTRACE(("CREATELOCKPATH FAILED creating %s, "
35938  "'%s' proxy lock path=%s pid=%d\n",
35939  buf, strerror(err), lockPath, osGetpid(0)));
35940  return err;
35941  }
35942  }
35943  }
35944  start=i+1;
35945  }
35946  buf[i] = lockPath[i];
35947  }
35948  OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
35949  return 0;
35950 }
35951 
35952 /*
35953 ** Create a new VFS file descriptor (stored in memory obtained from
35954 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
35955 **
35956 ** The caller is responsible not only for closing the file descriptor
35957 ** but also for freeing the memory associated with the file descriptor.
35958 */
35959 static int proxyCreateUnixFile(
35960  const char *path, /* path for the new unixFile */
35961  unixFile **ppFile, /* unixFile created and returned by ref */
35962  int islockfile /* if non zero missing dirs will be created */
35963 ) {
35964  int fd = -1;
35965  unixFile *pNew;
35966  int rc = SQLITE_OK;
35967  int openFlags = O_RDWR | O_CREAT;
35968  sqlite3_vfs dummyVfs;
35969  int terrno = 0;
35970  UnixUnusedFd *pUnused = NULL;
35971 
35972  /* 1. first try to open/create the file
35973  ** 2. if that fails, and this is a lock file (not-conch), try creating
35974  ** the parent directories and then try again.
35975  ** 3. if that fails, try to open the file read-only
35976  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
35977  */
35978  pUnused = findReusableFd(path, openFlags);
35979  if( pUnused ){
35980  fd = pUnused->fd;
35981  }else{
35982  pUnused = sqlite3_malloc64(sizeof(*pUnused));
35983  if( !pUnused ){
35984  return SQLITE_NOMEM_BKPT;
35985  }
35986  }
35987  if( fd<0 ){
35988  fd = robust_open(path, openFlags, 0);
35989  terrno = errno;
35990  if( fd<0 && errno==ENOENT && islockfile ){
35991  if( proxyCreateLockPath(path) == SQLITE_OK ){
35992  fd = robust_open(path, openFlags, 0);
35993  }
35994  }
35995  }
35996  if( fd<0 ){
35997  openFlags = O_RDONLY;
35998  fd = robust_open(path, openFlags, 0);
35999  terrno = errno;
36000  }
36001  if( fd<0 ){
36002  if( islockfile ){
36003  return SQLITE_BUSY;
36004  }
36005  switch (terrno) {
36006  case EACCES:
36007  return SQLITE_PERM;
36008  case EIO:
36009  return SQLITE_IOERR_LOCK; /* even though it is the conch */
36010  default:
36011  return SQLITE_CANTOPEN_BKPT;
36012  }
36013  }
36014 
36015  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
36016  if( pNew==NULL ){
36017  rc = SQLITE_NOMEM_BKPT;
36018  goto end_create_proxy;
36019  }
36020  memset(pNew, 0, sizeof(unixFile));
36021  pNew->openFlags = openFlags;
36022  memset(&dummyVfs, 0, sizeof(dummyVfs));
36023  dummyVfs.pAppData = (void*)&autolockIoFinder;
36024  dummyVfs.zName = "dummy";
36025  pUnused->fd = fd;
36026  pUnused->flags = openFlags;
36027  pNew->pUnused = pUnused;
36028 
36029  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
36030  if( rc==SQLITE_OK ){
36031  *ppFile = pNew;
36032  return SQLITE_OK;
36033  }
36034 end_create_proxy:
36035  robust_close(pNew, fd, __LINE__);
36036  sqlite3_free(pNew);
36037  sqlite3_free(pUnused);
36038  return rc;
36039 }
36040 
36041 #ifdef SQLITE_TEST
36042 /* simulate multiple hosts by creating unique hostid file paths */
36043 SQLITE_API int sqlite3_hostid_num = 0;
36044 #endif
36045 
36046 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
36047 
36048 #ifdef HAVE_GETHOSTUUID
36049 /* Not always defined in the headers as it ought to be */
36050 extern int gethostuuid(uuid_t id, const struct timespec *wait);
36051 #endif
36052 
36053 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
36054 ** bytes of writable memory.
36055 */
36056 static int proxyGetHostID(unsigned char *pHostID, int *pError){
36057  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
36058  memset(pHostID, 0, PROXY_HOSTIDLEN);
36059 #ifdef HAVE_GETHOSTUUID
36060  {
36061  struct timespec timeout = {1, 0}; /* 1 sec timeout */
36062  if( gethostuuid(pHostID, &timeout) ){
36063  int err = errno;
36064  if( pError ){
36065  *pError = err;
36066  }
36067  return SQLITE_IOERR;
36068  }
36069  }
36070 #else
36071  UNUSED_PARAMETER(pError);
36072 #endif
36073 #ifdef SQLITE_TEST
36074  /* simulate multiple hosts by creating unique hostid file paths */
36075  if( sqlite3_hostid_num != 0){
36076  pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
36077  }
36078 #endif
36079 
36080  return SQLITE_OK;
36081 }
36082 
36083 /* The conch file contains the header, host id and lock file path
36084  */
36085 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
36086 #define PROXY_HEADERLEN 1 /* conch file header length */
36087 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
36088 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
36089 
36090 /*
36091 ** Takes an open conch file, copies the contents to a new path and then moves
36092 ** it back. The newly created file's file descriptor is assigned to the
36093 ** conch file structure and finally the original conch file descriptor is
36094 ** closed. Returns zero if successful.
36095 */
36096 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
36097  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36098  unixFile *conchFile = pCtx->conchFile;
36099  char tPath[MAXPATHLEN];
36100  char buf[PROXY_MAXCONCHLEN];
36101  char *cPath = pCtx->conchFilePath;
36102  size_t readLen = 0;
36103  size_t pathLen = 0;
36104  char errmsg[64] = "";
36105  int fd = -1;
36106  int rc = -1;
36107  UNUSED_PARAMETER(myHostID);
36108 
36109  /* create a new path by replace the trailing '-conch' with '-break' */
36110  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
36111  if( pathLen>MAXPATHLEN || pathLen<6 ||
36112  (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
36113  sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
36114  goto end_breaklock;
36115  }
36116  /* read the conch content */
36117  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
36118  if( readLen<PROXY_PATHINDEX ){
36119  sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
36120  goto end_breaklock;
36121  }
36122  /* write it out to the temporary break file */
36123  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
36124  if( fd<0 ){
36125  sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
36126  goto end_breaklock;
36127  }
36128  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
36129  sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
36130  goto end_breaklock;
36131  }
36132  if( rename(tPath, cPath) ){
36133  sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
36134  goto end_breaklock;
36135  }
36136  rc = 0;
36137  fprintf(stderr, "broke stale lock on %s\n", cPath);
36138  robust_close(pFile, conchFile->h, __LINE__);
36139  conchFile->h = fd;
36140  conchFile->openFlags = O_RDWR | O_CREAT;
36141 
36142 end_breaklock:
36143  if( rc ){
36144  if( fd>=0 ){
36145  osUnlink(tPath);
36146  robust_close(pFile, fd, __LINE__);
36147  }
36148  fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
36149  }
36150  return rc;
36151 }
36152 
36153 /* Take the requested lock on the conch file and break a stale lock if the
36154 ** host id matches.
36155 */
36156 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
36157  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36158  unixFile *conchFile = pCtx->conchFile;
36159  int rc = SQLITE_OK;
36160  int nTries = 0;
36161  struct timespec conchModTime;
36162 
36163  memset(&conchModTime, 0, sizeof(conchModTime));
36164  do {
36165  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36166  nTries ++;
36167  if( rc==SQLITE_BUSY ){
36168  /* If the lock failed (busy):
36169  * 1st try: get the mod time of the conch, wait 0.5s and try again.
36170  * 2nd try: fail if the mod time changed or host id is different, wait
36171  * 10 sec and try again
36172  * 3rd try: break the lock unless the mod time has changed.
36173  */
36174  struct stat buf;
36175  if( osFstat(conchFile->h, &buf) ){
36176  storeLastErrno(pFile, errno);
36177  return SQLITE_IOERR_LOCK;
36178  }
36179 
36180  if( nTries==1 ){
36181  conchModTime = buf.st_mtimespec;
36182  usleep(500000); /* wait 0.5 sec and try the lock again*/
36183  continue;
36184  }
36185 
36186  assert( nTries>1 );
36187  if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
36188  conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
36189  return SQLITE_BUSY;
36190  }
36191 
36192  if( nTries==2 ){
36193  char tBuf[PROXY_MAXCONCHLEN];
36194  int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
36195  if( len<0 ){
36196  storeLastErrno(pFile, errno);
36197  return SQLITE_IOERR_LOCK;
36198  }
36199  if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
36200  /* don't break the lock if the host id doesn't match */
36201  if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
36202  return SQLITE_BUSY;
36203  }
36204  }else{
36205  /* don't break the lock on short read or a version mismatch */
36206  return SQLITE_BUSY;
36207  }
36208  usleep(10000000); /* wait 10 sec and try the lock again */
36209  continue;
36210  }
36211 
36212  assert( nTries==3 );
36213  if( 0==proxyBreakConchLock(pFile, myHostID) ){
36214  rc = SQLITE_OK;
36215  if( lockType==EXCLUSIVE_LOCK ){
36216  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
36217  }
36218  if( !rc ){
36219  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36220  }
36221  }
36222  }
36223  } while( rc==SQLITE_BUSY && nTries<3 );
36224 
36225  return rc;
36226 }
36227 
36228 /* Takes the conch by taking a shared lock and read the contents conch, if
36229 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
36230 ** lockPath means that the lockPath in the conch file will be used if the
36231 ** host IDs match, or a new lock path will be generated automatically
36232 ** and written to the conch file.
36233 */
36234 static int proxyTakeConch(unixFile *pFile){
36235  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36236 
36237  if( pCtx->conchHeld!=0 ){
36238  return SQLITE_OK;
36239  }else{
36240  unixFile *conchFile = pCtx->conchFile;
36241  uuid_t myHostID;
36242  int pError = 0;
36243  char readBuf[PROXY_MAXCONCHLEN];
36244  char lockPath[MAXPATHLEN];
36245  char *tempLockPath = NULL;
36246  int rc = SQLITE_OK;
36247  int createConch = 0;
36248  int hostIdMatch = 0;
36249  int readLen = 0;
36250  int tryOldLockPath = 0;
36251  int forceNewLockPath = 0;
36252 
36253  OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
36254  (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36255  osGetpid(0)));
36256 
36257  rc = proxyGetHostID(myHostID, &pError);
36258  if( (rc&0xff)==SQLITE_IOERR ){
36259  storeLastErrno(pFile, pError);
36260  goto end_takeconch;
36261  }
36262  rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
36263  if( rc!=SQLITE_OK ){
36264  goto end_takeconch;
36265  }
36266  /* read the existing conch file */
36267  readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
36268  if( readLen<0 ){
36269  /* I/O error: lastErrno set by seekAndRead */
36270  storeLastErrno(pFile, conchFile->lastErrno);
36271  rc = SQLITE_IOERR_READ;
36272  goto end_takeconch;
36273  }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
36274  readBuf[0]!=(char)PROXY_CONCHVERSION ){
36275  /* a short read or version format mismatch means we need to create a new
36276  ** conch file.
36277  */
36278  createConch = 1;
36279  }
36280  /* if the host id matches and the lock path already exists in the conch
36281  ** we'll try to use the path there, if we can't open that path, we'll
36282  ** retry with a new auto-generated path
36283  */
36284  do { /* in case we need to try again for an :auto: named lock file */
36285 
36286  if( !createConch && !forceNewLockPath ){
36287  hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
36288  PROXY_HOSTIDLEN);
36289  /* if the conch has data compare the contents */
36290  if( !pCtx->lockProxyPath ){
36291  /* for auto-named local lock file, just check the host ID and we'll
36292  ** use the local lock file path that's already in there
36293  */
36294  if( hostIdMatch ){
36295  size_t pathLen = (readLen - PROXY_PATHINDEX);
36296 
36297  if( pathLen>=MAXPATHLEN ){
36298  pathLen=MAXPATHLEN-1;
36299  }
36300  memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
36301  lockPath[pathLen] = 0;
36302  tempLockPath = lockPath;
36303  tryOldLockPath = 1;
36304  /* create a copy of the lock path if the conch is taken */
36305  goto end_takeconch;
36306  }
36307  }else if( hostIdMatch
36308  && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
36309  readLen-PROXY_PATHINDEX)
36310  ){
36311  /* conch host and lock path match */
36312  goto end_takeconch;
36313  }
36314  }
36315 
36316  /* if the conch isn't writable and doesn't match, we can't take it */
36317  if( (conchFile->openFlags&O_RDWR) == 0 ){
36318  rc = SQLITE_BUSY;
36319  goto end_takeconch;
36320  }
36321 
36322  /* either the conch didn't match or we need to create a new one */
36323  if( !pCtx->lockProxyPath ){
36324  proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
36325  tempLockPath = lockPath;
36326  /* create a copy of the lock path _only_ if the conch is taken */
36327  }
36328 
36329  /* update conch with host and path (this will fail if other process
36330  ** has a shared lock already), if the host id matches, use the big
36331  ** stick.
36332  */
36333  futimes(conchFile->h, NULL);
36334  if( hostIdMatch && !createConch ){
36335  if( conchFile->pInode && conchFile->pInode->nShared>1 ){
36336  /* We are trying for an exclusive lock but another thread in this
36337  ** same process is still holding a shared lock. */
36338  rc = SQLITE_BUSY;
36339  } else {
36340  rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36341  }
36342  }else{
36343  rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36344  }
36345  if( rc==SQLITE_OK ){
36346  char writeBuffer[PROXY_MAXCONCHLEN];
36347  int writeSize = 0;
36348 
36349  writeBuffer[0] = (char)PROXY_CONCHVERSION;
36350  memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
36351  if( pCtx->lockProxyPath!=NULL ){
36352  strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
36353  MAXPATHLEN);
36354  }else{
36355  strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
36356  }
36357  writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
36358  robust_ftruncate(conchFile->h, writeSize);
36359  rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
36360  full_fsync(conchFile->h,0,0);
36361  /* If we created a new conch file (not just updated the contents of a
36362  ** valid conch file), try to match the permissions of the database
36363  */
36364  if( rc==SQLITE_OK && createConch ){
36365  struct stat buf;
36366  int err = osFstat(pFile->h, &buf);
36367  if( err==0 ){
36368  mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
36369  S_IROTH|S_IWOTH);
36370  /* try to match the database file R/W permissions, ignore failure */
36371 #ifndef SQLITE_PROXY_DEBUG
36372  osFchmod(conchFile->h, cmode);
36373 #else
36374  do{
36375  rc = osFchmod(conchFile->h, cmode);
36376  }while( rc==(-1) && errno==EINTR );
36377  if( rc!=0 ){
36378  int code = errno;
36379  fprintf(stderr, "fchmod %o FAILED with %d %s\n",
36380  cmode, code, strerror(code));
36381  } else {
36382  fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
36383  }
36384  }else{
36385  int code = errno;
36386  fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
36387  err, code, strerror(code));
36388 #endif
36389  }
36390  }
36391  }
36392  conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
36393 
36394  end_takeconch:
36395  OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
36396  if( rc==SQLITE_OK && pFile->openFlags ){
36397  int fd;
36398  if( pFile->h>=0 ){
36399  robust_close(pFile, pFile->h, __LINE__);
36400  }
36401  pFile->h = -1;
36402  fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
36403  OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
36404  if( fd>=0 ){
36405  pFile->h = fd;
36406  }else{
36407  rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
36408  during locking */
36409  }
36410  }
36411  if( rc==SQLITE_OK && !pCtx->lockProxy ){
36412  char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
36413  rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
36414  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
36415  /* we couldn't create the proxy lock file with the old lock file path
36416  ** so try again via auto-naming
36417  */
36418  forceNewLockPath = 1;
36419  tryOldLockPath = 0;
36420  continue; /* go back to the do {} while start point, try again */
36421  }
36422  }
36423  if( rc==SQLITE_OK ){
36424  /* Need to make a copy of path if we extracted the value
36425  ** from the conch file or the path was allocated on the stack
36426  */
36427  if( tempLockPath ){
36428  pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
36429  if( !pCtx->lockProxyPath ){
36430  rc = SQLITE_NOMEM_BKPT;
36431  }
36432  }
36433  }
36434  if( rc==SQLITE_OK ){
36435  pCtx->conchHeld = 1;
36436 
36437  if( pCtx->lockProxy->pMethod == &afpIoMethods ){
36438  afpLockingContext *afpCtx;
36439  afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
36440  afpCtx->dbPath = pCtx->lockProxyPath;
36441  }
36442  } else {
36443  conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36444  }
36445  OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
36446  rc==SQLITE_OK?"ok":"failed"));
36447  return rc;
36448  } while (1); /* in case we need to retry the :auto: lock file -
36449  ** we should never get here except via the 'continue' call. */
36450  }
36451 }
36452 
36453 /*
36454 ** If pFile holds a lock on a conch file, then release that lock.
36455 */
36456 static int proxyReleaseConch(unixFile *pFile){
36457  int rc = SQLITE_OK; /* Subroutine return code */
36458  proxyLockingContext *pCtx; /* The locking context for the proxy lock */
36459  unixFile *conchFile; /* Name of the conch file */
36460 
36461  pCtx = (proxyLockingContext *)pFile->lockingContext;
36462  conchFile = pCtx->conchFile;
36463  OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
36464  (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36465  osGetpid(0)));
36466  if( pCtx->conchHeld>0 ){
36467  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36468  }
36469  pCtx->conchHeld = 0;
36470  OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
36471  (rc==SQLITE_OK ? "ok" : "failed")));
36472  return rc;
36473 }
36474 
36475 /*
36476 ** Given the name of a database file, compute the name of its conch file.
36477 ** Store the conch filename in memory obtained from sqlite3_malloc64().
36478 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
36479 ** or SQLITE_NOMEM if unable to obtain memory.
36480 **
36481 ** The caller is responsible for ensuring that the allocated memory
36482 ** space is eventually freed.
36483 **
36484 ** *pConchPath is set to NULL if a memory allocation error occurs.
36485 */
36486 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
36487  int i; /* Loop counter */
36488  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
36489  char *conchPath; /* buffer in which to construct conch name */
36490 
36491  /* Allocate space for the conch filename and initialize the name to
36492  ** the name of the original database file. */
36493  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
36494  if( conchPath==0 ){
36495  return SQLITE_NOMEM_BKPT;
36496  }
36497  memcpy(conchPath, dbPath, len+1);
36498 
36499  /* now insert a "." before the last / character */
36500  for( i=(len-1); i>=0; i-- ){
36501  if( conchPath[i]=='/' ){
36502  i++;
36503  break;
36504  }
36505  }
36506  conchPath[i]='.';
36507  while ( i<len ){
36508  conchPath[i+1]=dbPath[i];
36509  i++;
36510  }
36511 
36512  /* append the "-conch" suffix to the file */
36513  memcpy(&conchPath[i+1], "-conch", 7);
36514  assert( (int)strlen(conchPath) == len+7 );
36515 
36516  return SQLITE_OK;
36517 }
36518 
36519 
36520 /* Takes a fully configured proxy locking-style unix file and switches
36521 ** the local lock file path
36522 */
36523 static int switchLockProxyPath(unixFile *pFile, const char *path) {
36524  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36525  char *oldPath = pCtx->lockProxyPath;
36526  int rc = SQLITE_OK;
36527 
36528  if( pFile->eFileLock!=NO_LOCK ){
36529  return SQLITE_BUSY;
36530  }
36531 
36532  /* nothing to do if the path is NULL, :auto: or matches the existing path */
36533  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
36534  (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
36535  return SQLITE_OK;
36536  }else{
36537  unixFile *lockProxy = pCtx->lockProxy;
36538  pCtx->lockProxy=NULL;
36539  pCtx->conchHeld = 0;
36540  if( lockProxy!=NULL ){
36541  rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
36542  if( rc ) return rc;
36543  sqlite3_free(lockProxy);
36544  }
36545  sqlite3_free(oldPath);
36546  pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
36547  }
36548 
36549  return rc;
36550 }
36551 
36552 /*
36553 ** pFile is a file that has been opened by a prior xOpen call. dbPath
36554 ** is a string buffer at least MAXPATHLEN+1 characters in size.
36555 **
36556 ** This routine find the filename associated with pFile and writes it
36557 ** int dbPath.
36558 */
36559 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
36560 #if defined(__APPLE__)
36561  if( pFile->pMethod == &afpIoMethods ){
36562  /* afp style keeps a reference to the db path in the filePath field
36563  ** of the struct */
36564  assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36565  strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
36566  MAXPATHLEN);
36567  } else
36568 #endif
36569  if( pFile->pMethod == &dotlockIoMethods ){
36570  /* dot lock style uses the locking context to store the dot lock
36571  ** file path */
36572  int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
36573  memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
36574  }else{
36575  /* all other styles use the locking context to store the db file path */
36576  assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36577  strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
36578  }
36579  return SQLITE_OK;
36580 }
36581 
36582 /*
36583 ** Takes an already filled in unix file and alters it so all file locking
36584 ** will be performed on the local proxy lock file. The following fields
36585 ** are preserved in the locking context so that they can be restored and
36586 ** the unix structure properly cleaned up at close time:
36587 ** ->lockingContext
36588 ** ->pMethod
36589 */
36590 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
36591  proxyLockingContext *pCtx;
36592  char dbPath[MAXPATHLEN+1]; /* Name of the database file */
36593  char *lockPath=NULL;
36594  int rc = SQLITE_OK;
36595 
36596  if( pFile->eFileLock!=NO_LOCK ){
36597  return SQLITE_BUSY;
36598  }
36599  proxyGetDbPathForUnixFile(pFile, dbPath);
36600  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
36601  lockPath=NULL;
36602  }else{
36603  lockPath=(char *)path;
36604  }
36605 
36606  OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
36607  (lockPath ? lockPath : ":auto:"), osGetpid(0)));
36608 
36609  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
36610  if( pCtx==0 ){
36611  return SQLITE_NOMEM_BKPT;
36612  }
36613  memset(pCtx, 0, sizeof(*pCtx));
36614 
36615  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
36616  if( rc==SQLITE_OK ){
36617  rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
36618  if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
36619  /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
36620  ** (c) the file system is read-only, then enable no-locking access.
36621  ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
36622  ** that openFlags will have only one of O_RDONLY or O_RDWR.
36623  */
36624  struct statfs fsInfo;
36625  struct stat conchInfo;
36626  int goLockless = 0;
36627 
36628  if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
36629  int err = errno;
36630  if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
36631  goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
36632  }
36633  }
36634  if( goLockless ){
36635  pCtx->conchHeld = -1; /* read only FS/ lockless */
36636  rc = SQLITE_OK;
36637  }
36638  }
36639  }
36640  if( rc==SQLITE_OK && lockPath ){
36641  pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
36642  }
36643 
36644  if( rc==SQLITE_OK ){
36645  pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
36646  if( pCtx->dbPath==NULL ){
36647  rc = SQLITE_NOMEM_BKPT;
36648  }
36649  }
36650  if( rc==SQLITE_OK ){
36651  /* all memory is allocated, proxys are created and assigned,
36652  ** switch the locking context and pMethod then return.
36653  */
36654  pCtx->oldLockingContext = pFile->lockingContext;
36655  pFile->lockingContext = pCtx;
36656  pCtx->pOldMethod = pFile->pMethod;
36657  pFile->pMethod = &proxyIoMethods;
36658  }else{
36659  if( pCtx->conchFile ){
36660  pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
36661  sqlite3_free(pCtx->conchFile);
36662  }
36663  sqlite3DbFree(0, pCtx->lockProxyPath);
36664  sqlite3_free(pCtx->conchFilePath);
36665  sqlite3_free(pCtx);
36666  }
36667  OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
36668  (rc==SQLITE_OK ? "ok" : "failed")));
36669  return rc;
36670 }
36671 
36672 
36673 /*
36674 ** This routine handles sqlite3_file_control() calls that are specific
36675 ** to proxy locking.
36676 */
36677 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
36678  switch( op ){
36680  unixFile *pFile = (unixFile*)id;
36681  if( pFile->pMethod == &proxyIoMethods ){
36682  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36683  proxyTakeConch(pFile);
36684  if( pCtx->lockProxyPath ){
36685  *(const char **)pArg = pCtx->lockProxyPath;
36686  }else{
36687  *(const char **)pArg = ":auto: (not held)";
36688  }
36689  } else {
36690  *(const char **)pArg = NULL;
36691  }
36692  return SQLITE_OK;
36693  }
36695  unixFile *pFile = (unixFile*)id;
36696  int rc = SQLITE_OK;
36697  int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
36698  if( pArg==NULL || (const char *)pArg==0 ){
36699  if( isProxyStyle ){
36700  /* turn off proxy locking - not supported. If support is added for
36701  ** switching proxy locking mode off then it will need to fail if
36702  ** the journal mode is WAL mode.
36703  */
36704  rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
36705  }else{
36706  /* turn off proxy locking - already off - NOOP */
36707  rc = SQLITE_OK;
36708  }
36709  }else{
36710  const char *proxyPath = (const char *)pArg;
36711  if( isProxyStyle ){
36712  proxyLockingContext *pCtx =
36713  (proxyLockingContext*)pFile->lockingContext;
36714  if( !strcmp(pArg, ":auto:")
36715  || (pCtx->lockProxyPath &&
36716  !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
36717  ){
36718  rc = SQLITE_OK;
36719  }else{
36720  rc = switchLockProxyPath(pFile, proxyPath);
36721  }
36722  }else{
36723  /* turn on proxy file locking */
36724  rc = proxyTransformUnixFile(pFile, proxyPath);
36725  }
36726  }
36727  return rc;
36728  }
36729  default: {
36730  assert( 0 ); /* The call assures that only valid opcodes are sent */
36731  }
36732  }
36733  /*NOTREACHED*/
36734  return SQLITE_ERROR;
36735 }
36736 
36737 /*
36738 ** Within this division (the proxying locking implementation) the procedures
36739 ** above this point are all utilities. The lock-related methods of the
36740 ** proxy-locking sqlite3_io_method object follow.
36741 */
36742 
36743 
36744 /*
36745 ** This routine checks if there is a RESERVED lock held on the specified
36746 ** file by this or any other process. If such a lock is held, set *pResOut
36747 ** to a non-zero value otherwise *pResOut is set to zero. The return value
36748 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
36749 */
36750 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
36751  unixFile *pFile = (unixFile*)id;
36752  int rc = proxyTakeConch(pFile);
36753  if( rc==SQLITE_OK ){
36754  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36755  if( pCtx->conchHeld>0 ){
36756  unixFile *proxy = pCtx->lockProxy;
36757  return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
36758  }else{ /* conchHeld < 0 is lockless */
36759  pResOut=0;
36760  }
36761  }
36762  return rc;
36763 }
36764 
36765 /*
36766 ** Lock the file with the lock specified by parameter eFileLock - one
36767 ** of the following:
36768 **
36769 ** (1) SHARED_LOCK
36770 ** (2) RESERVED_LOCK
36771 ** (3) PENDING_LOCK
36772 ** (4) EXCLUSIVE_LOCK
36773 **
36774 ** Sometimes when requesting one lock state, additional lock states
36775 ** are inserted in between. The locking might fail on one of the later
36776 ** transitions leaving the lock state different from what it started but
36777 ** still short of its goal. The following chart shows the allowed
36778 ** transitions and the inserted intermediate states:
36779 **
36780 ** UNLOCKED -> SHARED
36781 ** SHARED -> RESERVED
36782 ** SHARED -> (PENDING) -> EXCLUSIVE
36783 ** RESERVED -> (PENDING) -> EXCLUSIVE
36784 ** PENDING -> EXCLUSIVE
36785 **
36786 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
36787 ** routine to lower a locking level.
36788 */
36789 static int proxyLock(sqlite3_file *id, int eFileLock) {
36790  unixFile *pFile = (unixFile*)id;
36791  int rc = proxyTakeConch(pFile);
36792  if( rc==SQLITE_OK ){
36793  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36794  if( pCtx->conchHeld>0 ){
36795  unixFile *proxy = pCtx->lockProxy;
36796  rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
36797  pFile->eFileLock = proxy->eFileLock;
36798  }else{
36799  /* conchHeld < 0 is lockless */
36800  }
36801  }
36802  return rc;
36803 }
36804 
36805 
36806 /*
36807 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
36808 ** must be either NO_LOCK or SHARED_LOCK.
36809 **
36810 ** If the locking level of the file descriptor is already at or below
36811 ** the requested locking level, this routine is a no-op.
36812 */
36813 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
36814  unixFile *pFile = (unixFile*)id;
36815  int rc = proxyTakeConch(pFile);
36816  if( rc==SQLITE_OK ){
36817  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36818  if( pCtx->conchHeld>0 ){
36819  unixFile *proxy = pCtx->lockProxy;
36820  rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
36821  pFile->eFileLock = proxy->eFileLock;
36822  }else{
36823  /* conchHeld < 0 is lockless */
36824  }
36825  }
36826  return rc;
36827 }
36828 
36829 /*
36830 ** Close a file that uses proxy locks.
36831 */
36832 static int proxyClose(sqlite3_file *id) {
36833  if( ALWAYS(id) ){
36834  unixFile *pFile = (unixFile*)id;
36835  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36836  unixFile *lockProxy = pCtx->lockProxy;
36837  unixFile *conchFile = pCtx->conchFile;
36838  int rc = SQLITE_OK;
36839 
36840  if( lockProxy ){
36841  rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
36842  if( rc ) return rc;
36843  rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
36844  if( rc ) return rc;
36845  sqlite3_free(lockProxy);
36846  pCtx->lockProxy = 0;
36847  }
36848  if( conchFile ){
36849  if( pCtx->conchHeld ){
36850  rc = proxyReleaseConch(pFile);
36851  if( rc ) return rc;
36852  }
36853  rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
36854  if( rc ) return rc;
36855  sqlite3_free(conchFile);
36856  }
36857  sqlite3DbFree(0, pCtx->lockProxyPath);
36858  sqlite3_free(pCtx->conchFilePath);
36859  sqlite3DbFree(0, pCtx->dbPath);
36860  /* restore the original locking context and pMethod then close it */
36861  pFile->lockingContext = pCtx->oldLockingContext;
36862  pFile->pMethod = pCtx->pOldMethod;
36863  sqlite3_free(pCtx);
36864  return pFile->pMethod->xClose(id);
36865  }
36866  return SQLITE_OK;
36867 }
36868 
36869 
36870 
36871 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
36872 /*
36873 ** The proxy locking style is intended for use with AFP filesystems.
36874 ** And since AFP is only supported on MacOSX, the proxy locking is also
36875 ** restricted to MacOSX.
36876 **
36877 **
36878 ******************* End of the proxy lock implementation **********************
36879 ******************************************************************************/
36880 
36881 /*
36882 ** Initialize the operating system interface.
36883 **
36884 ** This routine registers all VFS implementations for unix-like operating
36885 ** systems. This routine, and the sqlite3_os_end() routine that follows,
36886 ** should be the only routines in this file that are visible from other
36887 ** files.
36888 **
36889 ** This routine is called once during SQLite initialization and by a
36890 ** single thread. The memory allocation and mutex subsystems have not
36891 ** necessarily been initialized when this routine is called, and so they
36892 ** should not be used.
36893 */
36895  /*
36896  ** The following macro defines an initializer for an sqlite3_vfs object.
36897  ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
36898  ** to the "finder" function. (pAppData is a pointer to a pointer because
36899  ** silly C90 rules prohibit a void* from being cast to a function pointer
36900  ** and so we have to go through the intermediate pointer to avoid problems
36901  ** when compiling with -pedantic-errors on GCC.)
36902  **
36903  ** The FINDER parameter to this macro is the name of the pointer to the
36904  ** finder-function. The finder-function returns a pointer to the
36905  ** sqlite_io_methods object that implements the desired locking
36906  ** behaviors. See the division above that contains the IOMETHODS
36907  ** macro for addition information on finder-functions.
36908  **
36909  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
36910  ** object. But the "autolockIoFinder" available on MacOSX does a little
36911  ** more than that; it looks at the filesystem type that hosts the
36912  ** database file and tries to choose an locking method appropriate for
36913  ** that filesystem time.
36914  */
36915  #define UNIXVFS(VFSNAME, FINDER) { \
36916  3, /* iVersion */ \
36917  sizeof(unixFile), /* szOsFile */ \
36918  MAX_PATHNAME, /* mxPathname */ \
36919  0, /* pNext */ \
36920  VFSNAME, /* zName */ \
36921  (void*)&FINDER, /* pAppData */ \
36922  unixOpen, /* xOpen */ \
36923  unixDelete, /* xDelete */ \
36924  unixAccess, /* xAccess */ \
36925  unixFullPathname, /* xFullPathname */ \
36926  unixDlOpen, /* xDlOpen */ \
36927  unixDlError, /* xDlError */ \
36928  unixDlSym, /* xDlSym */ \
36929  unixDlClose, /* xDlClose */ \
36930  unixRandomness, /* xRandomness */ \
36931  unixSleep, /* xSleep */ \
36932  unixCurrentTime, /* xCurrentTime */ \
36933  unixGetLastError, /* xGetLastError */ \
36934  unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
36935  unixSetSystemCall, /* xSetSystemCall */ \
36936  unixGetSystemCall, /* xGetSystemCall */ \
36937  unixNextSystemCall, /* xNextSystemCall */ \
36938  }
36939 
36940  /*
36941  ** All default VFSes for unix are contained in the following array.
36942  **
36943  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
36944  ** by the SQLite core when the VFS is registered. So the following
36945  ** array cannot be const.
36946  */
36947  static sqlite3_vfs aVfs[] = {
36948 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36949  UNIXVFS("unix", autolockIoFinder ),
36950 #elif OS_VXWORKS
36951  UNIXVFS("unix", vxworksIoFinder ),
36952 #else
36953  UNIXVFS("unix", posixIoFinder ),
36954 #endif
36955  UNIXVFS("unix-none", nolockIoFinder ),
36956  UNIXVFS("unix-dotfile", dotlockIoFinder ),
36957  UNIXVFS("unix-excl", posixIoFinder ),
36958 #if OS_VXWORKS
36959  UNIXVFS("unix-namedsem", semIoFinder ),
36960 #endif
36961 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
36962  UNIXVFS("unix-posix", posixIoFinder ),
36963 #endif
36964 #if SQLITE_ENABLE_LOCKING_STYLE
36965  UNIXVFS("unix-flock", flockIoFinder ),
36966 #endif
36967 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36968  UNIXVFS("unix-afp", afpIoFinder ),
36969  UNIXVFS("unix-nfs", nfsIoFinder ),
36970  UNIXVFS("unix-proxy", proxyIoFinder ),
36971 #endif
36972  };
36973  unsigned int i; /* Loop counter */
36974 
36975  /* Double-check that the aSyscall[] array has been constructed
36976  ** correctly. See ticket [bb3a86e890c8e96ab] */
36977  assert( ArraySize(aSyscall)==28 );
36978 
36979  /* Register all VFSes defined in the aVfs[] array */
36980  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
36981  sqlite3_vfs_register(&aVfs[i], i==0);
36982  }
36983  return SQLITE_OK;
36984 }
36985 
36986 /*
36987 ** Shutdown the operating system interface.
36988 **
36989 ** Some operating systems might need to do some cleanup in this routine,
36990 ** to release dynamically allocated objects. But not on unix.
36991 ** This routine is a no-op for unix.
36992 */
36994  return SQLITE_OK;
36995 }
36996 
36997 #endif /* SQLITE_OS_UNIX */
36998 
36999 /************** End of os_unix.c *********************************************/
37000 /************** Begin file os_win.c ******************************************/
37001 /*
37002 ** 2004 May 22
37003 **
37004 ** The author disclaims copyright to this source code. In place of
37005 ** a legal notice, here is a blessing:
37006 **
37007 ** May you do good and not evil.
37008 ** May you find forgiveness for yourself and forgive others.
37009 ** May you share freely, never taking more than you give.
37010 **
37011 ******************************************************************************
37012 **
37013 ** This file contains code that is specific to Windows.
37014 */
37015 /* #include "sqliteInt.h" */
37016 #if SQLITE_OS_WIN /* This file is used for Windows only */
37017 
37018 /*
37019 ** Include code that is common to all os_*.c files
37020 */
37021 /************** Include os_common.h in the middle of os_win.c ****************/
37022 /************** Begin file os_common.h ***************************************/
37023 /*
37024 ** 2004 May 22
37025 **
37026 ** The author disclaims copyright to this source code. In place of
37027 ** a legal notice, here is a blessing:
37028 **
37029 ** May you do good and not evil.
37030 ** May you find forgiveness for yourself and forgive others.
37031 ** May you share freely, never taking more than you give.
37032 **
37033 ******************************************************************************
37034 **
37035 ** This file contains macros and a little bit of code that is common to
37036 ** all of the platform-specific files (os_*.c) and is #included into those
37037 ** files.
37038 **
37039 ** This file should be #included by the os_*.c files only. It is not a
37040 ** general purpose header file.
37041 */
37042 #ifndef _OS_COMMON_H_
37043 #define _OS_COMMON_H_
37044 
37045 /*
37046 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
37047 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
37048 ** switch. The following code should catch this problem at compile-time.
37049 */
37050 #ifdef MEMORY_DEBUG
37051 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
37052 #endif
37053 
37054 /*
37055 ** Macros for performance tracing. Normally turned off. Only works
37056 ** on i486 hardware.
37057 */
37058 #ifdef SQLITE_PERFORMANCE_TRACE
37059 
37060 /*
37061 ** hwtime.h contains inline assembler code for implementing
37062 ** high-performance timing routines.
37063 */
37064 /************** Include hwtime.h in the middle of os_common.h ****************/
37065 /************** Begin file hwtime.h ******************************************/
37066 /*
37067 ** 2008 May 27
37068 **
37069 ** The author disclaims copyright to this source code. In place of
37070 ** a legal notice, here is a blessing:
37071 **
37072 ** May you do good and not evil.
37073 ** May you find forgiveness for yourself and forgive others.
37074 ** May you share freely, never taking more than you give.
37075 **
37076 ******************************************************************************
37077 **
37078 ** This file contains inline asm code for retrieving "high-performance"
37079 ** counters for x86 class CPUs.
37080 */
37081 #ifndef SQLITE_HWTIME_H
37082 #define SQLITE_HWTIME_H
37083 
37084 /*
37085 ** The following routine only works on pentium-class (or newer) processors.
37086 ** It uses the RDTSC opcode to read the cycle count value out of the
37087 ** processor and returns that value. This can be used for high-res
37088 ** profiling.
37089 */
37090 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
37091  (defined(i386) || defined(__i386__) || defined(_M_IX86))
37092 
37093  #if defined(__GNUC__)
37094 
37095  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37096  unsigned int lo, hi;
37097  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
37098  return (sqlite_uint64)hi << 32 | lo;
37099  }
37100 
37101  #elif defined(_MSC_VER)
37102 
37103  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
37104  __asm {
37105  rdtsc
37106  ret ; return value at EDX:EAX
37107  }
37108  }
37109 
37110  #endif
37111 
37112 #elif (defined(__GNUC__) && defined(__x86_64__))
37113 
37114  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37115  unsigned long val;
37116  __asm__ __volatile__ ("rdtsc" : "=A" (val));
37117  return val;
37118  }
37119 
37120 #elif (defined(__GNUC__) && defined(__ppc__))
37121 
37122  __inline__ sqlite_uint64 sqlite3Hwtime(void){
37123  unsigned long long retval;
37124  unsigned long junk;
37125  __asm__ __volatile__ ("\n\
37126  1: mftbu %1\n\
37127  mftb %L0\n\
37128  mftbu %0\n\
37129  cmpw %0,%1\n\
37130  bne 1b"
37131  : "=r" (retval), "=r" (junk));
37132  return retval;
37133  }
37134 
37135 #else
37136 
37137  #error Need implementation of sqlite3Hwtime() for your platform.
37138 
37139  /*
37140  ** To compile without implementing sqlite3Hwtime() for your platform,
37141  ** you can remove the above #error and use the following
37142  ** stub function. You will lose timing support for many
37143  ** of the debugging and testing utilities, but it should at
37144  ** least compile and run.
37145  */
37146 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
37147 
37148 #endif
37149 
37150 #endif /* !defined(SQLITE_HWTIME_H) */
37151 
37152 /************** End of hwtime.h **********************************************/
37153 /************** Continuing where we left off in os_common.h ******************/
37154 
37155 static sqlite_uint64 g_start;
37156 static sqlite_uint64 g_elapsed;
37157 #define TIMER_START g_start=sqlite3Hwtime()
37158 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
37159 #define TIMER_ELAPSED g_elapsed
37160 #else
37161 #define TIMER_START
37162 #define TIMER_END
37163 #define TIMER_ELAPSED ((sqlite_uint64)0)
37164 #endif
37165 
37166 /*
37167 ** If we compile with the SQLITE_TEST macro set, then the following block
37168 ** of code will give us the ability to simulate a disk I/O error. This
37169 ** is used for testing the I/O recovery logic.
37170 */
37171 #if defined(SQLITE_TEST)
37172 SQLITE_API extern int sqlite3_io_error_hit;
37173 SQLITE_API extern int sqlite3_io_error_hardhit;
37174 SQLITE_API extern int sqlite3_io_error_pending;
37175 SQLITE_API extern int sqlite3_io_error_persist;
37176 SQLITE_API extern int sqlite3_io_error_benign;
37177 SQLITE_API extern int sqlite3_diskfull_pending;
37178 SQLITE_API extern int sqlite3_diskfull;
37179 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
37180 #define SimulateIOError(CODE) \
37181  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
37182  || sqlite3_io_error_pending-- == 1 ) \
37183  { local_ioerr(); CODE; }
37184 static void local_ioerr(){
37185  IOTRACE(("IOERR\n"));
37186  sqlite3_io_error_hit++;
37187  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
37188 }
37189 #define SimulateDiskfullError(CODE) \
37190  if( sqlite3_diskfull_pending ){ \
37191  if( sqlite3_diskfull_pending == 1 ){ \
37192  local_ioerr(); \
37193  sqlite3_diskfull = 1; \
37194  sqlite3_io_error_hit = 1; \
37195  CODE; \
37196  }else{ \
37197  sqlite3_diskfull_pending--; \
37198  } \
37199  }
37200 #else
37201 #define SimulateIOErrorBenign(X)
37202 #define SimulateIOError(A)
37203 #define SimulateDiskfullError(A)
37204 #endif /* defined(SQLITE_TEST) */
37205 
37206 /*
37207 ** When testing, keep a count of the number of open files.
37208 */
37209 #if defined(SQLITE_TEST)
37210 SQLITE_API extern int sqlite3_open_file_count;
37211 #define OpenCounter(X) sqlite3_open_file_count+=(X)
37212 #else
37213 #define OpenCounter(X)
37214 #endif /* defined(SQLITE_TEST) */
37215 
37216 #endif /* !defined(_OS_COMMON_H_) */
37217 
37218 /************** End of os_common.h *******************************************/
37219 /************** Continuing where we left off in os_win.c *********************/
37220 
37221 /*
37222 ** Include the header file for the Windows VFS.
37223 */
37224 /* #include "os_win.h" */
37225 
37226 /*
37227 ** Compiling and using WAL mode requires several APIs that are only
37228 ** available in Windows platforms based on the NT kernel.
37229 */
37230 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
37231 # error "WAL mode requires support from the Windows NT kernel, compile\
37232  with SQLITE_OMIT_WAL."
37233 #endif
37234 
37235 #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
37236 # error "Memory mapped files require support from the Windows NT kernel,\
37237  compile with SQLITE_MAX_MMAP_SIZE=0."
37238 #endif
37239 
37240 /*
37241 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
37242 ** based on the sub-platform)?
37243 */
37244 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
37245 # define SQLITE_WIN32_HAS_ANSI
37246 #endif
37247 
37248 /*
37249 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
37250 ** based on the sub-platform)?
37251 */
37252 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
37253  !defined(SQLITE_WIN32_NO_WIDE)
37254 # define SQLITE_WIN32_HAS_WIDE
37255 #endif
37256 
37257 /*
37258 ** Make sure at least one set of Win32 APIs is available.
37259 */
37260 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
37261 # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
37262  must be defined."
37263 #endif
37264 
37265 /*
37266 ** Define the required Windows SDK version constants if they are not
37267 ** already available.
37268 */
37269 #ifndef NTDDI_WIN8
37270 # define NTDDI_WIN8 0x06020000
37271 #endif
37272 
37273 #ifndef NTDDI_WINBLUE
37274 # define NTDDI_WINBLUE 0x06030000
37275 #endif
37276 
37277 #ifndef NTDDI_WINTHRESHOLD
37278 # define NTDDI_WINTHRESHOLD 0x06040000
37279 #endif
37280 
37281 /*
37282 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
37283 ** target system. GetVersionEx was first deprecated in Win8.1.
37284 */
37285 #ifndef SQLITE_WIN32_GETVERSIONEX
37286 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
37287 # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
37288 # else
37289 # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
37290 # endif
37291 #endif
37292 
37293 /*
37294 ** Check to see if the CreateFileMappingA function is supported on the
37295 ** target system. It is unavailable when using "mincore.lib" on Win10.
37296 ** When compiling for Windows 10, always assume "mincore.lib" is in use.
37297 */
37298 #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
37299 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
37300 # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
37301 # else
37302 # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
37303 # endif
37304 #endif
37305 
37306 /*
37307 ** This constant should already be defined (in the "WinDef.h" SDK file).
37308 */
37309 #ifndef MAX_PATH
37310 # define MAX_PATH (260)
37311 #endif
37312 
37313 /*
37314 ** Maximum pathname length (in chars) for Win32. This should normally be
37315 ** MAX_PATH.
37316 */
37317 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
37318 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
37319 #endif
37320 
37321 /*
37322 ** This constant should already be defined (in the "WinNT.h" SDK file).
37323 */
37324 #ifndef UNICODE_STRING_MAX_CHARS
37325 # define UNICODE_STRING_MAX_CHARS (32767)
37326 #endif
37327 
37328 /*
37329 ** Maximum pathname length (in chars) for WinNT. This should normally be
37330 ** UNICODE_STRING_MAX_CHARS.
37331 */
37332 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
37333 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
37334 #endif
37335 
37336 /*
37337 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
37338 ** characters, so we allocate 4 bytes per character assuming worst-case of
37339 ** 4-bytes-per-character for UTF8.
37340 */
37341 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
37342 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
37343 #endif
37344 
37345 /*
37346 ** Maximum pathname length (in bytes) for WinNT. This should normally be
37347 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
37348 */
37349 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
37350 # define SQLITE_WINNT_MAX_PATH_BYTES \
37351  (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
37352 #endif
37353 
37354 /*
37355 ** Maximum error message length (in chars) for WinRT.
37356 */
37357 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
37358 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
37359 #endif
37360 
37361 /*
37362 ** Returns non-zero if the character should be treated as a directory
37363 ** separator.
37364 */
37365 #ifndef winIsDirSep
37366 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
37367 #endif
37368 
37369 /*
37370 ** This macro is used when a local variable is set to a value that is
37371 ** [sometimes] not used by the code (e.g. via conditional compilation).
37372 */
37373 #ifndef UNUSED_VARIABLE_VALUE
37374 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
37375 #endif
37376 
37377 /*
37378 ** Returns the character that should be used as the directory separator.
37379 */
37380 #ifndef winGetDirSep
37381 # define winGetDirSep() '\\'
37382 #endif
37383 
37384 /*
37385 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
37386 ** mode or memory mapped files (e.g. these APIs are available in the Windows
37387 ** CE SDK; however, they are not present in the header file)?
37388 */
37389 #if SQLITE_WIN32_FILEMAPPING_API && \
37390  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37391 /*
37392 ** Two of the file mapping APIs are different under WinRT. Figure out which
37393 ** set we need.
37394 */
37395 #if SQLITE_OS_WINRT
37396 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
37397  LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
37398 
37399 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
37400 #else
37401 #if defined(SQLITE_WIN32_HAS_ANSI)
37402 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
37403  DWORD, DWORD, DWORD, LPCSTR);
37404 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
37405 
37406 #if defined(SQLITE_WIN32_HAS_WIDE)
37407 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
37408  DWORD, DWORD, DWORD, LPCWSTR);
37409 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
37410 
37411 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
37412 #endif /* SQLITE_OS_WINRT */
37413 
37414 /*
37415 ** These file mapping APIs are common to both Win32 and WinRT.
37416 */
37417 
37418 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
37419 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
37420 #endif /* SQLITE_WIN32_FILEMAPPING_API */
37421 
37422 /*
37423 ** Some Microsoft compilers lack this definition.
37424 */
37425 #ifndef INVALID_FILE_ATTRIBUTES
37426 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
37427 #endif
37428 
37429 #ifndef FILE_FLAG_MASK
37430 # define FILE_FLAG_MASK (0xFF3C0000)
37431 #endif
37432 
37433 #ifndef FILE_ATTRIBUTE_MASK
37434 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
37435 #endif
37436 
37437 #ifndef SQLITE_OMIT_WAL
37438 /* Forward references to structures used for WAL */
37439 typedef struct winShm winShm; /* A connection to shared-memory */
37440 typedef struct winShmNode winShmNode; /* A region of shared-memory */
37441 #endif
37442 
37443 /*
37444 ** WinCE lacks native support for file locking so we have to fake it
37445 ** with some code of our own.
37446 */
37447 #if SQLITE_OS_WINCE
37448 typedef struct winceLock {
37449  int nReaders; /* Number of reader locks obtained */
37450  BOOL bPending; /* Indicates a pending lock has been obtained */
37451  BOOL bReserved; /* Indicates a reserved lock has been obtained */
37452  BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
37453 } winceLock;
37454 #endif
37455 
37456 /*
37457 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
37458 ** portability layer.
37459 */
37460 typedef struct winFile winFile;
37461 struct winFile {
37462  const sqlite3_io_methods *pMethod; /*** Must be first ***/
37463  sqlite3_vfs *pVfs; /* The VFS used to open this file */
37464  HANDLE h; /* Handle for accessing the file */
37465  u8 locktype; /* Type of lock currently held on this file */
37466  short sharedLockByte; /* Randomly chosen byte used as a shared lock */
37467  u8 ctrlFlags; /* Flags. See WINFILE_* below */
37468  DWORD lastErrno; /* The Windows errno from the last I/O error */
37469 #ifndef SQLITE_OMIT_WAL
37470  winShm *pShm; /* Instance of shared memory on this file */
37471 #endif
37472  const char *zPath; /* Full pathname of this file */
37473  int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
37474 #if SQLITE_OS_WINCE
37475  LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
37476  HANDLE hMutex; /* Mutex used to control access to shared lock */
37477  HANDLE hShared; /* Shared memory segment used for locking */
37478  winceLock local; /* Locks obtained by this instance of winFile */
37479  winceLock *shared; /* Global shared lock memory for the file */
37480 #endif
37481 #if SQLITE_MAX_MMAP_SIZE>0
37482  int nFetchOut; /* Number of outstanding xFetch references */
37483  HANDLE hMap; /* Handle for accessing memory mapping */
37484  void *pMapRegion; /* Area memory mapped */
37485  sqlite3_int64 mmapSize; /* Usable size of mapped region */
37486  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
37487  sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
37488 #endif
37489 };
37490 
37491 /*
37492 ** The winVfsAppData structure is used for the pAppData member for all of the
37493 ** Win32 VFS variants.
37494 */
37495 typedef struct winVfsAppData winVfsAppData;
37496 struct winVfsAppData {
37497  const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
37498  void *pAppData; /* The extra pAppData, if any. */
37499  BOOL bNoLock; /* Non-zero if locking is disabled. */
37500 };
37501 
37502 /*
37503 ** Allowed values for winFile.ctrlFlags
37504 */
37505 #define WINFILE_RDONLY 0x02 /* Connection is read only */
37506 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
37507 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
37508 
37509 /*
37510  * The size of the buffer used by sqlite3_win32_write_debug().
37511  */
37512 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
37513 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
37514 #endif
37515 
37516 /*
37517  * The value used with sqlite3_win32_set_directory() to specify that
37518  * the data directory should be changed.
37519  */
37520 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
37521 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
37522 #endif
37523 
37524 /*
37525  * The value used with sqlite3_win32_set_directory() to specify that
37526  * the temporary directory should be changed.
37527  */
37528 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
37529 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
37530 #endif
37531 
37532 /*
37533  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
37534  * various Win32 API heap functions instead of our own.
37535  */
37536 #ifdef SQLITE_WIN32_MALLOC
37537 
37538 /*
37539  * If this is non-zero, an isolated heap will be created by the native Win32
37540  * allocator subsystem; otherwise, the default process heap will be used. This
37541  * setting has no effect when compiling for WinRT. By default, this is enabled
37542  * and an isolated heap will be created to store all allocated data.
37543  *
37544  ******************************************************************************
37545  * WARNING: It is important to note that when this setting is non-zero and the
37546  * winMemShutdown function is called (e.g. by the sqlite3_shutdown
37547  * function), all data that was allocated using the isolated heap will
37548  * be freed immediately and any attempt to access any of that freed
37549  * data will almost certainly result in an immediate access violation.
37550  ******************************************************************************
37551  */
37552 #ifndef SQLITE_WIN32_HEAP_CREATE
37553 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
37554 #endif
37555 
37556 /*
37557  * This is cache size used in the calculation of the initial size of the
37558  * Win32-specific heap. It cannot be negative.
37559  */
37560 #ifndef SQLITE_WIN32_CACHE_SIZE
37561 # if SQLITE_DEFAULT_CACHE_SIZE>=0
37562 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
37563 # else
37564 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
37565 # endif
37566 #endif
37567 
37568 /*
37569  * The initial size of the Win32-specific heap. This value may be zero.
37570  */
37571 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
37572 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
37573  (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
37574 #endif
37575 
37576 /*
37577  * The maximum size of the Win32-specific heap. This value may be zero.
37578  */
37579 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
37580 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
37581 #endif
37582 
37583 /*
37584  * The extra flags to use in calls to the Win32 heap APIs. This value may be
37585  * zero for the default behavior.
37586  */
37587 #ifndef SQLITE_WIN32_HEAP_FLAGS
37588 # define SQLITE_WIN32_HEAP_FLAGS (0)
37589 #endif
37590 
37591 
37592 /*
37593 ** The winMemData structure stores information required by the Win32-specific
37594 ** sqlite3_mem_methods implementation.
37595 */
37596 typedef struct winMemData winMemData;
37597 struct winMemData {
37598 #ifndef NDEBUG
37599  u32 magic1; /* Magic number to detect structure corruption. */
37600 #endif
37601  HANDLE hHeap; /* The handle to our heap. */
37602  BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
37603 #ifndef NDEBUG
37604  u32 magic2; /* Magic number to detect structure corruption. */
37605 #endif
37606 };
37607 
37608 #ifndef NDEBUG
37609 #define WINMEM_MAGIC1 0x42b2830b
37610 #define WINMEM_MAGIC2 0xbd4d7cf4
37611 #endif
37612 
37613 static struct winMemData win_mem_data = {
37614 #ifndef NDEBUG
37615  WINMEM_MAGIC1,
37616 #endif
37617  NULL, FALSE
37618 #ifndef NDEBUG
37619  ,WINMEM_MAGIC2
37620 #endif
37621 };
37622 
37623 #ifndef NDEBUG
37624 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
37625 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
37626 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
37627 #else
37628 #define winMemAssertMagic()
37629 #endif
37630 
37631 #define winMemGetDataPtr() &win_mem_data
37632 #define winMemGetHeap() win_mem_data.hHeap
37633 #define winMemGetOwned() win_mem_data.bOwned
37634 
37635 static void *winMemMalloc(int nBytes);
37636 static void winMemFree(void *pPrior);
37637 static void *winMemRealloc(void *pPrior, int nBytes);
37638 static int winMemSize(void *p);
37639 static int winMemRoundup(int n);
37640 static int winMemInit(void *pAppData);
37641 static void winMemShutdown(void *pAppData);
37642 
37643 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
37644 #endif /* SQLITE_WIN32_MALLOC */
37645 
37646 /*
37647 ** The following variable is (normally) set once and never changes
37648 ** thereafter. It records whether the operating system is Win9x
37649 ** or WinNT.
37650 **
37651 ** 0: Operating system unknown.
37652 ** 1: Operating system is Win9x.
37653 ** 2: Operating system is WinNT.
37654 **
37655 ** In order to facilitate testing on a WinNT system, the test fixture
37656 ** can manually set this value to 1 to emulate Win98 behavior.
37657 */
37658 #ifdef SQLITE_TEST
37659 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37660 #else
37661 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37662 #endif
37663 
37664 #ifndef SYSCALL
37665 # define SYSCALL sqlite3_syscall_ptr
37666 #endif
37667 
37668 /*
37669 ** This function is not available on Windows CE or WinRT.
37670  */
37671 
37672 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
37673 # define osAreFileApisANSI() 1
37674 #endif
37675 
37676 /*
37677 ** Many system calls are accessed through pointer-to-functions so that
37678 ** they may be overridden at runtime to facilitate fault injection during
37679 ** testing and sandboxing. The following array holds the names and pointers
37680 ** to all overrideable system calls.
37681 */
37682 static struct win_syscall {
37683  const char *zName; /* Name of the system call */
37684  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
37685  sqlite3_syscall_ptr pDefault; /* Default value */
37686 } aSyscall[] = {
37687 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37688  { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
37689 #else
37690  { "AreFileApisANSI", (SYSCALL)0, 0 },
37691 #endif
37692 
37693 #ifndef osAreFileApisANSI
37694 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
37695 #endif
37696 
37697 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37698  { "CharLowerW", (SYSCALL)CharLowerW, 0 },
37699 #else
37700  { "CharLowerW", (SYSCALL)0, 0 },
37701 #endif
37702 
37703 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
37704 
37705 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37706  { "CharUpperW", (SYSCALL)CharUpperW, 0 },
37707 #else
37708  { "CharUpperW", (SYSCALL)0, 0 },
37709 #endif
37710 
37711 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
37712 
37713  { "CloseHandle", (SYSCALL)CloseHandle, 0 },
37714 
37715 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
37716 
37717 #if defined(SQLITE_WIN32_HAS_ANSI)
37718  { "CreateFileA", (SYSCALL)CreateFileA, 0 },
37719 #else
37720  { "CreateFileA", (SYSCALL)0, 0 },
37721 #endif
37722 
37723 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
37724  LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
37725 
37726 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37727  { "CreateFileW", (SYSCALL)CreateFileW, 0 },
37728 #else
37729  { "CreateFileW", (SYSCALL)0, 0 },
37730 #endif
37731 
37732 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
37733  LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
37734 
37735 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
37736  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
37737  SQLITE_WIN32_CREATEFILEMAPPINGA
37738  { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
37739 #else
37740  { "CreateFileMappingA", (SYSCALL)0, 0 },
37741 #endif
37742 
37743 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37744  DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
37745 
37746 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37747  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
37748  { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
37749 #else
37750  { "CreateFileMappingW", (SYSCALL)0, 0 },
37751 #endif
37752 
37753 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37754  DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
37755 
37756 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37757  { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
37758 #else
37759  { "CreateMutexW", (SYSCALL)0, 0 },
37760 #endif
37761 
37762 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
37763  LPCWSTR))aSyscall[8].pCurrent)
37764 
37765 #if defined(SQLITE_WIN32_HAS_ANSI)
37766  { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
37767 #else
37768  { "DeleteFileA", (SYSCALL)0, 0 },
37769 #endif
37770 
37771 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
37772 
37773 #if defined(SQLITE_WIN32_HAS_WIDE)
37774  { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
37775 #else
37776  { "DeleteFileW", (SYSCALL)0, 0 },
37777 #endif
37778 
37779 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
37780 
37781 #if SQLITE_OS_WINCE
37782  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
37783 #else
37784  { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
37785 #endif
37786 
37787 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37788  LPFILETIME))aSyscall[11].pCurrent)
37789 
37790 #if SQLITE_OS_WINCE
37791  { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
37792 #else
37793  { "FileTimeToSystemTime", (SYSCALL)0, 0 },
37794 #endif
37795 
37796 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37797  LPSYSTEMTIME))aSyscall[12].pCurrent)
37798 
37799  { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
37800 
37801 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
37802 
37803 #if defined(SQLITE_WIN32_HAS_ANSI)
37804  { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
37805 #else
37806  { "FormatMessageA", (SYSCALL)0, 0 },
37807 #endif
37808 
37809 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
37810  DWORD,va_list*))aSyscall[14].pCurrent)
37811 
37812 #if defined(SQLITE_WIN32_HAS_WIDE)
37813  { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
37814 #else
37815  { "FormatMessageW", (SYSCALL)0, 0 },
37816 #endif
37817 
37818 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
37819  DWORD,va_list*))aSyscall[15].pCurrent)
37820 
37821 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37822  { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
37823 #else
37824  { "FreeLibrary", (SYSCALL)0, 0 },
37825 #endif
37826 
37827 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
37828 
37829  { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
37830 
37831 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
37832 
37833 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37834  { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
37835 #else
37836  { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
37837 #endif
37838 
37839 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
37840  LPDWORD))aSyscall[18].pCurrent)
37841 
37842 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37843  { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
37844 #else
37845  { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
37846 #endif
37847 
37848 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
37849  LPDWORD))aSyscall[19].pCurrent)
37850 
37851 #if defined(SQLITE_WIN32_HAS_ANSI)
37852  { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
37853 #else
37854  { "GetFileAttributesA", (SYSCALL)0, 0 },
37855 #endif
37856 
37857 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
37858 
37859 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37860  { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
37861 #else
37862  { "GetFileAttributesW", (SYSCALL)0, 0 },
37863 #endif
37864 
37865 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
37866 
37867 #if defined(SQLITE_WIN32_HAS_WIDE)
37868  { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
37869 #else
37870  { "GetFileAttributesExW", (SYSCALL)0, 0 },
37871 #endif
37872 
37873 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
37874  LPVOID))aSyscall[22].pCurrent)
37875 
37876 #if !SQLITE_OS_WINRT
37877  { "GetFileSize", (SYSCALL)GetFileSize, 0 },
37878 #else
37879  { "GetFileSize", (SYSCALL)0, 0 },
37880 #endif
37881 
37882 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
37883 
37884 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37885  { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
37886 #else
37887  { "GetFullPathNameA", (SYSCALL)0, 0 },
37888 #endif
37889 
37890 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
37891  LPSTR*))aSyscall[24].pCurrent)
37892 
37893 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37894  { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
37895 #else
37896  { "GetFullPathNameW", (SYSCALL)0, 0 },
37897 #endif
37898 
37899 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
37900  LPWSTR*))aSyscall[25].pCurrent)
37901 
37902  { "GetLastError", (SYSCALL)GetLastError, 0 },
37903 
37904 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
37905 
37906 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37907 #if SQLITE_OS_WINCE
37908  /* The GetProcAddressA() routine is only available on Windows CE. */
37909  { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
37910 #else
37911  /* All other Windows platforms expect GetProcAddress() to take
37912  ** an ANSI string regardless of the _UNICODE setting */
37913  { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
37914 #endif
37915 #else
37916  { "GetProcAddressA", (SYSCALL)0, 0 },
37917 #endif
37918 
37919 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
37920  LPCSTR))aSyscall[27].pCurrent)
37921 
37922 #if !SQLITE_OS_WINRT
37923  { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
37924 #else
37925  { "GetSystemInfo", (SYSCALL)0, 0 },
37926 #endif
37927 
37928 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
37929 
37930  { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
37931 
37932 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
37933 
37934 #if !SQLITE_OS_WINCE
37935  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
37936 #else
37937  { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
37938 #endif
37939 
37940 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
37941  LPFILETIME))aSyscall[30].pCurrent)
37942 
37943 #if defined(SQLITE_WIN32_HAS_ANSI)
37944  { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
37945 #else
37946  { "GetTempPathA", (SYSCALL)0, 0 },
37947 #endif
37948 
37949 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
37950 
37951 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37952  { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
37953 #else
37954  { "GetTempPathW", (SYSCALL)0, 0 },
37955 #endif
37956 
37957 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
37958 
37959 #if !SQLITE_OS_WINRT
37960  { "GetTickCount", (SYSCALL)GetTickCount, 0 },
37961 #else
37962  { "GetTickCount", (SYSCALL)0, 0 },
37963 #endif
37964 
37965 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
37966 
37967 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
37968  { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
37969 #else
37970  { "GetVersionExA", (SYSCALL)0, 0 },
37971 #endif
37972 
37973 #define osGetVersionExA ((BOOL(WINAPI*)( \
37974  LPOSVERSIONINFOA))aSyscall[34].pCurrent)
37975 
37976 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37977  SQLITE_WIN32_GETVERSIONEX
37978  { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
37979 #else
37980  { "GetVersionExW", (SYSCALL)0, 0 },
37981 #endif
37982 
37983 #define osGetVersionExW ((BOOL(WINAPI*)( \
37984  LPOSVERSIONINFOW))aSyscall[35].pCurrent)
37985 
37986  { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
37987 
37988 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
37989  SIZE_T))aSyscall[36].pCurrent)
37990 
37991 #if !SQLITE_OS_WINRT
37992  { "HeapCreate", (SYSCALL)HeapCreate, 0 },
37993 #else
37994  { "HeapCreate", (SYSCALL)0, 0 },
37995 #endif
37996 
37997 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
37998  SIZE_T))aSyscall[37].pCurrent)
37999 
38000 #if !SQLITE_OS_WINRT
38001  { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
38002 #else
38003  { "HeapDestroy", (SYSCALL)0, 0 },
38004 #endif
38005 
38006 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
38007 
38008  { "HeapFree", (SYSCALL)HeapFree, 0 },
38009 
38010 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
38011 
38012  { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
38013 
38014 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
38015  SIZE_T))aSyscall[40].pCurrent)
38016 
38017  { "HeapSize", (SYSCALL)HeapSize, 0 },
38018 
38019 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
38020  LPCVOID))aSyscall[41].pCurrent)
38021 
38022 #if !SQLITE_OS_WINRT
38023  { "HeapValidate", (SYSCALL)HeapValidate, 0 },
38024 #else
38025  { "HeapValidate", (SYSCALL)0, 0 },
38026 #endif
38027 
38028 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
38029  LPCVOID))aSyscall[42].pCurrent)
38030 
38031 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38032  { "HeapCompact", (SYSCALL)HeapCompact, 0 },
38033 #else
38034  { "HeapCompact", (SYSCALL)0, 0 },
38035 #endif
38036 
38037 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
38038 
38039 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38040  { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
38041 #else
38042  { "LoadLibraryA", (SYSCALL)0, 0 },
38043 #endif
38044 
38045 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
38046 
38047 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
38048  !defined(SQLITE_OMIT_LOAD_EXTENSION)
38049  { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
38050 #else
38051  { "LoadLibraryW", (SYSCALL)0, 0 },
38052 #endif
38053 
38054 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
38055 
38056 #if !SQLITE_OS_WINRT
38057  { "LocalFree", (SYSCALL)LocalFree, 0 },
38058 #else
38059  { "LocalFree", (SYSCALL)0, 0 },
38060 #endif
38061 
38062 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
38063 
38064 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38065  { "LockFile", (SYSCALL)LockFile, 0 },
38066 #else
38067  { "LockFile", (SYSCALL)0, 0 },
38068 #endif
38069 
38070 #ifndef osLockFile
38071 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38072  DWORD))aSyscall[47].pCurrent)
38073 #endif
38074 
38075 #if !SQLITE_OS_WINCE
38076  { "LockFileEx", (SYSCALL)LockFileEx, 0 },
38077 #else
38078  { "LockFileEx", (SYSCALL)0, 0 },
38079 #endif
38080 
38081 #ifndef osLockFileEx
38082 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
38083  LPOVERLAPPED))aSyscall[48].pCurrent)
38084 #endif
38085 
38086 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
38087  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38088  { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
38089 #else
38090  { "MapViewOfFile", (SYSCALL)0, 0 },
38091 #endif
38092 
38093 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38094  SIZE_T))aSyscall[49].pCurrent)
38095 
38096  { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
38097 
38098 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
38099  int))aSyscall[50].pCurrent)
38100 
38101  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
38102 
38103 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
38104  LARGE_INTEGER*))aSyscall[51].pCurrent)
38105 
38106  { "ReadFile", (SYSCALL)ReadFile, 0 },
38107 
38108 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
38109  LPOVERLAPPED))aSyscall[52].pCurrent)
38110 
38111  { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
38112 
38113 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
38114 
38115 #if !SQLITE_OS_WINRT
38116  { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
38117 #else
38118  { "SetFilePointer", (SYSCALL)0, 0 },
38119 #endif
38120 
38121 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
38122  DWORD))aSyscall[54].pCurrent)
38123 
38124 #if !SQLITE_OS_WINRT
38125  { "Sleep", (SYSCALL)Sleep, 0 },
38126 #else
38127  { "Sleep", (SYSCALL)0, 0 },
38128 #endif
38129 
38130 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
38131 
38132  { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
38133 
38134 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
38135  LPFILETIME))aSyscall[56].pCurrent)
38136 
38137 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38138  { "UnlockFile", (SYSCALL)UnlockFile, 0 },
38139 #else
38140  { "UnlockFile", (SYSCALL)0, 0 },
38141 #endif
38142 
38143 #ifndef osUnlockFile
38144 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38145  DWORD))aSyscall[57].pCurrent)
38146 #endif
38147 
38148 #if !SQLITE_OS_WINCE
38149  { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
38150 #else
38151  { "UnlockFileEx", (SYSCALL)0, 0 },
38152 #endif
38153 
38154 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38155  LPOVERLAPPED))aSyscall[58].pCurrent)
38156 
38157 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
38158  { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
38159 #else
38160  { "UnmapViewOfFile", (SYSCALL)0, 0 },
38161 #endif
38162 
38163 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
38164 
38165  { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
38166 
38167 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
38168  LPCSTR,LPBOOL))aSyscall[60].pCurrent)
38169 
38170  { "WriteFile", (SYSCALL)WriteFile, 0 },
38171 
38172 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
38173  LPOVERLAPPED))aSyscall[61].pCurrent)
38174 
38175 #if SQLITE_OS_WINRT
38176  { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
38177 #else
38178  { "CreateEventExW", (SYSCALL)0, 0 },
38179 #endif
38180 
38181 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
38182  DWORD,DWORD))aSyscall[62].pCurrent)
38183 
38184 #if !SQLITE_OS_WINRT
38185  { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
38186 #else
38187  { "WaitForSingleObject", (SYSCALL)0, 0 },
38188 #endif
38189 
38190 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
38191  DWORD))aSyscall[63].pCurrent)
38192 
38193 #if !SQLITE_OS_WINCE
38194  { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
38195 #else
38196  { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
38197 #endif
38198 
38199 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
38200  BOOL))aSyscall[64].pCurrent)
38201 
38202 #if SQLITE_OS_WINRT
38203  { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
38204 #else
38205  { "SetFilePointerEx", (SYSCALL)0, 0 },
38206 #endif
38207 
38208 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
38209  PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
38210 
38211 #if SQLITE_OS_WINRT
38212  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
38213 #else
38214  { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
38215 #endif
38216 
38217 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
38218  FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
38219 
38220 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38221  { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
38222 #else
38223  { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
38224 #endif
38225 
38226 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
38227  SIZE_T))aSyscall[67].pCurrent)
38228 
38229 #if SQLITE_OS_WINRT
38230  { "CreateFile2", (SYSCALL)CreateFile2, 0 },
38231 #else
38232  { "CreateFile2", (SYSCALL)0, 0 },
38233 #endif
38234 
38235 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
38236  LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
38237 
38238 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38239  { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
38240 #else
38241  { "LoadPackagedLibrary", (SYSCALL)0, 0 },
38242 #endif
38243 
38244 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
38245  DWORD))aSyscall[69].pCurrent)
38246 
38247 #if SQLITE_OS_WINRT
38248  { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
38249 #else
38250  { "GetTickCount64", (SYSCALL)0, 0 },
38251 #endif
38252 
38253 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
38254 
38255 #if SQLITE_OS_WINRT
38256  { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
38257 #else
38258  { "GetNativeSystemInfo", (SYSCALL)0, 0 },
38259 #endif
38260 
38261 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
38262  LPSYSTEM_INFO))aSyscall[71].pCurrent)
38263 
38264 #if defined(SQLITE_WIN32_HAS_ANSI)
38265  { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
38266 #else
38267  { "OutputDebugStringA", (SYSCALL)0, 0 },
38268 #endif
38269 
38270 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
38271 
38272 #if defined(SQLITE_WIN32_HAS_WIDE)
38273  { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
38274 #else
38275  { "OutputDebugStringW", (SYSCALL)0, 0 },
38276 #endif
38277 
38278 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
38279 
38280  { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
38281 
38282 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
38283 
38284 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38285  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
38286 #else
38287  { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
38288 #endif
38289 
38290 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
38291  LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
38292 
38293 /*
38294 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
38295 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
38296 ** So do not try to make this is into a redefinable interface.
38297 */
38298 #if defined(InterlockedCompareExchange)
38299  { "InterlockedCompareExchange", (SYSCALL)0, 0 },
38300 
38301 #define osInterlockedCompareExchange InterlockedCompareExchange
38302 #else
38303  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
38304 
38305 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
38306  SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
38307 #endif /* defined(InterlockedCompareExchange) */
38308 
38309 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38310  { "UuidCreate", (SYSCALL)UuidCreate, 0 },
38311 #else
38312  { "UuidCreate", (SYSCALL)0, 0 },
38313 #endif
38314 
38315 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
38316 
38317 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38318  { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
38319 #else
38320  { "UuidCreateSequential", (SYSCALL)0, 0 },
38321 #endif
38322 
38323 #define osUuidCreateSequential \
38324  ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
38325 
38326 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
38327  { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
38328 #else
38329  { "FlushViewOfFile", (SYSCALL)0, 0 },
38330 #endif
38331 
38332 #define osFlushViewOfFile \
38333  ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
38334 
38335 }; /* End of the overrideable system calls */
38336 
38337 /*
38338 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
38339 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
38340 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
38341 ** system call named zName.
38342 */
38343 static int winSetSystemCall(
38344  sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
38345  const char *zName, /* Name of system call to override */
38346  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
38347 ){
38348  unsigned int i;
38349  int rc = SQLITE_NOTFOUND;
38350 
38351  UNUSED_PARAMETER(pNotUsed);
38352  if( zName==0 ){
38353  /* If no zName is given, restore all system calls to their default
38354  ** settings and return NULL
38355  */
38356  rc = SQLITE_OK;
38357  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38358  if( aSyscall[i].pDefault ){
38360  }
38361  }
38362  }else{
38363  /* If zName is specified, operate on only the one system call
38364  ** specified.
38365  */
38366  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38367  if( strcmp(zName, aSyscall[i].zName)==0 ){
38368  if( aSyscall[i].pDefault==0 ){
38370  }
38371  rc = SQLITE_OK;
38372  if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
38373  aSyscall[i].pCurrent = pNewFunc;
38374  break;
38375  }
38376  }
38377  }
38378  return rc;
38379 }
38380 
38381 /*
38382 ** Return the value of a system call. Return NULL if zName is not a
38383 ** recognized system call name. NULL is also returned if the system call
38384 ** is currently undefined.
38385 */
38386 static sqlite3_syscall_ptr winGetSystemCall(
38387  sqlite3_vfs *pNotUsed,
38388  const char *zName
38389 ){
38390  unsigned int i;
38391 
38392  UNUSED_PARAMETER(pNotUsed);
38393  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38394  if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
38395  }
38396  return 0;
38397 }
38398 
38399 /*
38400 ** Return the name of the first system call after zName. If zName==NULL
38401 ** then return the name of the first system call. Return NULL if zName
38402 ** is the last system call or if zName is not the name of a valid
38403 ** system call.
38404 */
38405 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
38406  int i = -1;
38407 
38408  UNUSED_PARAMETER(p);
38409  if( zName ){
38410  for(i=0; i<ArraySize(aSyscall)-1; i++){
38411  if( strcmp(zName, aSyscall[i].zName)==0 ) break;
38412  }
38413  }
38414  for(i++; i<ArraySize(aSyscall); i++){
38415  if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
38416  }
38417  return 0;
38418 }
38419 
38420 #ifdef SQLITE_WIN32_MALLOC
38421 /*
38422 ** If a Win32 native heap has been configured, this function will attempt to
38423 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
38424 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
38425 ** "pnLargest" argument, if non-zero, will be used to return the size of the
38426 ** largest committed free block in the heap, in bytes.
38427 */
38428 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
38429  int rc = SQLITE_OK;
38430  UINT nLargest = 0;
38431  HANDLE hHeap;
38432 
38433  winMemAssertMagic();
38434  hHeap = winMemGetHeap();
38435  assert( hHeap!=0 );
38436  assert( hHeap!=INVALID_HANDLE_VALUE );
38437 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38438  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38439 #endif
38440 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38441  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
38442  DWORD lastErrno = osGetLastError();
38443  if( lastErrno==NO_ERROR ){
38444  sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
38445  (void*)hHeap);
38446  rc = SQLITE_NOMEM_BKPT;
38447  }else{
38448  sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
38449  osGetLastError(), (void*)hHeap);
38450  rc = SQLITE_ERROR;
38451  }
38452  }
38453 #else
38454  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
38455  (void*)hHeap);
38456  rc = SQLITE_NOTFOUND;
38457 #endif
38458  if( pnLargest ) *pnLargest = nLargest;
38459  return rc;
38460 }
38461 
38462 /*
38463 ** If a Win32 native heap has been configured, this function will attempt to
38464 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
38465 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
38466 ** be returned and no changes will be made to the Win32 native heap.
38467 */
38468 SQLITE_API int sqlite3_win32_reset_heap(){
38469  int rc;
38470  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
38471  MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
38474  sqlite3_mutex_enter(pMaster);
38475  sqlite3_mutex_enter(pMem);
38476  winMemAssertMagic();
38477  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
38478  /*
38479  ** At this point, there should be no outstanding memory allocations on
38480  ** the heap. Also, since both the master and memsys locks are currently
38481  ** being held by us, no other function (i.e. from another thread) should
38482  ** be able to even access the heap. Attempt to destroy and recreate our
38483  ** isolated Win32 native heap now.
38484  */
38485  assert( winMemGetHeap()!=NULL );
38486  assert( winMemGetOwned() );
38487  assert( sqlite3_memory_used()==0 );
38488  winMemShutdown(winMemGetDataPtr());
38489  assert( winMemGetHeap()==NULL );
38490  assert( !winMemGetOwned() );
38491  assert( sqlite3_memory_used()==0 );
38492  rc = winMemInit(winMemGetDataPtr());
38493  assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
38494  assert( rc!=SQLITE_OK || winMemGetOwned() );
38495  assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
38496  }else{
38497  /*
38498  ** The Win32 native heap cannot be modified because it may be in use.
38499  */
38500  rc = SQLITE_BUSY;
38501  }
38502  sqlite3_mutex_leave(pMem);
38503  sqlite3_mutex_leave(pMaster);
38504  return rc;
38505 }
38506 #endif /* SQLITE_WIN32_MALLOC */
38507 
38508 /*
38509 ** This function outputs the specified (ANSI) string to the Win32 debugger
38510 ** (if available).
38511 */
38512 
38513 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
38514  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
38515  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
38516  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
38517  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
38518 #ifdef SQLITE_ENABLE_API_ARMOR
38519  if( !zBuf ){
38520  (void)SQLITE_MISUSE_BKPT;
38521  return;
38522  }
38523 #endif
38524 #if defined(SQLITE_WIN32_HAS_ANSI)
38525  if( nMin>0 ){
38526  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38527  memcpy(zDbgBuf, zBuf, nMin);
38528  osOutputDebugStringA(zDbgBuf);
38529  }else{
38530  osOutputDebugStringA(zBuf);
38531  }
38532 #elif defined(SQLITE_WIN32_HAS_WIDE)
38533  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38534  if ( osMultiByteToWideChar(
38535  osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
38536  nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
38537  return;
38538  }
38539  osOutputDebugStringW((LPCWSTR)zDbgBuf);
38540 #else
38541  if( nMin>0 ){
38542  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38543  memcpy(zDbgBuf, zBuf, nMin);
38544  fprintf(stderr, "%s", zDbgBuf);
38545  }else{
38546  fprintf(stderr, "%s", zBuf);
38547  }
38548 #endif
38549 }
38550 
38551 /*
38552 ** The following routine suspends the current thread for at least ms
38553 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
38554 */
38555 #if SQLITE_OS_WINRT
38556 static HANDLE sleepObj = NULL;
38557 #endif
38558 
38559 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
38560 #if SQLITE_OS_WINRT
38561  if ( sleepObj==NULL ){
38562  sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
38563  SYNCHRONIZE);
38564  }
38565  assert( sleepObj!=NULL );
38566  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
38567 #else
38568  osSleep(milliseconds);
38569 #endif
38570 }
38571 
38572 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
38573  SQLITE_THREADSAFE>0
38574 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
38575  DWORD rc;
38576  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
38577  TRUE))==WAIT_IO_COMPLETION ){}
38578  return rc;
38579 }
38580 #endif
38581 
38582 /*
38583 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
38584 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
38585 **
38586 ** Here is an interesting observation: Win95, Win98, and WinME lack
38587 ** the LockFileEx() API. But we can still statically link against that
38588 ** API as long as we don't call it when running Win95/98/ME. A call to
38589 ** this routine is used to determine if the host is Win95/98/ME or
38590 ** WinNT/2K/XP so that we will know whether or not we can safely call
38591 ** the LockFileEx() API.
38592 */
38593 
38594 #if !SQLITE_WIN32_GETVERSIONEX
38595 # define osIsNT() (1)
38596 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
38597 # define osIsNT() (1)
38598 #elif !defined(SQLITE_WIN32_HAS_WIDE)
38599 # define osIsNT() (0)
38600 #else
38601 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
38602 #endif
38603 
38604 /*
38605 ** This function determines if the machine is running a version of Windows
38606 ** based on the NT kernel.
38607 */
38608 SQLITE_API int sqlite3_win32_is_nt(void){
38609 #if SQLITE_OS_WINRT
38610  /*
38611  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
38612  ** kernel.
38613  */
38614  return 1;
38615 #elif SQLITE_WIN32_GETVERSIONEX
38616  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
38617 #if defined(SQLITE_WIN32_HAS_ANSI)
38618  OSVERSIONINFOA sInfo;
38619  sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38620  osGetVersionExA(&sInfo);
38621  osInterlockedCompareExchange(&sqlite3_os_type,
38622  (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38623 #elif defined(SQLITE_WIN32_HAS_WIDE)
38624  OSVERSIONINFOW sInfo;
38625  sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38626  osGetVersionExW(&sInfo);
38627  osInterlockedCompareExchange(&sqlite3_os_type,
38628  (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38629 #endif
38630  }
38631  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38632 #elif SQLITE_TEST
38633  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38634 #else
38635  /*
38636  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
38637  ** deprecated are always assumed to be based on the NT kernel.
38638  */
38639  return 1;
38640 #endif
38641 }
38642 
38643 #ifdef SQLITE_WIN32_MALLOC
38644 /*
38645 ** Allocate nBytes of memory.
38646 */
38647 static void *winMemMalloc(int nBytes){
38648  HANDLE hHeap;
38649  void *p;
38650 
38651  winMemAssertMagic();
38652  hHeap = winMemGetHeap();
38653  assert( hHeap!=0 );
38654  assert( hHeap!=INVALID_HANDLE_VALUE );
38655 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38656  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38657 #endif
38658  assert( nBytes>=0 );
38659  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38660  if( !p ){
38661  sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
38662  nBytes, osGetLastError(), (void*)hHeap);
38663  }
38664  return p;
38665 }
38666 
38667 /*
38668 ** Free memory.
38669 */
38670 static void winMemFree(void *pPrior){
38671  HANDLE hHeap;
38672 
38673  winMemAssertMagic();
38674  hHeap = winMemGetHeap();
38675  assert( hHeap!=0 );
38676  assert( hHeap!=INVALID_HANDLE_VALUE );
38677 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38678  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38679 #endif
38680  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
38681  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
38682  sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
38683  pPrior, osGetLastError(), (void*)hHeap);
38684  }
38685 }
38686 
38687 /*
38688 ** Change the size of an existing memory allocation
38689 */
38690 static void *winMemRealloc(void *pPrior, int nBytes){
38691  HANDLE hHeap;
38692  void *p;
38693 
38694  winMemAssertMagic();
38695  hHeap = winMemGetHeap();
38696  assert( hHeap!=0 );
38697  assert( hHeap!=INVALID_HANDLE_VALUE );
38698 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38699  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38700 #endif
38701  assert( nBytes>=0 );
38702  if( !pPrior ){
38703  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38704  }else{
38705  p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
38706  }
38707  if( !p ){
38708  sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
38709  pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
38710  (void*)hHeap);
38711  }
38712  return p;
38713 }
38714 
38715 /*
38716 ** Return the size of an outstanding allocation, in bytes.
38717 */
38718 static int winMemSize(void *p){
38719  HANDLE hHeap;
38720  SIZE_T n;
38721 
38722  winMemAssertMagic();
38723  hHeap = winMemGetHeap();
38724  assert( hHeap!=0 );
38725  assert( hHeap!=INVALID_HANDLE_VALUE );
38726 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38727  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
38728 #endif
38729  if( !p ) return 0;
38730  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
38731  if( n==(SIZE_T)-1 ){
38732  sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
38733  p, osGetLastError(), (void*)hHeap);
38734  return 0;
38735  }
38736  return (int)n;
38737 }
38738 
38739 /*
38740 ** Round up a request size to the next valid allocation size.
38741 */
38742 static int winMemRoundup(int n){
38743  return n;
38744 }
38745 
38746 /*
38747 ** Initialize this module.
38748 */
38749 static int winMemInit(void *pAppData){
38750  winMemData *pWinMemData = (winMemData *)pAppData;
38751 
38752  if( !pWinMemData ) return SQLITE_ERROR;
38753  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38754  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38755 
38756 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
38757  if( !pWinMemData->hHeap ){
38758  DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
38759  DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
38760  if( dwMaximumSize==0 ){
38761  dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
38762  }else if( dwInitialSize>dwMaximumSize ){
38763  dwInitialSize = dwMaximumSize;
38764  }
38765  pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
38766  dwInitialSize, dwMaximumSize);
38767  if( !pWinMemData->hHeap ){
38769  "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
38770  osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
38771  dwMaximumSize);
38772  return SQLITE_NOMEM_BKPT;
38773  }
38774  pWinMemData->bOwned = TRUE;
38775  assert( pWinMemData->bOwned );
38776  }
38777 #else
38778  pWinMemData->hHeap = osGetProcessHeap();
38779  if( !pWinMemData->hHeap ){
38781  "failed to GetProcessHeap (%lu)", osGetLastError());
38782  return SQLITE_NOMEM_BKPT;
38783  }
38784  pWinMemData->bOwned = FALSE;
38785  assert( !pWinMemData->bOwned );
38786 #endif
38787  assert( pWinMemData->hHeap!=0 );
38788  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38789 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38790  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38791 #endif
38792  return SQLITE_OK;
38793 }
38794 
38795 /*
38796 ** Deinitialize this module.
38797 */
38798 static void winMemShutdown(void *pAppData){
38799  winMemData *pWinMemData = (winMemData *)pAppData;
38800 
38801  if( !pWinMemData ) return;
38802  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38803  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38804 
38805  if( pWinMemData->hHeap ){
38806  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38807 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38808  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38809 #endif
38810  if( pWinMemData->bOwned ){
38811  if( !osHeapDestroy(pWinMemData->hHeap) ){
38812  sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
38813  osGetLastError(), (void*)pWinMemData->hHeap);
38814  }
38815  pWinMemData->bOwned = FALSE;
38816  }
38817  pWinMemData->hHeap = NULL;
38818  }
38819 }
38820 
38821 /*
38822 ** Populate the low-level memory allocation function pointers in
38823 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
38824 ** arguments specify the block of memory to manage.
38825 **
38826 ** This routine is only called by sqlite3_config(), and therefore
38827 ** is not required to be threadsafe (it is not).
38828 */
38829 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
38830  static const sqlite3_mem_methods winMemMethods = {
38831  winMemMalloc,
38832  winMemFree,
38833  winMemRealloc,
38834  winMemSize,
38835  winMemRoundup,
38836  winMemInit,
38837  winMemShutdown,
38838  &win_mem_data
38839  };
38840  return &winMemMethods;
38841 }
38842 
38844  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
38845 }
38846 #endif /* SQLITE_WIN32_MALLOC */
38847 
38848 /*
38849 ** Convert a UTF-8 string to Microsoft Unicode.
38850 **
38851 ** Space to hold the returned string is obtained from sqlite3_malloc().
38852 */
38853 static LPWSTR winUtf8ToUnicode(const char *zText){
38854  int nChar;
38855  LPWSTR zWideText;
38856 
38857  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
38858  if( nChar==0 ){
38859  return 0;
38860  }
38861  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
38862  if( zWideText==0 ){
38863  return 0;
38864  }
38865  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
38866  nChar);
38867  if( nChar==0 ){
38868  sqlite3_free(zWideText);
38869  zWideText = 0;
38870  }
38871  return zWideText;
38872 }
38873 
38874 /*
38875 ** Convert a Microsoft Unicode string to UTF-8.
38876 **
38877 ** Space to hold the returned string is obtained from sqlite3_malloc().
38878 */
38879 static char *winUnicodeToUtf8(LPCWSTR zWideText){
38880  int nByte;
38881  char *zText;
38882 
38883  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
38884  if( nByte == 0 ){
38885  return 0;
38886  }
38887  zText = sqlite3MallocZero( nByte );
38888  if( zText==0 ){
38889  return 0;
38890  }
38891  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
38892  0, 0);
38893  if( nByte == 0 ){
38894  sqlite3_free(zText);
38895  zText = 0;
38896  }
38897  return zText;
38898 }
38899 
38900 /*
38901 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
38902 ** code page.
38903 **
38904 ** Space to hold the returned string is obtained from sqlite3_malloc().
38905 */
38906 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
38907  int nByte;
38908  LPWSTR zMbcsText;
38909  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38910 
38911  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
38912  0)*sizeof(WCHAR);
38913  if( nByte==0 ){
38914  return 0;
38915  }
38916  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
38917  if( zMbcsText==0 ){
38918  return 0;
38919  }
38920  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
38921  nByte);
38922  if( nByte==0 ){
38923  sqlite3_free(zMbcsText);
38924  zMbcsText = 0;
38925  }
38926  return zMbcsText;
38927 }
38928 
38929 /*
38930 ** Convert a Microsoft Unicode string to a multi-byte character string,
38931 ** using the ANSI or OEM code page.
38932 **
38933 ** Space to hold the returned string is obtained from sqlite3_malloc().
38934 */
38935 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
38936  int nByte;
38937  char *zText;
38938  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38939 
38940  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
38941  if( nByte == 0 ){
38942  return 0;
38943  }
38944  zText = sqlite3MallocZero( nByte );
38945  if( zText==0 ){
38946  return 0;
38947  }
38948  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
38949  nByte, 0, 0);
38950  if( nByte == 0 ){
38951  sqlite3_free(zText);
38952  zText = 0;
38953  }
38954  return zText;
38955 }
38956 
38957 /*
38958 ** Convert a multi-byte character string to UTF-8.
38959 **
38960 ** Space to hold the returned string is obtained from sqlite3_malloc().
38961 */
38962 static char *winMbcsToUtf8(const char *zText, int useAnsi){
38963  char *zTextUtf8;
38964  LPWSTR zTmpWide;
38965 
38966  zTmpWide = winMbcsToUnicode(zText, useAnsi);
38967  if( zTmpWide==0 ){
38968  return 0;
38969  }
38970  zTextUtf8 = winUnicodeToUtf8(zTmpWide);
38971  sqlite3_free(zTmpWide);
38972  return zTextUtf8;
38973 }
38974 
38975 /*
38976 ** Convert a UTF-8 string to a multi-byte character string.
38977 **
38978 ** Space to hold the returned string is obtained from sqlite3_malloc().
38979 */
38980 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
38981  char *zTextMbcs;
38982  LPWSTR zTmpWide;
38983 
38984  zTmpWide = winUtf8ToUnicode(zText);
38985  if( zTmpWide==0 ){
38986  return 0;
38987  }
38988  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
38989  sqlite3_free(zTmpWide);
38990  return zTextMbcs;
38991 }
38992 
38993 /*
38994 ** This is a public wrapper for the winUtf8ToUnicode() function.
38995 */
38996 SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
38997 #ifdef SQLITE_ENABLE_API_ARMOR
38998  if( !zText ){
38999  (void)SQLITE_MISUSE_BKPT;
39000  return 0;
39001  }
39002 #endif
39003 #ifndef SQLITE_OMIT_AUTOINIT
39004  if( sqlite3_initialize() ) return 0;
39005 #endif
39006  return winUtf8ToUnicode(zText);
39007 }
39008 
39009 /*
39010 ** This is a public wrapper for the winUnicodeToUtf8() function.
39011 */
39012 SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
39013 #ifdef SQLITE_ENABLE_API_ARMOR
39014  if( !zWideText ){
39015  (void)SQLITE_MISUSE_BKPT;
39016  return 0;
39017  }
39018 #endif
39019 #ifndef SQLITE_OMIT_AUTOINIT
39020  if( sqlite3_initialize() ) return 0;
39021 #endif
39022  return winUnicodeToUtf8(zWideText);
39023 }
39024 
39025 /*
39026 ** This is a public wrapper for the winMbcsToUtf8() function.
39027 */
39028 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
39029 #ifdef SQLITE_ENABLE_API_ARMOR
39030  if( !zText ){
39031  (void)SQLITE_MISUSE_BKPT;
39032  return 0;
39033  }
39034 #endif
39035 #ifndef SQLITE_OMIT_AUTOINIT
39036  if( sqlite3_initialize() ) return 0;
39037 #endif
39038  return winMbcsToUtf8(zText, osAreFileApisANSI());
39039 }
39040 
39041 /*
39042 ** This is a public wrapper for the winMbcsToUtf8() function.
39043 */
39044 SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
39045 #ifdef SQLITE_ENABLE_API_ARMOR
39046  if( !zText ){
39047  (void)SQLITE_MISUSE_BKPT;
39048  return 0;
39049  }
39050 #endif
39051 #ifndef SQLITE_OMIT_AUTOINIT
39052  if( sqlite3_initialize() ) return 0;
39053 #endif
39054  return winMbcsToUtf8(zText, useAnsi);
39055 }
39056 
39057 /*
39058 ** This is a public wrapper for the winUtf8ToMbcs() function.
39059 */
39060 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
39061 #ifdef SQLITE_ENABLE_API_ARMOR
39062  if( !zText ){
39063  (void)SQLITE_MISUSE_BKPT;
39064  return 0;
39065  }
39066 #endif
39067 #ifndef SQLITE_OMIT_AUTOINIT
39068  if( sqlite3_initialize() ) return 0;
39069 #endif
39070  return winUtf8ToMbcs(zText, osAreFileApisANSI());
39071 }
39072 
39073 /*
39074 ** This is a public wrapper for the winUtf8ToMbcs() function.
39075 */
39076 SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
39077 #ifdef SQLITE_ENABLE_API_ARMOR
39078  if( !zText ){
39079  (void)SQLITE_MISUSE_BKPT;
39080  return 0;
39081  }
39082 #endif
39083 #ifndef SQLITE_OMIT_AUTOINIT
39084  if( sqlite3_initialize() ) return 0;
39085 #endif
39086  return winUtf8ToMbcs(zText, useAnsi);
39087 }
39088 
39089 /*
39090 ** This function sets the data directory or the temporary directory based on
39091 ** the provided arguments. The type argument must be 1 in order to set the
39092 ** data directory or 2 in order to set the temporary directory. The zValue
39093 ** argument is the name of the directory to use. The return value will be
39094 ** SQLITE_OK if successful.
39095 */
39096 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
39097  char **ppDirectory = 0;
39098 #ifndef SQLITE_OMIT_AUTOINIT
39099  int rc = sqlite3_initialize();
39100  if( rc ) return rc;
39101 #endif
39102  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
39103  ppDirectory = &sqlite3_data_directory;
39104  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
39105  ppDirectory = &sqlite3_temp_directory;
39106  }
39107  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
39108  || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
39109  );
39110  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
39111  if( ppDirectory ){
39112  char *zValueUtf8 = 0;
39113  if( zValue && zValue[0] ){
39114  zValueUtf8 = winUnicodeToUtf8(zValue);
39115  if ( zValueUtf8==0 ){
39116  return SQLITE_NOMEM_BKPT;
39117  }
39118  }
39119  sqlite3_free(*ppDirectory);
39120  *ppDirectory = zValueUtf8;
39121  return SQLITE_OK;
39122  }
39123  return SQLITE_ERROR;
39124 }
39125 
39126 /*
39127 ** The return value of winGetLastErrorMsg
39128 ** is zero if the error message fits in the buffer, or non-zero
39129 ** otherwise (if the message was truncated).
39130 */
39131 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
39132  /* FormatMessage returns 0 on failure. Otherwise it
39133  ** returns the number of TCHARs written to the output
39134  ** buffer, excluding the terminating null char.
39135  */
39136  DWORD dwLen = 0;
39137  char *zOut = 0;
39138 
39139  if( osIsNT() ){
39140 #if SQLITE_OS_WINRT
39141  WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
39142  dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
39143  FORMAT_MESSAGE_IGNORE_INSERTS,
39144  NULL,
39145  lastErrno,
39146  0,
39147  zTempWide,
39148  SQLITE_WIN32_MAX_ERRMSG_CHARS,
39149  0);
39150 #else
39151  LPWSTR zTempWide = NULL;
39152  dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39153  FORMAT_MESSAGE_FROM_SYSTEM |
39154  FORMAT_MESSAGE_IGNORE_INSERTS,
39155  NULL,
39156  lastErrno,
39157  0,
39158  (LPWSTR) &zTempWide,
39159  0,
39160  0);
39161 #endif
39162  if( dwLen > 0 ){
39163  /* allocate a buffer and convert to UTF8 */
39165  zOut = winUnicodeToUtf8(zTempWide);
39167 #if !SQLITE_OS_WINRT
39168  /* free the system buffer allocated by FormatMessage */
39169  osLocalFree(zTempWide);
39170 #endif
39171  }
39172  }
39173 #ifdef SQLITE_WIN32_HAS_ANSI
39174  else{
39175  char *zTemp = NULL;
39176  dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39177  FORMAT_MESSAGE_FROM_SYSTEM |
39178  FORMAT_MESSAGE_IGNORE_INSERTS,
39179  NULL,
39180  lastErrno,
39181  0,
39182  (LPSTR) &zTemp,
39183  0,
39184  0);
39185  if( dwLen > 0 ){
39186  /* allocate a buffer and convert to UTF8 */
39188  zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
39190  /* free the system buffer allocated by FormatMessage */
39191  osLocalFree(zTemp);
39192  }
39193  }
39194 #endif
39195  if( 0 == dwLen ){
39196  sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
39197  }else{
39198  /* copy a maximum of nBuf chars to output buffer */
39199  sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
39200  /* free the UTF8 buffer */
39201  sqlite3_free(zOut);
39202  }
39203  return 0;
39204 }
39205 
39206 /*
39207 **
39208 ** This function - winLogErrorAtLine() - is only ever called via the macro
39209 ** winLogError().
39210 **
39211 ** This routine is invoked after an error occurs in an OS function.
39212 ** It logs a message using sqlite3_log() containing the current value of
39213 ** error code and, if possible, the human-readable equivalent from
39214 ** FormatMessage.
39215 **
39216 ** The first argument passed to the macro should be the error code that
39217 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
39218 ** The two subsequent arguments should be the name of the OS function that
39219 ** failed and the associated file-system path, if any.
39220 */
39221 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
39222 static int winLogErrorAtLine(
39223  int errcode, /* SQLite error code */
39224  DWORD lastErrno, /* Win32 last error */
39225  const char *zFunc, /* Name of OS function that failed */
39226  const char *zPath, /* File path associated with error */
39227  int iLine /* Source line number where error occurred */
39228 ){
39229  char zMsg[500]; /* Human readable error text */
39230  int i; /* Loop counter */
39231 
39232  zMsg[0] = 0;
39233  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
39234  assert( errcode!=SQLITE_OK );
39235  if( zPath==0 ) zPath = "";
39236  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
39237  zMsg[i] = 0;
39238  sqlite3_log(errcode,
39239  "os_win.c:%d: (%lu) %s(%s) - %s",
39240  iLine, lastErrno, zFunc, zPath, zMsg
39241  );
39242 
39243  return errcode;
39244 }
39245 
39246 /*
39247 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
39248 ** will be retried following a locking error - probably caused by
39249 ** antivirus software. Also the initial delay before the first retry.
39250 ** The delay increases linearly with each retry.
39251 */
39252 #ifndef SQLITE_WIN32_IOERR_RETRY
39253 # define SQLITE_WIN32_IOERR_RETRY 10
39254 #endif
39255 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
39256 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
39257 #endif
39258 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
39259 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
39260 
39261 /*
39262 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
39263 ** error code obtained via GetLastError() is eligible to be retried. It
39264 ** must accept the error code DWORD as its only argument and should return
39265 ** non-zero if the error code is transient in nature and the operation
39266 ** responsible for generating the original error might succeed upon being
39267 ** retried. The argument to this macro should be a variable.
39268 **
39269 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
39270 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
39271 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
39272 ** may be used to include additional error codes in the set that should
39273 ** result in the failing I/O operation being retried by the caller. If
39274 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
39275 ** identical to those of the "winIoerrCanRetry1" macro.
39276 */
39277 #if !defined(winIoerrCanRetry1)
39278 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
39279  ((a)==ERROR_SHARING_VIOLATION) || \
39280  ((a)==ERROR_LOCK_VIOLATION) || \
39281  ((a)==ERROR_DEV_NOT_EXIST) || \
39282  ((a)==ERROR_NETNAME_DELETED) || \
39283  ((a)==ERROR_SEM_TIMEOUT) || \
39284  ((a)==ERROR_NETWORK_UNREACHABLE))
39285 #endif
39286 
39287 /*
39288 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
39289 ** to see if it should be retried. Return TRUE to retry. Return FALSE
39290 ** to give up with an error.
39291 */
39292 static int winRetryIoerr(int *pnRetry, DWORD *pError){
39293  DWORD e = osGetLastError();
39294  if( *pnRetry>=winIoerrRetry ){
39295  if( pError ){
39296  *pError = e;
39297  }
39298  return 0;
39299  }
39300  if( winIoerrCanRetry1(e) ){
39301  sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39302  ++*pnRetry;
39303  return 1;
39304  }
39305 #if defined(winIoerrCanRetry2)
39306  else if( winIoerrCanRetry2(e) ){
39307  sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39308  ++*pnRetry;
39309  return 1;
39310  }
39311 #endif
39312  if( pError ){
39313  *pError = e;
39314  }
39315  return 0;
39316 }
39317 
39318 /*
39319 ** Log a I/O error retry episode.
39320 */
39321 static void winLogIoerr(int nRetry, int lineno){
39322  if( nRetry ){
39324  "delayed %dms for lock/sharing conflict at line %d",
39325  winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
39326  );
39327  }
39328 }
39329 
39330 /*
39331 ** This #if does not rely on the SQLITE_OS_WINCE define because the
39332 ** corresponding section in "date.c" cannot use it.
39333 */
39334 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
39335  (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
39336 /*
39337 ** The MSVC CRT on Windows CE may not have a localtime() function.
39338 ** So define a substitute.
39339 */
39340 /* # include <time.h> */
39341 struct tm *__cdecl localtime(const time_t *t)
39342 {
39343  static struct tm y;
39344  FILETIME uTm, lTm;
39345  SYSTEMTIME pTm;
39346  sqlite3_int64 t64;
39347  t64 = *t;
39348  t64 = (t64 + 11644473600)*10000000;
39349  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
39350  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
39351  osFileTimeToLocalFileTime(&uTm,&lTm);
39352  osFileTimeToSystemTime(&lTm,&pTm);
39353  y.tm_year = pTm.wYear - 1900;
39354  y.tm_mon = pTm.wMonth - 1;
39355  y.tm_wday = pTm.wDayOfWeek;
39356  y.tm_mday = pTm.wDay;
39357  y.tm_hour = pTm.wHour;
39358  y.tm_min = pTm.wMinute;
39359  y.tm_sec = pTm.wSecond;
39360  return &y;
39361 }
39362 #endif
39363 
39364 #if SQLITE_OS_WINCE
39365 /*************************************************************************
39366 ** This section contains code for WinCE only.
39367 */
39368 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
39369 
39370 /*
39371 ** Acquire a lock on the handle h
39372 */
39373 static void winceMutexAcquire(HANDLE h){
39374  DWORD dwErr;
39375  do {
39376  dwErr = osWaitForSingleObject(h, INFINITE);
39377  } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
39378 }
39379 /*
39380 ** Release a lock acquired by winceMutexAcquire()
39381 */
39382 #define winceMutexRelease(h) ReleaseMutex(h)
39383 
39384 /*
39385 ** Create the mutex and shared memory used for locking in the file
39386 ** descriptor pFile
39387 */
39388 static int winceCreateLock(const char *zFilename, winFile *pFile){
39389  LPWSTR zTok;
39390  LPWSTR zName;
39391  DWORD lastErrno;
39392  BOOL bLogged = FALSE;
39393  BOOL bInit = TRUE;
39394 
39395  zName = winUtf8ToUnicode(zFilename);
39396  if( zName==0 ){
39397  /* out of memory */
39398  return SQLITE_IOERR_NOMEM_BKPT;
39399  }
39400 
39401  /* Initialize the local lockdata */
39402  memset(&pFile->local, 0, sizeof(pFile->local));
39403 
39404  /* Replace the backslashes from the filename and lowercase it
39405  ** to derive a mutex name. */
39406  zTok = osCharLowerW(zName);
39407  for (;*zTok;zTok++){
39408  if (*zTok == '\\') *zTok = '_';
39409  }
39410 
39411  /* Create/open the named mutex */
39412  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
39413  if (!pFile->hMutex){
39414  pFile->lastErrno = osGetLastError();
39415  sqlite3_free(zName);
39416  return winLogError(SQLITE_IOERR, pFile->lastErrno,
39417  "winceCreateLock1", zFilename);
39418  }
39419 
39420  /* Acquire the mutex before continuing */
39421  winceMutexAcquire(pFile->hMutex);
39422 
39423  /* Since the names of named mutexes, semaphores, file mappings etc are
39424  ** case-sensitive, take advantage of that by uppercasing the mutex name
39425  ** and using that as the shared filemapping name.
39426  */
39427  osCharUpperW(zName);
39428  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
39429  PAGE_READWRITE, 0, sizeof(winceLock),
39430  zName);
39431 
39432  /* Set a flag that indicates we're the first to create the memory so it
39433  ** must be zero-initialized */
39434  lastErrno = osGetLastError();
39435  if (lastErrno == ERROR_ALREADY_EXISTS){
39436  bInit = FALSE;
39437  }
39438 
39439  sqlite3_free(zName);
39440 
39441  /* If we succeeded in making the shared memory handle, map it. */
39442  if( pFile->hShared ){
39443  pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
39444  FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
39445  /* If mapping failed, close the shared memory handle and erase it */
39446  if( !pFile->shared ){
39447  pFile->lastErrno = osGetLastError();
39448  winLogError(SQLITE_IOERR, pFile->lastErrno,
39449  "winceCreateLock2", zFilename);
39450  bLogged = TRUE;
39451  osCloseHandle(pFile->hShared);
39452  pFile->hShared = NULL;
39453  }
39454  }
39455 
39456  /* If shared memory could not be created, then close the mutex and fail */
39457  if( pFile->hShared==NULL ){
39458  if( !bLogged ){
39459  pFile->lastErrno = lastErrno;
39460  winLogError(SQLITE_IOERR, pFile->lastErrno,
39461  "winceCreateLock3", zFilename);
39462  bLogged = TRUE;
39463  }
39464  winceMutexRelease(pFile->hMutex);
39465  osCloseHandle(pFile->hMutex);
39466  pFile->hMutex = NULL;
39467  return SQLITE_IOERR;
39468  }
39469 
39470  /* Initialize the shared memory if we're supposed to */
39471  if( bInit ){
39472  memset(pFile->shared, 0, sizeof(winceLock));
39473  }
39474 
39475  winceMutexRelease(pFile->hMutex);
39476  return SQLITE_OK;
39477 }
39478 
39479 /*
39480 ** Destroy the part of winFile that deals with wince locks
39481 */
39482 static void winceDestroyLock(winFile *pFile){
39483  if (pFile->hMutex){
39484  /* Acquire the mutex */
39485  winceMutexAcquire(pFile->hMutex);
39486 
39487  /* The following blocks should probably assert in debug mode, but they
39488  are to cleanup in case any locks remained open */
39489  if (pFile->local.nReaders){
39490  pFile->shared->nReaders --;
39491  }
39492  if (pFile->local.bReserved){
39493  pFile->shared->bReserved = FALSE;
39494  }
39495  if (pFile->local.bPending){
39496  pFile->shared->bPending = FALSE;
39497  }
39498  if (pFile->local.bExclusive){
39499  pFile->shared->bExclusive = FALSE;
39500  }
39501 
39502  /* De-reference and close our copy of the shared memory handle */
39503  osUnmapViewOfFile(pFile->shared);
39504  osCloseHandle(pFile->hShared);
39505 
39506  /* Done with the mutex */
39507  winceMutexRelease(pFile->hMutex);
39508  osCloseHandle(pFile->hMutex);
39509  pFile->hMutex = NULL;
39510  }
39511 }
39512 
39513 /*
39514 ** An implementation of the LockFile() API of Windows for CE
39515 */
39516 static BOOL winceLockFile(
39517  LPHANDLE phFile,
39518  DWORD dwFileOffsetLow,
39519  DWORD dwFileOffsetHigh,
39520  DWORD nNumberOfBytesToLockLow,
39521  DWORD nNumberOfBytesToLockHigh
39522 ){
39523  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39524  BOOL bReturn = FALSE;
39525 
39526  UNUSED_PARAMETER(dwFileOffsetHigh);
39527  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
39528 
39529  if (!pFile->hMutex) return TRUE;
39530  winceMutexAcquire(pFile->hMutex);
39531 
39532  /* Wanting an exclusive lock? */
39533  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
39534  && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
39535  if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
39536  pFile->shared->bExclusive = TRUE;
39537  pFile->local.bExclusive = TRUE;
39538  bReturn = TRUE;
39539  }
39540  }
39541 
39542  /* Want a read-only lock? */
39543  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
39544  nNumberOfBytesToLockLow == 1){
39545  if (pFile->shared->bExclusive == 0){
39546  pFile->local.nReaders ++;
39547  if (pFile->local.nReaders == 1){
39548  pFile->shared->nReaders ++;
39549  }
39550  bReturn = TRUE;
39551  }
39552  }
39553 
39554  /* Want a pending lock? */
39555  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39556  && nNumberOfBytesToLockLow == 1){
39557  /* If no pending lock has been acquired, then acquire it */
39558  if (pFile->shared->bPending == 0) {
39559  pFile->shared->bPending = TRUE;
39560  pFile->local.bPending = TRUE;
39561  bReturn = TRUE;
39562  }
39563  }
39564 
39565  /* Want a reserved lock? */
39566  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39567  && nNumberOfBytesToLockLow == 1){
39568  if (pFile->shared->bReserved == 0) {
39569  pFile->shared->bReserved = TRUE;
39570  pFile->local.bReserved = TRUE;
39571  bReturn = TRUE;
39572  }
39573  }
39574 
39575  winceMutexRelease(pFile->hMutex);
39576  return bReturn;
39577 }
39578 
39579 /*
39580 ** An implementation of the UnlockFile API of Windows for CE
39581 */
39582 static BOOL winceUnlockFile(
39583  LPHANDLE phFile,
39584  DWORD dwFileOffsetLow,
39585  DWORD dwFileOffsetHigh,
39586  DWORD nNumberOfBytesToUnlockLow,
39587  DWORD nNumberOfBytesToUnlockHigh
39588 ){
39589  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39590  BOOL bReturn = FALSE;
39591 
39592  UNUSED_PARAMETER(dwFileOffsetHigh);
39593  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
39594 
39595  if (!pFile->hMutex) return TRUE;
39596  winceMutexAcquire(pFile->hMutex);
39597 
39598  /* Releasing a reader lock or an exclusive lock */
39599  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
39600  /* Did we have an exclusive lock? */
39601  if (pFile->local.bExclusive){
39602  assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
39603  pFile->local.bExclusive = FALSE;
39604  pFile->shared->bExclusive = FALSE;
39605  bReturn = TRUE;
39606  }
39607 
39608  /* Did we just have a reader lock? */
39609  else if (pFile->local.nReaders){
39610  assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
39611  || nNumberOfBytesToUnlockLow == 1);
39612  pFile->local.nReaders --;
39613  if (pFile->local.nReaders == 0)
39614  {
39615  pFile->shared->nReaders --;
39616  }
39617  bReturn = TRUE;
39618  }
39619  }
39620 
39621  /* Releasing a pending lock */
39622  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39623  && nNumberOfBytesToUnlockLow == 1){
39624  if (pFile->local.bPending){
39625  pFile->local.bPending = FALSE;
39626  pFile->shared->bPending = FALSE;
39627  bReturn = TRUE;
39628  }
39629  }
39630  /* Releasing a reserved lock */
39631  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39632  && nNumberOfBytesToUnlockLow == 1){
39633  if (pFile->local.bReserved) {
39634  pFile->local.bReserved = FALSE;
39635  pFile->shared->bReserved = FALSE;
39636  bReturn = TRUE;
39637  }
39638  }
39639 
39640  winceMutexRelease(pFile->hMutex);
39641  return bReturn;
39642 }
39643 /*
39644 ** End of the special code for wince
39645 *****************************************************************************/
39646 #endif /* SQLITE_OS_WINCE */
39647 
39648 /*
39649 ** Lock a file region.
39650 */
39651 static BOOL winLockFile(
39652  LPHANDLE phFile,
39653  DWORD flags,
39654  DWORD offsetLow,
39655  DWORD offsetHigh,
39656  DWORD numBytesLow,
39657  DWORD numBytesHigh
39658 ){
39659 #if SQLITE_OS_WINCE
39660  /*
39661  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39662  ** API LockFile.
39663  */
39664  return winceLockFile(phFile, offsetLow, offsetHigh,
39665  numBytesLow, numBytesHigh);
39666 #else
39667  if( osIsNT() ){
39668  OVERLAPPED ovlp;
39669  memset(&ovlp, 0, sizeof(OVERLAPPED));
39670  ovlp.Offset = offsetLow;
39671  ovlp.OffsetHigh = offsetHigh;
39672  return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
39673  }else{
39674  return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39675  numBytesHigh);
39676  }
39677 #endif
39678 }
39679 
39680 /*
39681 ** Unlock a file region.
39682  */
39683 static BOOL winUnlockFile(
39684  LPHANDLE phFile,
39685  DWORD offsetLow,
39686  DWORD offsetHigh,
39687  DWORD numBytesLow,
39688  DWORD numBytesHigh
39689 ){
39690 #if SQLITE_OS_WINCE
39691  /*
39692  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39693  ** API UnlockFile.
39694  */
39695  return winceUnlockFile(phFile, offsetLow, offsetHigh,
39696  numBytesLow, numBytesHigh);
39697 #else
39698  if( osIsNT() ){
39699  OVERLAPPED ovlp;
39700  memset(&ovlp, 0, sizeof(OVERLAPPED));
39701  ovlp.Offset = offsetLow;
39702  ovlp.OffsetHigh = offsetHigh;
39703  return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
39704  }else{
39705  return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39706  numBytesHigh);
39707  }
39708 #endif
39709 }
39710 
39711 /*****************************************************************************
39712 ** The next group of routines implement the I/O methods specified
39713 ** by the sqlite3_io_methods object.
39714 ******************************************************************************/
39715 
39716 /*
39717 ** Some Microsoft compilers lack this definition.
39718 */
39719 #ifndef INVALID_SET_FILE_POINTER
39720 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
39721 #endif
39722 
39723 /*
39724 ** Move the current position of the file handle passed as the first
39725 ** argument to offset iOffset within the file. If successful, return 0.
39726 ** Otherwise, set pFile->lastErrno and return non-zero.
39727 */
39728 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
39729 #if !SQLITE_OS_WINRT
39730  LONG upperBits; /* Most sig. 32 bits of new offset */
39731  LONG lowerBits; /* Least sig. 32 bits of new offset */
39732  DWORD dwRet; /* Value returned by SetFilePointer() */
39733  DWORD lastErrno; /* Value returned by GetLastError() */
39734 
39735  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
39736 
39737  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
39738  lowerBits = (LONG)(iOffset & 0xffffffff);
39739 
39740  /* API oddity: If successful, SetFilePointer() returns a dword
39741  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
39742  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
39743  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
39744  ** whether an error has actually occurred, it is also necessary to call
39745  ** GetLastError().
39746  */
39747  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
39748 
39749  if( (dwRet==INVALID_SET_FILE_POINTER
39750  && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
39751  pFile->lastErrno = lastErrno;
39752  winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39753  "winSeekFile", pFile->zPath);
39754  OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39755  return 1;
39756  }
39757 
39758  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39759  return 0;
39760 #else
39761  /*
39762  ** Same as above, except that this implementation works for WinRT.
39763  */
39764 
39765  LARGE_INTEGER x; /* The new offset */
39766  BOOL bRet; /* Value returned by SetFilePointerEx() */
39767 
39768  x.QuadPart = iOffset;
39769  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
39770 
39771  if(!bRet){
39772  pFile->lastErrno = osGetLastError();
39773  winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39774  "winSeekFile", pFile->zPath);
39775  OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39776  return 1;
39777  }
39778 
39779  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39780  return 0;
39781 #endif
39782 }
39783 
39784 #if SQLITE_MAX_MMAP_SIZE>0
39785 /* Forward references to VFS helper methods used for memory mapped files */
39786 static int winMapfile(winFile*, sqlite3_int64);
39787 static int winUnmapfile(winFile*);
39788 #endif
39789 
39790 /*
39791 ** Close a file.
39792 **
39793 ** It is reported that an attempt to close a handle might sometimes
39794 ** fail. This is a very unreasonable result, but Windows is notorious
39795 ** for being unreasonable so I do not doubt that it might happen. If
39796 ** the close fails, we pause for 100 milliseconds and try again. As
39797 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
39798 ** giving up and returning an error.
39799 */
39800 #define MX_CLOSE_ATTEMPT 3
39801 static int winClose(sqlite3_file *id){
39802  int rc, cnt = 0;
39803  winFile *pFile = (winFile*)id;
39804 
39805  assert( id!=0 );
39806 #ifndef SQLITE_OMIT_WAL
39807  assert( pFile->pShm==0 );
39808 #endif
39809  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
39810  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
39811  osGetCurrentProcessId(), pFile, pFile->h));
39812 
39813 #if SQLITE_MAX_MMAP_SIZE>0
39814  winUnmapfile(pFile);
39815 #endif
39816 
39817  do{
39818  rc = osCloseHandle(pFile->h);
39819  /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
39820  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
39821 #if SQLITE_OS_WINCE
39822 #define WINCE_DELETION_ATTEMPTS 3
39823  {
39824  winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
39825  if( pAppData==NULL || !pAppData->bNoLock ){
39826  winceDestroyLock(pFile);
39827  }
39828  }
39829  if( pFile->zDeleteOnClose ){
39830  int cnt = 0;
39831  while(
39832  osDeleteFileW(pFile->zDeleteOnClose)==0
39833  && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
39834  && cnt++ < WINCE_DELETION_ATTEMPTS
39835  ){
39836  sqlite3_win32_sleep(100); /* Wait a little before trying again */
39837  }
39838  sqlite3_free(pFile->zDeleteOnClose);
39839  }
39840 #endif
39841  if( rc ){
39842  pFile->h = NULL;
39843  }
39844  OpenCounter(-1);
39845  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
39846  osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
39847  return rc ? SQLITE_OK
39848  : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
39849  "winClose", pFile->zPath);
39850 }
39851 
39852 /*
39853 ** Read data from a file into a buffer. Return SQLITE_OK if all
39854 ** bytes were read successfully and SQLITE_IOERR if anything goes
39855 ** wrong.
39856 */
39857 static int winRead(
39858  sqlite3_file *id, /* File to read from */
39859  void *pBuf, /* Write content into this buffer */
39860  int amt, /* Number of bytes to read */
39861  sqlite3_int64 offset /* Begin reading at this offset */
39862 ){
39863 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39864  OVERLAPPED overlapped; /* The offset for ReadFile. */
39865 #endif
39866  winFile *pFile = (winFile*)id; /* file handle */
39867  DWORD nRead; /* Number of bytes actually read from file */
39868  int nRetry = 0; /* Number of retrys */
39869 
39870  assert( id!=0 );
39871  assert( amt>0 );
39872  assert( offset>=0 );
39874  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39875  "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39876  pFile->h, pBuf, amt, offset, pFile->locktype));
39877 
39878 #if SQLITE_MAX_MMAP_SIZE>0
39879  /* Deal with as much of this read request as possible by transfering
39880  ** data from the memory mapping using memcpy(). */
39881  if( offset<pFile->mmapSize ){
39882  if( offset+amt <= pFile->mmapSize ){
39883  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
39884  OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39885  osGetCurrentProcessId(), pFile, pFile->h));
39886  return SQLITE_OK;
39887  }else{
39888  int nCopy = (int)(pFile->mmapSize - offset);
39889  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
39890  pBuf = &((u8 *)pBuf)[nCopy];
39891  amt -= nCopy;
39892  offset += nCopy;
39893  }
39894  }
39895 #endif
39896 
39897 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39898  if( winSeekFile(pFile, offset) ){
39899  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39900  osGetCurrentProcessId(), pFile, pFile->h));
39901  return SQLITE_FULL;
39902  }
39903  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
39904 #else
39905  memset(&overlapped, 0, sizeof(OVERLAPPED));
39906  overlapped.Offset = (LONG)(offset & 0xffffffff);
39907  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39908  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
39909  osGetLastError()!=ERROR_HANDLE_EOF ){
39910 #endif
39911  DWORD lastErrno;
39912  if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39913  pFile->lastErrno = lastErrno;
39914  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
39915  osGetCurrentProcessId(), pFile, pFile->h));
39916  return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
39917  "winRead", pFile->zPath);
39918  }
39919  winLogIoerr(nRetry, __LINE__);
39920  if( nRead<(DWORD)amt ){
39921  /* Unread parts of the buffer must be zero-filled */
39922  memset(&((char*)pBuf)[nRead], 0, amt-nRead);
39923  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
39924  osGetCurrentProcessId(), pFile, pFile->h));
39925  return SQLITE_IOERR_SHORT_READ;
39926  }
39927 
39928  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39929  osGetCurrentProcessId(), pFile, pFile->h));
39930  return SQLITE_OK;
39931 }
39932 
39933 /*
39934 ** Write data from a buffer into a file. Return SQLITE_OK on success
39935 ** or some other error code on failure.
39936 */
39937 static int winWrite(
39938  sqlite3_file *id, /* File to write into */
39939  const void *pBuf, /* The bytes to be written */
39940  int amt, /* Number of bytes to write */
39941  sqlite3_int64 offset /* Offset into the file to begin writing at */
39942 ){
39943  int rc = 0; /* True if error has occurred, else false */
39944  winFile *pFile = (winFile*)id; /* File handle */
39945  int nRetry = 0; /* Number of retries */
39946 
39947  assert( amt>0 );
39948  assert( pFile );
39951 
39952  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39953  "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39954  pFile->h, pBuf, amt, offset, pFile->locktype));
39955 
39956 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
39957  /* Deal with as much of this write request as possible by transfering
39958  ** data from the memory mapping using memcpy(). */
39959  if( offset<pFile->mmapSize ){
39960  if( offset+amt <= pFile->mmapSize ){
39961  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
39962  OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39963  osGetCurrentProcessId(), pFile, pFile->h));
39964  return SQLITE_OK;
39965  }else{
39966  int nCopy = (int)(pFile->mmapSize - offset);
39967  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
39968  pBuf = &((u8 *)pBuf)[nCopy];
39969  amt -= nCopy;
39970  offset += nCopy;
39971  }
39972  }
39973 #endif
39974 
39975 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39976  rc = winSeekFile(pFile, offset);
39977  if( rc==0 ){
39978 #else
39979  {
39980 #endif
39981 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39982  OVERLAPPED overlapped; /* The offset for WriteFile. */
39983 #endif
39984  u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
39985  int nRem = amt; /* Number of bytes yet to be written */
39986  DWORD nWrite; /* Bytes written by each WriteFile() call */
39987  DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
39988 
39989 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39990  memset(&overlapped, 0, sizeof(OVERLAPPED));
39991  overlapped.Offset = (LONG)(offset & 0xffffffff);
39992  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39993 #endif
39994 
39995  while( nRem>0 ){
39996 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39997  if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
39998 #else
39999  if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
40000 #endif
40001  if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
40002  break;
40003  }
40004  assert( nWrite==0 || nWrite<=(DWORD)nRem );
40005  if( nWrite==0 || nWrite>(DWORD)nRem ){
40006  lastErrno = osGetLastError();
40007  break;
40008  }
40009 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
40010  offset += nWrite;
40011  overlapped.Offset = (LONG)(offset & 0xffffffff);
40012  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
40013 #endif
40014  aRem += nWrite;
40015  nRem -= nWrite;
40016  }
40017  if( nRem>0 ){
40018  pFile->lastErrno = lastErrno;
40019  rc = 1;
40020  }
40021  }
40022 
40023  if( rc ){
40024  if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
40025  || ( pFile->lastErrno==ERROR_DISK_FULL )){
40026  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
40027  osGetCurrentProcessId(), pFile, pFile->h));
40028  return winLogError(SQLITE_FULL, pFile->lastErrno,
40029  "winWrite1", pFile->zPath);
40030  }
40031  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
40032  osGetCurrentProcessId(), pFile, pFile->h));
40033  return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
40034  "winWrite2", pFile->zPath);
40035  }else{
40036  winLogIoerr(nRetry, __LINE__);
40037  }
40038  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40039  osGetCurrentProcessId(), pFile, pFile->h));
40040  return SQLITE_OK;
40041 }
40042 
40043 /*
40044 ** Truncate an open file to a specified size
40045 */
40046 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
40047  winFile *pFile = (winFile*)id; /* File handle object */
40048  int rc = SQLITE_OK; /* Return code for this function */
40049  DWORD lastErrno;
40050 
40051  assert( pFile );
40053  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
40054  osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
40055 
40056  /* If the user has configured a chunk-size for this file, truncate the
40057  ** file so that it consists of an integer number of chunks (i.e. the
40058  ** actual file size after the operation may be larger than the requested
40059  ** size).
40060  */
40061  if( pFile->szChunk>0 ){
40062  nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
40063  }
40064 
40065  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
40066  if( winSeekFile(pFile, nByte) ){
40067  rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
40068  "winTruncate1", pFile->zPath);
40069  }else if( 0==osSetEndOfFile(pFile->h) &&
40070  ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
40071  pFile->lastErrno = lastErrno;
40072  rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
40073  "winTruncate2", pFile->zPath);
40074  }
40075 
40076 #if SQLITE_MAX_MMAP_SIZE>0
40077  /* If the file was truncated to a size smaller than the currently
40078  ** mapped region, reduce the effective mapping size as well. SQLite will
40079  ** use read() and write() to access data beyond this point from now on.
40080  */
40081  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
40082  pFile->mmapSize = nByte;
40083  }
40084 #endif
40085 
40086  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40087  osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
40088  return rc;
40089 }
40090 
40091 #ifdef SQLITE_TEST
40092 /*
40093 ** Count the number of fullsyncs and normal syncs. This is used to test
40094 ** that syncs and fullsyncs are occuring at the right times.
40095 */
40096 SQLITE_API int sqlite3_sync_count = 0;
40097 SQLITE_API int sqlite3_fullsync_count = 0;
40098 #endif
40099 
40100 /*
40101 ** Make sure all writes to a particular file are committed to disk.
40102 */
40103 static int winSync(sqlite3_file *id, int flags){
40104 #ifndef SQLITE_NO_SYNC
40105  /*
40106  ** Used only when SQLITE_NO_SYNC is not defined.
40107  */
40108  BOOL rc;
40109 #endif
40110 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
40111  defined(SQLITE_HAVE_OS_TRACE)
40112  /*
40113  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
40114  ** OSTRACE() macros.
40115  */
40116  winFile *pFile = (winFile*)id;
40117 #else
40118  UNUSED_PARAMETER(id);
40119 #endif
40120 
40121  assert( pFile );
40122  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
40123  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
40124  || (flags&0x0F)==SQLITE_SYNC_FULL
40125  );
40126 
40127  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
40128  ** line is to test that doing so does not cause any problems.
40129  */
40130  SimulateDiskfullError( return SQLITE_FULL );
40131 
40132  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
40133  osGetCurrentProcessId(), pFile, pFile->h, flags,
40134  pFile->locktype));
40135 
40136 #ifndef SQLITE_TEST
40137  UNUSED_PARAMETER(flags);
40138 #else
40139  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
40140  sqlite3_fullsync_count++;
40141  }
40142  sqlite3_sync_count++;
40143 #endif
40144 
40145  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
40146  ** no-op
40147  */
40148 #ifdef SQLITE_NO_SYNC
40149  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40150  osGetCurrentProcessId(), pFile, pFile->h));
40151  return SQLITE_OK;
40152 #else
40153 #if SQLITE_MAX_MMAP_SIZE>0
40154  if( pFile->pMapRegion ){
40155  if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
40156  OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40157  "rc=SQLITE_OK\n", osGetCurrentProcessId(),
40158  pFile, pFile->pMapRegion));
40159  }else{
40160  pFile->lastErrno = osGetLastError();
40161  OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40162  "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
40163  pFile, pFile->pMapRegion));
40164  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
40165  "winSync1", pFile->zPath);
40166  }
40167  }
40168 #endif
40169  rc = osFlushFileBuffers(pFile->h);
40170  SimulateIOError( rc=FALSE );
40171  if( rc ){
40172  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40173  osGetCurrentProcessId(), pFile, pFile->h));
40174  return SQLITE_OK;
40175  }else{
40176  pFile->lastErrno = osGetLastError();
40177  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
40178  osGetCurrentProcessId(), pFile, pFile->h));
40179  return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
40180  "winSync2", pFile->zPath);
40181  }
40182 #endif
40183 }
40184 
40185 /*
40186 ** Determine the current size of a file in bytes
40187 */
40188 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
40189  winFile *pFile = (winFile*)id;
40190  int rc = SQLITE_OK;
40191 
40192  assert( id!=0 );
40193  assert( pSize!=0 );
40195  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
40196 
40197 #if SQLITE_OS_WINRT
40198  {
40199  FILE_STANDARD_INFO info;
40200  if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
40201  &info, sizeof(info)) ){
40202  *pSize = info.EndOfFile.QuadPart;
40203  }else{
40204  pFile->lastErrno = osGetLastError();
40205  rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40206  "winFileSize", pFile->zPath);
40207  }
40208  }
40209 #else
40210  {
40211  DWORD upperBits;
40212  DWORD lowerBits;
40213  DWORD lastErrno;
40214 
40215  lowerBits = osGetFileSize(pFile->h, &upperBits);
40216  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
40217  if( (lowerBits == INVALID_FILE_SIZE)
40218  && ((lastErrno = osGetLastError())!=NO_ERROR) ){
40219  pFile->lastErrno = lastErrno;
40220  rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40221  "winFileSize", pFile->zPath);
40222  }
40223  }
40224 #endif
40225  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
40226  pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
40227  return rc;
40228 }
40229 
40230 /*
40231 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
40232 */
40233 #ifndef LOCKFILE_FAIL_IMMEDIATELY
40234 # define LOCKFILE_FAIL_IMMEDIATELY 1
40235 #endif
40236 
40237 #ifndef LOCKFILE_EXCLUSIVE_LOCK
40238 # define LOCKFILE_EXCLUSIVE_LOCK 2
40239 #endif
40240 
40241 /*
40242 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
40243 ** When the LockFile function was used, it was always expected to fail
40244 ** immediately if the lock could not be obtained. Also, it always expected to
40245 ** obtain an exclusive lock. These flags are used with the LockFileEx function
40246 ** and reflect those expectations; therefore, they should not be changed.
40247 */
40248 #ifndef SQLITE_LOCKFILE_FLAGS
40249 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
40250  LOCKFILE_EXCLUSIVE_LOCK)
40251 #endif
40252 
40253 /*
40254 ** Currently, SQLite never calls the LockFileEx function without wanting the
40255 ** call to fail immediately if the lock cannot be obtained.
40256 */
40257 #ifndef SQLITE_LOCKFILEEX_FLAGS
40258 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
40259 #endif
40260 
40261 /*
40262 ** Acquire a reader lock.
40263 ** Different API routines are called depending on whether or not this
40264 ** is Win9x or WinNT.
40265 */
40266 static int winGetReadLock(winFile *pFile){
40267  int res;
40268  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40269  if( osIsNT() ){
40270 #if SQLITE_OS_WINCE
40271  /*
40272  ** NOTE: Windows CE is handled differently here due its lack of the Win32
40273  ** API LockFileEx.
40274  */
40275  res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
40276 #else
40277  res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
40278  SHARED_SIZE, 0);
40279 #endif
40280  }
40281 #ifdef SQLITE_WIN32_HAS_ANSI
40282  else{
40283  int lk;
40284  sqlite3_randomness(sizeof(lk), &lk);
40285  pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
40286  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40287  SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40288  }
40289 #endif
40290  if( res == 0 ){
40291  pFile->lastErrno = osGetLastError();
40292  /* No need to log a failure to lock */
40293  }
40294  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
40295  return res;
40296 }
40297 
40298 /*
40299 ** Undo a readlock
40300 */
40301 static int winUnlockReadLock(winFile *pFile){
40302  int res;
40303  DWORD lastErrno;
40304  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40305  if( osIsNT() ){
40306  res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40307  }
40308 #ifdef SQLITE_WIN32_HAS_ANSI
40309  else{
40310  res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40311  }
40312 #endif
40313  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
40314  pFile->lastErrno = lastErrno;
40315  winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
40316  "winUnlockReadLock", pFile->zPath);
40317  }
40318  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
40319  return res;
40320 }
40321 
40322 /*
40323 ** Lock the file with the lock specified by parameter locktype - one
40324 ** of the following:
40325 **
40326 ** (1) SHARED_LOCK
40327 ** (2) RESERVED_LOCK
40328 ** (3) PENDING_LOCK
40329 ** (4) EXCLUSIVE_LOCK
40330 **
40331 ** Sometimes when requesting one lock state, additional lock states
40332 ** are inserted in between. The locking might fail on one of the later
40333 ** transitions leaving the lock state different from what it started but
40334 ** still short of its goal. The following chart shows the allowed
40335 ** transitions and the inserted intermediate states:
40336 **
40337 ** UNLOCKED -> SHARED
40338 ** SHARED -> RESERVED
40339 ** SHARED -> (PENDING) -> EXCLUSIVE
40340 ** RESERVED -> (PENDING) -> EXCLUSIVE
40341 ** PENDING -> EXCLUSIVE
40342 **
40343 ** This routine will only increase a lock. The winUnlock() routine
40344 ** erases all locks at once and returns us immediately to locking level 0.
40345 ** It is not possible to lower the locking level one step at a time. You
40346 ** must go straight to locking level 0.
40347 */
40348 static int winLock(sqlite3_file *id, int locktype){
40349  int rc = SQLITE_OK; /* Return code from subroutines */
40350  int res = 1; /* Result of a Windows lock call */
40351  int newLocktype; /* Set pFile->locktype to this value before exiting */
40352  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
40353  winFile *pFile = (winFile*)id;
40354  DWORD lastErrno = NO_ERROR;
40355 
40356  assert( id!=0 );
40357  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40358  pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40359 
40360  /* If there is already a lock of this type or more restrictive on the
40361  ** OsFile, do nothing. Don't use the end_lock: exit path, as
40362  ** sqlite3OsEnterMutex() hasn't been called yet.
40363  */
40364  if( pFile->locktype>=locktype ){
40365  OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
40366  return SQLITE_OK;
40367  }
40368 
40369  /* Do not allow any kind of write-lock on a read-only database
40370  */
40371  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
40372  return SQLITE_IOERR_LOCK;
40373  }
40374 
40375  /* Make sure the locking sequence is correct
40376  */
40377  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
40378  assert( locktype!=PENDING_LOCK );
40379  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
40380 
40381  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
40382  ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
40383  ** the PENDING_LOCK byte is temporary.
40384  */
40385  newLocktype = pFile->locktype;
40386  if( pFile->locktype==NO_LOCK
40387  || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
40388  ){
40389  int cnt = 3;
40390  while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40391  PENDING_BYTE, 0, 1, 0))==0 ){
40392  /* Try 3 times to get the pending lock. This is needed to work
40393  ** around problems caused by indexing and/or anti-virus software on
40394  ** Windows systems.
40395  ** If you are using this code as a model for alternative VFSes, do not
40396  ** copy this retry logic. It is a hack intended for Windows only.
40397  */
40398  lastErrno = osGetLastError();
40399  OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
40400  pFile->h, cnt, res));
40401  if( lastErrno==ERROR_INVALID_HANDLE ){
40402  pFile->lastErrno = lastErrno;
40403  rc = SQLITE_IOERR_LOCK;
40404  OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
40405  pFile->h, cnt, sqlite3ErrName(rc)));
40406  return rc;
40407  }
40408  if( cnt ) sqlite3_win32_sleep(1);
40409  }
40410  gotPendingLock = res;
40411  if( !res ){
40412  lastErrno = osGetLastError();
40413  }
40414  }
40415 
40416  /* Acquire a shared lock
40417  */
40418  if( locktype==SHARED_LOCK && res ){
40419  assert( pFile->locktype==NO_LOCK );
40420  res = winGetReadLock(pFile);
40421  if( res ){
40422  newLocktype = SHARED_LOCK;
40423  }else{
40424  lastErrno = osGetLastError();
40425  }
40426  }
40427 
40428  /* Acquire a RESERVED lock
40429  */
40430  if( locktype==RESERVED_LOCK && res ){
40431  assert( pFile->locktype==SHARED_LOCK );
40432  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
40433  if( res ){
40434  newLocktype = RESERVED_LOCK;
40435  }else{
40436  lastErrno = osGetLastError();
40437  }
40438  }
40439 
40440  /* Acquire a PENDING lock
40441  */
40442  if( locktype==EXCLUSIVE_LOCK && res ){
40443  newLocktype = PENDING_LOCK;
40444  gotPendingLock = 0;
40445  }
40446 
40447  /* Acquire an EXCLUSIVE lock
40448  */
40449  if( locktype==EXCLUSIVE_LOCK && res ){
40450  assert( pFile->locktype>=SHARED_LOCK );
40451  res = winUnlockReadLock(pFile);
40452  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
40453  SHARED_SIZE, 0);
40454  if( res ){
40455  newLocktype = EXCLUSIVE_LOCK;
40456  }else{
40457  lastErrno = osGetLastError();
40458  winGetReadLock(pFile);
40459  }
40460  }
40461 
40462  /* If we are holding a PENDING lock that ought to be released, then
40463  ** release it now.
40464  */
40465  if( gotPendingLock && locktype==SHARED_LOCK ){
40466  winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40467  }
40468 
40469  /* Update the state of the lock has held in the file descriptor then
40470  ** return the appropriate result code.
40471  */
40472  if( res ){
40473  rc = SQLITE_OK;
40474  }else{
40475  pFile->lastErrno = lastErrno;
40476  rc = SQLITE_BUSY;
40477  OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
40478  pFile->h, locktype, newLocktype));
40479  }
40480  pFile->locktype = (u8)newLocktype;
40481  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
40482  pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40483  return rc;
40484 }
40485 
40486 /*
40487 ** This routine checks if there is a RESERVED lock held on the specified
40488 ** file by this or any other process. If such a lock is held, return
40489 ** non-zero, otherwise zero.
40490 */
40491 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
40492  int res;
40493  winFile *pFile = (winFile*)id;
40494 
40496  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
40497 
40498  assert( id!=0 );
40499  if( pFile->locktype>=RESERVED_LOCK ){
40500  res = 1;
40501  OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
40502  }else{
40503  res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
40504  if( res ){
40505  winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40506  }
40507  res = !res;
40508  OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
40509  }
40510  *pResOut = res;
40511  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
40512  pFile->h, pResOut, *pResOut));
40513  return SQLITE_OK;
40514 }
40515 
40516 /*
40517 ** Lower the locking level on file descriptor id to locktype. locktype
40518 ** must be either NO_LOCK or SHARED_LOCK.
40519 **
40520 ** If the locking level of the file descriptor is already at or below
40521 ** the requested locking level, this routine is a no-op.
40522 **
40523 ** It is not possible for this routine to fail if the second argument
40524 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
40525 ** might return SQLITE_IOERR;
40526 */
40527 static int winUnlock(sqlite3_file *id, int locktype){
40528  int type;
40529  winFile *pFile = (winFile*)id;
40530  int rc = SQLITE_OK;
40531  assert( pFile!=0 );
40532  assert( locktype<=SHARED_LOCK );
40533  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40534  pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40535  type = pFile->locktype;
40536  if( type>=EXCLUSIVE_LOCK ){
40537  winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40538  if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
40539  /* This should never happen. We should always be able to
40540  ** reacquire the read lock */
40541  rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
40542  "winUnlock", pFile->zPath);
40543  }
40544  }
40545  if( type>=RESERVED_LOCK ){
40546  winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40547  }
40548  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
40549  winUnlockReadLock(pFile);
40550  }
40551  if( type>=PENDING_LOCK ){
40552  winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40553  }
40554  pFile->locktype = (u8)locktype;
40555  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
40556  pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40557  return rc;
40558 }
40559 
40560 /******************************************************************************
40561 ****************************** No-op Locking **********************************
40562 **
40563 ** Of the various locking implementations available, this is by far the
40564 ** simplest: locking is ignored. No attempt is made to lock the database
40565 ** file for reading or writing.
40566 **
40567 ** This locking mode is appropriate for use on read-only databases
40568 ** (ex: databases that are burned into CD-ROM, for example.) It can
40569 ** also be used if the application employs some external mechanism to
40570 ** prevent simultaneous access of the same database by two or more
40571 ** database connections. But there is a serious risk of database
40572 ** corruption if this locking mode is used in situations where multiple
40573 ** database connections are accessing the same database file at the same
40574 ** time and one or more of those connections are writing.
40575 */
40576 
40577 static int winNolockLock(sqlite3_file *id, int locktype){
40578  UNUSED_PARAMETER(id);
40579  UNUSED_PARAMETER(locktype);
40580  return SQLITE_OK;
40581 }
40582 
40583 static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
40584  UNUSED_PARAMETER(id);
40585  UNUSED_PARAMETER(pResOut);
40586  return SQLITE_OK;
40587 }
40588 
40589 static int winNolockUnlock(sqlite3_file *id, int locktype){
40590  UNUSED_PARAMETER(id);
40591  UNUSED_PARAMETER(locktype);
40592  return SQLITE_OK;
40593 }
40594 
40595 /******************* End of the no-op lock implementation *********************
40596 ******************************************************************************/
40597 
40598 /*
40599 ** If *pArg is initially negative then this is a query. Set *pArg to
40600 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
40601 **
40602 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
40603 */
40604 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
40605  if( *pArg<0 ){
40606  *pArg = (pFile->ctrlFlags & mask)!=0;
40607  }else if( (*pArg)==0 ){
40608  pFile->ctrlFlags &= ~mask;
40609  }else{
40610  pFile->ctrlFlags |= mask;
40611  }
40612 }
40613 
40614 /* Forward references to VFS helper methods used for temporary files */
40615 static int winGetTempname(sqlite3_vfs *, char **);
40616 static int winIsDir(const void *);
40617 static BOOL winIsDriveLetterAndColon(const char *);
40618 
40619 /*
40620 ** Control and query of the open file handle.
40621 */
40622 static int winFileControl(sqlite3_file *id, int op, void *pArg){
40623  winFile *pFile = (winFile*)id;
40624  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
40625  switch( op ){
40626  case SQLITE_FCNTL_LOCKSTATE: {
40627  *(int*)pArg = pFile->locktype;
40628  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40629  return SQLITE_OK;
40630  }
40631  case SQLITE_FCNTL_LAST_ERRNO: {
40632  *(int*)pArg = (int)pFile->lastErrno;
40633  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40634  return SQLITE_OK;
40635  }
40636  case SQLITE_FCNTL_CHUNK_SIZE: {
40637  pFile->szChunk = *(int *)pArg;
40638  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40639  return SQLITE_OK;
40640  }
40641  case SQLITE_FCNTL_SIZE_HINT: {
40642  if( pFile->szChunk>0 ){
40643  sqlite3_int64 oldSz;
40644  int rc = winFileSize(id, &oldSz);
40645  if( rc==SQLITE_OK ){
40646  sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
40647  if( newSz>oldSz ){
40649  rc = winTruncate(id, newSz);
40651  }
40652  }
40653  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40654  return rc;
40655  }
40656  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40657  return SQLITE_OK;
40658  }
40659  case SQLITE_FCNTL_PERSIST_WAL: {
40660  winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
40661  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40662  return SQLITE_OK;
40663  }
40665  winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
40666  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40667  return SQLITE_OK;
40668  }
40669  case SQLITE_FCNTL_VFSNAME: {
40670  *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
40671  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40672  return SQLITE_OK;
40673  }
40675  int *a = (int*)pArg;
40676  if( a[0]>0 ){
40677  winIoerrRetry = a[0];
40678  }else{
40679  a[0] = winIoerrRetry;
40680  }
40681  if( a[1]>0 ){
40682  winIoerrRetryDelay = a[1];
40683  }else{
40684  a[1] = winIoerrRetryDelay;
40685  }
40686  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40687  return SQLITE_OK;
40688  }
40690  LPHANDLE phFile = (LPHANDLE)pArg;
40691  *phFile = pFile->h;
40692  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40693  return SQLITE_OK;
40694  }
40695 #ifdef SQLITE_TEST
40697  LPHANDLE phFile = (LPHANDLE)pArg;
40698  HANDLE hOldFile = pFile->h;
40699  pFile->h = *phFile;
40700  *phFile = hOldFile;
40701  OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
40702  hOldFile, pFile->h));
40703  return SQLITE_OK;
40704  }
40705 #endif
40707  char *zTFile = 0;
40708  int rc = winGetTempname(pFile->pVfs, &zTFile);
40709  if( rc==SQLITE_OK ){
40710  *(char**)pArg = zTFile;
40711  }
40712  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40713  return rc;
40714  }
40715 #if SQLITE_MAX_MMAP_SIZE>0
40716  case SQLITE_FCNTL_MMAP_SIZE: {
40717  i64 newLimit = *(i64*)pArg;
40718  int rc = SQLITE_OK;
40719  if( newLimit>sqlite3GlobalConfig.mxMmap ){
40720  newLimit = sqlite3GlobalConfig.mxMmap;
40721  }
40722  *(i64*)pArg = pFile->mmapSizeMax;
40723  if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
40724  pFile->mmapSizeMax = newLimit;
40725  if( pFile->mmapSize>0 ){
40726  winUnmapfile(pFile);
40727  rc = winMapfile(pFile, -1);
40728  }
40729  }
40730  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40731  return rc;
40732  }
40733 #endif
40734  }
40735  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
40736  return SQLITE_NOTFOUND;
40737 }
40738 
40739 /*
40740 ** Return the sector size in bytes of the underlying block device for
40741 ** the specified file. This is almost always 512 bytes, but may be
40742 ** larger for some devices.
40743 **
40744 ** SQLite code assumes this function cannot fail. It also assumes that
40745 ** if two files are created in the same file-system directory (i.e.
40746 ** a database and its journal file) that the sector size will be the
40747 ** same for both.
40748 */
40749 static int winSectorSize(sqlite3_file *id){
40750  (void)id;
40752 }
40753 
40754 /*
40755 ** Return a vector of device characteristics.
40756 */
40757 static int winDeviceCharacteristics(sqlite3_file *id){
40758  winFile *p = (winFile*)id;
40760  ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
40761 }
40762 
40763 /*
40764 ** Windows will only let you create file view mappings
40765 ** on allocation size granularity boundaries.
40766 ** During sqlite3_os_init() we do a GetSystemInfo()
40767 ** to get the granularity size.
40768 */
40769 static SYSTEM_INFO winSysInfo;
40770 
40771 #ifndef SQLITE_OMIT_WAL
40772 
40773 /*
40774 ** Helper functions to obtain and relinquish the global mutex. The
40775 ** global mutex is used to protect the winLockInfo objects used by
40776 ** this file, all of which may be shared by multiple threads.
40777 **
40778 ** Function winShmMutexHeld() is used to assert() that the global mutex
40779 ** is held when required. This function is only used as part of assert()
40780 ** statements. e.g.
40781 **
40782 ** winShmEnterMutex()
40783 ** assert( winShmMutexHeld() );
40784 ** winShmLeaveMutex()
40785 */
40786 static void winShmEnterMutex(void){
40788 }
40789 static void winShmLeaveMutex(void){
40791 }
40792 #ifndef NDEBUG
40793 static int winShmMutexHeld(void) {
40795 }
40796 #endif
40797 
40798 /*
40799 ** Object used to represent a single file opened and mmapped to provide
40800 ** shared memory. When multiple threads all reference the same
40801 ** log-summary, each thread has its own winFile object, but they all
40802 ** point to a single instance of this object. In other words, each
40803 ** log-summary is opened only once per process.
40804 **
40805 ** winShmMutexHeld() must be true when creating or destroying
40806 ** this object or while reading or writing the following fields:
40807 **
40808 ** nRef
40809 ** pNext
40810 **
40811 ** The following fields are read-only after the object is created:
40812 **
40813 ** fid
40814 ** zFilename
40815 **
40816 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
40817 ** winShmMutexHeld() is true when reading or writing any other field
40818 ** in this structure.
40819 **
40820 */
40821 struct winShmNode {
40822  sqlite3_mutex *mutex; /* Mutex to access this object */
40823  char *zFilename; /* Name of the file */
40824  winFile hFile; /* File handle from winOpen */
40825 
40826  int szRegion; /* Size of shared-memory regions */
40827  int nRegion; /* Size of array apRegion */
40828  struct ShmRegion {
40829  HANDLE hMap; /* File handle from CreateFileMapping */
40830  void *pMap;
40831  } *aRegion;
40832  DWORD lastErrno; /* The Windows errno from the last I/O error */
40833 
40834  int nRef; /* Number of winShm objects pointing to this */
40835  winShm *pFirst; /* All winShm objects pointing to this */
40836  winShmNode *pNext; /* Next in list of all winShmNode objects */
40837 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40838  u8 nextShmId; /* Next available winShm.id value */
40839 #endif
40840 };
40841 
40842 /*
40843 ** A global array of all winShmNode objects.
40844 **
40845 ** The winShmMutexHeld() must be true while reading or writing this list.
40846 */
40847 static winShmNode *winShmNodeList = 0;
40848 
40849 /*
40850 ** Structure used internally by this VFS to record the state of an
40851 ** open shared memory connection.
40852 **
40853 ** The following fields are initialized when this object is created and
40854 ** are read-only thereafter:
40855 **
40856 ** winShm.pShmNode
40857 ** winShm.id
40858 **
40859 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
40860 ** while accessing any read/write fields.
40861 */
40862 struct winShm {
40863  winShmNode *pShmNode; /* The underlying winShmNode object */
40864  winShm *pNext; /* Next winShm with the same winShmNode */
40865  u8 hasMutex; /* True if holding the winShmNode mutex */
40866  u16 sharedMask; /* Mask of shared locks held */
40867  u16 exclMask; /* Mask of exclusive locks held */
40868 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40869  u8 id; /* Id of this connection with its winShmNode */
40870 #endif
40871 };
40872 
40873 /*
40874 ** Constants used for locking
40875 */
40876 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
40877 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
40878 
40879 /*
40880 ** Apply advisory locks for all n bytes beginning at ofst.
40881 */
40882 #define WINSHM_UNLCK 1
40883 #define WINSHM_RDLCK 2
40884 #define WINSHM_WRLCK 3
40885 static int winShmSystemLock(
40886  winShmNode *pFile, /* Apply locks to this open shared-memory segment */
40887  int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
40888  int ofst, /* Offset to first byte to be locked/unlocked */
40889  int nByte /* Number of bytes to lock or unlock */
40890 ){
40891  int rc = 0; /* Result code form Lock/UnlockFileEx() */
40892 
40893  /* Access to the winShmNode object is serialized by the caller */
40894  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
40895 
40896  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
40897  pFile->hFile.h, lockType, ofst, nByte));
40898 
40899  /* Release/Acquire the system-level lock */
40900  if( lockType==WINSHM_UNLCK ){
40901  rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
40902  }else{
40903  /* Initialize the locking parameters */
40904  DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
40905  if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
40906  rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
40907  }
40908 
40909  if( rc!= 0 ){
40910  rc = SQLITE_OK;
40911  }else{
40912  pFile->lastErrno = osGetLastError();
40913  rc = SQLITE_BUSY;
40914  }
40915 
40916  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
40917  pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
40918  "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
40919 
40920  return rc;
40921 }
40922 
40923 /* Forward references to VFS methods */
40924 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
40925 static int winDelete(sqlite3_vfs *,const char*,int);
40926 
40927 /*
40928 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
40929 **
40930 ** This is not a VFS shared-memory method; it is a utility function called
40931 ** by VFS shared-memory methods.
40932 */
40933 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
40934  winShmNode **pp;
40935  winShmNode *p;
40936  assert( winShmMutexHeld() );
40937  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
40938  osGetCurrentProcessId(), deleteFlag));
40939  pp = &winShmNodeList;
40940  while( (p = *pp)!=0 ){
40941  if( p->nRef==0 ){
40942  int i;
40943  if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
40944  for(i=0; i<p->nRegion; i++){
40945  BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
40946  OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
40947  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40948  UNUSED_VARIABLE_VALUE(bRc);
40949  bRc = osCloseHandle(p->aRegion[i].hMap);
40950  OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
40951  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40952  UNUSED_VARIABLE_VALUE(bRc);
40953  }
40954  if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
40956  winClose((sqlite3_file *)&p->hFile);
40958  }
40959  if( deleteFlag ){
40962  winDelete(pVfs, p->zFilename, 0);
40965  }
40966  *pp = p->pNext;
40967  sqlite3_free(p->aRegion);
40968  sqlite3_free(p);
40969  }else{
40970  pp = &p->pNext;
40971  }
40972  }
40973 }
40974 
40975 /*
40976 ** Open the shared-memory area associated with database file pDbFd.
40977 **
40978 ** When opening a new shared-memory file, if no other instances of that
40979 ** file are currently open, in this process or in other processes, then
40980 ** the file must be truncated to zero length or have its header cleared.
40981 */
40982 static int winOpenSharedMemory(winFile *pDbFd){
40983  struct winShm *p; /* The connection to be opened */
40984  struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
40985  int rc; /* Result code */
40986  struct winShmNode *pNew; /* Newly allocated winShmNode */
40987  int nName; /* Size of zName in bytes */
40988 
40989  assert( pDbFd->pShm==0 ); /* Not previously opened */
40990 
40991  /* Allocate space for the new sqlite3_shm object. Also speculatively
40992  ** allocate space for a new winShmNode and filename.
40993  */
40994  p = sqlite3MallocZero( sizeof(*p) );
40995  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
40996  nName = sqlite3Strlen30(pDbFd->zPath);
40997  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
40998  if( pNew==0 ){
40999  sqlite3_free(p);
41000  return SQLITE_IOERR_NOMEM_BKPT;
41001  }
41002  pNew->zFilename = (char*)&pNew[1];
41003  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
41004  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
41005 
41006  /* Look to see if there is an existing winShmNode that can be used.
41007  ** If no matching winShmNode currently exists, create a new one.
41008  */
41009  winShmEnterMutex();
41010  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
41011  /* TBD need to come up with better match here. Perhaps
41012  ** use FILE_ID_BOTH_DIR_INFO Structure.
41013  */
41014  if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
41015  }
41016  if( pShmNode ){
41017  sqlite3_free(pNew);
41018  }else{
41019  pShmNode = pNew;
41020  pNew = 0;
41021  ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
41022  pShmNode->pNext = winShmNodeList;
41023  winShmNodeList = pShmNode;
41024 
41025  if( sqlite3GlobalConfig.bCoreMutex ){
41026  pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
41027  if( pShmNode->mutex==0 ){
41029  goto shm_open_err;
41030  }
41031  }
41032 
41033  rc = winOpen(pDbFd->pVfs,
41034  pShmNode->zFilename, /* Name of the file (UTF-8) */
41035  (sqlite3_file*)&pShmNode->hFile, /* File handle here */
41037  0);
41038  if( SQLITE_OK!=rc ){
41039  goto shm_open_err;
41040  }
41041 
41042  /* Check to see if another process is holding the dead-man switch.
41043  ** If not, truncate the file to zero length.
41044  */
41045  if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
41046  rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
41047  if( rc!=SQLITE_OK ){
41048  rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
41049  "winOpenShm", pDbFd->zPath);
41050  }
41051  }
41052  if( rc==SQLITE_OK ){
41053  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
41054  rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
41055  }
41056  if( rc ) goto shm_open_err;
41057  }
41058 
41059  /* Make the new connection a child of the winShmNode */
41060  p->pShmNode = pShmNode;
41061 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
41062  p->id = pShmNode->nextShmId++;
41063 #endif
41064  pShmNode->nRef++;
41065  pDbFd->pShm = p;
41066  winShmLeaveMutex();
41067 
41068  /* The reference count on pShmNode has already been incremented under
41069  ** the cover of the winShmEnterMutex() mutex and the pointer from the
41070  ** new (struct winShm) object to the pShmNode has been set. All that is
41071  ** left to do is to link the new object into the linked list starting
41072  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
41073  ** mutex.
41074  */
41075  sqlite3_mutex_enter(pShmNode->mutex);
41076  p->pNext = pShmNode->pFirst;
41077  pShmNode->pFirst = p;
41078  sqlite3_mutex_leave(pShmNode->mutex);
41079  return SQLITE_OK;
41080 
41081  /* Jump here on any error */
41082 shm_open_err:
41083  winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
41084  winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
41085  sqlite3_free(p);
41086  sqlite3_free(pNew);
41087  winShmLeaveMutex();
41088  return rc;
41089 }
41090 
41091 /*
41092 ** Close a connection to shared-memory. Delete the underlying
41093 ** storage if deleteFlag is true.
41094 */
41095 static int winShmUnmap(
41096  sqlite3_file *fd, /* Database holding shared memory */
41097  int deleteFlag /* Delete after closing if true */
41098 ){
41099  winFile *pDbFd; /* Database holding shared-memory */
41100  winShm *p; /* The connection to be closed */
41101  winShmNode *pShmNode; /* The underlying shared-memory file */
41102  winShm **pp; /* For looping over sibling connections */
41103 
41104  pDbFd = (winFile*)fd;
41105  p = pDbFd->pShm;
41106  if( p==0 ) return SQLITE_OK;
41107  pShmNode = p->pShmNode;
41108 
41109  /* Remove connection p from the set of connections associated
41110  ** with pShmNode */
41111  sqlite3_mutex_enter(pShmNode->mutex);
41112  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
41113  *pp = p->pNext;
41114 
41115  /* Free the connection p */
41116  sqlite3_free(p);
41117  pDbFd->pShm = 0;
41118  sqlite3_mutex_leave(pShmNode->mutex);
41119 
41120  /* If pShmNode->nRef has reached 0, then close the underlying
41121  ** shared-memory file, too */
41122  winShmEnterMutex();
41123  assert( pShmNode->nRef>0 );
41124  pShmNode->nRef--;
41125  if( pShmNode->nRef==0 ){
41126  winShmPurge(pDbFd->pVfs, deleteFlag);
41127  }
41128  winShmLeaveMutex();
41129 
41130  return SQLITE_OK;
41131 }
41132 
41133 /*
41134 ** Change the lock state for a shared-memory segment.
41135 */
41136 static int winShmLock(
41137  sqlite3_file *fd, /* Database file holding the shared memory */
41138  int ofst, /* First lock to acquire or release */
41139  int n, /* Number of locks to acquire or release */
41140  int flags /* What to do with the lock */
41141 ){
41142  winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
41143  winShm *p = pDbFd->pShm; /* The shared memory being locked */
41144  winShm *pX; /* For looping over all siblings */
41145  winShmNode *pShmNode = p->pShmNode;
41146  int rc = SQLITE_OK; /* Result code */
41147  u16 mask; /* Mask of locks to take or release */
41148 
41149  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
41150  assert( n>=1 );
41151  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
41153  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
41154  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
41155  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
41156 
41157  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
41158  assert( n>1 || mask==(1<<ofst) );
41159  sqlite3_mutex_enter(pShmNode->mutex);
41160  if( flags & SQLITE_SHM_UNLOCK ){
41161  u16 allMask = 0; /* Mask of locks held by siblings */
41162 
41163  /* See if any siblings hold this same lock */
41164  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41165  if( pX==p ) continue;
41166  assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
41167  allMask |= pX->sharedMask;
41168  }
41169 
41170  /* Unlock the system-level locks */
41171  if( (mask & allMask)==0 ){
41172  rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
41173  }else{
41174  rc = SQLITE_OK;
41175  }
41176 
41177  /* Undo the local locks */
41178  if( rc==SQLITE_OK ){
41179  p->exclMask &= ~mask;
41180  p->sharedMask &= ~mask;
41181  }
41182  }else if( flags & SQLITE_SHM_SHARED ){
41183  u16 allShared = 0; /* Union of locks held by connections other than "p" */
41184 
41185  /* Find out which shared locks are already held by sibling connections.
41186  ** If any sibling already holds an exclusive lock, go ahead and return
41187  ** SQLITE_BUSY.
41188  */
41189  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41190  if( (pX->exclMask & mask)!=0 ){
41191  rc = SQLITE_BUSY;
41192  break;
41193  }
41194  allShared |= pX->sharedMask;
41195  }
41196 
41197  /* Get shared locks at the system level, if necessary */
41198  if( rc==SQLITE_OK ){
41199  if( (allShared & mask)==0 ){
41200  rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
41201  }else{
41202  rc = SQLITE_OK;
41203  }
41204  }
41205 
41206  /* Get the local shared locks */
41207  if( rc==SQLITE_OK ){
41208  p->sharedMask |= mask;
41209  }
41210  }else{
41211  /* Make sure no sibling connections hold locks that will block this
41212  ** lock. If any do, return SQLITE_BUSY right away.
41213  */
41214  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41215  if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
41216  rc = SQLITE_BUSY;
41217  break;
41218  }
41219  }
41220 
41221  /* Get the exclusive locks at the system level. Then if successful
41222  ** also mark the local connection as being locked.
41223  */
41224  if( rc==SQLITE_OK ){
41225  rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
41226  if( rc==SQLITE_OK ){
41227  assert( (p->sharedMask & mask)==0 );
41228  p->exclMask |= mask;
41229  }
41230  }
41231  }
41232  sqlite3_mutex_leave(pShmNode->mutex);
41233  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
41234  osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
41235  sqlite3ErrName(rc)));
41236  return rc;
41237 }
41238 
41239 /*
41240 ** Implement a memory barrier or memory fence on shared memory.
41241 **
41242 ** All loads and stores begun before the barrier must complete before
41243 ** any load or store begun after the barrier.
41244 */
41245 static void winShmBarrier(
41246  sqlite3_file *fd /* Database holding the shared memory */
41247 ){
41248  UNUSED_PARAMETER(fd);
41249  sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
41250  winShmEnterMutex(); /* Also mutex, for redundancy */
41251  winShmLeaveMutex();
41252 }
41253 
41254 /*
41255 ** This function is called to obtain a pointer to region iRegion of the
41256 ** shared-memory associated with the database file fd. Shared-memory regions
41257 ** are numbered starting from zero. Each shared-memory region is szRegion
41258 ** bytes in size.
41259 **
41260 ** If an error occurs, an error code is returned and *pp is set to NULL.
41261 **
41262 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
41263 ** region has not been allocated (by any client, including one running in a
41264 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
41265 ** isWrite is non-zero and the requested shared-memory region has not yet
41266 ** been allocated, it is allocated by this function.
41267 **
41268 ** If the shared-memory region has already been allocated or is allocated by
41269 ** this call as described above, then it is mapped into this processes
41270 ** address space (if it is not already), *pp is set to point to the mapped
41271 ** memory and SQLITE_OK returned.
41272 */
41273 static int winShmMap(
41274  sqlite3_file *fd, /* Handle open on database file */
41275  int iRegion, /* Region to retrieve */
41276  int szRegion, /* Size of regions */
41277  int isWrite, /* True to extend file if necessary */
41278  void volatile **pp /* OUT: Mapped memory */
41279 ){
41280  winFile *pDbFd = (winFile*)fd;
41281  winShm *pShm = pDbFd->pShm;
41282  winShmNode *pShmNode;
41283  int rc = SQLITE_OK;
41284 
41285  if( !pShm ){
41286  rc = winOpenSharedMemory(pDbFd);
41287  if( rc!=SQLITE_OK ) return rc;
41288  pShm = pDbFd->pShm;
41289  }
41290  pShmNode = pShm->pShmNode;
41291 
41292  sqlite3_mutex_enter(pShmNode->mutex);
41293  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
41294 
41295  if( pShmNode->nRegion<=iRegion ){
41296  struct ShmRegion *apNew; /* New aRegion[] array */
41297  int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
41298  sqlite3_int64 sz; /* Current size of wal-index file */
41299 
41300  pShmNode->szRegion = szRegion;
41301 
41302  /* The requested region is not mapped into this processes address space.
41303  ** Check to see if it has been allocated (i.e. if the wal-index file is
41304  ** large enough to contain the requested region).
41305  */
41306  rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
41307  if( rc!=SQLITE_OK ){
41308  rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41309  "winShmMap1", pDbFd->zPath);
41310  goto shmpage_out;
41311  }
41312 
41313  if( sz<nByte ){
41314  /* The requested memory region does not exist. If isWrite is set to
41315  ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
41316  **
41317  ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
41318  ** the requested memory region.
41319  */
41320  if( !isWrite ) goto shmpage_out;
41321  rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
41322  if( rc!=SQLITE_OK ){
41323  rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41324  "winShmMap2", pDbFd->zPath);
41325  goto shmpage_out;
41326  }
41327  }
41328 
41329  /* Map the requested memory region into this processes address space. */
41330  apNew = (struct ShmRegion *)sqlite3_realloc64(
41331  pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
41332  );
41333  if( !apNew ){
41335  goto shmpage_out;
41336  }
41337  pShmNode->aRegion = apNew;
41338 
41339  while( pShmNode->nRegion<=iRegion ){
41340  HANDLE hMap = NULL; /* file-mapping handle */
41341  void *pMap = 0; /* Mapped memory region */
41342 
41343 #if SQLITE_OS_WINRT
41344  hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
41345  NULL, PAGE_READWRITE, nByte, NULL
41346  );
41347 #elif defined(SQLITE_WIN32_HAS_WIDE)
41348  hMap = osCreateFileMappingW(pShmNode->hFile.h,
41349  NULL, PAGE_READWRITE, 0, nByte, NULL
41350  );
41351 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41352  hMap = osCreateFileMappingA(pShmNode->hFile.h,
41353  NULL, PAGE_READWRITE, 0, nByte, NULL
41354  );
41355 #endif
41356  OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
41357  osGetCurrentProcessId(), pShmNode->nRegion, nByte,
41358  hMap ? "ok" : "failed"));
41359  if( hMap ){
41360  int iOffset = pShmNode->nRegion*szRegion;
41361  int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41362 #if SQLITE_OS_WINRT
41363  pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41364  iOffset - iOffsetShift, szRegion + iOffsetShift
41365  );
41366 #else
41367  pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41368  0, iOffset - iOffsetShift, szRegion + iOffsetShift
41369  );
41370 #endif
41371  OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
41372  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
41373  szRegion, pMap ? "ok" : "failed"));
41374  }
41375  if( !pMap ){
41376  pShmNode->lastErrno = osGetLastError();
41377  rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
41378  "winShmMap3", pDbFd->zPath);
41379  if( hMap ) osCloseHandle(hMap);
41380  goto shmpage_out;
41381  }
41382 
41383  pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
41384  pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
41385  pShmNode->nRegion++;
41386  }
41387  }
41388 
41389 shmpage_out:
41390  if( pShmNode->nRegion>iRegion ){
41391  int iOffset = iRegion*szRegion;
41392  int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41393  char *p = (char *)pShmNode->aRegion[iRegion].pMap;
41394  *pp = (void *)&p[iOffsetShift];
41395  }else{
41396  *pp = 0;
41397  }
41398  sqlite3_mutex_leave(pShmNode->mutex);
41399  return rc;
41400 }
41401 
41402 #else
41403 # define winShmMap 0
41404 # define winShmLock 0
41405 # define winShmBarrier 0
41406 # define winShmUnmap 0
41407 #endif /* #ifndef SQLITE_OMIT_WAL */
41408 
41409 /*
41410 ** Cleans up the mapped region of the specified file, if any.
41411 */
41412 #if SQLITE_MAX_MMAP_SIZE>0
41413 static int winUnmapfile(winFile *pFile){
41414  assert( pFile!=0 );
41415  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
41416  "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
41417  osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
41418  pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
41419  if( pFile->pMapRegion ){
41420  if( !osUnmapViewOfFile(pFile->pMapRegion) ){
41421  pFile->lastErrno = osGetLastError();
41422  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
41423  "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
41424  pFile->pMapRegion));
41425  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41426  "winUnmapfile1", pFile->zPath);
41427  }
41428  pFile->pMapRegion = 0;
41429  pFile->mmapSize = 0;
41430  pFile->mmapSizeActual = 0;
41431  }
41432  if( pFile->hMap!=NULL ){
41433  if( !osCloseHandle(pFile->hMap) ){
41434  pFile->lastErrno = osGetLastError();
41435  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
41436  osGetCurrentProcessId(), pFile, pFile->hMap));
41437  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41438  "winUnmapfile2", pFile->zPath);
41439  }
41440  pFile->hMap = NULL;
41441  }
41442  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41443  osGetCurrentProcessId(), pFile));
41444  return SQLITE_OK;
41445 }
41446 
41447 /*
41448 ** Memory map or remap the file opened by file-descriptor pFd (if the file
41449 ** is already mapped, the existing mapping is replaced by the new). Or, if
41450 ** there already exists a mapping for this file, and there are still
41451 ** outstanding xFetch() references to it, this function is a no-op.
41452 **
41453 ** If parameter nByte is non-negative, then it is the requested size of
41454 ** the mapping to create. Otherwise, if nByte is less than zero, then the
41455 ** requested size is the size of the file on disk. The actual size of the
41456 ** created mapping is either the requested size or the value configured
41457 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
41458 **
41459 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
41460 ** recreated as a result of outstanding references) or an SQLite error
41461 ** code otherwise.
41462 */
41463 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
41464  sqlite3_int64 nMap = nByte;
41465  int rc;
41466 
41467  assert( nMap>=0 || pFd->nFetchOut==0 );
41468  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
41469  osGetCurrentProcessId(), pFd, nByte));
41470 
41471  if( pFd->nFetchOut>0 ) return SQLITE_OK;
41472 
41473  if( nMap<0 ){
41474  rc = winFileSize((sqlite3_file*)pFd, &nMap);
41475  if( rc ){
41476  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
41477  osGetCurrentProcessId(), pFd));
41478  return SQLITE_IOERR_FSTAT;
41479  }
41480  }
41481  if( nMap>pFd->mmapSizeMax ){
41482  nMap = pFd->mmapSizeMax;
41483  }
41484  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
41485 
41486  if( nMap==0 && pFd->mmapSize>0 ){
41487  winUnmapfile(pFd);
41488  }
41489  if( nMap!=pFd->mmapSize ){
41490  void *pNew = 0;
41491  DWORD protect = PAGE_READONLY;
41492  DWORD flags = FILE_MAP_READ;
41493 
41494  winUnmapfile(pFd);
41495 #ifdef SQLITE_MMAP_READWRITE
41496  if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
41497  protect = PAGE_READWRITE;
41498  flags |= FILE_MAP_WRITE;
41499  }
41500 #endif
41501 #if SQLITE_OS_WINRT
41502  pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
41503 #elif defined(SQLITE_WIN32_HAS_WIDE)
41504  pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
41505  (DWORD)((nMap>>32) & 0xffffffff),
41506  (DWORD)(nMap & 0xffffffff), NULL);
41507 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41508  pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
41509  (DWORD)((nMap>>32) & 0xffffffff),
41510  (DWORD)(nMap & 0xffffffff), NULL);
41511 #endif
41512  if( pFd->hMap==NULL ){
41513  pFd->lastErrno = osGetLastError();
41514  rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41515  "winMapfile1", pFd->zPath);
41516  /* Log the error, but continue normal operation using xRead/xWrite */
41517  OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
41518  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41519  return SQLITE_OK;
41520  }
41521  assert( (nMap % winSysInfo.dwPageSize)==0 );
41522  assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
41523 #if SQLITE_OS_WINRT
41524  pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
41525 #else
41526  pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
41527 #endif
41528  if( pNew==NULL ){
41529  osCloseHandle(pFd->hMap);
41530  pFd->hMap = NULL;
41531  pFd->lastErrno = osGetLastError();
41532  rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41533  "winMapfile2", pFd->zPath);
41534  /* Log the error, but continue normal operation using xRead/xWrite */
41535  OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
41536  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41537  return SQLITE_OK;
41538  }
41539  pFd->pMapRegion = pNew;
41540  pFd->mmapSize = nMap;
41541  pFd->mmapSizeActual = nMap;
41542  }
41543 
41544  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41545  osGetCurrentProcessId(), pFd));
41546  return SQLITE_OK;
41547 }
41548 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
41549 
41550 /*
41551 ** If possible, return a pointer to a mapping of file fd starting at offset
41552 ** iOff. The mapping must be valid for at least nAmt bytes.
41553 **
41554 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
41555 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
41556 ** Finally, if an error does occur, return an SQLite error code. The final
41557 ** value of *pp is undefined in this case.
41558 **
41559 ** If this function does return a pointer, the caller must eventually
41560 ** release the reference by calling winUnfetch().
41561 */
41562 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
41563 #if SQLITE_MAX_MMAP_SIZE>0
41564  winFile *pFd = (winFile*)fd; /* The underlying database file */
41565 #endif
41566  *pp = 0;
41567 
41568  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
41569  osGetCurrentProcessId(), fd, iOff, nAmt, pp));
41570 
41571 #if SQLITE_MAX_MMAP_SIZE>0
41572  if( pFd->mmapSizeMax>0 ){
41573  if( pFd->pMapRegion==0 ){
41574  int rc = winMapfile(pFd, -1);
41575  if( rc!=SQLITE_OK ){
41576  OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
41577  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41578  return rc;
41579  }
41580  }
41581  if( pFd->mmapSize >= iOff+nAmt ){
41582  *pp = &((u8 *)pFd->pMapRegion)[iOff];
41583  pFd->nFetchOut++;
41584  }
41585  }
41586 #endif
41587 
41588  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
41589  osGetCurrentProcessId(), fd, pp, *pp));
41590  return SQLITE_OK;
41591 }
41592 
41593 /*
41594 ** If the third argument is non-NULL, then this function releases a
41595 ** reference obtained by an earlier call to winFetch(). The second
41596 ** argument passed to this function must be the same as the corresponding
41597 ** argument that was passed to the winFetch() invocation.
41598 **
41599 ** Or, if the third argument is NULL, then this function is being called
41600 ** to inform the VFS layer that, according to POSIX, any existing mapping
41601 ** may now be invalid and should be unmapped.
41602 */
41603 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
41604 #if SQLITE_MAX_MMAP_SIZE>0
41605  winFile *pFd = (winFile*)fd; /* The underlying database file */
41606 
41607  /* If p==0 (unmap the entire file) then there must be no outstanding
41608  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
41609  ** then there must be at least one outstanding. */
41610  assert( (p==0)==(pFd->nFetchOut==0) );
41611 
41612  /* If p!=0, it must match the iOff value. */
41613  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
41614 
41615  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
41616  osGetCurrentProcessId(), pFd, iOff, p));
41617 
41618  if( p ){
41619  pFd->nFetchOut--;
41620  }else{
41621  /* FIXME: If Windows truly always prevents truncating or deleting a
41622  ** file while a mapping is held, then the following winUnmapfile() call
41623  ** is unnecessary can be omitted - potentially improving
41624  ** performance. */
41625  winUnmapfile(pFd);
41626  }
41627 
41628  assert( pFd->nFetchOut>=0 );
41629 #endif
41630 
41631  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41632  osGetCurrentProcessId(), fd));
41633  return SQLITE_OK;
41634 }
41635 
41636 /*
41637 ** Here ends the implementation of all sqlite3_file methods.
41638 **
41639 ********************** End sqlite3_file Methods *******************************
41640 ******************************************************************************/
41641 
41642 /*
41643 ** This vector defines all the methods that can operate on an
41644 ** sqlite3_file for win32.
41645 */
41646 static const sqlite3_io_methods winIoMethod = {
41647  3, /* iVersion */
41648  winClose, /* xClose */
41649  winRead, /* xRead */
41650  winWrite, /* xWrite */
41651  winTruncate, /* xTruncate */
41652  winSync, /* xSync */
41653  winFileSize, /* xFileSize */
41654  winLock, /* xLock */
41655  winUnlock, /* xUnlock */
41656  winCheckReservedLock, /* xCheckReservedLock */
41657  winFileControl, /* xFileControl */
41658  winSectorSize, /* xSectorSize */
41659  winDeviceCharacteristics, /* xDeviceCharacteristics */
41660  winShmMap, /* xShmMap */
41661  winShmLock, /* xShmLock */
41662  winShmBarrier, /* xShmBarrier */
41663  winShmUnmap, /* xShmUnmap */
41664  winFetch, /* xFetch */
41665  winUnfetch /* xUnfetch */
41666 };
41667 
41668 /*
41669 ** This vector defines all the methods that can operate on an
41670 ** sqlite3_file for win32 without performing any locking.
41671 */
41672 static const sqlite3_io_methods winIoNolockMethod = {
41673  3, /* iVersion */
41674  winClose, /* xClose */
41675  winRead, /* xRead */
41676  winWrite, /* xWrite */
41677  winTruncate, /* xTruncate */
41678  winSync, /* xSync */
41679  winFileSize, /* xFileSize */
41680  winNolockLock, /* xLock */
41681  winNolockUnlock, /* xUnlock */
41682  winNolockCheckReservedLock, /* xCheckReservedLock */
41683  winFileControl, /* xFileControl */
41684  winSectorSize, /* xSectorSize */
41685  winDeviceCharacteristics, /* xDeviceCharacteristics */
41686  winShmMap, /* xShmMap */
41687  winShmLock, /* xShmLock */
41688  winShmBarrier, /* xShmBarrier */
41689  winShmUnmap, /* xShmUnmap */
41690  winFetch, /* xFetch */
41691  winUnfetch /* xUnfetch */
41692 };
41693 
41694 static winVfsAppData winAppData = {
41695  &winIoMethod, /* pMethod */
41696  0, /* pAppData */
41697  0 /* bNoLock */
41698 };
41699 
41700 static winVfsAppData winNolockAppData = {
41701  &winIoNolockMethod, /* pMethod */
41702  0, /* pAppData */
41703  1 /* bNoLock */
41704 };
41705 
41706 /****************************************************************************
41707 **************************** sqlite3_vfs methods ****************************
41708 **
41709 ** This division contains the implementation of methods on the
41710 ** sqlite3_vfs object.
41711 */
41712 
41713 #if defined(__CYGWIN__)
41714 /*
41715 ** Convert a filename from whatever the underlying operating system
41716 ** supports for filenames into UTF-8. Space to hold the result is
41717 ** obtained from malloc and must be freed by the calling function.
41718 */
41719 static char *winConvertToUtf8Filename(const void *zFilename){
41720  char *zConverted = 0;
41721  if( osIsNT() ){
41722  zConverted = winUnicodeToUtf8(zFilename);
41723  }
41724 #ifdef SQLITE_WIN32_HAS_ANSI
41725  else{
41726  zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
41727  }
41728 #endif
41729  /* caller will handle out of memory */
41730  return zConverted;
41731 }
41732 #endif
41733 
41734 /*
41735 ** Convert a UTF-8 filename into whatever form the underlying
41736 ** operating system wants filenames in. Space to hold the result
41737 ** is obtained from malloc and must be freed by the calling
41738 ** function.
41739 */
41740 static void *winConvertFromUtf8Filename(const char *zFilename){
41741  void *zConverted = 0;
41742  if( osIsNT() ){
41743  zConverted = winUtf8ToUnicode(zFilename);
41744  }
41745 #ifdef SQLITE_WIN32_HAS_ANSI
41746  else{
41747  zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
41748  }
41749 #endif
41750  /* caller will handle out of memory */
41751  return zConverted;
41752 }
41753 
41754 /*
41755 ** This function returns non-zero if the specified UTF-8 string buffer
41756 ** ends with a directory separator character or one was successfully
41757 ** added to it.
41758 */
41759 static int winMakeEndInDirSep(int nBuf, char *zBuf){
41760  if( zBuf ){
41761  int nLen = sqlite3Strlen30(zBuf);
41762  if( nLen>0 ){
41763  if( winIsDirSep(zBuf[nLen-1]) ){
41764  return 1;
41765  }else if( nLen+1<nBuf ){
41766  zBuf[nLen] = winGetDirSep();
41767  zBuf[nLen+1] = '\0';
41768  return 1;
41769  }
41770  }
41771  }
41772  return 0;
41773 }
41774 
41775 /*
41776 ** Create a temporary file name and store the resulting pointer into pzBuf.
41777 ** The pointer returned in pzBuf must be freed via sqlite3_free().
41778 */
41779 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
41780  static char zChars[] =
41781  "abcdefghijklmnopqrstuvwxyz"
41782  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
41783  "0123456789";
41784  size_t i, j;
41786  int nMax, nBuf, nDir, nLen;
41787  char *zBuf;
41788 
41789  /* It's odd to simulate an io-error here, but really this is just
41790  ** using the io-error infrastructure to test that SQLite handles this
41791  ** function failing.
41792  */
41793  SimulateIOError( return SQLITE_IOERR );
41794 
41795  /* Allocate a temporary buffer to store the fully qualified file
41796  ** name for the temporary file. If this fails, we cannot continue.
41797  */
41798  nMax = pVfs->mxPathname; nBuf = nMax + 2;
41799  zBuf = sqlite3MallocZero( nBuf );
41800  if( !zBuf ){
41801  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41802  return SQLITE_IOERR_NOMEM_BKPT;
41803  }
41804 
41805  /* Figure out the effective temporary directory. First, check if one
41806  ** has been explicitly set by the application; otherwise, use the one
41807  ** configured by the operating system.
41808  */
41809  nDir = nMax - (nPre + 15);
41810  assert( nDir>0 );
41811  if( sqlite3_temp_directory ){
41812  int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
41813  if( nDirLen>0 ){
41814  if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
41815  nDirLen++;
41816  }
41817  if( nDirLen>nDir ){
41818  sqlite3_free(zBuf);
41819  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41820  return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
41821  }
41822  sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
41823  }
41824  }
41825 #if defined(__CYGWIN__)
41826  else{
41827  static const char *azDirs[] = {
41828  0, /* getenv("SQLITE_TMPDIR") */
41829  0, /* getenv("TMPDIR") */
41830  0, /* getenv("TMP") */
41831  0, /* getenv("TEMP") */
41832  0, /* getenv("USERPROFILE") */
41833  "/var/tmp",
41834  "/usr/tmp",
41835  "/tmp",
41836  ".",
41837  0 /* List terminator */
41838  };
41839  unsigned int i;
41840  const char *zDir = 0;
41841 
41842  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
41843  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
41844  if( !azDirs[2] ) azDirs[2] = getenv("TMP");
41845  if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
41846  if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
41847  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
41848  void *zConverted;
41849  if( zDir==0 ) continue;
41850  /* If the path starts with a drive letter followed by the colon
41851  ** character, assume it is already a native Win32 path; otherwise,
41852  ** it must be converted to a native Win32 path via the Cygwin API
41853  ** prior to using it.
41854  */
41855  if( winIsDriveLetterAndColon(zDir) ){
41856  zConverted = winConvertFromUtf8Filename(zDir);
41857  if( !zConverted ){
41858  sqlite3_free(zBuf);
41859  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41860  return SQLITE_IOERR_NOMEM_BKPT;
41861  }
41862  if( winIsDir(zConverted) ){
41863  sqlite3_snprintf(nMax, zBuf, "%s", zDir);
41864  sqlite3_free(zConverted);
41865  break;
41866  }
41867  sqlite3_free(zConverted);
41868  }else{
41869  zConverted = sqlite3MallocZero( nMax+1 );
41870  if( !zConverted ){
41871  sqlite3_free(zBuf);
41872  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41873  return SQLITE_IOERR_NOMEM_BKPT;
41874  }
41875  if( cygwin_conv_path(
41876  osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
41877  zConverted, nMax+1)<0 ){
41878  sqlite3_free(zConverted);
41879  sqlite3_free(zBuf);
41880  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
41881  return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
41882  "winGetTempname2", zDir);
41883  }
41884  if( winIsDir(zConverted) ){
41885  /* At this point, we know the candidate directory exists and should
41886  ** be used. However, we may need to convert the string containing
41887  ** its name into UTF-8 (i.e. if it is UTF-16 right now).
41888  */
41889  char *zUtf8 = winConvertToUtf8Filename(zConverted);
41890  if( !zUtf8 ){
41891  sqlite3_free(zConverted);
41892  sqlite3_free(zBuf);
41893  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41894  return SQLITE_IOERR_NOMEM_BKPT;
41895  }
41896  sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41897  sqlite3_free(zUtf8);
41898  sqlite3_free(zConverted);
41899  break;
41900  }
41901  sqlite3_free(zConverted);
41902  }
41903  }
41904  }
41905 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
41906  else if( osIsNT() ){
41907  char *zMulti;
41908  LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
41909  if( !zWidePath ){
41910  sqlite3_free(zBuf);
41911  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41912  return SQLITE_IOERR_NOMEM_BKPT;
41913  }
41914  if( osGetTempPathW(nMax, zWidePath)==0 ){
41915  sqlite3_free(zWidePath);
41916  sqlite3_free(zBuf);
41917  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41918  return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41919  "winGetTempname2", 0);
41920  }
41921  zMulti = winUnicodeToUtf8(zWidePath);
41922  if( zMulti ){
41923  sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
41924  sqlite3_free(zMulti);
41925  sqlite3_free(zWidePath);
41926  }else{
41927  sqlite3_free(zWidePath);
41928  sqlite3_free(zBuf);
41929  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41930  return SQLITE_IOERR_NOMEM_BKPT;
41931  }
41932  }
41933 #ifdef SQLITE_WIN32_HAS_ANSI
41934  else{
41935  char *zUtf8;
41936  char *zMbcsPath = sqlite3MallocZero( nMax );
41937  if( !zMbcsPath ){
41938  sqlite3_free(zBuf);
41939  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41940  return SQLITE_IOERR_NOMEM_BKPT;
41941  }
41942  if( osGetTempPathA(nMax, zMbcsPath)==0 ){
41943  sqlite3_free(zBuf);
41944  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41945  return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41946  "winGetTempname3", 0);
41947  }
41948  zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
41949  if( zUtf8 ){
41950  sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41951  sqlite3_free(zUtf8);
41952  }else{
41953  sqlite3_free(zBuf);
41954  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41955  return SQLITE_IOERR_NOMEM_BKPT;
41956  }
41957  }
41958 #endif /* SQLITE_WIN32_HAS_ANSI */
41959 #endif /* !SQLITE_OS_WINRT */
41960 
41961  /*
41962  ** Check to make sure the temporary directory ends with an appropriate
41963  ** separator. If it does not and there is not enough space left to add
41964  ** one, fail.
41965  */
41966  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
41967  sqlite3_free(zBuf);
41968  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41969  return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
41970  }
41971 
41972  /*
41973  ** Check that the output buffer is large enough for the temporary file
41974  ** name in the following format:
41975  **
41976  ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
41977  **
41978  ** If not, return SQLITE_ERROR. The number 17 is used here in order to
41979  ** account for the space used by the 15 character random suffix and the
41980  ** two trailing NUL characters. The final directory separator character
41981  ** has already added if it was not already present.
41982  */
41983  nLen = sqlite3Strlen30(zBuf);
41984  if( (nLen + nPre + 17) > nBuf ){
41985  sqlite3_free(zBuf);
41986  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41987  return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
41988  }
41989 
41990  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
41991 
41992  j = sqlite3Strlen30(zBuf);
41993  sqlite3_randomness(15, &zBuf[j]);
41994  for(i=0; i<15; i++, j++){
41995  zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
41996  }
41997  zBuf[j] = 0;
41998  zBuf[j+1] = 0;
41999  *pzBuf = zBuf;
42000 
42001  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
42002  return SQLITE_OK;
42003 }
42004 
42005 /*
42006 ** Return TRUE if the named file is really a directory. Return false if
42007 ** it is something other than a directory, or if there is any kind of memory
42008 ** allocation failure.
42009 */
42010 static int winIsDir(const void *zConverted){
42011  DWORD attr;
42012  int rc = 0;
42013  DWORD lastErrno;
42014 
42015  if( osIsNT() ){
42016  int cnt = 0;
42017  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42018  memset(&sAttrData, 0, sizeof(sAttrData));
42019  while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42020  GetFileExInfoStandard,
42021  &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42022  if( !rc ){
42023  return 0; /* Invalid name? */
42024  }
42025  attr = sAttrData.dwFileAttributes;
42026 #if SQLITE_OS_WINCE==0
42027  }else{
42028  attr = osGetFileAttributesA((char*)zConverted);
42029 #endif
42030  }
42031  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
42032 }
42033 
42034 /*
42035 ** Open a file.
42036 */
42037 static int winOpen(
42038  sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
42039  const char *zName, /* Name of the file (UTF-8) */
42040  sqlite3_file *id, /* Write the SQLite file handle here */
42041  int flags, /* Open mode flags */
42042  int *pOutFlags /* Status return flags */
42043 ){
42044  HANDLE h;
42045  DWORD lastErrno = 0;
42046  DWORD dwDesiredAccess;
42047  DWORD dwShareMode;
42048  DWORD dwCreationDisposition;
42049  DWORD dwFlagsAndAttributes = 0;
42050 #if SQLITE_OS_WINCE
42051  int isTemp = 0;
42052 #endif
42053  winVfsAppData *pAppData;
42054  winFile *pFile = (winFile*)id;
42055  void *zConverted; /* Filename in OS encoding */
42056  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
42057  int cnt = 0;
42058 
42059  /* If argument zPath is a NULL pointer, this function is required to open
42060  ** a temporary file. Use this buffer to store the file name in.
42061  */
42062  char *zTmpname = 0; /* For temporary filename, if necessary. */
42063 
42064  int rc = SQLITE_OK; /* Function Return Code */
42065 #if !defined(NDEBUG) || SQLITE_OS_WINCE
42066  int eType = flags&0xFFFFFF00; /* Type of file to open */
42067 #endif
42068 
42069  int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
42070  int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
42071  int isCreate = (flags & SQLITE_OPEN_CREATE);
42072  int isReadonly = (flags & SQLITE_OPEN_READONLY);
42073  int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
42074 
42075 #ifndef NDEBUG
42076  int isOpenJournal = (isCreate && (
42078  || eType==SQLITE_OPEN_MAIN_JOURNAL
42079  || eType==SQLITE_OPEN_WAL
42080  ));
42081 #endif
42082 
42083  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
42084  zUtf8Name, id, flags, pOutFlags));
42085 
42086  /* Check the following statements are true:
42087  **
42088  ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
42089  ** (b) if CREATE is set, then READWRITE must also be set, and
42090  ** (c) if EXCLUSIVE is set, then CREATE must also be set.
42091  ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
42092  */
42093  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
42094  assert(isCreate==0 || isReadWrite);
42095  assert(isExclusive==0 || isCreate);
42096  assert(isDelete==0 || isCreate);
42097 
42098  /* The main DB, main journal, WAL file and master journal are never
42099  ** automatically deleted. Nor are they ever temporary files. */
42100  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
42101  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
42102  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
42103  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
42104 
42105  /* Assert that the upper layer has set one of the "file-type" flags. */
42106  assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
42109  || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
42110  );
42111 
42112  assert( pFile!=0 );
42113  memset(pFile, 0, sizeof(winFile));
42114  pFile->h = INVALID_HANDLE_VALUE;
42115 
42116 #if SQLITE_OS_WINRT
42117  if( !zUtf8Name && !sqlite3_temp_directory ){
42119  "sqlite3_temp_directory variable should be set for WinRT");
42120  }
42121 #endif
42122 
42123  /* If the second argument to this function is NULL, generate a
42124  ** temporary file name to use
42125  */
42126  if( !zUtf8Name ){
42127  assert( isDelete && !isOpenJournal );
42128  rc = winGetTempname(pVfs, &zTmpname);
42129  if( rc!=SQLITE_OK ){
42130  OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
42131  return rc;
42132  }
42133  zUtf8Name = zTmpname;
42134  }
42135 
42136  /* Database filenames are double-zero terminated if they are not
42137  ** URIs with parameters. Hence, they can always be passed into
42138  ** sqlite3_uri_parameter().
42139  */
42140  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
42141  zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
42142 
42143  /* Convert the filename to the system encoding. */
42144  zConverted = winConvertFromUtf8Filename(zUtf8Name);
42145  if( zConverted==0 ){
42146  sqlite3_free(zTmpname);
42147  OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
42148  return SQLITE_IOERR_NOMEM_BKPT;
42149  }
42150 
42151  if( winIsDir(zConverted) ){
42152  sqlite3_free(zConverted);
42153  sqlite3_free(zTmpname);
42154  OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
42155  return SQLITE_CANTOPEN_ISDIR;
42156  }
42157 
42158  if( isReadWrite ){
42159  dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
42160  }else{
42161  dwDesiredAccess = GENERIC_READ;
42162  }
42163 
42164  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
42165  ** created. SQLite doesn't use it to indicate "exclusive access"
42166  ** as it is usually understood.
42167  */
42168  if( isExclusive ){
42169  /* Creates a new file, only if it does not already exist. */
42170  /* If the file exists, it fails. */
42171  dwCreationDisposition = CREATE_NEW;
42172  }else if( isCreate ){
42173  /* Open existing file, or create if it doesn't exist */
42174  dwCreationDisposition = OPEN_ALWAYS;
42175  }else{
42176  /* Opens a file, only if it exists. */
42177  dwCreationDisposition = OPEN_EXISTING;
42178  }
42179 
42180  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
42181 
42182  if( isDelete ){
42183 #if SQLITE_OS_WINCE
42184  dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
42185  isTemp = 1;
42186 #else
42187  dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
42188  | FILE_ATTRIBUTE_HIDDEN
42189  | FILE_FLAG_DELETE_ON_CLOSE;
42190 #endif
42191  }else{
42192  dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
42193  }
42194  /* Reports from the internet are that performance is always
42195  ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
42196 #if SQLITE_OS_WINCE
42197  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
42198 #endif
42199 
42200  if( osIsNT() ){
42201 #if SQLITE_OS_WINRT
42202  CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
42203  extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
42204  extendedParameters.dwFileAttributes =
42205  dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
42206  extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
42207  extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
42208  extendedParameters.lpSecurityAttributes = NULL;
42209  extendedParameters.hTemplateFile = NULL;
42210  while( (h = osCreateFile2((LPCWSTR)zConverted,
42211  dwDesiredAccess,
42212  dwShareMode,
42213  dwCreationDisposition,
42214  &extendedParameters))==INVALID_HANDLE_VALUE &&
42215  winRetryIoerr(&cnt, &lastErrno) ){
42216  /* Noop */
42217  }
42218 #else
42219  while( (h = osCreateFileW((LPCWSTR)zConverted,
42220  dwDesiredAccess,
42221  dwShareMode, NULL,
42222  dwCreationDisposition,
42223  dwFlagsAndAttributes,
42224  NULL))==INVALID_HANDLE_VALUE &&
42225  winRetryIoerr(&cnt, &lastErrno) ){
42226  /* Noop */
42227  }
42228 #endif
42229  }
42230 #ifdef SQLITE_WIN32_HAS_ANSI
42231  else{
42232  while( (h = osCreateFileA((LPCSTR)zConverted,
42233  dwDesiredAccess,
42234  dwShareMode, NULL,
42235  dwCreationDisposition,
42236  dwFlagsAndAttributes,
42237  NULL))==INVALID_HANDLE_VALUE &&
42238  winRetryIoerr(&cnt, &lastErrno) ){
42239  /* Noop */
42240  }
42241  }
42242 #endif
42243  winLogIoerr(cnt, __LINE__);
42244 
42245  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
42246  dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42247 
42248  if( h==INVALID_HANDLE_VALUE ){
42249  pFile->lastErrno = lastErrno;
42250  winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
42251  sqlite3_free(zConverted);
42252  sqlite3_free(zTmpname);
42253  if( isReadWrite && !isExclusive ){
42254  return winOpen(pVfs, zName, id,
42255  ((flags|SQLITE_OPEN_READONLY) &
42257  pOutFlags);
42258  }else{
42259  return SQLITE_CANTOPEN_BKPT;
42260  }
42261  }
42262 
42263  if( pOutFlags ){
42264  if( isReadWrite ){
42265  *pOutFlags = SQLITE_OPEN_READWRITE;
42266  }else{
42267  *pOutFlags = SQLITE_OPEN_READONLY;
42268  }
42269  }
42270 
42271  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
42272  "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
42273  *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42274 
42275  pAppData = (winVfsAppData*)pVfs->pAppData;
42276 
42277 #if SQLITE_OS_WINCE
42278  {
42279  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
42280  && ((pAppData==NULL) || !pAppData->bNoLock)
42281  && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
42282  ){
42283  osCloseHandle(h);
42284  sqlite3_free(zConverted);
42285  sqlite3_free(zTmpname);
42286  OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
42287  return rc;
42288  }
42289  }
42290  if( isTemp ){
42291  pFile->zDeleteOnClose = zConverted;
42292  }else
42293 #endif
42294  {
42295  sqlite3_free(zConverted);
42296  }
42297 
42298  sqlite3_free(zTmpname);
42299  pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
42300  pFile->pVfs = pVfs;
42301  pFile->h = h;
42302  if( isReadonly ){
42303  pFile->ctrlFlags |= WINFILE_RDONLY;
42304  }
42305  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
42306  pFile->ctrlFlags |= WINFILE_PSOW;
42307  }
42308  pFile->lastErrno = NO_ERROR;
42309  pFile->zPath = zName;
42310 #if SQLITE_MAX_MMAP_SIZE>0
42311  pFile->hMap = NULL;
42312  pFile->pMapRegion = 0;
42313  pFile->mmapSize = 0;
42314  pFile->mmapSizeActual = 0;
42315  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
42316 #endif
42317 
42318  OpenCounter(+1);
42319  return rc;
42320 }
42321 
42322 /*
42323 ** Delete the named file.
42324 **
42325 ** Note that Windows does not allow a file to be deleted if some other
42326 ** process has it open. Sometimes a virus scanner or indexing program
42327 ** will open a journal file shortly after it is created in order to do
42328 ** whatever it does. While this other process is holding the
42329 ** file open, we will be unable to delete it. To work around this
42330 ** problem, we delay 100 milliseconds and try to delete again. Up
42331 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
42332 ** up and returning an error.
42333 */
42334 static int winDelete(
42335  sqlite3_vfs *pVfs, /* Not used on win32 */
42336  const char *zFilename, /* Name of file to delete */
42337  int syncDir /* Not used on win32 */
42338 ){
42339  int cnt = 0;
42340  int rc;
42341  DWORD attr;
42342  DWORD lastErrno = 0;
42343  void *zConverted;
42344  UNUSED_PARAMETER(pVfs);
42345  UNUSED_PARAMETER(syncDir);
42346 
42348  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
42349 
42350  zConverted = winConvertFromUtf8Filename(zFilename);
42351  if( zConverted==0 ){
42352  OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42353  return SQLITE_IOERR_NOMEM_BKPT;
42354  }
42355  if( osIsNT() ){
42356  do {
42357 #if SQLITE_OS_WINRT
42358  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42359  memset(&sAttrData, 0, sizeof(sAttrData));
42360  if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
42361  &sAttrData) ){
42362  attr = sAttrData.dwFileAttributes;
42363  }else{
42364  lastErrno = osGetLastError();
42365  if( lastErrno==ERROR_FILE_NOT_FOUND
42366  || lastErrno==ERROR_PATH_NOT_FOUND ){
42367  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42368  }else{
42369  rc = SQLITE_ERROR;
42370  }
42371  break;
42372  }
42373 #else
42374  attr = osGetFileAttributesW(zConverted);
42375 #endif
42376  if ( attr==INVALID_FILE_ATTRIBUTES ){
42377  lastErrno = osGetLastError();
42378  if( lastErrno==ERROR_FILE_NOT_FOUND
42379  || lastErrno==ERROR_PATH_NOT_FOUND ){
42380  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42381  }else{
42382  rc = SQLITE_ERROR;
42383  }
42384  break;
42385  }
42386  if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42387  rc = SQLITE_ERROR; /* Files only. */
42388  break;
42389  }
42390  if ( osDeleteFileW(zConverted) ){
42391  rc = SQLITE_OK; /* Deleted OK. */
42392  break;
42393  }
42394  if ( !winRetryIoerr(&cnt, &lastErrno) ){
42395  rc = SQLITE_ERROR; /* No more retries. */
42396  break;
42397  }
42398  } while(1);
42399  }
42400 #ifdef SQLITE_WIN32_HAS_ANSI
42401  else{
42402  do {
42403  attr = osGetFileAttributesA(zConverted);
42404  if ( attr==INVALID_FILE_ATTRIBUTES ){
42405  lastErrno = osGetLastError();
42406  if( lastErrno==ERROR_FILE_NOT_FOUND
42407  || lastErrno==ERROR_PATH_NOT_FOUND ){
42408  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42409  }else{
42410  rc = SQLITE_ERROR;
42411  }
42412  break;
42413  }
42414  if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42415  rc = SQLITE_ERROR; /* Files only. */
42416  break;
42417  }
42418  if ( osDeleteFileA(zConverted) ){
42419  rc = SQLITE_OK; /* Deleted OK. */
42420  break;
42421  }
42422  if ( !winRetryIoerr(&cnt, &lastErrno) ){
42423  rc = SQLITE_ERROR; /* No more retries. */
42424  break;
42425  }
42426  } while(1);
42427  }
42428 #endif
42429  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
42430  rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
42431  }else{
42432  winLogIoerr(cnt, __LINE__);
42433  }
42434  sqlite3_free(zConverted);
42435  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
42436  return rc;
42437 }
42438 
42439 /*
42440 ** Check the existence and status of a file.
42441 */
42442 static int winAccess(
42443  sqlite3_vfs *pVfs, /* Not used on win32 */
42444  const char *zFilename, /* Name of file to check */
42445  int flags, /* Type of test to make on this file */
42446  int *pResOut /* OUT: Result */
42447 ){
42448  DWORD attr;
42449  int rc = 0;
42450  DWORD lastErrno = 0;
42451  void *zConverted;
42452  UNUSED_PARAMETER(pVfs);
42453 
42455  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
42456  zFilename, flags, pResOut));
42457 
42458  zConverted = winConvertFromUtf8Filename(zFilename);
42459  if( zConverted==0 ){
42460  OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42461  return SQLITE_IOERR_NOMEM_BKPT;
42462  }
42463  if( osIsNT() ){
42464  int cnt = 0;
42465  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42466  memset(&sAttrData, 0, sizeof(sAttrData));
42467  while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42468  GetFileExInfoStandard,
42469  &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42470  if( rc ){
42471  /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
42472  ** as if it does not exist.
42473  */
42474  if( flags==SQLITE_ACCESS_EXISTS
42475  && sAttrData.nFileSizeHigh==0
42476  && sAttrData.nFileSizeLow==0 ){
42477  attr = INVALID_FILE_ATTRIBUTES;
42478  }else{
42479  attr = sAttrData.dwFileAttributes;
42480  }
42481  }else{
42482  winLogIoerr(cnt, __LINE__);
42483  if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
42484  sqlite3_free(zConverted);
42485  return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
42486  zFilename);
42487  }else{
42488  attr = INVALID_FILE_ATTRIBUTES;
42489  }
42490  }
42491  }
42492 #ifdef SQLITE_WIN32_HAS_ANSI
42493  else{
42494  attr = osGetFileAttributesA((char*)zConverted);
42495  }
42496 #endif
42497  sqlite3_free(zConverted);
42498  switch( flags ){
42499  case SQLITE_ACCESS_READ:
42500  case SQLITE_ACCESS_EXISTS:
42501  rc = attr!=INVALID_FILE_ATTRIBUTES;
42502  break;
42504  rc = attr!=INVALID_FILE_ATTRIBUTES &&
42505  (attr & FILE_ATTRIBUTE_READONLY)==0;
42506  break;
42507  default:
42508  assert(!"Invalid flags argument");
42509  }
42510  *pResOut = rc;
42511  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
42512  zFilename, pResOut, *pResOut));
42513  return SQLITE_OK;
42514 }
42515 
42516 /*
42517 ** Returns non-zero if the specified path name starts with a drive letter
42518 ** followed by a colon character.
42519 */
42520 static BOOL winIsDriveLetterAndColon(
42521  const char *zPathname
42522 ){
42523  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
42524 }
42525 
42526 /*
42527 ** Returns non-zero if the specified path name should be used verbatim. If
42528 ** non-zero is returned from this function, the calling function must simply
42529 ** use the provided path name verbatim -OR- resolve it into a full path name
42530 ** using the GetFullPathName Win32 API function (if available).
42531 */
42532 static BOOL winIsVerbatimPathname(
42533  const char *zPathname
42534 ){
42535  /*
42536  ** If the path name starts with a forward slash or a backslash, it is either
42537  ** a legal UNC name, a volume relative path, or an absolute path name in the
42538  ** "Unix" format on Windows. There is no easy way to differentiate between
42539  ** the final two cases; therefore, we return the safer return value of TRUE
42540  ** so that callers of this function will simply use it verbatim.
42541  */
42542  if ( winIsDirSep(zPathname[0]) ){
42543  return TRUE;
42544  }
42545 
42546  /*
42547  ** If the path name starts with a letter and a colon it is either a volume
42548  ** relative path or an absolute path. Callers of this function must not
42549  ** attempt to treat it as a relative path name (i.e. they should simply use
42550  ** it verbatim).
42551  */
42552  if ( winIsDriveLetterAndColon(zPathname) ){
42553  return TRUE;
42554  }
42555 
42556  /*
42557  ** If we get to this point, the path name should almost certainly be a purely
42558  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
42559  */
42560  return FALSE;
42561 }
42562 
42563 /*
42564 ** Turn a relative pathname into a full pathname. Write the full
42565 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
42566 ** bytes in size.
42567 */
42568 static int winFullPathname(
42569  sqlite3_vfs *pVfs, /* Pointer to vfs object */
42570  const char *zRelative, /* Possibly relative input path */
42571  int nFull, /* Size of output buffer in bytes */
42572  char *zFull /* Output buffer */
42573 ){
42574 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42575  DWORD nByte;
42576  void *zConverted;
42577  char *zOut;
42578 #endif
42579 
42580  /* If this path name begins with "/X:", where "X" is any alphabetic
42581  ** character, discard the initial "/" from the pathname.
42582  */
42583  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
42584  zRelative++;
42585  }
42586 
42587 #if defined(__CYGWIN__)
42588  SimulateIOError( return SQLITE_ERROR );
42589  UNUSED_PARAMETER(nFull);
42590  assert( nFull>=pVfs->mxPathname );
42591  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42592  /*
42593  ** NOTE: We are dealing with a relative path name and the data
42594  ** directory has been set. Therefore, use it as the basis
42595  ** for converting the relative path name to an absolute
42596  ** one by prepending the data directory and a slash.
42597  */
42598  char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42599  if( !zOut ){
42600  return SQLITE_IOERR_NOMEM_BKPT;
42601  }
42602  if( cygwin_conv_path(
42603  (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
42604  CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
42605  sqlite3_free(zOut);
42606  return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42607  "winFullPathname1", zRelative);
42608  }else{
42609  char *zUtf8 = winConvertToUtf8Filename(zOut);
42610  if( !zUtf8 ){
42611  sqlite3_free(zOut);
42612  return SQLITE_IOERR_NOMEM_BKPT;
42613  }
42614  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42615  sqlite3_data_directory, winGetDirSep(), zUtf8);
42616  sqlite3_free(zUtf8);
42617  sqlite3_free(zOut);
42618  }
42619  }else{
42620  char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42621  if( !zOut ){
42622  return SQLITE_IOERR_NOMEM_BKPT;
42623  }
42624  if( cygwin_conv_path(
42625  (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
42626  zRelative, zOut, pVfs->mxPathname+1)<0 ){
42627  sqlite3_free(zOut);
42628  return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42629  "winFullPathname2", zRelative);
42630  }else{
42631  char *zUtf8 = winConvertToUtf8Filename(zOut);
42632  if( !zUtf8 ){
42633  sqlite3_free(zOut);
42634  return SQLITE_IOERR_NOMEM_BKPT;
42635  }
42636  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
42637  sqlite3_free(zUtf8);
42638  sqlite3_free(zOut);
42639  }
42640  }
42641  return SQLITE_OK;
42642 #endif
42643 
42644 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
42645  SimulateIOError( return SQLITE_ERROR );
42646  /* WinCE has no concept of a relative pathname, or so I am told. */
42647  /* WinRT has no way to convert a relative path to an absolute one. */
42648  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42649  /*
42650  ** NOTE: We are dealing with a relative path name and the data
42651  ** directory has been set. Therefore, use it as the basis
42652  ** for converting the relative path name to an absolute
42653  ** one by prepending the data directory and a backslash.
42654  */
42655  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42656  sqlite3_data_directory, winGetDirSep(), zRelative);
42657  }else{
42658  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
42659  }
42660  return SQLITE_OK;
42661 #endif
42662 
42663 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42664  /* It's odd to simulate an io-error here, but really this is just
42665  ** using the io-error infrastructure to test that SQLite handles this
42666  ** function failing. This function could fail if, for example, the
42667  ** current working directory has been unlinked.
42668  */
42669  SimulateIOError( return SQLITE_ERROR );
42670  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42671  /*
42672  ** NOTE: We are dealing with a relative path name and the data
42673  ** directory has been set. Therefore, use it as the basis
42674  ** for converting the relative path name to an absolute
42675  ** one by prepending the data directory and a backslash.
42676  */
42677  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42678  sqlite3_data_directory, winGetDirSep(), zRelative);
42679  return SQLITE_OK;
42680  }
42681  zConverted = winConvertFromUtf8Filename(zRelative);
42682  if( zConverted==0 ){
42683  return SQLITE_IOERR_NOMEM_BKPT;
42684  }
42685  if( osIsNT() ){
42686  LPWSTR zTemp;
42687  nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
42688  if( nByte==0 ){
42689  sqlite3_free(zConverted);
42690  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42691  "winFullPathname1", zRelative);
42692  }
42693  nByte += 3;
42694  zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42695  if( zTemp==0 ){
42696  sqlite3_free(zConverted);
42697  return SQLITE_IOERR_NOMEM_BKPT;
42698  }
42699  nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
42700  if( nByte==0 ){
42701  sqlite3_free(zConverted);
42702  sqlite3_free(zTemp);
42703  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42704  "winFullPathname2", zRelative);
42705  }
42706  sqlite3_free(zConverted);
42707  zOut = winUnicodeToUtf8(zTemp);
42708  sqlite3_free(zTemp);
42709  }
42710 #ifdef SQLITE_WIN32_HAS_ANSI
42711  else{
42712  char *zTemp;
42713  nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
42714  if( nByte==0 ){
42715  sqlite3_free(zConverted);
42716  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42717  "winFullPathname3", zRelative);
42718  }
42719  nByte += 3;
42720  zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42721  if( zTemp==0 ){
42722  sqlite3_free(zConverted);
42723  return SQLITE_IOERR_NOMEM_BKPT;
42724  }
42725  nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
42726  if( nByte==0 ){
42727  sqlite3_free(zConverted);
42728  sqlite3_free(zTemp);
42729  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42730  "winFullPathname4", zRelative);
42731  }
42732  sqlite3_free(zConverted);
42733  zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
42734  sqlite3_free(zTemp);
42735  }
42736 #endif
42737  if( zOut ){
42738  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
42739  sqlite3_free(zOut);
42740  return SQLITE_OK;
42741  }else{
42742  return SQLITE_IOERR_NOMEM_BKPT;
42743  }
42744 #endif
42745 }
42746 
42747 #ifndef SQLITE_OMIT_LOAD_EXTENSION
42748 /*
42749 ** Interfaces for opening a shared library, finding entry points
42750 ** within the shared library, and closing the shared library.
42751 */
42752 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
42753  HANDLE h;
42754 #if defined(__CYGWIN__)
42755  int nFull = pVfs->mxPathname+1;
42756  char *zFull = sqlite3MallocZero( nFull );
42757  void *zConverted = 0;
42758  if( zFull==0 ){
42759  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42760  return 0;
42761  }
42762  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
42763  sqlite3_free(zFull);
42764  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42765  return 0;
42766  }
42767  zConverted = winConvertFromUtf8Filename(zFull);
42768  sqlite3_free(zFull);
42769 #else
42770  void *zConverted = winConvertFromUtf8Filename(zFilename);
42771  UNUSED_PARAMETER(pVfs);
42772 #endif
42773  if( zConverted==0 ){
42774  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42775  return 0;
42776  }
42777  if( osIsNT() ){
42778 #if SQLITE_OS_WINRT
42779  h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
42780 #else
42781  h = osLoadLibraryW((LPCWSTR)zConverted);
42782 #endif
42783  }
42784 #ifdef SQLITE_WIN32_HAS_ANSI
42785  else{
42786  h = osLoadLibraryA((char*)zConverted);
42787  }
42788 #endif
42789  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
42790  sqlite3_free(zConverted);
42791  return (void*)h;
42792 }
42793 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
42794  UNUSED_PARAMETER(pVfs);
42795  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
42796 }
42797 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
42798  FARPROC proc;
42799  UNUSED_PARAMETER(pVfs);
42800  proc = osGetProcAddressA((HANDLE)pH, zSym);
42801  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
42802  (void*)pH, zSym, (void*)proc));
42803  return (void(*)(void))proc;
42804 }
42805 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
42806  UNUSED_PARAMETER(pVfs);
42807  osFreeLibrary((HANDLE)pHandle);
42808  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
42809 }
42810 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
42811  #define winDlOpen 0
42812  #define winDlError 0
42813  #define winDlSym 0
42814  #define winDlClose 0
42815 #endif
42816 
42817 /* State information for the randomness gatherer. */
42818 typedef struct EntropyGatherer EntropyGatherer;
42819 struct EntropyGatherer {
42820  unsigned char *a; /* Gather entropy into this buffer */
42821  int na; /* Size of a[] in bytes */
42822  int i; /* XOR next input into a[i] */
42823  int nXor; /* Number of XOR operations done */
42824 };
42825 
42826 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
42827 /* Mix sz bytes of entropy into p. */
42828 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
42829  int j, k;
42830  for(j=0, k=p->i; j<sz; j++){
42831  p->a[k++] ^= x[j];
42832  if( k>=p->na ) k = 0;
42833  }
42834  p->i = k;
42835  p->nXor += sz;
42836 }
42837 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
42838 
42839 /*
42840 ** Write up to nBuf bytes of randomness into zBuf.
42841 */
42842 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42843 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
42844  UNUSED_PARAMETER(pVfs);
42845  memset(zBuf, 0, nBuf);
42846  return nBuf;
42847 #else
42848  EntropyGatherer e;
42849  UNUSED_PARAMETER(pVfs);
42850  memset(zBuf, 0, nBuf);
42851 #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
42852  rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
42853 #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
42854  e.a = (unsigned char*)zBuf;
42855  e.na = nBuf;
42856  e.nXor = 0;
42857  e.i = 0;
42858  {
42859  SYSTEMTIME x;
42860  osGetSystemTime(&x);
42861  xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
42862  }
42863  {
42864  DWORD pid = osGetCurrentProcessId();
42865  xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
42866  }
42867 #if SQLITE_OS_WINRT
42868  {
42869  ULONGLONG cnt = osGetTickCount64();
42870  xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
42871  }
42872 #else
42873  {
42874  DWORD cnt = osGetTickCount();
42875  xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
42876  }
42877 #endif /* SQLITE_OS_WINRT */
42878  {
42879  LARGE_INTEGER i;
42880  osQueryPerformanceCounter(&i);
42881  xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
42882  }
42883 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
42884  {
42885  UUID id;
42886  memset(&id, 0, sizeof(UUID));
42887  osUuidCreate(&id);
42888  xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42889  memset(&id, 0, sizeof(UUID));
42890  osUuidCreateSequential(&id);
42891  xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42892  }
42893 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
42894  return e.nXor>nBuf ? nBuf : e.nXor;
42895 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
42896 }
42897 
42898 
42899 /*
42900 ** Sleep for a little while. Return the amount of time slept.
42901 */
42902 static int winSleep(sqlite3_vfs *pVfs, int microsec){
42903  sqlite3_win32_sleep((microsec+999)/1000);
42904  UNUSED_PARAMETER(pVfs);
42905  return ((microsec+999)/1000)*1000;
42906 }
42907 
42908 /*
42909 ** The following variable, if set to a non-zero value, is interpreted as
42910 ** the number of seconds since 1970 and is used to set the result of
42911 ** sqlite3OsCurrentTime() during testing.
42912 */
42913 #ifdef SQLITE_TEST
42914 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
42915 #endif
42916 
42917 /*
42918 ** Find the current time (in Universal Coordinated Time). Write into *piNow
42919 ** the current time and date as a Julian Day number times 86_400_000. In
42920 ** other words, write into *piNow the number of milliseconds since the Julian
42921 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
42922 ** proleptic Gregorian calendar.
42923 **
42924 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
42925 ** cannot be found.
42926 */
42927 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
42928  /* FILETIME structure is a 64-bit value representing the number of
42929  100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
42930  */
42931  FILETIME ft;
42932  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
42933 #ifdef SQLITE_TEST
42934  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
42935 #endif
42936  /* 2^32 - to avoid use of LL and warnings in gcc */
42937  static const sqlite3_int64 max32BitValue =
42938  (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
42939  (sqlite3_int64)294967296;
42940 
42941 #if SQLITE_OS_WINCE
42942  SYSTEMTIME time;
42943  osGetSystemTime(&time);
42944  /* if SystemTimeToFileTime() fails, it returns zero. */
42945  if (!osSystemTimeToFileTime(&time,&ft)){
42946  return SQLITE_ERROR;
42947  }
42948 #else
42949  osGetSystemTimeAsFileTime( &ft );
42950 #endif
42951 
42952  *piNow = winFiletimeEpoch +
42953  ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
42954  (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
42955 
42956 #ifdef SQLITE_TEST
42957  if( sqlite3_current_time ){
42958  *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
42959  }
42960 #endif
42961  UNUSED_PARAMETER(pVfs);
42962  return SQLITE_OK;
42963 }
42964 
42965 /*
42966 ** Find the current time (in Universal Coordinated Time). Write the
42967 ** current time and date as a Julian Day number into *prNow and
42968 ** return 0. Return 1 if the time and date cannot be found.
42969 */
42970 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
42971  int rc;
42972  sqlite3_int64 i;
42973  rc = winCurrentTimeInt64(pVfs, &i);
42974  if( !rc ){
42975  *prNow = i/86400000.0;
42976  }
42977  return rc;
42978 }
42979 
42980 /*
42981 ** The idea is that this function works like a combination of
42982 ** GetLastError() and FormatMessage() on Windows (or errno and
42983 ** strerror_r() on Unix). After an error is returned by an OS
42984 ** function, SQLite calls this function with zBuf pointing to
42985 ** a buffer of nBuf bytes. The OS layer should populate the
42986 ** buffer with a nul-terminated UTF-8 encoded error message
42987 ** describing the last IO error to have occurred within the calling
42988 ** thread.
42989 **
42990 ** If the error message is too large for the supplied buffer,
42991 ** it should be truncated. The return value of xGetLastError
42992 ** is zero if the error message fits in the buffer, or non-zero
42993 ** otherwise (if the message was truncated). If non-zero is returned,
42994 ** then it is not necessary to include the nul-terminator character
42995 ** in the output buffer.
42996 **
42997 ** Not supplying an error message will have no adverse effect
42998 ** on SQLite. It is fine to have an implementation that never
42999 ** returns an error message:
43000 **
43001 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43002 ** assert(zBuf[0]=='\0');
43003 ** return 0;
43004 ** }
43005 **
43006 ** However if an error message is supplied, it will be incorporated
43007 ** by sqlite into the error message available to the user using
43008 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
43009 */
43010 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
43011  DWORD e = osGetLastError();
43012  UNUSED_PARAMETER(pVfs);
43013  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
43014  return e;
43015 }
43016 
43017 /*
43018 ** Initialize and deinitialize the operating system interface.
43019 */
43020 SQLITE_API int sqlite3_os_init(void){
43021  static sqlite3_vfs winVfs = {
43022  3, /* iVersion */
43023  sizeof(winFile), /* szOsFile */
43024  SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
43025  0, /* pNext */
43026  "win32", /* zName */
43027  &winAppData, /* pAppData */
43028  winOpen, /* xOpen */
43029  winDelete, /* xDelete */
43030  winAccess, /* xAccess */
43031  winFullPathname, /* xFullPathname */
43032  winDlOpen, /* xDlOpen */
43033  winDlError, /* xDlError */
43034  winDlSym, /* xDlSym */
43035  winDlClose, /* xDlClose */
43036  winRandomness, /* xRandomness */
43037  winSleep, /* xSleep */
43038  winCurrentTime, /* xCurrentTime */
43039  winGetLastError, /* xGetLastError */
43040  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43041  winSetSystemCall, /* xSetSystemCall */
43042  winGetSystemCall, /* xGetSystemCall */
43043  winNextSystemCall, /* xNextSystemCall */
43044  };
43045 #if defined(SQLITE_WIN32_HAS_WIDE)
43046  static sqlite3_vfs winLongPathVfs = {
43047  3, /* iVersion */
43048  sizeof(winFile), /* szOsFile */
43049  SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43050  0, /* pNext */
43051  "win32-longpath", /* zName */
43052  &winAppData, /* pAppData */
43053  winOpen, /* xOpen */
43054  winDelete, /* xDelete */
43055  winAccess, /* xAccess */
43056  winFullPathname, /* xFullPathname */
43057  winDlOpen, /* xDlOpen */
43058  winDlError, /* xDlError */
43059  winDlSym, /* xDlSym */
43060  winDlClose, /* xDlClose */
43061  winRandomness, /* xRandomness */
43062  winSleep, /* xSleep */
43063  winCurrentTime, /* xCurrentTime */
43064  winGetLastError, /* xGetLastError */
43065  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43066  winSetSystemCall, /* xSetSystemCall */
43067  winGetSystemCall, /* xGetSystemCall */
43068  winNextSystemCall, /* xNextSystemCall */
43069  };
43070 #endif
43071  static sqlite3_vfs winNolockVfs = {
43072  3, /* iVersion */
43073  sizeof(winFile), /* szOsFile */
43074  SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
43075  0, /* pNext */
43076  "win32-none", /* zName */
43077  &winNolockAppData, /* pAppData */
43078  winOpen, /* xOpen */
43079  winDelete, /* xDelete */
43080  winAccess, /* xAccess */
43081  winFullPathname, /* xFullPathname */
43082  winDlOpen, /* xDlOpen */
43083  winDlError, /* xDlError */
43084  winDlSym, /* xDlSym */
43085  winDlClose, /* xDlClose */
43086  winRandomness, /* xRandomness */
43087  winSleep, /* xSleep */
43088  winCurrentTime, /* xCurrentTime */
43089  winGetLastError, /* xGetLastError */
43090  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43091  winSetSystemCall, /* xSetSystemCall */
43092  winGetSystemCall, /* xGetSystemCall */
43093  winNextSystemCall, /* xNextSystemCall */
43094  };
43095 #if defined(SQLITE_WIN32_HAS_WIDE)
43096  static sqlite3_vfs winLongPathNolockVfs = {
43097  3, /* iVersion */
43098  sizeof(winFile), /* szOsFile */
43099  SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43100  0, /* pNext */
43101  "win32-longpath-none", /* zName */
43102  &winNolockAppData, /* pAppData */
43103  winOpen, /* xOpen */
43104  winDelete, /* xDelete */
43105  winAccess, /* xAccess */
43106  winFullPathname, /* xFullPathname */
43107  winDlOpen, /* xDlOpen */
43108  winDlError, /* xDlError */
43109  winDlSym, /* xDlSym */
43110  winDlClose, /* xDlClose */
43111  winRandomness, /* xRandomness */
43112  winSleep, /* xSleep */
43113  winCurrentTime, /* xCurrentTime */
43114  winGetLastError, /* xGetLastError */
43115  winCurrentTimeInt64, /* xCurrentTimeInt64 */
43116  winSetSystemCall, /* xSetSystemCall */
43117  winGetSystemCall, /* xGetSystemCall */
43118  winNextSystemCall, /* xNextSystemCall */
43119  };
43120 #endif
43121 
43122  /* Double-check that the aSyscall[] array has been constructed
43123  ** correctly. See ticket [bb3a86e890c8e96ab] */
43124  assert( ArraySize(aSyscall)==80 );
43125 
43126  /* get memory map allocation granularity */
43127  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
43128 #if SQLITE_OS_WINRT
43129  osGetNativeSystemInfo(&winSysInfo);
43130 #else
43131  osGetSystemInfo(&winSysInfo);
43132 #endif
43133  assert( winSysInfo.dwAllocationGranularity>0 );
43134  assert( winSysInfo.dwPageSize>0 );
43135 
43136  sqlite3_vfs_register(&winVfs, 1);
43137 
43138 #if defined(SQLITE_WIN32_HAS_WIDE)
43139  sqlite3_vfs_register(&winLongPathVfs, 0);
43140 #endif
43141 
43142  sqlite3_vfs_register(&winNolockVfs, 0);
43143 
43144 #if defined(SQLITE_WIN32_HAS_WIDE)
43145  sqlite3_vfs_register(&winLongPathNolockVfs, 0);
43146 #endif
43147 
43148  return SQLITE_OK;
43149 }
43150 
43151 SQLITE_API int sqlite3_os_end(void){
43152 #if SQLITE_OS_WINRT
43153  if( sleepObj!=NULL ){
43154  osCloseHandle(sleepObj);
43155  sleepObj = NULL;
43156  }
43157 #endif
43158  return SQLITE_OK;
43159 }
43160 
43161 #endif /* SQLITE_OS_WIN */
43162 
43163 /************** End of os_win.c **********************************************/
43164 /************** Begin file bitvec.c ******************************************/
43165 /*
43166 ** 2008 February 16
43167 **
43168 ** The author disclaims copyright to this source code. In place of
43169 ** a legal notice, here is a blessing:
43170 **
43171 ** May you do good and not evil.
43172 ** May you find forgiveness for yourself and forgive others.
43173 ** May you share freely, never taking more than you give.
43174 **
43175 *************************************************************************
43176 ** This file implements an object that represents a fixed-length
43177 ** bitmap. Bits are numbered starting with 1.
43178 **
43179 ** A bitmap is used to record which pages of a database file have been
43180 ** journalled during a transaction, or which pages have the "dont-write"
43181 ** property. Usually only a few pages are meet either condition.
43182 ** So the bitmap is usually sparse and has low cardinality.
43183 ** But sometimes (for example when during a DROP of a large table) most
43184 ** or all of the pages in a database can get journalled. In those cases,
43185 ** the bitmap becomes dense with high cardinality. The algorithm needs
43186 ** to handle both cases well.
43187 **
43188 ** The size of the bitmap is fixed when the object is created.
43189 **
43190 ** All bits are clear when the bitmap is created. Individual bits
43191 ** may be set or cleared one at a time.
43192 **
43193 ** Test operations are about 100 times more common that set operations.
43194 ** Clear operations are exceedingly rare. There are usually between
43195 ** 5 and 500 set operations per Bitvec object, though the number of sets can
43196 ** sometimes grow into tens of thousands or larger. The size of the
43197 ** Bitvec object is the number of pages in the database file at the
43198 ** start of a transaction, and is thus usually less than a few thousand,
43199 ** but can be as large as 2 billion for a really big database.
43200 */
43201 /* #include "sqliteInt.h" */
43202 
43203 /* Size of the Bitvec structure in bytes. */
43204 #define BITVEC_SZ 512
43205 
43206 /* Round the union size down to the nearest pointer boundary, since that's how
43207 ** it will be aligned within the Bitvec struct. */
43208 #define BITVEC_USIZE \
43209  (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
43210 
43211 /* Type of the array "element" for the bitmap representation.
43212 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
43213 ** Setting this to the "natural word" size of your CPU may improve
43214 ** performance. */
43215 #define BITVEC_TELEM u8
43216 /* Size, in bits, of the bitmap element. */
43217 #define BITVEC_SZELEM 8
43218 /* Number of elements in a bitmap array. */
43219 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
43220 /* Number of bits in the bitmap array. */
43221 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
43222 
43223 /* Number of u32 values in hash table. */
43224 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
43225 /* Maximum number of entries in hash table before
43226 ** sub-dividing and re-hashing. */
43227 #define BITVEC_MXHASH (BITVEC_NINT/2)
43228 /* Hashing function for the aHash representation.
43229 ** Empirical testing showed that the *37 multiplier
43230 ** (an arbitrary prime)in the hash function provided
43231 ** no fewer collisions than the no-op *1. */
43232 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
43233 
43234 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
43235 
43236 
43237 /*
43238 ** A bitmap is an instance of the following structure.
43239 **
43240 ** This bitmap records the existence of zero or more bits
43241 ** with values between 1 and iSize, inclusive.
43242 **
43243 ** There are three possible representations of the bitmap.
43244 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
43245 ** bitmap. The least significant bit is bit 1.
43246 **
43247 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
43248 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
43249 **
43250 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
43251 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
43252 ** handles up to iDivisor separate values of i. apSub[0] holds
43253 ** values between 1 and iDivisor. apSub[1] holds values between
43254 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
43255 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
43256 ** to hold deal with values between 1 and iDivisor.
43257 */
43258 struct Bitvec {
43259  u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
43260  u32 nSet; /* Number of bits that are set - only valid for aHash
43261  ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
43262  ** this would be 125. */
43263  u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
43264  /* Should >=0 for apSub element. */
43265  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
43266  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
43267  union {
43268  BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
43269  u32 aHash[BITVEC_NINT]; /* Hash table representation */
43270  Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
43271  } u;
43272 };
43273 
43274 /*
43275 ** Create a new bitmap object able to handle bits between 0 and iSize,
43276 ** inclusive. Return a pointer to the new object. Return NULL if
43277 ** malloc fails.
43278 */
43280  Bitvec *p;
43281  assert( sizeof(*p)==BITVEC_SZ );
43282  p = sqlite3MallocZero( sizeof(*p) );
43283  if( p ){
43284  p->iSize = iSize;
43285  }
43286  return p;
43287 }
43288 
43289 /*
43290 ** Check to see if the i-th bit is set. Return true or false.
43291 ** If p is NULL (if the bitmap has not been created) or if
43292 ** i is out of range, then return false.
43293 */
43295  assert( p!=0 );
43296  i--;
43297  if( i>=p->iSize ) return 0;
43298  while( p->iDivisor ){
43299  u32 bin = i/p->iDivisor;
43300  i = i%p->iDivisor;
43301  p = p->u.apSub[bin];
43302  if (!p) {
43303  return 0;
43304  }
43305  }
43306  if( p->iSize<=BITVEC_NBIT ){
43307  return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
43308  } else{
43309  u32 h = BITVEC_HASH(i++);
43310  while( p->u.aHash[h] ){
43311  if( p->u.aHash[h]==i ) return 1;
43312  h = (h+1) % BITVEC_NINT;
43313  }
43314  return 0;
43315  }
43316 }
43318  return p!=0 && sqlite3BitvecTestNotNull(p,i);
43319 }
43320 
43321 /*
43322 ** Set the i-th bit. Return 0 on success and an error code if
43323 ** anything goes wrong.
43324 **
43325 ** This routine might cause sub-bitmaps to be allocated. Failing
43326 ** to get the memory needed to hold the sub-bitmap is the only
43327 ** that can go wrong with an insert, assuming p and i are valid.
43328 **
43329 ** The calling function must ensure that p is a valid Bitvec object
43330 ** and that the value for "i" is within range of the Bitvec object.
43331 ** Otherwise the behavior is undefined.
43332 */
43334  u32 h;
43335  if( p==0 ) return SQLITE_OK;
43336  assert( i>0 );
43337  assert( i<=p->iSize );
43338  i--;
43339  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
43340  u32 bin = i/p->iDivisor;
43341  i = i%p->iDivisor;
43342  if( p->u.apSub[bin]==0 ){
43343  p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
43344  if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
43345  }
43346  p = p->u.apSub[bin];
43347  }
43348  if( p->iSize<=BITVEC_NBIT ){
43349  p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
43350  return SQLITE_OK;
43351  }
43352  h = BITVEC_HASH(i++);
43353  /* if there wasn't a hash collision, and this doesn't */
43354  /* completely fill the hash, then just add it without */
43355  /* worring about sub-dividing and re-hashing. */
43356  if( !p->u.aHash[h] ){
43357  if (p->nSet<(BITVEC_NINT-1)) {
43358  goto bitvec_set_end;
43359  } else {
43360  goto bitvec_set_rehash;
43361  }
43362  }
43363  /* there was a collision, check to see if it's already */
43364  /* in hash, if not, try to find a spot for it */
43365  do {
43366  if( p->u.aHash[h]==i ) return SQLITE_OK;
43367  h++;
43368  if( h>=BITVEC_NINT ) h = 0;
43369  } while( p->u.aHash[h] );
43370  /* we didn't find it in the hash. h points to the first */
43371  /* available free spot. check to see if this is going to */
43372  /* make our hash too "full". */
43373 bitvec_set_rehash:
43374  if( p->nSet>=BITVEC_MXHASH ){
43375  unsigned int j;
43376  int rc;
43377  u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
43378  if( aiValues==0 ){
43379  return SQLITE_NOMEM_BKPT;
43380  }else{
43381  memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43382  memset(p->u.apSub, 0, sizeof(p->u.apSub));
43383  p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
43384  rc = sqlite3BitvecSet(p, i);
43385  for(j=0; j<BITVEC_NINT; j++){
43386  if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
43387  }
43388  sqlite3StackFree(0, aiValues);
43389  return rc;
43390  }
43391  }
43392 bitvec_set_end:
43393  p->nSet++;
43394  p->u.aHash[h] = i;
43395  return SQLITE_OK;
43396 }
43397 
43398 /*
43399 ** Clear the i-th bit.
43400 **
43401 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
43402 ** that BitvecClear can use to rebuilt its hash table.
43403 */
43404 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
43405  if( p==0 ) return;
43406  assert( i>0 );
43407  i--;
43408  while( p->iDivisor ){
43409  u32 bin = i/p->iDivisor;
43410  i = i%p->iDivisor;
43411  p = p->u.apSub[bin];
43412  if (!p) {
43413  return;
43414  }
43415  }
43416  if( p->iSize<=BITVEC_NBIT ){
43417  p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
43418  }else{
43419  unsigned int j;
43420  u32 *aiValues = pBuf;
43421  memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43422  memset(p->u.aHash, 0, sizeof(p->u.aHash));
43423  p->nSet = 0;
43424  for(j=0; j<BITVEC_NINT; j++){
43425  if( aiValues[j] && aiValues[j]!=(i+1) ){
43426  u32 h = BITVEC_HASH(aiValues[j]-1);
43427  p->nSet++;
43428  while( p->u.aHash[h] ){
43429  h++;
43430  if( h>=BITVEC_NINT ) h = 0;
43431  }
43432  p->u.aHash[h] = aiValues[j];
43433  }
43434  }
43435  }
43436 }
43437 
43438 /*
43439 ** Destroy a bitmap object. Reclaim all memory used.
43440 */
43442  if( p==0 ) return;
43443  if( p->iDivisor ){
43444  unsigned int i;
43445  for(i=0; i<BITVEC_NPTR; i++){
43446  sqlite3BitvecDestroy(p->u.apSub[i]);
43447  }
43448  }
43449  sqlite3_free(p);
43450 }
43451 
43452 /*
43453 ** Return the value of the iSize parameter specified when Bitvec *p
43454 ** was created.
43455 */
43457  return p->iSize;
43458 }
43459 
43460 #ifndef SQLITE_OMIT_BUILTIN_TEST
43461 /*
43462 ** Let V[] be an array of unsigned characters sufficient to hold
43463 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
43464 ** Then the following macros can be used to set, clear, or test
43465 ** individual bits within V.
43466 */
43467 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
43468 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
43469 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
43470 
43471 /*
43472 ** This routine runs an extensive test of the Bitvec code.
43473 **
43474 ** The input is an array of integers that acts as a program
43475 ** to test the Bitvec. The integers are opcodes followed
43476 ** by 0, 1, or 3 operands, depending on the opcode. Another
43477 ** opcode follows immediately after the last operand.
43478 **
43479 ** There are 6 opcodes numbered from 0 through 5. 0 is the
43480 ** "halt" opcode and causes the test to end.
43481 **
43482 ** 0 Halt and return the number of errors
43483 ** 1 N S X Set N bits beginning with S and incrementing by X
43484 ** 2 N S X Clear N bits beginning with S and incrementing by X
43485 ** 3 N Set N randomly chosen bits
43486 ** 4 N Clear N randomly chosen bits
43487 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
43488 **
43489 ** The opcodes 1 through 4 perform set and clear operations are performed
43490 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
43491 ** Opcode 5 works on the linear array only, not on the Bitvec.
43492 ** Opcode 5 is used to deliberately induce a fault in order to
43493 ** confirm that error detection works.
43494 **
43495 ** At the conclusion of the test the linear array is compared
43496 ** against the Bitvec object. If there are any differences,
43497 ** an error is returned. If they are the same, zero is returned.
43498 **
43499 ** If a memory allocation error occurs, return -1.
43500 */
43502  Bitvec *pBitvec = 0;
43503  unsigned char *pV = 0;
43504  int rc = -1;
43505  int i, nx, pc, op;
43506  void *pTmpSpace;
43507 
43508  /* Allocate the Bitvec to be tested and a linear array of
43509  ** bits to act as the reference */
43510  pBitvec = sqlite3BitvecCreate( sz );
43511  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
43512  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
43513  if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
43514 
43515  /* NULL pBitvec tests */
43516  sqlite3BitvecSet(0, 1);
43517  sqlite3BitvecClear(0, 1, pTmpSpace);
43518 
43519  /* Run the program */
43520  pc = 0;
43521  while( (op = aOp[pc])!=0 ){
43522  switch( op ){
43523  case 1:
43524  case 2:
43525  case 5: {
43526  nx = 4;
43527  i = aOp[pc+2] - 1;
43528  aOp[pc+2] += aOp[pc+3];
43529  break;
43530  }
43531  case 3:
43532  case 4:
43533  default: {
43534  nx = 2;
43535  sqlite3_randomness(sizeof(i), &i);
43536  break;
43537  }
43538  }
43539  if( (--aOp[pc+1]) > 0 ) nx = 0;
43540  pc += nx;
43541  i = (i & 0x7fffffff)%sz;
43542  if( (op & 1)!=0 ){
43543  SETBIT(pV, (i+1));
43544  if( op!=5 ){
43545  if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
43546  }
43547  }else{
43548  CLEARBIT(pV, (i+1));
43549  sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
43550  }
43551  }
43552 
43553  /* Test to make sure the linear array exactly matches the
43554  ** Bitvec object. Start with the assumption that they do
43555  ** match (rc==0). Change rc to non-zero if a discrepancy
43556  ** is found.
43557  */
43558  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
43559  + sqlite3BitvecTest(pBitvec, 0)
43560  + (sqlite3BitvecSize(pBitvec) - sz);
43561  for(i=1; i<=sz; i++){
43562  if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
43563  rc = i;
43564  break;
43565  }
43566  }
43567 
43568  /* Free allocated structure */
43569 bitvec_end:
43570  sqlite3_free(pTmpSpace);
43571  sqlite3_free(pV);
43572  sqlite3BitvecDestroy(pBitvec);
43573  return rc;
43574 }
43575 #endif /* SQLITE_OMIT_BUILTIN_TEST */
43576 
43577 /************** End of bitvec.c **********************************************/
43578 /************** Begin file pcache.c ******************************************/
43579 /*
43580 ** 2008 August 05
43581 **
43582 ** The author disclaims copyright to this source code. In place of
43583 ** a legal notice, here is a blessing:
43584 **
43585 ** May you do good and not evil.
43586 ** May you find forgiveness for yourself and forgive others.
43587 ** May you share freely, never taking more than you give.
43588 **
43589 *************************************************************************
43590 ** This file implements that page cache.
43591 */
43592 /* #include "sqliteInt.h" */
43593 
43594 /*
43595 ** A complete page cache is an instance of this structure. Every
43596 ** entry in the cache holds a single page of the database file. The
43597 ** btree layer only operates on the cached copy of the database pages.
43598 **
43599 ** A page cache entry is "clean" if it exactly matches what is currently
43600 ** on disk. A page is "dirty" if it has been modified and needs to be
43601 ** persisted to disk.
43602 **
43603 ** pDirty, pDirtyTail, pSynced:
43604 ** All dirty pages are linked into the doubly linked list using
43605 ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
43606 ** such that p was added to the list more recently than p->pDirtyNext.
43607 ** PCache.pDirty points to the first (newest) element in the list and
43608 ** pDirtyTail to the last (oldest).
43609 **
43610 ** The PCache.pSynced variable is used to optimize searching for a dirty
43611 ** page to eject from the cache mid-transaction. It is better to eject
43612 ** a page that does not require a journal sync than one that does.
43613 ** Therefore, pSynced is maintained to that it *almost* always points
43614 ** to either the oldest page in the pDirty/pDirtyTail list that has a
43615 ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
43616 ** (so that the right page to eject can be found by following pDirtyPrev
43617 ** pointers).
43618 */
43619 struct PCache {
43620  PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
43621  PgHdr *pSynced; /* Last synced page in dirty page list */
43622  int nRefSum; /* Sum of ref counts over all pages */
43623  int szCache; /* Configured cache size */
43624  int szSpill; /* Size before spilling occurs */
43625  int szPage; /* Size of every page in this cache */
43626  int szExtra; /* Size of extra space for each page */
43627  u8 bPurgeable; /* True if pages are on backing store */
43628  u8 eCreate; /* eCreate value for for xFetch() */
43629  int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
43630  void *pStress; /* Argument to xStress */
43631  sqlite3_pcache *pCache; /* Pluggable cache module */
43632 };
43633 
43634 /********************************** Test and Debug Logic **********************/
43635 /*
43636 ** Debug tracing macros. Enable by by changing the "0" to "1" and
43637 ** recompiling.
43638 **
43639 ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
43640 ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
43641 ** is displayed for many operations, resulting in a lot of output.
43642 */
43643 #if defined(SQLITE_DEBUG) && 0
43644  int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
43645  int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
43646 # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
43647  void pcacheDump(PCache *pCache){
43648  int N;
43649  int i, j;
43650  sqlite3_pcache_page *pLower;
43651  PgHdr *pPg;
43652  unsigned char *a;
43653 
43654  if( sqlite3PcacheTrace<2 ) return;
43655  if( pCache->pCache==0 ) return;
43656  N = sqlite3PcachePagecount(pCache);
43657  if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
43658  for(i=1; i<=N; i++){
43659  pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
43660  if( pLower==0 ) continue;
43661  pPg = (PgHdr*)pLower->pExtra;
43662  printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
43663  a = (unsigned char *)pLower->pBuf;
43664  for(j=0; j<12; j++) printf("%02x", a[j]);
43665  printf("\n");
43666  if( pPg->pPage==0 ){
43667  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
43668  }
43669  }
43670  }
43671  #else
43672 # define pcacheTrace(X)
43673 # define pcacheDump(X)
43674 #endif
43675 
43676 /*
43677 ** Check invariants on a PgHdr entry. Return true if everything is OK.
43678 ** Return false if any invariant is violated.
43679 **
43680 ** This routine is for use inside of assert() statements only. For
43681 ** example:
43682 **
43683 ** assert( sqlite3PcachePageSanity(pPg) );
43684 */
43685 #if SQLITE_DEBUG
43686 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
43687  PCache *pCache;
43688  assert( pPg!=0 );
43689  assert( pPg->pgno>0 ); /* Page number is 1 or more */
43690  pCache = pPg->pCache;
43691  assert( pCache!=0 ); /* Every page has an associated PCache */
43692  if( pPg->flags & PGHDR_CLEAN ){
43693  assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
43694  assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
43695  assert( pCache->pDirtyTail!=pPg );
43696  }
43697  /* WRITEABLE pages must also be DIRTY */
43698  if( pPg->flags & PGHDR_WRITEABLE ){
43699  assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
43700  }
43701  /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
43702  ** for example, when using the sqlite3PagerDontWrite() optimization:
43703  ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
43704  ** (2) Page X moved to freelist, WRITEABLE is cleared
43705  ** (3) Page X reused, WRITEABLE is set again
43706  ** If NEED_SYNC had been cleared in step 2, then it would not be reset
43707  ** in step 3, and page might be written into the database without first
43708  ** syncing the rollback journal, which might cause corruption on a power
43709  ** loss.
43710  **
43711  ** Another example is when the database page size is smaller than the
43712  ** disk sector size. When any page of a sector is journalled, all pages
43713  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
43714  ** in case they are later modified, since all pages in the same sector
43715  ** must be journalled and synced before any of those pages can be safely
43716  ** written.
43717  */
43718  return 1;
43719 }
43720 #endif /* SQLITE_DEBUG */
43721 
43722 
43723 /********************************** Linked List Management ********************/
43724 
43725 /* Allowed values for second argument to pcacheManageDirtyList() */
43726 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
43727 #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
43728 #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
43729 
43730 /*
43731 ** Manage pPage's participation on the dirty list. Bits of the addRemove
43732 ** argument determines what operation to do. The 0x01 bit means first
43733 ** remove pPage from the dirty list. The 0x02 means add pPage back to
43734 ** the dirty list. Doing both moves pPage to the front of the dirty list.
43735 */
43736 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
43737  PCache *p = pPage->pCache;
43738 
43739  pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
43740  addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
43741  pPage->pgno));
43742  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
43743  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
43744  assert( pPage->pDirtyPrev || pPage==p->pDirty );
43745 
43746  /* Update the PCache1.pSynced variable if necessary. */
43747  if( p->pSynced==pPage ){
43748  p->pSynced = pPage->pDirtyPrev;
43749  }
43750 
43751  if( pPage->pDirtyNext ){
43752  pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
43753  }else{
43754  assert( pPage==p->pDirtyTail );
43755  p->pDirtyTail = pPage->pDirtyPrev;
43756  }
43757  if( pPage->pDirtyPrev ){
43758  pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
43759  }else{
43760  /* If there are now no dirty pages in the cache, set eCreate to 2.
43761  ** This is an optimization that allows sqlite3PcacheFetch() to skip
43762  ** searching for a dirty page to eject from the cache when it might
43763  ** otherwise have to. */
43764  assert( pPage==p->pDirty );
43765  p->pDirty = pPage->pDirtyNext;
43766  assert( p->bPurgeable || p->eCreate==2 );
43767  if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
43768  assert( p->bPurgeable==0 || p->eCreate==1 );
43769  p->eCreate = 2;
43770  }
43771  }
43772  pPage->pDirtyNext = 0;
43773  pPage->pDirtyPrev = 0;
43774  }
43775  if( addRemove & PCACHE_DIRTYLIST_ADD ){
43776  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
43777 
43778  pPage->pDirtyNext = p->pDirty;
43779  if( pPage->pDirtyNext ){
43780  assert( pPage->pDirtyNext->pDirtyPrev==0 );
43781  pPage->pDirtyNext->pDirtyPrev = pPage;
43782  }else{
43783  p->pDirtyTail = pPage;
43784  if( p->bPurgeable ){
43785  assert( p->eCreate==2 );
43786  p->eCreate = 1;
43787  }
43788  }
43789  p->pDirty = pPage;
43790 
43791  /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
43792  ** pSynced to point to it. Checking the NEED_SYNC flag is an
43793  ** optimization, as if pSynced points to a page with the NEED_SYNC
43794  ** flag set sqlite3PcacheFetchStress() searches through all newer
43795  ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
43796  if( !p->pSynced
43797  && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
43798  ){
43799  p->pSynced = pPage;
43800  }
43801  }
43802  pcacheDump(p);
43803 }
43804 
43805 /*
43806 ** Wrapper around the pluggable caches xUnpin method. If the cache is
43807 ** being used for an in-memory database, this function is a no-op.
43808 */
43809 static void pcacheUnpin(PgHdr *p){
43810  if( p->pCache->bPurgeable ){
43811  pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
43812  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
43813  pcacheDump(p->pCache);
43814  }
43815 }
43816 
43817 /*
43818 ** Compute the number of pages of cache requested. p->szCache is the
43819 ** cache size requested by the "PRAGMA cache_size" statement.
43820 */
43822  if( p->szCache>=0 ){
43823  /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
43824  ** suggested cache size is set to N. */
43825  return p->szCache;
43826  }else{
43827  /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
43828  ** the number of cache pages is adjusted to use approximately abs(N*1024)
43829  ** bytes of memory. */
43830  return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
43831  }
43832 }
43833 
43834 /*************************************************** General Interfaces ******
43835 **
43836 ** Initialize and shutdown the page cache subsystem. Neither of these
43837 ** functions are threadsafe.
43838 */
43840  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
43841  /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
43842  ** built-in default page cache is used instead of the application defined
43843  ** page cache. */
43845  }
43846  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
43847 }
43849  if( sqlite3GlobalConfig.pcache2.xShutdown ){
43850  /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
43851  sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
43852  }
43853 }
43854 
43855 /*
43856 ** Return the size in bytes of a PCache object.
43857 */
43858 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
43859 
43860 /*
43861 ** Create a new PCache object. Storage space to hold the object
43862 ** has already been allocated and is passed in as the p pointer.
43863 ** The caller discovers how much space needs to be allocated by
43864 ** calling sqlite3PcacheSize().
43865 */
43867  int szPage, /* Size of every page */
43868  int szExtra, /* Extra space associated with each page */
43869  int bPurgeable, /* True if pages are on backing store */
43870  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
43871  void *pStress, /* Argument to xStress */
43872  PCache *p /* Preallocated space for the PCache */
43873 ){
43874  memset(p, 0, sizeof(PCache));
43875  p->szPage = 1;
43876  p->szExtra = szExtra;
43877  p->bPurgeable = bPurgeable;
43878  p->eCreate = 2;
43879  p->xStress = xStress;
43880  p->pStress = pStress;
43881  p->szCache = 100;
43882  p->szSpill = 1;
43883  pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
43884  return sqlite3PcacheSetPageSize(p, szPage);
43885 }
43886 
43887 /*
43888 ** Change the page size for PCache object. The caller must ensure that there
43889 ** are no outstanding page references when this function is called.
43890 */
43892  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
43893  if( pCache->szPage ){
43894  sqlite3_pcache *pNew;
43895  pNew = sqlite3GlobalConfig.pcache2.xCreate(
43896  szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
43897  pCache->bPurgeable
43898  );
43899  if( pNew==0 ) return SQLITE_NOMEM_BKPT;
43900  sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
43901  if( pCache->pCache ){
43902  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43903  }
43904  pCache->pCache = pNew;
43905  pCache->szPage = szPage;
43906  pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
43907  }
43908  return SQLITE_OK;
43909 }
43910 
43911 /*
43912 ** Try to obtain a page from the cache.
43913 **
43914 ** This routine returns a pointer to an sqlite3_pcache_page object if
43915 ** such an object is already in cache, or if a new one is created.
43916 ** This routine returns a NULL pointer if the object was not in cache
43917 ** and could not be created.
43918 **
43919 ** The createFlags should be 0 to check for existing pages and should
43920 ** be 3 (not 1, but 3) to try to create a new page.
43921 **
43922 ** If the createFlag is 0, then NULL is always returned if the page
43923 ** is not already in the cache. If createFlag is 1, then a new page
43924 ** is created only if that can be done without spilling dirty pages
43925 ** and without exceeding the cache size limit.
43926 **
43927 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
43928 ** initialize the sqlite3_pcache_page object and convert it into a
43929 ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
43930 ** routines are split this way for performance reasons. When separated
43931 ** they can both (usually) operate without having to push values to
43932 ** the stack on entry and pop them back off on exit, which saves a
43933 ** lot of pushing and popping.
43934 */
43936  PCache *pCache, /* Obtain the page from this cache */
43937  Pgno pgno, /* Page number to obtain */
43938  int createFlag /* If true, create page if it does not exist already */
43939 ){
43940  int eCreate;
43941  sqlite3_pcache_page *pRes;
43942 
43943  assert( pCache!=0 );
43944  assert( pCache->pCache!=0 );
43945  assert( createFlag==3 || createFlag==0 );
43946  assert( pgno>0 );
43947  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
43948 
43949  /* eCreate defines what to do if the page does not exist.
43950  ** 0 Do not allocate a new page. (createFlag==0)
43951  ** 1 Allocate a new page if doing so is inexpensive.
43952  ** (createFlag==1 AND bPurgeable AND pDirty)
43953  ** 2 Allocate a new page even it doing so is difficult.
43954  ** (createFlag==1 AND !(bPurgeable AND pDirty)
43955  */
43956  eCreate = createFlag & pCache->eCreate;
43957  assert( eCreate==0 || eCreate==1 || eCreate==2 );
43958  assert( createFlag==0 || pCache->eCreate==eCreate );
43959  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
43960  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43961  pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
43962  createFlag?" create":"",pRes));
43963  return pRes;
43964 }
43965 
43966 /*
43967 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
43968 ** page because no clean pages are available for reuse and the cache
43969 ** size limit has been reached, then this routine can be invoked to
43970 ** try harder to allocate a page. This routine might invoke the stress
43971 ** callback to spill dirty pages to the journal. It will then try to
43972 ** allocate the new page and will only fail to allocate a new page on
43973 ** an OOM error.
43974 **
43975 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
43976 */
43978  PCache *pCache, /* Obtain the page from this cache */
43979  Pgno pgno, /* Page number to obtain */
43980  sqlite3_pcache_page **ppPage /* Write result here */
43981 ){
43982  PgHdr *pPg;
43983  if( pCache->eCreate==2 ) return 0;
43984 
43985  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
43986  /* Find a dirty page to write-out and recycle. First try to find a
43987  ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
43988  ** cleared), but if that is not possible settle for any other
43989  ** unreferenced dirty page.
43990  **
43991  ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
43992  ** flag is currently referenced, then the following may leave pSynced
43993  ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
43994  ** cleared). This is Ok, as pSynced is just an optimization. */
43995  for(pPg=pCache->pSynced;
43996  pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
43997  pPg=pPg->pDirtyPrev
43998  );
43999  pCache->pSynced = pPg;
44000  if( !pPg ){
44001  for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
44002  }
44003  if( pPg ){
44004  int rc;
44005 #ifdef SQLITE_LOG_CACHE_SPILL
44006  sqlite3_log(SQLITE_FULL,
44007  "spill page %d making room for %d - cache used: %d/%d",
44008  pPg->pgno, pgno,
44009  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
44010  numberOfCachePages(pCache));
44011 #endif
44012  pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
44013  rc = pCache->xStress(pCache->pStress, pPg);
44014  pcacheDump(pCache);
44015  if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
44016  return rc;
44017  }
44018  }
44019  }
44020  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
44021  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
44022 }
44023 
44024 /*
44025 ** This is a helper routine for sqlite3PcacheFetchFinish()
44026 **
44027 ** In the uncommon case where the page being fetched has not been
44028 ** initialized, this routine is invoked to do the initialization.
44029 ** This routine is broken out into a separate function since it
44030 ** requires extra stack manipulation that can be avoided in the common
44031 ** case.
44032 */
44034  PCache *pCache, /* Obtain the page from this cache */
44035  Pgno pgno, /* Page number obtained */
44036  sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
44037 ){
44038  PgHdr *pPgHdr;
44039  assert( pPage!=0 );
44040  pPgHdr = (PgHdr*)pPage->pExtra;
44041  assert( pPgHdr->pPage==0 );
44042  memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
44043  pPgHdr->pPage = pPage;
44044  pPgHdr->pData = pPage->pBuf;
44045  pPgHdr->pExtra = (void *)&pPgHdr[1];
44046  memset(pPgHdr->pExtra, 0, pCache->szExtra);
44047  pPgHdr->pCache = pCache;
44048  pPgHdr->pgno = pgno;
44049  pPgHdr->flags = PGHDR_CLEAN;
44050  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
44051 }
44052 
44053 /*
44054 ** This routine converts the sqlite3_pcache_page object returned by
44055 ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
44056 ** must be called after sqlite3PcacheFetch() in order to get a usable
44057 ** result.
44058 */
44060  PCache *pCache, /* Obtain the page from this cache */
44061  Pgno pgno, /* Page number obtained */
44062  sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
44063 ){
44064  PgHdr *pPgHdr;
44065 
44066  assert( pPage!=0 );
44067  pPgHdr = (PgHdr *)pPage->pExtra;
44068 
44069  if( !pPgHdr->pPage ){
44070  return pcacheFetchFinishWithInit(pCache, pgno, pPage);
44071  }
44072  pCache->nRefSum++;
44073  pPgHdr->nRef++;
44074  assert( sqlite3PcachePageSanity(pPgHdr) );
44075  return pPgHdr;
44076 }
44077 
44078 /*
44079 ** Decrement the reference count on a page. If the page is clean and the
44080 ** reference count drops to 0, then it is made eligible for recycling.
44081 */
44083  assert( p->nRef>0 );
44084  p->pCache->nRefSum--;
44085  if( (--p->nRef)==0 ){
44086  if( p->flags&PGHDR_CLEAN ){
44087  pcacheUnpin(p);
44088  }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
44089  /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
44090  ** then page p is already at the head of the dirty list and the
44091  ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
44092  ** tag above. */
44094  }
44095  }
44096 }
44097 
44098 /*
44099 ** Increase the reference count of a supplied page by 1.
44100 */
44102  assert(p->nRef>0);
44103  assert( sqlite3PcachePageSanity(p) );
44104  p->nRef++;
44105  p->pCache->nRefSum++;
44106 }
44107 
44108 /*
44109 ** Drop a page from the cache. There must be exactly one reference to the
44110 ** page. This function deletes that reference, so after it returns the
44111 ** page pointed to by p is invalid.
44112 */
44114  assert( p->nRef==1 );
44115  assert( sqlite3PcachePageSanity(p) );
44116  if( p->flags&PGHDR_DIRTY ){
44118  }
44119  p->pCache->nRefSum--;
44120  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
44121 }
44122 
44123 /*
44124 ** Make sure the page is marked as dirty. If it isn't dirty already,
44125 ** make it so.
44126 */
44128  assert( p->nRef>0 );
44129  assert( sqlite3PcachePageSanity(p) );
44130  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
44131  p->flags &= ~PGHDR_DONT_WRITE;
44132  if( p->flags & PGHDR_CLEAN ){
44133  p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
44134  pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
44135  assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
44137  }
44138  assert( sqlite3PcachePageSanity(p) );
44139  }
44140 }
44141 
44142 /*
44143 ** Make sure the page is marked as clean. If it isn't clean already,
44144 ** make it so.
44145 */
44147  assert( sqlite3PcachePageSanity(p) );
44148  if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
44149  assert( (p->flags & PGHDR_CLEAN)==0 );
44152  p->flags |= PGHDR_CLEAN;
44153  pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
44154  assert( sqlite3PcachePageSanity(p) );
44155  if( p->nRef==0 ){
44156  pcacheUnpin(p);
44157  }
44158  }
44159 }
44160 
44161 /*
44162 ** Make every page in the cache clean.
44163 */
44165  PgHdr *p;
44166  pcacheTrace(("%p.CLEAN-ALL\n",pCache));
44167  while( (p = pCache->pDirty)!=0 ){
44169  }
44170 }
44171 
44172 /*
44173 ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
44174 */
44176  PgHdr *p;
44177  pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
44178  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44180  }
44181  pCache->pSynced = pCache->pDirtyTail;
44182 }
44183 
44184 /*
44185 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
44186 */
44188  PgHdr *p;
44189  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44190  p->flags &= ~PGHDR_NEED_SYNC;
44191  }
44192  pCache->pSynced = pCache->pDirtyTail;
44193 }
44194 
44195 /*
44196 ** Change the page number of page p to newPgno.
44197 */
44198 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
44199  PCache *pCache = p->pCache;
44200  assert( p->nRef>0 );
44201  assert( newPgno>0 );
44202  assert( sqlite3PcachePageSanity(p) );
44203  pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
44204  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
44205  p->pgno = newPgno;
44206  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
44208  }
44209 }
44210 
44211 /*
44212 ** Drop every cache entry whose page number is greater than "pgno". The
44213 ** caller must ensure that there are no outstanding references to any pages
44214 ** other than page 1 with a page number greater than pgno.
44215 **
44216 ** If there is a reference to page 1 and the pgno parameter passed to this
44217 ** function is 0, then the data area associated with page 1 is zeroed, but
44218 ** the page object is not dropped.
44219 */
44221  if( pCache->pCache ){
44222  PgHdr *p;
44223  PgHdr *pNext;
44224  pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
44225  for(p=pCache->pDirty; p; p=pNext){
44226  pNext = p->pDirtyNext;
44227  /* This routine never gets call with a positive pgno except right
44228  ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
44229  ** it must be that pgno==0.
44230  */
44231  assert( p->pgno>0 );
44232  if( p->pgno>pgno ){
44233  assert( p->flags&PGHDR_DIRTY );
44235  }
44236  }
44237  if( pgno==0 && pCache->nRefSum ){
44238  sqlite3_pcache_page *pPage1;
44239  pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
44240  if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
44241  ** pCache->nRefSum>0 */
44242  memset(pPage1->pBuf, 0, pCache->szPage);
44243  pgno = 1;
44244  }
44245  }
44246  sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
44247  }
44248 }
44249 
44250 /*
44251 ** Close a cache.
44252 */
44254  assert( pCache->pCache!=0 );
44255  pcacheTrace(("%p.CLOSE\n",pCache));
44256  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
44257 }
44258 
44259 /*
44260 ** Discard the contents of the cache.
44261 */
44263  sqlite3PcacheTruncate(pCache, 0);
44264 }
44265 
44266 /*
44267 ** Merge two lists of pages connected by pDirty and in pgno order.
44268 ** Do not bother fixing the pDirtyPrev pointers.
44269 */
44271  PgHdr result, *pTail;
44272  pTail = &result;
44273  assert( pA!=0 && pB!=0 );
44274  for(;;){
44275  if( pA->pgno<pB->pgno ){
44276  pTail->pDirty = pA;
44277  pTail = pA;
44278  pA = pA->pDirty;
44279  if( pA==0 ){
44280  pTail->pDirty = pB;
44281  break;
44282  }
44283  }else{
44284  pTail->pDirty = pB;
44285  pTail = pB;
44286  pB = pB->pDirty;
44287  if( pB==0 ){
44288  pTail->pDirty = pA;
44289  break;
44290  }
44291  }
44292  }
44293  return result.pDirty;
44294 }
44295 
44296 /*
44297 ** Sort the list of pages in accending order by pgno. Pages are
44298 ** connected by pDirty pointers. The pDirtyPrev pointers are
44299 ** corrupted by this sort.
44300 **
44301 ** Since there cannot be more than 2^31 distinct pages in a database,
44302 ** there cannot be more than 31 buckets required by the merge sorter.
44303 ** One extra bucket is added to catch overflow in case something
44304 ** ever changes to make the previous sentence incorrect.
44305 */
44306 #define N_SORT_BUCKET 32
44308  PgHdr *a[N_SORT_BUCKET], *p;
44309  int i;
44310  memset(a, 0, sizeof(a));
44311  while( pIn ){
44312  p = pIn;
44313  pIn = p->pDirty;
44314  p->pDirty = 0;
44315  for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
44316  if( a[i]==0 ){
44317  a[i] = p;
44318  break;
44319  }else{
44320  p = pcacheMergeDirtyList(a[i], p);
44321  a[i] = 0;
44322  }
44323  }
44324  if( NEVER(i==N_SORT_BUCKET-1) ){
44325  /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
44326  ** the input list. But that is impossible.
44327  */
44328  a[i] = pcacheMergeDirtyList(a[i], p);
44329  }
44330  }
44331  p = a[0];
44332  for(i=1; i<N_SORT_BUCKET; i++){
44333  if( a[i]==0 ) continue;
44334  p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
44335  }
44336  return p;
44337 }
44338 
44339 /*
44340 ** Return a list of all dirty pages in the cache, sorted by page number.
44341 */
44343  PgHdr *p;
44344  for(p=pCache->pDirty; p; p=p->pDirtyNext){
44345  p->pDirty = p->pDirtyNext;
44346  }
44347  return pcacheSortDirtyList(pCache->pDirty);
44348 }
44349 
44350 /*
44351 ** Return the total number of references to all pages held by the cache.
44352 **
44353 ** This is not the total number of pages referenced, but the sum of the
44354 ** reference count for all pages.
44355 */
44357  return pCache->nRefSum;
44358 }
44359 
44360 /*
44361 ** Return the number of references to the page supplied as an argument.
44362 */
44364  return p->nRef;
44365 }
44366 
44367 /*
44368 ** Return the total number of pages in the cache.
44369 */
44371  assert( pCache->pCache!=0 );
44372  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
44373 }
44374 
44375 #ifdef SQLITE_TEST
44376 /*
44377 ** Get the suggested cache-size value.
44378 */
44379 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
44380  return numberOfCachePages(pCache);
44381 }
44382 #endif
44383 
44384 /*
44385 ** Set the suggested cache-size value.
44386 */
44388  assert( pCache->pCache!=0 );
44389  pCache->szCache = mxPage;
44390  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
44391  numberOfCachePages(pCache));
44392 }
44393 
44394 /*
44395 ** Set the suggested cache-spill value. Make no changes if if the
44396 ** argument is zero. Return the effective cache-spill size, which will
44397 ** be the larger of the szSpill and szCache.
44398 */
44400  int res;
44401  assert( p->pCache!=0 );
44402  if( mxPage ){
44403  if( mxPage<0 ){
44404  mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
44405  }
44406  p->szSpill = mxPage;
44407  }
44408  res = numberOfCachePages(p);
44409  if( res<p->szSpill ) res = p->szSpill;
44410  return res;
44411 }
44412 
44413 /*
44414 ** Free up as much memory as possible from the page cache.
44415 */
44417  assert( pCache->pCache!=0 );
44418  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
44419 }
44420 
44421 /*
44422 ** Return the size of the header added by this middleware layer
44423 ** in the page-cache hierarchy.
44424 */
44426 
44427 /*
44428 ** Return the number of dirty pages currently in the cache, as a percentage
44429 ** of the configured cache size.
44430 */
44432  PgHdr *pDirty;
44433  int nDirty = 0;
44434  int nCache = numberOfCachePages(pCache);
44435  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
44436  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
44437 }
44438 
44439 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
44440 /*
44441 ** For all dirty pages currently in the cache, invoke the specified
44442 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
44443 ** defined.
44444 */
44445 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
44446  PgHdr *pDirty;
44447  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
44448  xIter(pDirty);
44449  }
44450 }
44451 #endif
44452 
44453 /************** End of pcache.c **********************************************/
44454 /************** Begin file pcache1.c *****************************************/
44455 /*
44456 ** 2008 November 05
44457 **
44458 ** The author disclaims copyright to this source code. In place of
44459 ** a legal notice, here is a blessing:
44460 **
44461 ** May you do good and not evil.
44462 ** May you find forgiveness for yourself and forgive others.
44463 ** May you share freely, never taking more than you give.
44464 **
44465 *************************************************************************
44466 **
44467 ** This file implements the default page cache implementation (the
44468 ** sqlite3_pcache interface). It also contains part of the implementation
44469 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
44470 ** If the default page cache implementation is overridden, then neither of
44471 ** these two features are available.
44472 **
44473 ** A Page cache line looks like this:
44474 **
44475 ** -------------------------------------------------------------
44476 ** | database page content | PgHdr1 | MemPage | PgHdr |
44477 ** -------------------------------------------------------------
44478 **
44479 ** The database page content is up front (so that buffer overreads tend to
44480 ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
44481 ** is the extension added by the btree.c module containing information such
44482 ** as the database page number and how that database page is used. PgHdr
44483 ** is added by the pcache.c layer and contains information used to keep track
44484 ** of which pages are "dirty". PgHdr1 is an extension added by this
44485 ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
44486 ** PgHdr1 contains information needed to look up a page by its page number.
44487 ** The superclass sqlite3_pcache_page.pBuf points to the start of the
44488 ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
44489 **
44490 ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
44491 ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
44492 ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
44493 ** size can vary according to architecture, compile-time options, and
44494 ** SQLite library version number.
44495 **
44496 ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
44497 ** using a separate memory allocation from the database page content. This
44498 ** seeks to overcome the "clownshoe" problem (also called "internal
44499 ** fragmentation" in academic literature) of allocating a few bytes more
44500 ** than a power of two with the memory allocator rounding up to the next
44501 ** power of two, and leaving the rounded-up space unused.
44502 **
44503 ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
44504 ** with this module. Information is passed back and forth as PgHdr1 pointers.
44505 **
44506 ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
44507 ** The btree.c module deals with pointers to MemPage objects.
44508 **
44509 ** SOURCE OF PAGE CACHE MEMORY:
44510 **
44511 ** Memory for a page might come from any of three sources:
44512 **
44513 ** (1) The general-purpose memory allocator - sqlite3Malloc()
44514 ** (2) Global page-cache memory provided using sqlite3_config() with
44515 ** SQLITE_CONFIG_PAGECACHE.
44516 ** (3) PCache-local bulk allocation.
44517 **
44518 ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
44519 ** that is allocated when the page cache is created. The size of the local
44520 ** bulk allocation can be adjusted using
44521 **
44522 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
44523 **
44524 ** If N is positive, then N pages worth of memory are allocated using a single
44525 ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
44526 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
44527 ** for as many pages as can be accomodated.
44528 **
44529 ** Only one of (2) or (3) can be used. Once the memory available to (2) or
44530 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
44531 ** memory allocator (1).
44532 **
44533 ** Earlier versions of SQLite used only methods (1) and (2). But experiments
44534 ** show that method (3) with N==100 provides about a 5% performance boost for
44535 ** common workloads.
44536 */
44537 /* #include "sqliteInt.h" */
44538 
44539 typedef struct PCache1 PCache1;
44540 typedef struct PgHdr1 PgHdr1;
44541 typedef struct PgFreeslot PgFreeslot;
44542 typedef struct PGroup PGroup;
44543 
44544 /*
44545 ** Each cache entry is represented by an instance of the following
44546 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
44547 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
44548 ** in memory.
44549 */
44550 struct PgHdr1 {
44551  sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
44552  unsigned int iKey; /* Key value (page number) */
44553  u8 isPinned; /* Page in use, not on the LRU list */
44554  u8 isBulkLocal; /* This page from bulk local storage */
44555  u8 isAnchor; /* This is the PGroup.lru element */
44556  PgHdr1 *pNext; /* Next in hash table chain */
44557  PCache1 *pCache; /* Cache that currently owns this page */
44558  PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
44559  PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
44560 };
44561 
44562 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
44563 ** of one or more PCaches that are able to recycle each other's unpinned
44564 ** pages when they are under memory pressure. A PGroup is an instance of
44565 ** the following object.
44566 **
44567 ** This page cache implementation works in one of two modes:
44568 **
44569 ** (1) Every PCache is the sole member of its own PGroup. There is
44570 ** one PGroup per PCache.
44571 **
44572 ** (2) There is a single global PGroup that all PCaches are a member
44573 ** of.
44574 **
44575 ** Mode 1 uses more memory (since PCache instances are not able to rob
44576 ** unused pages from other PCaches) but it also operates without a mutex,
44577 ** and is therefore often faster. Mode 2 requires a mutex in order to be
44578 ** threadsafe, but recycles pages more efficiently.
44579 **
44580 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
44581 ** PGroup which is the pcache1.grp global variable and its mutex is
44582 ** SQLITE_MUTEX_STATIC_LRU.
44583 */
44584 struct PGroup {
44585  sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
44586  unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
44587  unsigned int nMinPage; /* Sum of nMin for purgeable caches */
44588  unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
44589  unsigned int nCurrentPage; /* Number of purgeable pages allocated */
44590  PgHdr1 lru; /* The beginning and end of the LRU list */
44591 };
44592 
44593 /* Each page cache is an instance of the following object. Every
44594 ** open database file (including each in-memory database and each
44595 ** temporary or transient database) has a single page cache which
44596 ** is an instance of this object.
44597 **
44598 ** Pointers to structures of this type are cast and returned as
44599 ** opaque sqlite3_pcache* handles.
44600 */
44601 struct PCache1 {
44602  /* Cache configuration parameters. Page size (szPage) and the purgeable
44603  ** flag (bPurgeable) are set when the cache is created. nMax may be
44604  ** modified at any time by a call to the pcache1Cachesize() method.
44605  ** The PGroup mutex must be held when accessing nMax.
44606  */
44607  PGroup *pGroup; /* PGroup this cache belongs to */
44608  int szPage; /* Size of database content section */
44609  int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
44610  int szAlloc; /* Total size of one pcache line */
44611  int bPurgeable; /* True if cache is purgeable */
44612  unsigned int nMin; /* Minimum number of pages reserved */
44613  unsigned int nMax; /* Configured "cache_size" value */
44614  unsigned int n90pct; /* nMax*9/10 */
44615  unsigned int iMaxKey; /* Largest key seen since xTruncate() */
44616 
44617  /* Hash table of all pages. The following variables may only be accessed
44618  ** when the accessor is holding the PGroup mutex.
44619  */
44620  unsigned int nRecyclable; /* Number of pages in the LRU list */
44621  unsigned int nPage; /* Total number of pages in apHash */
44622  unsigned int nHash; /* Number of slots in apHash[] */
44623  PgHdr1 **apHash; /* Hash table for fast lookup by key */
44624  PgHdr1 *pFree; /* List of unused pcache-local pages */
44625  void *pBulk; /* Bulk memory used by pcache-local */
44626 };
44627 
44628 /*
44629 ** Free slots in the allocator used to divide up the global page cache
44630 ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
44631 */
44632 struct PgFreeslot {
44633  PgFreeslot *pNext; /* Next free slot */
44634 };
44635 
44636 /*
44637 ** Global data used by this cache.
44638 */
44639 static SQLITE_WSD struct PCacheGlobal {
44640  PGroup grp; /* The global PGroup for mode (2) */
44641 
44642  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
44643  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
44644  ** fixed at sqlite3_initialize() time and do not require mutex protection.
44645  ** The nFreeSlot and pFree values do require mutex protection.
44646  */
44647  int isInit; /* True if initialized */
44648  int separateCache; /* Use a new PGroup for each PCache */
44649  int nInitPage; /* Initial bulk allocation size */
44650  int szSlot; /* Size of each free slot */
44651  int nSlot; /* The number of pcache slots */
44652  int nReserve; /* Try to keep nFreeSlot above this */
44653  void *pStart, *pEnd; /* Bounds of global page cache memory */
44654  /* Above requires no mutex. Use mutex below for variable that follow. */
44655  sqlite3_mutex *mutex; /* Mutex for accessing the following: */
44656  PgFreeslot *pFree; /* Free page blocks */
44657  int nFreeSlot; /* Number of unused pcache slots */
44658  /* The following value requires a mutex to change. We skip the mutex on
44659  ** reading because (1) most platforms read a 32-bit integer atomically and
44660  ** (2) even if an incorrect value is read, no great harm is done since this
44661  ** is really just an optimization. */
44662  int bUnderPressure; /* True if low on PAGECACHE memory */
44663 } pcache1_g;
44664 
44665 /*
44666 ** All code in this file should access the global structure above via the
44667 ** alias "pcache1". This ensures that the WSD emulation is used when
44668 ** compiling for systems that do not support real WSD.
44669 */
44670 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
44671 
44672 /*
44673 ** Macros to enter and leave the PCache LRU mutex.
44674 */
44675 #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
44676 # define pcache1EnterMutex(X) assert((X)->mutex==0)
44677 # define pcache1LeaveMutex(X) assert((X)->mutex==0)
44678 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
44679 #else
44680 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
44681 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
44682 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
44683 #endif
44684 
44685 /******************************************************************************/
44686 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
44687 
44688 
44689 /*
44690 ** This function is called during initialization if a static buffer is
44691 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
44692 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
44693 ** enough to contain 'n' buffers of 'sz' bytes each.
44694 **
44695 ** This routine is called from sqlite3_initialize() and so it is guaranteed
44696 ** to be serialized already. There is no need for further mutexing.
44697 */
44698 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
44699  if( pcache1.isInit ){
44700  PgFreeslot *p;
44701  if( pBuf==0 ) sz = n = 0;
44702  sz = ROUNDDOWN8(sz);
44703  pcache1.szSlot = sz;
44704  pcache1.nSlot = pcache1.nFreeSlot = n;
44705  pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
44706  pcache1.pStart = pBuf;
44707  pcache1.pFree = 0;
44708  pcache1.bUnderPressure = 0;
44709  while( n-- ){
44710  p = (PgFreeslot*)pBuf;
44711  p->pNext = pcache1.pFree;
44712  pcache1.pFree = p;
44713  pBuf = (void*)&((char*)pBuf)[sz];
44714  }
44715  pcache1.pEnd = pBuf;
44716  }
44717 }
44718 
44719 /*
44720 ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
44721 ** true if pCache->pFree ends up containing one or more free pages.
44722 */
44723 static int pcache1InitBulk(PCache1 *pCache){
44724  i64 szBulk;
44725  char *zBulk;
44726  if( pcache1.nInitPage==0 ) return 0;
44727  /* Do not bother with a bulk allocation if the cache size very small */
44728  if( pCache->nMax<3 ) return 0;
44730  if( pcache1.nInitPage>0 ){
44731  szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
44732  }else{
44733  szBulk = -1024 * (i64)pcache1.nInitPage;
44734  }
44735  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
44736  szBulk = pCache->szAlloc*(i64)pCache->nMax;
44737  }
44738  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
44740  if( zBulk ){
44741  int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
44742  int i;
44743  for(i=0; i<nBulk; i++){
44744  PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
44745  pX->page.pBuf = zBulk;
44746  pX->page.pExtra = &pX[1];
44747  pX->isBulkLocal = 1;
44748  pX->isAnchor = 0;
44749  pX->pNext = pCache->pFree;
44750  pCache->pFree = pX;
44751  zBulk += pCache->szAlloc;
44752  }
44753  }
44754  return pCache->pFree!=0;
44755 }
44756 
44757 /*
44758 ** Malloc function used within this file to allocate space from the buffer
44759 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
44760 ** such buffer exists or there is no space left in it, this function falls
44761 ** back to sqlite3Malloc().
44762 **
44763 ** Multiple threads can run this routine at the same time. Global variables
44764 ** in pcache1 need to be protected via mutex.
44765 */
44766 static void *pcache1Alloc(int nByte){
44767  void *p = 0;
44768  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
44769  if( nByte<=pcache1.szSlot ){
44771  p = (PgHdr1 *)pcache1.pFree;
44772  if( p ){
44773  pcache1.pFree = pcache1.pFree->pNext;
44774  pcache1.nFreeSlot--;
44775  pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44776  assert( pcache1.nFreeSlot>=0 );
44779  }
44781  }
44782  if( p==0 ){
44783  /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
44784  ** it from sqlite3Malloc instead.
44785  */
44786  p = sqlite3Malloc(nByte);
44787 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44788  if( p ){
44789  int sz = sqlite3MallocSize(p);
44794  }
44795 #endif
44797  }
44798  return p;
44799 }
44800 
44801 /*
44802 ** Free an allocated buffer obtained from pcache1Alloc().
44803 */
44804 static void pcache1Free(void *p){
44805  if( p==0 ) return;
44806  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
44807  PgFreeslot *pSlot;
44810  pSlot = (PgFreeslot*)p;
44811  pSlot->pNext = pcache1.pFree;
44812  pcache1.pFree = pSlot;
44813  pcache1.nFreeSlot++;
44814  pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44815  assert( pcache1.nFreeSlot<=pcache1.nSlot );
44817  }else{
44818  assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44820 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44821  {
44822  int nFreed = 0;
44823  nFreed = sqlite3MallocSize(p);
44827  }
44828 #endif
44829  sqlite3_free(p);
44830  }
44831 }
44832 
44833 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44834 /*
44835 ** Return the size of a pcache allocation
44836 */
44837 static int pcache1MemSize(void *p){
44838  if( p>=pcache1.pStart && p<pcache1.pEnd ){
44839  return pcache1.szSlot;
44840  }else{
44841  int iSize;
44842  assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44844  iSize = sqlite3MallocSize(p);
44846  return iSize;
44847  }
44848 }
44849 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
44850 
44851 /*
44852 ** Allocate a new page object initially associated with cache pCache.
44853 */
44854 static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
44855  PgHdr1 *p = 0;
44856  void *pPg;
44857 
44858  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44859  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
44860  p = pCache->pFree;
44861  pCache->pFree = p->pNext;
44862  p->pNext = 0;
44863  }else{
44864 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44865  /* The group mutex must be released before pcache1Alloc() is called. This
44866  ** is because it might call sqlite3_release_memory(), which assumes that
44867  ** this mutex is not held. */
44868  assert( pcache1.separateCache==0 );
44869  assert( pCache->pGroup==&pcache1.grp );
44870  pcache1LeaveMutex(pCache->pGroup);
44871 #endif
44872  if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
44873 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44874  pPg = pcache1Alloc(pCache->szPage);
44875  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
44876  if( !pPg || !p ){
44877  pcache1Free(pPg);
44878  sqlite3_free(p);
44879  pPg = 0;
44880  }
44881 #else
44882  pPg = pcache1Alloc(pCache->szAlloc);
44883  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
44884 #endif
44885  if( benignMalloc ){ sqlite3EndBenignMalloc(); }
44886 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44887  pcache1EnterMutex(pCache->pGroup);
44888 #endif
44889  if( pPg==0 ) return 0;
44890  p->page.pBuf = pPg;
44891  p->page.pExtra = &p[1];
44892  p->isBulkLocal = 0;
44893  p->isAnchor = 0;
44894  }
44895  if( pCache->bPurgeable ){
44896  pCache->pGroup->nCurrentPage++;
44897  }
44898  return p;
44899 }
44900 
44901 /*
44902 ** Free a page object allocated by pcache1AllocPage().
44903 */
44904 static void pcache1FreePage(PgHdr1 *p){
44905  PCache1 *pCache;
44906  assert( p!=0 );
44907  pCache = p->pCache;
44908  assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
44909  if( p->isBulkLocal ){
44910  p->pNext = pCache->pFree;
44911  pCache->pFree = p;
44912  }else{
44913  pcache1Free(p->page.pBuf);
44914 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44915  sqlite3_free(p);
44916 #endif
44917  }
44918  if( pCache->bPurgeable ){
44919  pCache->pGroup->nCurrentPage--;
44920  }
44921 }
44922 
44923 /*
44924 ** Malloc function used by SQLite to obtain space from the buffer configured
44925 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
44926 ** exists, this function falls back to sqlite3Malloc().
44927 */
44929  return pcache1Alloc(sz);
44930 }
44931 
44932 /*
44933 ** Free an allocated buffer obtained from sqlite3PageMalloc().
44934 */
44936  pcache1Free(p);
44937 }
44938 
44939 
44940 /*
44941 ** Return true if it desirable to avoid allocating a new page cache
44942 ** entry.
44943 **
44944 ** If memory was allocated specifically to the page cache using
44945 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
44946 ** it is desirable to avoid allocating a new page cache entry because
44947 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
44948 ** for all page cache needs and we should not need to spill the
44949 ** allocation onto the heap.
44950 **
44951 ** Or, the heap is used for all page cache memory but the heap is
44952 ** under memory pressure, then again it is desirable to avoid
44953 ** allocating a new page cache entry in order to avoid stressing
44954 ** the heap even further.
44955 */
44957  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
44958  return pcache1.bUnderPressure;
44959  }else{
44960  return sqlite3HeapNearlyFull();
44961  }
44962 }
44963 
44964 /******************************************************************************/
44965 /******** General Implementation Functions ************************************/
44966 
44967 /*
44968 ** This function is used to resize the hash table used by the cache passed
44969 ** as the first argument.
44970 **
44971 ** The PCache mutex must be held when this function is called.
44972 */
44973 static void pcache1ResizeHash(PCache1 *p){
44974  PgHdr1 **apNew;
44975  unsigned int nNew;
44976  unsigned int i;
44977 
44978  assert( sqlite3_mutex_held(p->pGroup->mutex) );
44979 
44980  nNew = p->nHash*2;
44981  if( nNew<256 ){
44982  nNew = 256;
44983  }
44984 
44986  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
44987  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
44988  if( p->nHash ){ sqlite3EndBenignMalloc(); }
44990  if( apNew ){
44991  for(i=0; i<p->nHash; i++){
44992  PgHdr1 *pPage;
44993  PgHdr1 *pNext = p->apHash[i];
44994  while( (pPage = pNext)!=0 ){
44995  unsigned int h = pPage->iKey % nNew;
44996  pNext = pPage->pNext;
44997  pPage->pNext = apNew[h];
44998  apNew[h] = pPage;
44999  }
45000  }
45001  sqlite3_free(p->apHash);
45002  p->apHash = apNew;
45003  p->nHash = nNew;
45004  }
45005 }
45006 
45007 /*
45008 ** This function is used internally to remove the page pPage from the
45009 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
45010 ** LRU list, then this function is a no-op.
45011 **
45012 ** The PGroup mutex must be held when this function is called.
45013 */
45014 static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
45015  PCache1 *pCache;
45016 
45017  assert( pPage!=0 );
45018  assert( pPage->isPinned==0 );
45019  pCache = pPage->pCache;
45020  assert( pPage->pLruNext );
45021  assert( pPage->pLruPrev );
45022  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45023  pPage->pLruPrev->pLruNext = pPage->pLruNext;
45024  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
45025  pPage->pLruNext = 0;
45026  pPage->pLruPrev = 0;
45027  pPage->isPinned = 1;
45028  assert( pPage->isAnchor==0 );
45029  assert( pCache->pGroup->lru.isAnchor==1 );
45030  pCache->nRecyclable--;
45031  return pPage;
45032 }
45033 
45034 
45035 /*
45036 ** Remove the page supplied as an argument from the hash table
45037 ** (PCache1.apHash structure) that it is currently stored in.
45038 ** Also free the page if freePage is true.
45039 **
45040 ** The PGroup mutex must be held when this function is called.
45041 */
45042 static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
45043  unsigned int h;
45044  PCache1 *pCache = pPage->pCache;
45045  PgHdr1 **pp;
45046 
45047  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45048  h = pPage->iKey % pCache->nHash;
45049  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
45050  *pp = (*pp)->pNext;
45051 
45052  pCache->nPage--;
45053  if( freeFlag ) pcache1FreePage(pPage);
45054 }
45055 
45056 /*
45057 ** If there are currently more than nMaxPage pages allocated, try
45058 ** to recycle pages to reduce the number allocated to nMaxPage.
45059 */
45060 static void pcache1EnforceMaxPage(PCache1 *pCache){
45061  PGroup *pGroup = pCache->pGroup;
45062  PgHdr1 *p;
45063  assert( sqlite3_mutex_held(pGroup->mutex) );
45064  while( pGroup->nCurrentPage>pGroup->nMaxPage
45065  && (p=pGroup->lru.pLruPrev)->isAnchor==0
45066  ){
45067  assert( p->pCache->pGroup==pGroup );
45068  assert( p->isPinned==0 );
45069  pcache1PinPage(p);
45070  pcache1RemoveFromHash(p, 1);
45071  }
45072  if( pCache->nPage==0 && pCache->pBulk ){
45073  sqlite3_free(pCache->pBulk);
45074  pCache->pBulk = pCache->pFree = 0;
45075  }
45076 }
45077 
45078 /*
45079 ** Discard all pages from cache pCache with a page number (key value)
45080 ** greater than or equal to iLimit. Any pinned pages that meet this
45081 ** criteria are unpinned before they are discarded.
45082 **
45083 ** The PCache mutex must be held when this function is called.
45084 */
45086  PCache1 *pCache, /* The cache to truncate */
45087  unsigned int iLimit /* Drop pages with this pgno or larger */
45088 ){
45089  TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
45090  unsigned int h, iStop;
45091  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45092  assert( pCache->iMaxKey >= iLimit );
45093  assert( pCache->nHash > 0 );
45094  if( pCache->iMaxKey - iLimit < pCache->nHash ){
45095  /* If we are just shaving the last few pages off the end of the
45096  ** cache, then there is no point in scanning the entire hash table.
45097  ** Only scan those hash slots that might contain pages that need to
45098  ** be removed. */
45099  h = iLimit % pCache->nHash;
45100  iStop = pCache->iMaxKey % pCache->nHash;
45101  TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
45102  }else{
45103  /* This is the general case where many pages are being removed.
45104  ** It is necessary to scan the entire hash table */
45105  h = pCache->nHash/2;
45106  iStop = h - 1;
45107  }
45108  for(;;){
45109  PgHdr1 **pp;
45110  PgHdr1 *pPage;
45111  assert( h<pCache->nHash );
45112  pp = &pCache->apHash[h];
45113  while( (pPage = *pp)!=0 ){
45114  if( pPage->iKey>=iLimit ){
45115  pCache->nPage--;
45116  *pp = pPage->pNext;
45117  if( !pPage->isPinned ) pcache1PinPage(pPage);
45118  pcache1FreePage(pPage);
45119  }else{
45120  pp = &pPage->pNext;
45121  TESTONLY( if( nPage>=0 ) nPage++; )
45122  }
45123  }
45124  if( h==iStop ) break;
45125  h = (h+1) % pCache->nHash;
45126  }
45127  assert( nPage<0 || pCache->nPage==(unsigned)nPage );
45128 }
45129 
45130 /******************************************************************************/
45131 /******** sqlite3_pcache Methods **********************************************/
45132 
45133 /*
45134 ** Implementation of the sqlite3_pcache.xInit method.
45135 */
45136 static int pcache1Init(void *NotUsed){
45137  UNUSED_PARAMETER(NotUsed);
45138  assert( pcache1.isInit==0 );
45139  memset(&pcache1, 0, sizeof(pcache1));
45140 
45141 
45142  /*
45143  ** The pcache1.separateCache variable is true if each PCache has its own
45144  ** private PGroup (mode-1). pcache1.separateCache is false if the single
45145  ** PGroup in pcache1.grp is used for all page caches (mode-2).
45146  **
45147  ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
45148  **
45149  ** * Use a unified cache in single-threaded applications that have
45150  ** configured a start-time buffer for use as page-cache memory using
45151  ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
45152  ** pBuf argument.
45153  **
45154  ** * Otherwise use separate caches (mode-1)
45155  */
45156 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
45157  pcache1.separateCache = 0;
45158 #elif SQLITE_THREADSAFE
45159  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
45160  || sqlite3GlobalConfig.bCoreMutex>0;
45161 #else
45162  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
45163 #endif
45164 
45165 #if SQLITE_THREADSAFE
45166  if( sqlite3GlobalConfig.bCoreMutex ){
45169  }
45170 #endif
45171  if( pcache1.separateCache
45172  && sqlite3GlobalConfig.nPage!=0
45173  && sqlite3GlobalConfig.pPage==0
45174  ){
45175  pcache1.nInitPage = sqlite3GlobalConfig.nPage;
45176  }else{
45177  pcache1.nInitPage = 0;
45178  }
45179  pcache1.grp.mxPinned = 10;
45180  pcache1.isInit = 1;
45181  return SQLITE_OK;
45182 }
45183 
45184 /*
45185 ** Implementation of the sqlite3_pcache.xShutdown method.
45186 ** Note that the static mutex allocated in xInit does
45187 ** not need to be freed.
45188 */
45189 static void pcache1Shutdown(void *NotUsed){
45190  UNUSED_PARAMETER(NotUsed);
45191  assert( pcache1.isInit!=0 );
45192  memset(&pcache1, 0, sizeof(pcache1));
45193 }
45194 
45195 /* forward declaration */
45196 static void pcache1Destroy(sqlite3_pcache *p);
45197 
45198 /*
45199 ** Implementation of the sqlite3_pcache.xCreate method.
45200 **
45201 ** Allocate a new cache.
45202 */
45203 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
45204  PCache1 *pCache; /* The newly created page cache */
45205  PGroup *pGroup; /* The group the new page cache will belong to */
45206  int sz; /* Bytes of memory required to allocate the new cache */
45207 
45208  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
45209  assert( szExtra < 300 );
45210 
45211  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
45212  pCache = (PCache1 *)sqlite3MallocZero(sz);
45213  if( pCache ){
45214  if( pcache1.separateCache ){
45215  pGroup = (PGroup*)&pCache[1];
45216  pGroup->mxPinned = 10;
45217  }else{
45218  pGroup = &pcache1.grp;
45219  }
45220  if( pGroup->lru.isAnchor==0 ){
45221  pGroup->lru.isAnchor = 1;
45222  pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
45223  }
45224  pCache->pGroup = pGroup;
45225  pCache->szPage = szPage;
45226  pCache->szExtra = szExtra;
45227  pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
45228  pCache->bPurgeable = (bPurgeable ? 1 : 0);
45229  pcache1EnterMutex(pGroup);
45230  pcache1ResizeHash(pCache);
45231  if( bPurgeable ){
45232  pCache->nMin = 10;
45233  pGroup->nMinPage += pCache->nMin;
45234  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45235  }
45236  pcache1LeaveMutex(pGroup);
45237  if( pCache->nHash==0 ){
45238  pcache1Destroy((sqlite3_pcache*)pCache);
45239  pCache = 0;
45240  }
45241  }
45242  return (sqlite3_pcache *)pCache;
45243 }
45244 
45245 /*
45246 ** Implementation of the sqlite3_pcache.xCachesize method.
45247 **
45248 ** Configure the cache_size limit for a cache.
45249 */
45250 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
45251  PCache1 *pCache = (PCache1 *)p;
45252  if( pCache->bPurgeable ){
45253  PGroup *pGroup = pCache->pGroup;
45254  pcache1EnterMutex(pGroup);
45255  pGroup->nMaxPage += (nMax - pCache->nMax);
45256  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45257  pCache->nMax = nMax;
45258  pCache->n90pct = pCache->nMax*9/10;
45259  pcache1EnforceMaxPage(pCache);
45260  pcache1LeaveMutex(pGroup);
45261  }
45262 }
45263 
45264 /*
45265 ** Implementation of the sqlite3_pcache.xShrink method.
45266 **
45267 ** Free up as much memory as possible.
45268 */
45270  PCache1 *pCache = (PCache1*)p;
45271  if( pCache->bPurgeable ){
45272  PGroup *pGroup = pCache->pGroup;
45273  int savedMaxPage;
45274  pcache1EnterMutex(pGroup);
45275  savedMaxPage = pGroup->nMaxPage;
45276  pGroup->nMaxPage = 0;
45277  pcache1EnforceMaxPage(pCache);
45278  pGroup->nMaxPage = savedMaxPage;
45279  pcache1LeaveMutex(pGroup);
45280  }
45281 }
45282 
45283 /*
45284 ** Implementation of the sqlite3_pcache.xPagecount method.
45285 */
45287  int n;
45288  PCache1 *pCache = (PCache1*)p;
45289  pcache1EnterMutex(pCache->pGroup);
45290  n = pCache->nPage;
45291  pcache1LeaveMutex(pCache->pGroup);
45292  return n;
45293 }
45294 
45295 
45296 /*
45297 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
45298 ** in the header of the pcache1Fetch() procedure.
45299 **
45300 ** This steps are broken out into a separate procedure because they are
45301 ** usually not needed, and by avoiding the stack initialization required
45302 ** for these steps, the main pcache1Fetch() procedure can run faster.
45303 */
45305  PCache1 *pCache,
45306  unsigned int iKey,
45307  int createFlag
45308 ){
45309  unsigned int nPinned;
45310  PGroup *pGroup = pCache->pGroup;
45311  PgHdr1 *pPage = 0;
45312 
45313  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
45314  assert( pCache->nPage >= pCache->nRecyclable );
45315  nPinned = pCache->nPage - pCache->nRecyclable;
45316  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
45317  assert( pCache->n90pct == pCache->nMax*9/10 );
45318  if( createFlag==1 && (
45319  nPinned>=pGroup->mxPinned
45320  || nPinned>=pCache->n90pct
45321  || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
45322  )){
45323  return 0;
45324  }
45325 
45326  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
45327  assert( pCache->nHash>0 && pCache->apHash );
45328 
45329  /* Step 4. Try to recycle a page. */
45330  if( pCache->bPurgeable
45331  && !pGroup->lru.pLruPrev->isAnchor
45332  && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
45333  ){
45334  PCache1 *pOther;
45335  pPage = pGroup->lru.pLruPrev;
45336  assert( pPage->isPinned==0 );
45337  pcache1RemoveFromHash(pPage, 0);
45338  pcache1PinPage(pPage);
45339  pOther = pPage->pCache;
45340  if( pOther->szAlloc != pCache->szAlloc ){
45341  pcache1FreePage(pPage);
45342  pPage = 0;
45343  }else{
45344  pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
45345  }
45346  }
45347 
45348  /* Step 5. If a usable page buffer has still not been found,
45349  ** attempt to allocate a new one.
45350  */
45351  if( !pPage ){
45352  pPage = pcache1AllocPage(pCache, createFlag==1);
45353  }
45354 
45355  if( pPage ){
45356  unsigned int h = iKey % pCache->nHash;
45357  pCache->nPage++;
45358  pPage->iKey = iKey;
45359  pPage->pNext = pCache->apHash[h];
45360  pPage->pCache = pCache;
45361  pPage->pLruPrev = 0;
45362  pPage->pLruNext = 0;
45363  pPage->isPinned = 1;
45364  *(void **)pPage->page.pExtra = 0;
45365  pCache->apHash[h] = pPage;
45366  if( iKey>pCache->iMaxKey ){
45367  pCache->iMaxKey = iKey;
45368  }
45369  }
45370  return pPage;
45371 }
45372 
45373 /*
45374 ** Implementation of the sqlite3_pcache.xFetch method.
45375 **
45376 ** Fetch a page by key value.
45377 **
45378 ** Whether or not a new page may be allocated by this function depends on
45379 ** the value of the createFlag argument. 0 means do not allocate a new
45380 ** page. 1 means allocate a new page if space is easily available. 2
45381 ** means to try really hard to allocate a new page.
45382 **
45383 ** For a non-purgeable cache (a cache used as the storage for an in-memory
45384 ** database) there is really no difference between createFlag 1 and 2. So
45385 ** the calling function (pcache.c) will never have a createFlag of 1 on
45386 ** a non-purgeable cache.
45387 **
45388 ** There are three different approaches to obtaining space for a page,
45389 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
45390 **
45391 ** 1. Regardless of the value of createFlag, the cache is searched for a
45392 ** copy of the requested page. If one is found, it is returned.
45393 **
45394 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
45395 ** returned.
45396 **
45397 ** 3. If createFlag is 1, and the page is not already in the cache, then
45398 ** return NULL (do not allocate a new page) if any of the following
45399 ** conditions are true:
45400 **
45401 ** (a) the number of pages pinned by the cache is greater than
45402 ** PCache1.nMax, or
45403 **
45404 ** (b) the number of pages pinned by the cache is greater than
45405 ** the sum of nMax for all purgeable caches, less the sum of
45406 ** nMin for all other purgeable caches, or
45407 **
45408 ** 4. If none of the first three conditions apply and the cache is marked
45409 ** as purgeable, and if one of the following is true:
45410 **
45411 ** (a) The number of pages allocated for the cache is already
45412 ** PCache1.nMax, or
45413 **
45414 ** (b) The number of pages allocated for all purgeable caches is
45415 ** already equal to or greater than the sum of nMax for all
45416 ** purgeable caches,
45417 **
45418 ** (c) The system is under memory pressure and wants to avoid
45419 ** unnecessary pages cache entry allocations
45420 **
45421 ** then attempt to recycle a page from the LRU list. If it is the right
45422 ** size, return the recycled buffer. Otherwise, free the buffer and
45423 ** proceed to step 5.
45424 **
45425 ** 5. Otherwise, allocate and return a new page buffer.
45426 **
45427 ** There are two versions of this routine. pcache1FetchWithMutex() is
45428 ** the general case. pcache1FetchNoMutex() is a faster implementation for
45429 ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
45430 ** invokes the appropriate routine.
45431 */
45433  sqlite3_pcache *p,
45434  unsigned int iKey,
45435  int createFlag
45436 ){
45437  PCache1 *pCache = (PCache1 *)p;
45438  PgHdr1 *pPage = 0;
45439 
45440  /* Step 1: Search the hash table for an existing entry. */
45441  pPage = pCache->apHash[iKey % pCache->nHash];
45442  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
45443 
45444  /* Step 2: If the page was found in the hash table, then return it.
45445  ** If the page was not in the hash table and createFlag is 0, abort.
45446  ** Otherwise (page not in hash and createFlag!=0) continue with
45447  ** subsequent steps to try to create the page. */
45448  if( pPage ){
45449  if( !pPage->isPinned ){
45450  return pcache1PinPage(pPage);
45451  }else{
45452  return pPage;
45453  }
45454  }else if( createFlag ){
45455  /* Steps 3, 4, and 5 implemented by this subroutine */
45456  return pcache1FetchStage2(pCache, iKey, createFlag);
45457  }else{
45458  return 0;
45459  }
45460 }
45461 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
45462 static PgHdr1 *pcache1FetchWithMutex(
45463  sqlite3_pcache *p,
45464  unsigned int iKey,
45465  int createFlag
45466 ){
45467  PCache1 *pCache = (PCache1 *)p;
45468  PgHdr1 *pPage;
45469 
45470  pcache1EnterMutex(pCache->pGroup);
45471  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
45472  assert( pPage==0 || pCache->iMaxKey>=iKey );
45473  pcache1LeaveMutex(pCache->pGroup);
45474  return pPage;
45475 }
45476 #endif
45478  sqlite3_pcache *p,
45479  unsigned int iKey,
45480  int createFlag
45481 ){
45482 #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
45483  PCache1 *pCache = (PCache1 *)p;
45484 #endif
45485 
45486  assert( offsetof(PgHdr1,page)==0 );
45487  assert( pCache->bPurgeable || createFlag!=1 );
45488  assert( pCache->bPurgeable || pCache->nMin==0 );
45489  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
45490  assert( pCache->nMin==0 || pCache->bPurgeable );
45491  assert( pCache->nHash>0 );
45492 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
45493  if( pCache->pGroup->mutex ){
45494  return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
45495  }else
45496 #endif
45497  {
45498  return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
45499  }
45500 }
45501 
45502 
45503 /*
45504 ** Implementation of the sqlite3_pcache.xUnpin method.
45505 **
45506 ** Mark a page as unpinned (eligible for asynchronous recycling).
45507 */
45508 static void pcache1Unpin(
45509  sqlite3_pcache *p,
45510  sqlite3_pcache_page *pPg,
45511  int reuseUnlikely
45512 ){
45513  PCache1 *pCache = (PCache1 *)p;
45514  PgHdr1 *pPage = (PgHdr1 *)pPg;
45515  PGroup *pGroup = pCache->pGroup;
45516 
45517  assert( pPage->pCache==pCache );
45518  pcache1EnterMutex(pGroup);
45519 
45520  /* It is an error to call this function if the page is already
45521  ** part of the PGroup LRU list.
45522  */
45523  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
45524  assert( pPage->isPinned==1 );
45525 
45526  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
45527  pcache1RemoveFromHash(pPage, 1);
45528  }else{
45529  /* Add the page to the PGroup LRU list. */
45530  PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
45531  pPage->pLruPrev = &pGroup->lru;
45532  (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
45533  *ppFirst = pPage;
45534  pCache->nRecyclable++;
45535  pPage->isPinned = 0;
45536  }
45537 
45538  pcache1LeaveMutex(pCache->pGroup);
45539 }
45540 
45541 /*
45542 ** Implementation of the sqlite3_pcache.xRekey method.
45543 */
45544 static void pcache1Rekey(
45545  sqlite3_pcache *p,
45546  sqlite3_pcache_page *pPg,
45547  unsigned int iOld,
45548  unsigned int iNew
45549 ){
45550  PCache1 *pCache = (PCache1 *)p;
45551  PgHdr1 *pPage = (PgHdr1 *)pPg;
45552  PgHdr1 **pp;
45553  unsigned int h;
45554  assert( pPage->iKey==iOld );
45555  assert( pPage->pCache==pCache );
45556 
45557  pcache1EnterMutex(pCache->pGroup);
45558 
45559  h = iOld%pCache->nHash;
45560  pp = &pCache->apHash[h];
45561  while( (*pp)!=pPage ){
45562  pp = &(*pp)->pNext;
45563  }
45564  *pp = pPage->pNext;
45565 
45566  h = iNew%pCache->nHash;
45567  pPage->iKey = iNew;
45568  pPage->pNext = pCache->apHash[h];
45569  pCache->apHash[h] = pPage;
45570  if( iNew>pCache->iMaxKey ){
45571  pCache->iMaxKey = iNew;
45572  }
45573 
45574  pcache1LeaveMutex(pCache->pGroup);
45575 }
45576 
45577 /*
45578 ** Implementation of the sqlite3_pcache.xTruncate method.
45579 **
45580 ** Discard all unpinned pages in the cache with a page number equal to
45581 ** or greater than parameter iLimit. Any pinned pages with a page number
45582 ** equal to or greater than iLimit are implicitly unpinned.
45583 */
45584 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
45585  PCache1 *pCache = (PCache1 *)p;
45586  pcache1EnterMutex(pCache->pGroup);
45587  if( iLimit<=pCache->iMaxKey ){
45588  pcache1TruncateUnsafe(pCache, iLimit);
45589  pCache->iMaxKey = iLimit-1;
45590  }
45591  pcache1LeaveMutex(pCache->pGroup);
45592 }
45593 
45594 /*
45595 ** Implementation of the sqlite3_pcache.xDestroy method.
45596 **
45597 ** Destroy a cache allocated using pcache1Create().
45598 */
45600  PCache1 *pCache = (PCache1 *)p;
45601  PGroup *pGroup = pCache->pGroup;
45602  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
45603  pcache1EnterMutex(pGroup);
45604  if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
45605  assert( pGroup->nMaxPage >= pCache->nMax );
45606  pGroup->nMaxPage -= pCache->nMax;
45607  assert( pGroup->nMinPage >= pCache->nMin );
45608  pGroup->nMinPage -= pCache->nMin;
45609  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45610  pcache1EnforceMaxPage(pCache);
45611  pcache1LeaveMutex(pGroup);
45612  sqlite3_free(pCache->pBulk);
45613  sqlite3_free(pCache->apHash);
45614  sqlite3_free(pCache);
45615 }
45616 
45617 /*
45618 ** This function is called during initialization (sqlite3_initialize()) to
45619 ** install the default pluggable cache module, assuming the user has not
45620 ** already provided an alternative.
45621 */
45623  static const sqlite3_pcache_methods2 defaultMethods = {
45624  1, /* iVersion */
45625  0, /* pArg */
45626  pcache1Init, /* xInit */
45627  pcache1Shutdown, /* xShutdown */
45628  pcache1Create, /* xCreate */
45629  pcache1Cachesize, /* xCachesize */
45630  pcache1Pagecount, /* xPagecount */
45631  pcache1Fetch, /* xFetch */
45632  pcache1Unpin, /* xUnpin */
45633  pcache1Rekey, /* xRekey */
45634  pcache1Truncate, /* xTruncate */
45635  pcache1Destroy, /* xDestroy */
45636  pcache1Shrink /* xShrink */
45637  };
45638  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
45639 }
45640 
45641 /*
45642 ** Return the size of the header on each page of this PCACHE implementation.
45643 */
45645 
45646 /*
45647 ** Return the global mutex used by this PCACHE implementation. The
45648 ** sqlite3_status() routine needs access to this mutex.
45649 */
45651  return pcache1.mutex;
45652 }
45653 
45654 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45655 /*
45656 ** This function is called to free superfluous dynamically allocated memory
45657 ** held by the pager system. Memory in use by any SQLite pager allocated
45658 ** by the current thread may be sqlite3_free()ed.
45659 **
45660 ** nReq is the number of bytes of memory required. Once this much has
45661 ** been released, the function returns. The return value is the total number
45662 ** of bytes of memory released.
45663 */
45664 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
45665  int nFree = 0;
45666  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45667  assert( sqlite3_mutex_notheld(pcache1.mutex) );
45668  if( sqlite3GlobalConfig.nPage==0 ){
45669  PgHdr1 *p;
45670  pcache1EnterMutex(&pcache1.grp);
45671  while( (nReq<0 || nFree<nReq)
45672  && (p=pcache1.grp.lru.pLruPrev)!=0
45673  && p->isAnchor==0
45674  ){
45675  nFree += pcache1MemSize(p->page.pBuf);
45676 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
45677  nFree += sqlite3MemSize(p);
45678 #endif
45679  assert( p->isPinned==0 );
45680  pcache1PinPage(p);
45681  pcache1RemoveFromHash(p, 1);
45682  }
45683  pcache1LeaveMutex(&pcache1.grp);
45684  }
45685  return nFree;
45686 }
45687 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45688 
45689 #ifdef SQLITE_TEST
45690 /*
45691 ** This function is used by test procedures to inspect the internal state
45692 ** of the global cache.
45693 */
45694 SQLITE_PRIVATE void sqlite3PcacheStats(
45695  int *pnCurrent, /* OUT: Total number of pages cached */
45696  int *pnMax, /* OUT: Global maximum cache size */
45697  int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
45698  int *pnRecyclable /* OUT: Total number of pages available for recycling */
45699 ){
45700  PgHdr1 *p;
45701  int nRecyclable = 0;
45702  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
45703  assert( p->isPinned==0 );
45704  nRecyclable++;
45705  }
45706  *pnCurrent = pcache1.grp.nCurrentPage;
45707  *pnMax = (int)pcache1.grp.nMaxPage;
45708  *pnMin = (int)pcache1.grp.nMinPage;
45709  *pnRecyclable = nRecyclable;
45710 }
45711 #endif
45712 
45713 /************** End of pcache1.c *********************************************/
45714 /************** Begin file rowset.c ******************************************/
45715 /*
45716 ** 2008 December 3
45717 **
45718 ** The author disclaims copyright to this source code. In place of
45719 ** a legal notice, here is a blessing:
45720 **
45721 ** May you do good and not evil.
45722 ** May you find forgiveness for yourself and forgive others.
45723 ** May you share freely, never taking more than you give.
45724 **
45725 *************************************************************************
45726 **
45727 ** This module implements an object we call a "RowSet".
45728 **
45729 ** The RowSet object is a collection of rowids. Rowids
45730 ** are inserted into the RowSet in an arbitrary order. Inserts
45731 ** can be intermixed with tests to see if a given rowid has been
45732 ** previously inserted into the RowSet.
45733 **
45734 ** After all inserts are finished, it is possible to extract the
45735 ** elements of the RowSet in sorted order. Once this extraction
45736 ** process has started, no new elements may be inserted.
45737 **
45738 ** Hence, the primitive operations for a RowSet are:
45739 **
45740 ** CREATE
45741 ** INSERT
45742 ** TEST
45743 ** SMALLEST
45744 ** DESTROY
45745 **
45746 ** The CREATE and DESTROY primitives are the constructor and destructor,
45747 ** obviously. The INSERT primitive adds a new element to the RowSet.
45748 ** TEST checks to see if an element is already in the RowSet. SMALLEST
45749 ** extracts the least value from the RowSet.
45750 **
45751 ** The INSERT primitive might allocate additional memory. Memory is
45752 ** allocated in chunks so most INSERTs do no allocation. There is an
45753 ** upper bound on the size of allocated memory. No memory is freed
45754 ** until DESTROY.
45755 **
45756 ** The TEST primitive includes a "batch" number. The TEST primitive
45757 ** will only see elements that were inserted before the last change
45758 ** in the batch number. In other words, if an INSERT occurs between
45759 ** two TESTs where the TESTs have the same batch nubmer, then the
45760 ** value added by the INSERT will not be visible to the second TEST.
45761 ** The initial batch number is zero, so if the very first TEST contains
45762 ** a non-zero batch number, it will see all prior INSERTs.
45763 **
45764 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
45765 ** that is attempted.
45766 **
45767 ** The cost of an INSERT is roughly constant. (Sometimes new memory
45768 ** has to be allocated on an INSERT.) The cost of a TEST with a new
45769 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
45770 ** The cost of a TEST using the same batch number is O(logN). The cost
45771 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
45772 ** primitives are constant time. The cost of DESTROY is O(N).
45773 **
45774 ** TEST and SMALLEST may not be used by the same RowSet. This used to
45775 ** be possible, but the feature was not used, so it was removed in order
45776 ** to simplify the code.
45777 */
45778 /* #include "sqliteInt.h" */
45779 
45780 
45781 /*
45782 ** Target size for allocation chunks.
45783 */
45784 #define ROWSET_ALLOCATION_SIZE 1024
45785 
45786 /*
45787 ** The number of rowset entries per allocation chunk.
45788 */
45789 #define ROWSET_ENTRY_PER_CHUNK \
45790  ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
45791 
45792 /*
45793 ** Each entry in a RowSet is an instance of the following object.
45794 **
45795 ** This same object is reused to store a linked list of trees of RowSetEntry
45796 ** objects. In that alternative use, pRight points to the next entry
45797 ** in the list, pLeft points to the tree, and v is unused. The
45798 ** RowSet.pForest value points to the head of this forest list.
45799 */
45800 struct RowSetEntry {
45801  i64 v; /* ROWID value for this entry */
45802  struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
45803  struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
45804 };
45805 
45806 /*
45807 ** RowSetEntry objects are allocated in large chunks (instances of the
45808 ** following structure) to reduce memory allocation overhead. The
45809 ** chunks are kept on a linked list so that they can be deallocated
45810 ** when the RowSet is destroyed.
45811 */
45812 struct RowSetChunk {
45813  struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
45814  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
45815 };
45816 
45817 /*
45818 ** A RowSet in an instance of the following structure.
45819 **
45820 ** A typedef of this structure if found in sqliteInt.h.
45821 */
45822 struct RowSet {
45823  struct RowSetChunk *pChunk; /* List of all chunk allocations */
45824  sqlite3 *db; /* The database connection */
45825  struct RowSetEntry *pEntry; /* List of entries using pRight */
45826  struct RowSetEntry *pLast; /* Last entry on the pEntry list */
45827  struct RowSetEntry *pFresh; /* Source of new entry objects */
45828  struct RowSetEntry *pForest; /* List of binary trees of entries */
45829  u16 nFresh; /* Number of objects on pFresh */
45830  u16 rsFlags; /* Various flags */
45831  int iBatch; /* Current insert batch */
45832 };
45833 
45834 /*
45835 ** Allowed values for RowSet.rsFlags
45836 */
45837 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
45838 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
45839 
45840 /*
45841 ** Turn bulk memory into a RowSet object. N bytes of memory
45842 ** are available at pSpace. The db pointer is used as a memory context
45843 ** for any subsequent allocations that need to occur.
45844 ** Return a pointer to the new RowSet object.
45845 **
45846 ** It must be the case that N is sufficient to make a Rowset. If not
45847 ** an assertion fault occurs.
45848 **
45849 ** If N is larger than the minimum, use the surplus as an initial
45850 ** allocation of entries available to be filled.
45851 */
45852 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
45853  RowSet *p;
45854  assert( N >= ROUND8(sizeof(*p)) );
45855  p = pSpace;
45856  p->pChunk = 0;
45857  p->db = db;
45858  p->pEntry = 0;
45859  p->pLast = 0;
45860  p->pForest = 0;
45861  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
45862  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
45863  p->rsFlags = ROWSET_SORTED;
45864  p->iBatch = 0;
45865  return p;
45866 }
45867 
45868 /*
45869 ** Deallocate all chunks from a RowSet. This frees all memory that
45870 ** the RowSet has allocated over its lifetime. This routine is
45871 ** the destructor for the RowSet.
45872 */
45874  struct RowSetChunk *pChunk, *pNextChunk;
45875  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
45876  pNextChunk = pChunk->pNextChunk;
45877  sqlite3DbFree(p->db, pChunk);
45878  }
45879  p->pChunk = 0;
45880  p->nFresh = 0;
45881  p->pEntry = 0;
45882  p->pLast = 0;
45883  p->pForest = 0;
45884  p->rsFlags = ROWSET_SORTED;
45885 }
45886 
45887 /*
45888 ** Allocate a new RowSetEntry object that is associated with the
45889 ** given RowSet. Return a pointer to the new and completely uninitialized
45890 ** objected.
45891 **
45892 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
45893 ** routine returns NULL.
45894 */
45896  assert( p!=0 );
45897  if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
45898  /* We could allocate a fresh RowSetEntry each time one is needed, but it
45899  ** is more efficient to pull a preallocated entry from the pool */
45900  struct RowSetChunk *pNew;
45901  pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
45902  if( pNew==0 ){
45903  return 0;
45904  }
45905  pNew->pNextChunk = p->pChunk;
45906  p->pChunk = pNew;
45907  p->pFresh = pNew->aEntry;
45909  }
45910  p->nFresh--;
45911  return p->pFresh++;
45912 }
45913 
45914 /*
45915 ** Insert a new value into a RowSet.
45916 **
45917 ** The mallocFailed flag of the database connection is set if a
45918 ** memory allocation fails.
45919 */
45921  struct RowSetEntry *pEntry; /* The new entry */
45922  struct RowSetEntry *pLast; /* The last prior entry */
45923 
45924  /* This routine is never called after sqlite3RowSetNext() */
45925  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
45926 
45927  pEntry = rowSetEntryAlloc(p);
45928  if( pEntry==0 ) return;
45929  pEntry->v = rowid;
45930  pEntry->pRight = 0;
45931  pLast = p->pLast;
45932  if( pLast ){
45933  if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
45934  /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45935  ** where possible */
45936  p->rsFlags &= ~ROWSET_SORTED;
45937  }
45938  pLast->pRight = pEntry;
45939  }else{
45940  p->pEntry = pEntry;
45941  }
45942  p->pLast = pEntry;
45943 }
45944 
45945 /*
45946 ** Merge two lists of RowSetEntry objects. Remove duplicates.
45947 **
45948 ** The input lists are connected via pRight pointers and are
45949 ** assumed to each already be in sorted order.
45950 */
45952  struct RowSetEntry *pA, /* First sorted list to be merged */
45953  struct RowSetEntry *pB /* Second sorted list to be merged */
45954 ){
45955  struct RowSetEntry head;
45956  struct RowSetEntry *pTail;
45957 
45958  pTail = &head;
45959  assert( pA!=0 && pB!=0 );
45960  for(;;){
45961  assert( pA->pRight==0 || pA->v<=pA->pRight->v );
45962  assert( pB->pRight==0 || pB->v<=pB->pRight->v );
45963  if( pA->v<=pB->v ){
45964  if( pA->v<pB->v ) pTail = pTail->pRight = pA;
45965  pA = pA->pRight;
45966  if( pA==0 ){
45967  pTail->pRight = pB;
45968  break;
45969  }
45970  }else{
45971  pTail = pTail->pRight = pB;
45972  pB = pB->pRight;
45973  if( pB==0 ){
45974  pTail->pRight = pA;
45975  break;
45976  }
45977  }
45978  }
45979  return head.pRight;
45980 }
45981 
45982 /*
45983 ** Sort all elements on the list of RowSetEntry objects into order of
45984 ** increasing v.
45985 */
45986 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
45987  unsigned int i;
45988  struct RowSetEntry *pNext, *aBucket[40];
45989 
45990  memset(aBucket, 0, sizeof(aBucket));
45991  while( pIn ){
45992  pNext = pIn->pRight;
45993  pIn->pRight = 0;
45994  for(i=0; aBucket[i]; i++){
45995  pIn = rowSetEntryMerge(aBucket[i], pIn);
45996  aBucket[i] = 0;
45997  }
45998  aBucket[i] = pIn;
45999  pIn = pNext;
46000  }
46001  pIn = aBucket[0];
46002  for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
46003  if( aBucket[i]==0 ) continue;
46004  pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
46005  }
46006  return pIn;
46007 }
46008 
46009 
46010 /*
46011 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
46012 ** Convert this tree into a linked list connected by the pRight pointers
46013 ** and return pointers to the first and last elements of the new list.
46014 */
46015 static void rowSetTreeToList(
46016  struct RowSetEntry *pIn, /* Root of the input tree */
46017  struct RowSetEntry **ppFirst, /* Write head of the output list here */
46018  struct RowSetEntry **ppLast /* Write tail of the output list here */
46019 ){
46020  assert( pIn!=0 );
46021  if( pIn->pLeft ){
46022  struct RowSetEntry *p;
46023  rowSetTreeToList(pIn->pLeft, ppFirst, &p);
46024  p->pRight = pIn;
46025  }else{
46026  *ppFirst = pIn;
46027  }
46028  if( pIn->pRight ){
46029  rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
46030  }else{
46031  *ppLast = pIn;
46032  }
46033  assert( (*ppLast)->pRight==0 );
46034 }
46035 
46036 
46037 /*
46038 ** Convert a sorted list of elements (connected by pRight) into a binary
46039 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
46040 ** node taken from the head of *ppList. A depth of 2 means a tree with
46041 ** three nodes. And so forth.
46042 **
46043 ** Use as many entries from the input list as required and update the
46044 ** *ppList to point to the unused elements of the list. If the input
46045 ** list contains too few elements, then construct an incomplete tree
46046 ** and leave *ppList set to NULL.
46047 **
46048 ** Return a pointer to the root of the constructed binary tree.
46049 */
46051  struct RowSetEntry **ppList,
46052  int iDepth
46053 ){
46054  struct RowSetEntry *p; /* Root of the new tree */
46055  struct RowSetEntry *pLeft; /* Left subtree */
46056  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
46057  /* Prevent unnecessary deep recursion when we run out of entries */
46058  return 0;
46059  }
46060  if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
46061  /* This branch causes a *balanced* tree to be generated. A valid tree
46062  ** is still generated without this branch, but the tree is wildly
46063  ** unbalanced and inefficient. */
46064  pLeft = rowSetNDeepTree(ppList, iDepth-1);
46065  p = *ppList;
46066  if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
46067  /* It is safe to always return here, but the resulting tree
46068  ** would be unbalanced */
46069  return pLeft;
46070  }
46071  p->pLeft = pLeft;
46072  *ppList = p->pRight;
46073  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
46074  }else{
46075  p = *ppList;
46076  *ppList = p->pRight;
46077  p->pLeft = p->pRight = 0;
46078  }
46079  return p;
46080 }
46081 
46082 /*
46083 ** Convert a sorted list of elements into a binary tree. Make the tree
46084 ** as deep as it needs to be in order to contain the entire list.
46085 */
46086 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
46087  int iDepth; /* Depth of the tree so far */
46088  struct RowSetEntry *p; /* Current tree root */
46089  struct RowSetEntry *pLeft; /* Left subtree */
46090 
46091  assert( pList!=0 );
46092  p = pList;
46093  pList = p->pRight;
46094  p->pLeft = p->pRight = 0;
46095  for(iDepth=1; pList; iDepth++){
46096  pLeft = p;
46097  p = pList;
46098  pList = p->pRight;
46099  p->pLeft = pLeft;
46100  p->pRight = rowSetNDeepTree(&pList, iDepth);
46101  }
46102  return p;
46103 }
46104 
46105 /*
46106 ** Extract the smallest element from the RowSet.
46107 ** Write the element into *pRowid. Return 1 on success. Return
46108 ** 0 if the RowSet is already empty.
46109 **
46110 ** After this routine has been called, the sqlite3RowSetInsert()
46111 ** routine may not be called again.
46112 **
46113 ** This routine may not be called after sqlite3RowSetTest() has
46114 ** been used. Older versions of RowSet allowed that, but as the
46115 ** capability was not used by the code generator, it was removed
46116 ** for code economy.
46117 */
46119  assert( p!=0 );
46120  assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
46121 
46122  /* Merge the forest into a single sorted list on first call */
46123  if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46124  if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46125  p->pEntry = rowSetEntrySort(p->pEntry);
46126  }
46128  }
46129 
46130  /* Return the next entry on the list */
46131  if( p->pEntry ){
46132  *pRowid = p->pEntry->v;
46133  p->pEntry = p->pEntry->pRight;
46134  if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
46135  /* Free memory immediately, rather than waiting on sqlite3_finalize() */
46136  sqlite3RowSetClear(p);
46137  }
46138  return 1;
46139  }else{
46140  return 0;
46141  }
46142 }
46143 
46144 /*
46145 ** Check to see if element iRowid was inserted into the rowset as
46146 ** part of any insert batch prior to iBatch. Return 1 or 0.
46147 **
46148 ** If this is the first test of a new batch and if there exist entries
46149 ** on pRowSet->pEntry, then sort those entries into the forest at
46150 ** pRowSet->pForest so that they can be tested.
46151 */
46152 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
46153  struct RowSetEntry *p, *pTree;
46154 
46155  /* This routine is never called after sqlite3RowSetNext() */
46156  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
46157 
46158  /* Sort entries into the forest on the first test of a new batch.
46159  ** To save unnecessary work, only do this when the batch number changes.
46160  */
46161  if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
46162  p = pRowSet->pEntry;
46163  if( p ){
46164  struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
46165  if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46166  /* Only sort the current set of entiries if they need it */
46167  p = rowSetEntrySort(p);
46168  }
46169  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46170  ppPrevTree = &pTree->pRight;
46171  if( pTree->pLeft==0 ){
46172  pTree->pLeft = rowSetListToTree(p);
46173  break;
46174  }else{
46175  struct RowSetEntry *pAux, *pTail;
46176  rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
46177  pTree->pLeft = 0;
46178  p = rowSetEntryMerge(pAux, p);
46179  }
46180  }
46181  if( pTree==0 ){
46182  *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
46183  if( pTree ){
46184  pTree->v = 0;
46185  pTree->pRight = 0;
46186  pTree->pLeft = rowSetListToTree(p);
46187  }
46188  }
46189  pRowSet->pEntry = 0;
46190  pRowSet->pLast = 0;
46191  pRowSet->rsFlags |= ROWSET_SORTED;
46192  }
46193  pRowSet->iBatch = iBatch;
46194  }
46195 
46196  /* Test to see if the iRowid value appears anywhere in the forest.
46197  ** Return 1 if it does and 0 if not.
46198  */
46199  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46200  p = pTree->pLeft;
46201  while( p ){
46202  if( p->v<iRowid ){
46203  p = p->pRight;
46204  }else if( p->v>iRowid ){
46205  p = p->pLeft;
46206  }else{
46207  return 1;
46208  }
46209  }
46210  }
46211  return 0;
46212 }
46213 
46214 /************** End of rowset.c **********************************************/
46215 /************** Begin file pager.c *******************************************/
46216 /*
46217 ** 2001 September 15
46218 **
46219 ** The author disclaims copyright to this source code. In place of
46220 ** a legal notice, here is a blessing:
46221 **
46222 ** May you do good and not evil.
46223 ** May you find forgiveness for yourself and forgive others.
46224 ** May you share freely, never taking more than you give.
46225 **
46226 *************************************************************************
46227 ** This is the implementation of the page cache subsystem or "pager".
46228 **
46229 ** The pager is used to access a database disk file. It implements
46230 ** atomic commit and rollback through the use of a journal file that
46231 ** is separate from the database file. The pager also implements file
46232 ** locking to prevent two processes from writing the same database
46233 ** file simultaneously, or one process from reading the database while
46234 ** another is writing.
46235 */
46236 #ifndef SQLITE_OMIT_DISKIO
46237 /* #include "sqliteInt.h" */
46238 /************** Include wal.h in the middle of pager.c ***********************/
46239 /************** Begin file wal.h *********************************************/
46240 /*
46241 ** 2010 February 1
46242 **
46243 ** The author disclaims copyright to this source code. In place of
46244 ** a legal notice, here is a blessing:
46245 **
46246 ** May you do good and not evil.
46247 ** May you find forgiveness for yourself and forgive others.
46248 ** May you share freely, never taking more than you give.
46249 **
46250 *************************************************************************
46251 ** This header file defines the interface to the write-ahead logging
46252 ** system. Refer to the comments below and the header comment attached to
46253 ** the implementation of each function in log.c for further details.
46254 */
46255 
46256 #ifndef SQLITE_WAL_H
46257 #define SQLITE_WAL_H
46258 
46259 /* #include "sqliteInt.h" */
46260 
46261 /* Additional values that can be added to the sync_flags argument of
46262 ** sqlite3WalFrames():
46263 */
46264 #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
46265 #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
46266 
46267 #ifdef SQLITE_OMIT_WAL
46268 # define sqlite3WalOpen(x,y,z) 0
46269 # define sqlite3WalLimit(x,y)
46270 # define sqlite3WalClose(w,x,y,z) 0
46271 # define sqlite3WalBeginReadTransaction(y,z) 0
46272 # define sqlite3WalEndReadTransaction(z)
46273 # define sqlite3WalDbsize(y) 0
46274 # define sqlite3WalBeginWriteTransaction(y) 0
46275 # define sqlite3WalEndWriteTransaction(x) 0
46276 # define sqlite3WalUndo(x,y,z) 0
46277 # define sqlite3WalSavepoint(y,z)
46278 # define sqlite3WalSavepointUndo(y,z) 0
46279 # define sqlite3WalFrames(u,v,w,x,y,z) 0
46280 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
46281 # define sqlite3WalCallback(z) 0
46282 # define sqlite3WalExclusiveMode(y,z) 0
46283 # define sqlite3WalHeapMemory(z) 0
46284 # define sqlite3WalFramesize(z) 0
46285 # define sqlite3WalFindFrame(x,y,z) 0
46286 # define sqlite3WalFile(x) 0
46287 #else
46288 
46289 #define WAL_SAVEPOINT_NDATA 4
46290 
46291 /* Connection to a write-ahead log (WAL) file.
46292 ** There is one object of this type for each pager.
46293 */
46294 typedef struct Wal Wal;
46295 
46296 /* Open and close a connection to a write-ahead log. */
46297 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
46298 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
46299 
46300 /* Set the limiting size of a WAL file. */
46301 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
46302 
46303 /* Used by readers to open (lock) and close (unlock) a snapshot. A
46304 ** snapshot is like a read-transaction. It is the state of the database
46305 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
46306 ** preserves the current state even if the other threads or processes
46307 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
46308 ** transaction and releases the lock.
46309 */
46312 
46313 /* Read a page from the write-ahead log, if it is present. */
46314 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
46315 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
46316 
46317 /* If the WAL is not empty, return the size of the database. */
46318 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
46319 
46320 /* Obtain or release the WRITER lock. */
46323 
46324 /* Undo any frames written (but not committed) to the log */
46325 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
46326 
46327 /* Return an integer that records the current (uncommitted) write
46328 ** position in the WAL */
46329 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
46330 
46331 /* Move the write position of the WAL back to iFrame. Called in
46332 ** response to a ROLLBACK TO command. */
46333 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
46334 
46335 /* Write a frame or frames to the log. */
46336 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
46337 
46338 /* Copy pages from the log to the database file */
46340  Wal *pWal, /* Write-ahead log connection */
46341  int eMode, /* One of PASSIVE, FULL and RESTART */
46342  int (*xBusy)(void*), /* Function to call when busy */
46343  void *pBusyArg, /* Context argument for xBusyHandler */
46344  int sync_flags, /* Flags to sync db file with (or 0) */
46345  int nBuf, /* Size of buffer nBuf */
46346  u8 *zBuf, /* Temporary buffer to use */
46347  int *pnLog, /* OUT: Number of frames in WAL */
46348  int *pnCkpt /* OUT: Number of backfilled frames in WAL */
46349 );
46350 
46351 /* Return the value to pass to a sqlite3_wal_hook callback, the
46352 ** number of frames in the WAL at the point of the last commit since
46353 ** sqlite3WalCallback() was called. If no commits have occurred since
46354 ** the last call, then return 0.
46355 */
46357 
46358 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
46359 ** by the pager layer on the database file.
46360 */
46361 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
46362 
46363 /* Return true if the argument is non-NULL and the WAL module is using
46364 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46365 ** WAL module is using shared-memory, return false.
46366 */
46368 
46369 #ifdef SQLITE_ENABLE_SNAPSHOT
46370 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
46371 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
46372 #endif
46373 
46374 #ifdef SQLITE_ENABLE_ZIPVFS
46375 /* If the WAL file is not empty, return the number of bytes of content
46376 ** stored in each frame (i.e. the db page-size when the WAL was created).
46377 */
46378 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
46379 #endif
46380 
46381 /* Return the sqlite3_file object for the WAL file */
46382 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
46383 
46384 #endif /* ifndef SQLITE_OMIT_WAL */
46385 #endif /* SQLITE_WAL_H */
46386 
46387 /************** End of wal.h *************************************************/
46388 /************** Continuing where we left off in pager.c **********************/
46389 
46390 
46391 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
46392 **
46393 ** This comment block describes invariants that hold when using a rollback
46394 ** journal. These invariants do not apply for journal_mode=WAL,
46395 ** journal_mode=MEMORY, or journal_mode=OFF.
46396 **
46397 ** Within this comment block, a page is deemed to have been synced
46398 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
46399 ** Otherwise, the page is not synced until the xSync method of the VFS
46400 ** is called successfully on the file containing the page.
46401 **
46402 ** Definition: A page of the database file is said to be "overwriteable" if
46403 ** one or more of the following are true about the page:
46404 **
46405 ** (a) The original content of the page as it was at the beginning of
46406 ** the transaction has been written into the rollback journal and
46407 ** synced.
46408 **
46409 ** (b) The page was a freelist leaf page at the start of the transaction.
46410 **
46411 ** (c) The page number is greater than the largest page that existed in
46412 ** the database file at the start of the transaction.
46413 **
46414 ** (1) A page of the database file is never overwritten unless one of the
46415 ** following are true:
46416 **
46417 ** (a) The page and all other pages on the same sector are overwriteable.
46418 **
46419 ** (b) The atomic page write optimization is enabled, and the entire
46420 ** transaction other than the update of the transaction sequence
46421 ** number consists of a single page change.
46422 **
46423 ** (2) The content of a page written into the rollback journal exactly matches
46424 ** both the content in the database when the rollback journal was written
46425 ** and the content in the database at the beginning of the current
46426 ** transaction.
46427 **
46428 ** (3) Writes to the database file are an integer multiple of the page size
46429 ** in length and are aligned on a page boundary.
46430 **
46431 ** (4) Reads from the database file are either aligned on a page boundary and
46432 ** an integer multiple of the page size in length or are taken from the
46433 ** first 100 bytes of the database file.
46434 **
46435 ** (5) All writes to the database file are synced prior to the rollback journal
46436 ** being deleted, truncated, or zeroed.
46437 **
46438 ** (6) If a master journal file is used, then all writes to the database file
46439 ** are synced prior to the master journal being deleted.
46440 **
46441 ** Definition: Two databases (or the same database at two points it time)
46442 ** are said to be "logically equivalent" if they give the same answer to
46443 ** all queries. Note in particular the content of freelist leaf
46444 ** pages can be changed arbitrarily without affecting the logical equivalence
46445 ** of the database.
46446 **
46447 ** (7) At any time, if any subset, including the empty set and the total set,
46448 ** of the unsynced changes to a rollback journal are removed and the
46449 ** journal is rolled back, the resulting database file will be logically
46450 ** equivalent to the database file at the beginning of the transaction.
46451 **
46452 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
46453 ** is called to restore the database file to the same size it was at
46454 ** the beginning of the transaction. (In some VFSes, the xTruncate
46455 ** method is a no-op, but that does not change the fact the SQLite will
46456 ** invoke it.)
46457 **
46458 ** (9) Whenever the database file is modified, at least one bit in the range
46459 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
46460 ** the EXCLUSIVE lock, thus signaling other connections on the same
46461 ** database to flush their caches.
46462 **
46463 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
46464 ** than one billion transactions.
46465 **
46466 ** (11) A database file is well-formed at the beginning and at the conclusion
46467 ** of every transaction.
46468 **
46469 ** (12) An EXCLUSIVE lock is held on the database file when writing to
46470 ** the database file.
46471 **
46472 ** (13) A SHARED lock is held on the database file while reading any
46473 ** content out of the database file.
46474 **
46475 ******************************************************************************/
46476 
46477 /*
46478 ** Macros for troubleshooting. Normally turned off
46479 */
46480 #if 0
46481 int sqlite3PagerTrace=1; /* True to enable tracing */
46482 #define sqlite3DebugPrintf printf
46483 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
46484 #else
46485 #define PAGERTRACE(X)
46486 #endif
46487 
46488 /*
46489 ** The following two macros are used within the PAGERTRACE() macros above
46490 ** to print out file-descriptors.
46491 **
46492 ** PAGERID() takes a pointer to a Pager struct as its argument. The
46493 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
46494 ** struct as its argument.
46495 */
46496 #define PAGERID(p) ((int)(p->fd))
46497 #define FILEHANDLEID(fd) ((int)fd)
46498 
46499 /*
46500 ** The Pager.eState variable stores the current 'state' of a pager. A
46501 ** pager may be in any one of the seven states shown in the following
46502 ** state diagram.
46503 **
46504 ** OPEN <------+------+
46505 ** | | |
46506 ** V | |
46507 ** +---------> READER-------+ |
46508 ** | | |
46509 ** | V |
46510 ** |<-------WRITER_LOCKED------> ERROR
46511 ** | | ^
46512 ** | V |
46513 ** |<------WRITER_CACHEMOD-------->|
46514 ** | | |
46515 ** | V |
46516 ** |<-------WRITER_DBMOD---------->|
46517 ** | | |
46518 ** | V |
46519 ** +<------WRITER_FINISHED-------->+
46520 **
46521 **
46522 ** List of state transitions and the C [function] that performs each:
46523 **
46524 ** OPEN -> READER [sqlite3PagerSharedLock]
46525 ** READER -> OPEN [pager_unlock]
46526 **
46527 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
46528 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
46529 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
46530 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
46531 ** WRITER_*** -> READER [pager_end_transaction]
46532 **
46533 ** WRITER_*** -> ERROR [pager_error]
46534 ** ERROR -> OPEN [pager_unlock]
46535 **
46536 **
46537 ** OPEN:
46538 **
46539 ** The pager starts up in this state. Nothing is guaranteed in this
46540 ** state - the file may or may not be locked and the database size is
46541 ** unknown. The database may not be read or written.
46542 **
46543 ** * No read or write transaction is active.
46544 ** * Any lock, or no lock at all, may be held on the database file.
46545 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
46546 **
46547 ** READER:
46548 **
46549 ** In this state all the requirements for reading the database in
46550 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
46551 ** was) in exclusive-locking mode, a user-level read transaction is
46552 ** open. The database size is known in this state.
46553 **
46554 ** A connection running with locking_mode=normal enters this state when
46555 ** it opens a read-transaction on the database and returns to state
46556 ** OPEN after the read-transaction is completed. However a connection
46557 ** running in locking_mode=exclusive (including temp databases) remains in
46558 ** this state even after the read-transaction is closed. The only way
46559 ** a locking_mode=exclusive connection can transition from READER to OPEN
46560 ** is via the ERROR state (see below).
46561 **
46562 ** * A read transaction may be active (but a write-transaction cannot).
46563 ** * A SHARED or greater lock is held on the database file.
46564 ** * The dbSize variable may be trusted (even if a user-level read
46565 ** transaction is not active). The dbOrigSize and dbFileSize variables
46566 ** may not be trusted at this point.
46567 ** * If the database is a WAL database, then the WAL connection is open.
46568 ** * Even if a read-transaction is not open, it is guaranteed that
46569 ** there is no hot-journal in the file-system.
46570 **
46571 ** WRITER_LOCKED:
46572 **
46573 ** The pager moves to this state from READER when a write-transaction
46574 ** is first opened on the database. In WRITER_LOCKED state, all locks
46575 ** required to start a write-transaction are held, but no actual
46576 ** modifications to the cache or database have taken place.
46577 **
46578 ** In rollback mode, a RESERVED or (if the transaction was opened with
46579 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
46580 ** moving to this state, but the journal file is not written to or opened
46581 ** to in this state. If the transaction is committed or rolled back while
46582 ** in WRITER_LOCKED state, all that is required is to unlock the database
46583 ** file.
46584 **
46585 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
46586 ** If the connection is running with locking_mode=exclusive, an attempt
46587 ** is made to obtain an EXCLUSIVE lock on the database file.
46588 **
46589 ** * A write transaction is active.
46590 ** * If the connection is open in rollback-mode, a RESERVED or greater
46591 ** lock is held on the database file.
46592 ** * If the connection is open in WAL-mode, a WAL write transaction
46593 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
46594 ** called).
46595 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
46596 ** * The contents of the pager cache have not been modified.
46597 ** * The journal file may or may not be open.
46598 ** * Nothing (not even the first header) has been written to the journal.
46599 **
46600 ** WRITER_CACHEMOD:
46601 **
46602 ** A pager moves from WRITER_LOCKED state to this state when a page is
46603 ** first modified by the upper layer. In rollback mode the journal file
46604 ** is opened (if it is not already open) and a header written to the
46605 ** start of it. The database file on disk has not been modified.
46606 **
46607 ** * A write transaction is active.
46608 ** * A RESERVED or greater lock is held on the database file.
46609 ** * The journal file is open and the first header has been written
46610 ** to it, but the header has not been synced to disk.
46611 ** * The contents of the page cache have been modified.
46612 **
46613 ** WRITER_DBMOD:
46614 **
46615 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
46616 ** when it modifies the contents of the database file. WAL connections
46617 ** never enter this state (since they do not modify the database file,
46618 ** just the log file).
46619 **
46620 ** * A write transaction is active.
46621 ** * An EXCLUSIVE or greater lock is held on the database file.
46622 ** * The journal file is open and the first header has been written
46623 ** and synced to disk.
46624 ** * The contents of the page cache have been modified (and possibly
46625 ** written to disk).
46626 **
46627 ** WRITER_FINISHED:
46628 **
46629 ** It is not possible for a WAL connection to enter this state.
46630 **
46631 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
46632 ** state after the entire transaction has been successfully written into the
46633 ** database file. In this state the transaction may be committed simply
46634 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
46635 ** not possible to modify the database further. At this point, the upper
46636 ** layer must either commit or rollback the transaction.
46637 **
46638 ** * A write transaction is active.
46639 ** * An EXCLUSIVE or greater lock is held on the database file.
46640 ** * All writing and syncing of journal and database data has finished.
46641 ** If no error occurred, all that remains is to finalize the journal to
46642 ** commit the transaction. If an error did occur, the caller will need
46643 ** to rollback the transaction.
46644 **
46645 ** ERROR:
46646 **
46647 ** The ERROR state is entered when an IO or disk-full error (including
46648 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
46649 ** difficult to be sure that the in-memory pager state (cache contents,
46650 ** db size etc.) are consistent with the contents of the file-system.
46651 **
46652 ** Temporary pager files may enter the ERROR state, but in-memory pagers
46653 ** cannot.
46654 **
46655 ** For example, if an IO error occurs while performing a rollback,
46656 ** the contents of the page-cache may be left in an inconsistent state.
46657 ** At this point it would be dangerous to change back to READER state
46658 ** (as usually happens after a rollback). Any subsequent readers might
46659 ** report database corruption (due to the inconsistent cache), and if
46660 ** they upgrade to writers, they may inadvertently corrupt the database
46661 ** file. To avoid this hazard, the pager switches into the ERROR state
46662 ** instead of READER following such an error.
46663 **
46664 ** Once it has entered the ERROR state, any attempt to use the pager
46665 ** to read or write data returns an error. Eventually, once all
46666 ** outstanding transactions have been abandoned, the pager is able to
46667 ** transition back to OPEN state, discarding the contents of the
46668 ** page-cache and any other in-memory state at the same time. Everything
46669 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
46670 ** when a read-transaction is next opened on the pager (transitioning
46671 ** the pager into READER state). At that point the system has recovered
46672 ** from the error.
46673 **
46674 ** Specifically, the pager jumps into the ERROR state if:
46675 **
46676 ** 1. An error occurs while attempting a rollback. This happens in
46677 ** function sqlite3PagerRollback().
46678 **
46679 ** 2. An error occurs while attempting to finalize a journal file
46680 ** following a commit in function sqlite3PagerCommitPhaseTwo().
46681 **
46682 ** 3. An error occurs while attempting to write to the journal or
46683 ** database file in function pagerStress() in order to free up
46684 ** memory.
46685 **
46686 ** In other cases, the error is returned to the b-tree layer. The b-tree
46687 ** layer then attempts a rollback operation. If the error condition
46688 ** persists, the pager enters the ERROR state via condition (1) above.
46689 **
46690 ** Condition (3) is necessary because it can be triggered by a read-only
46691 ** statement executed within a transaction. In this case, if the error
46692 ** code were simply returned to the user, the b-tree layer would not
46693 ** automatically attempt a rollback, as it assumes that an error in a
46694 ** read-only statement cannot leave the pager in an internally inconsistent
46695 ** state.
46696 **
46697 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
46698 ** * There are one or more outstanding references to pages (after the
46699 ** last reference is dropped the pager should move back to OPEN state).
46700 ** * The pager is not an in-memory pager.
46701 **
46702 **
46703 ** Notes:
46704 **
46705 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
46706 ** connection is open in WAL mode. A WAL connection is always in one
46707 ** of the first four states.
46708 **
46709 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
46710 ** state. There are two exceptions: immediately after exclusive-mode has
46711 ** been turned on (and before any read or write transactions are
46712 ** executed), and when the pager is leaving the "error state".
46713 **
46714 ** * See also: assert_pager_state().
46715 */
46716 #define PAGER_OPEN 0
46717 #define PAGER_READER 1
46718 #define PAGER_WRITER_LOCKED 2
46719 #define PAGER_WRITER_CACHEMOD 3
46720 #define PAGER_WRITER_DBMOD 4
46721 #define PAGER_WRITER_FINISHED 5
46722 #define PAGER_ERROR 6
46723 
46724 /*
46725 ** The Pager.eLock variable is almost always set to one of the
46726 ** following locking-states, according to the lock currently held on
46727 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46728 ** This variable is kept up to date as locks are taken and released by
46729 ** the pagerLockDb() and pagerUnlockDb() wrappers.
46730 **
46731 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
46732 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
46733 ** the operation was successful. In these circumstances pagerLockDb() and
46734 ** pagerUnlockDb() take a conservative approach - eLock is always updated
46735 ** when unlocking the file, and only updated when locking the file if the
46736 ** VFS call is successful. This way, the Pager.eLock variable may be set
46737 ** to a less exclusive (lower) value than the lock that is actually held
46738 ** at the system level, but it is never set to a more exclusive value.
46739 **
46740 ** This is usually safe. If an xUnlock fails or appears to fail, there may
46741 ** be a few redundant xLock() calls or a lock may be held for longer than
46742 ** required, but nothing really goes wrong.
46743 **
46744 ** The exception is when the database file is unlocked as the pager moves
46745 ** from ERROR to OPEN state. At this point there may be a hot-journal file
46746 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
46747 ** transition, by the same pager or any other). If the call to xUnlock()
46748 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
46749 ** can confuse the call to xCheckReservedLock() call made later as part
46750 ** of hot-journal detection.
46751 **
46752 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
46753 ** lock held by this process or any others". So xCheckReservedLock may
46754 ** return true because the caller itself is holding an EXCLUSIVE lock (but
46755 ** doesn't know it because of a previous error in xUnlock). If this happens
46756 ** a hot-journal may be mistaken for a journal being created by an active
46757 ** transaction in another process, causing SQLite to read from the database
46758 ** without rolling it back.
46759 **
46760 ** To work around this, if a call to xUnlock() fails when unlocking the
46761 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
46762 ** is only changed back to a real locking state after a successful call
46763 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
46764 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
46765 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
46766 ** lock on the database file before attempting to roll it back. See function
46767 ** PagerSharedLock() for more detail.
46768 **
46769 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
46770 ** PAGER_OPEN state.
46771 */
46772 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
46773 
46774 /*
46775 ** A macro used for invoking the codec if there is one
46776 */
46777 #ifdef SQLITE_HAS_CODEC
46778 # define CODEC1(P,D,N,X,E) \
46779  if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
46780 # define CODEC2(P,D,N,X,E,O) \
46781  if( P->xCodec==0 ){ O=(char*)D; }else \
46782  if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
46783 #else
46784 # define CODEC1(P,D,N,X,E) /* NO-OP */
46785 # define CODEC2(P,D,N,X,E,O) O=(char*)D
46786 #endif
46787 
46788 /*
46789 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
46790 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
46791 ** This could conceivably cause corruption following a power failure on
46792 ** such a system. This is currently an undocumented limit.
46793 */
46794 #define MAX_SECTOR_SIZE 0x10000
46795 
46796 
46797 /*
46798 ** An instance of the following structure is allocated for each active
46799 ** savepoint and statement transaction in the system. All such structures
46800 ** are stored in the Pager.aSavepoint[] array, which is allocated and
46801 ** resized using sqlite3Realloc().
46802 **
46803 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
46804 ** set to 0. If a journal-header is written into the main journal while
46805 ** the savepoint is active, then iHdrOffset is set to the byte offset
46806 ** immediately following the last journal record written into the main
46807 ** journal before the journal-header. This is required during savepoint
46808 ** rollback (see pagerPlaybackSavepoint()).
46809 */
46812  i64 iOffset; /* Starting offset in main journal */
46813  i64 iHdrOffset; /* See above */
46814  Bitvec *pInSavepoint; /* Set of pages in this savepoint */
46815  Pgno nOrig; /* Original number of pages in file */
46816  Pgno iSubRec; /* Index of first record in sub-journal */
46817 #ifndef SQLITE_OMIT_WAL
46818  u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
46819 #endif
46820 };
46821 
46822 /*
46823 ** Bits of the Pager.doNotSpill flag. See further description below.
46824 */
46825 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
46826 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
46827 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
46828 
46829 /*
46830 ** An open page cache is an instance of struct Pager. A description of
46831 ** some of the more important member variables follows:
46832 **
46833 ** eState
46834 **
46835 ** The current 'state' of the pager object. See the comment and state
46836 ** diagram above for a description of the pager state.
46837 **
46838 ** eLock
46839 **
46840 ** For a real on-disk database, the current lock held on the database file -
46841 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46842 **
46843 ** For a temporary or in-memory database (neither of which require any
46844 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
46845 ** databases always have Pager.exclusiveMode==1, this tricks the pager
46846 ** logic into thinking that it already has all the locks it will ever
46847 ** need (and no reason to release them).
46848 **
46849 ** In some (obscure) circumstances, this variable may also be set to
46850 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
46851 ** details.
46852 **
46853 ** changeCountDone
46854 **
46855 ** This boolean variable is used to make sure that the change-counter
46856 ** (the 4-byte header field at byte offset 24 of the database file) is
46857 ** not updated more often than necessary.
46858 **
46859 ** It is set to true when the change-counter field is updated, which
46860 ** can only happen if an exclusive lock is held on the database file.
46861 ** It is cleared (set to false) whenever an exclusive lock is
46862 ** relinquished on the database file. Each time a transaction is committed,
46863 ** The changeCountDone flag is inspected. If it is true, the work of
46864 ** updating the change-counter is omitted for the current transaction.
46865 **
46866 ** This mechanism means that when running in exclusive mode, a connection
46867 ** need only update the change-counter once, for the first transaction
46868 ** committed.
46869 **
46870 ** setMaster
46871 **
46872 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
46873 ** (or may not) specify a master-journal name to be written into the
46874 ** journal file before it is synced to disk.
46875 **
46876 ** Whether or not a journal file contains a master-journal pointer affects
46877 ** the way in which the journal file is finalized after the transaction is
46878 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
46879 ** If a journal file does not contain a master-journal pointer, it is
46880 ** finalized by overwriting the first journal header with zeroes. If
46881 ** it does contain a master-journal pointer the journal file is finalized
46882 ** by truncating it to zero bytes, just as if the connection were
46883 ** running in "journal_mode=truncate" mode.
46884 **
46885 ** Journal files that contain master journal pointers cannot be finalized
46886 ** simply by overwriting the first journal-header with zeroes, as the
46887 ** master journal pointer could interfere with hot-journal rollback of any
46888 ** subsequently interrupted transaction that reuses the journal file.
46889 **
46890 ** The flag is cleared as soon as the journal file is finalized (either
46891 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
46892 ** journal file from being successfully finalized, the setMaster flag
46893 ** is cleared anyway (and the pager will move to ERROR state).
46894 **
46895 ** doNotSpill
46896 **
46897 ** This variables control the behavior of cache-spills (calls made by
46898 ** the pcache module to the pagerStress() routine to write cached data
46899 ** to the file-system in order to free up memory).
46900 **
46901 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
46902 ** writing to the database from pagerStress() is disabled altogether.
46903 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
46904 ** comes up during savepoint rollback that requires the pcache module
46905 ** to allocate a new page to prevent the journal file from being written
46906 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
46907 ** case is a user preference.
46908 **
46909 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
46910 ** pagerStress() is permitted, but syncing the journal file is not.
46911 ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
46912 ** is larger than the database page-size in order to prevent a journal sync
46913 ** from happening in between the journalling of two pages on the same sector.
46914 **
46915 ** subjInMemory
46916 **
46917 ** This is a boolean variable. If true, then any required sub-journal
46918 ** is opened as an in-memory journal file. If false, then in-memory
46919 ** sub-journals are only used for in-memory pager files.
46920 **
46921 ** This variable is updated by the upper layer each time a new
46922 ** write-transaction is opened.
46923 **
46924 ** dbSize, dbOrigSize, dbFileSize
46925 **
46926 ** Variable dbSize is set to the number of pages in the database file.
46927 ** It is valid in PAGER_READER and higher states (all states except for
46928 ** OPEN and ERROR).
46929 **
46930 ** dbSize is set based on the size of the database file, which may be
46931 ** larger than the size of the database (the value stored at offset
46932 ** 28 of the database header by the btree). If the size of the file
46933 ** is not an integer multiple of the page-size, the value stored in
46934 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
46935 ** Except, any file that is greater than 0 bytes in size is considered
46936 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
46937 ** to dbSize==1).
46938 **
46939 ** During a write-transaction, if pages with page-numbers greater than
46940 ** dbSize are modified in the cache, dbSize is updated accordingly.
46941 ** Similarly, if the database is truncated using PagerTruncateImage(),
46942 ** dbSize is updated.
46943 **
46944 ** Variables dbOrigSize and dbFileSize are valid in states
46945 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
46946 ** variable at the start of the transaction. It is used during rollback,
46947 ** and to determine whether or not pages need to be journalled before
46948 ** being modified.
46949 **
46950 ** Throughout a write-transaction, dbFileSize contains the size of
46951 ** the file on disk in pages. It is set to a copy of dbSize when the
46952 ** write-transaction is first opened, and updated when VFS calls are made
46953 ** to write or truncate the database file on disk.
46954 **
46955 ** The only reason the dbFileSize variable is required is to suppress
46956 ** unnecessary calls to xTruncate() after committing a transaction. If,
46957 ** when a transaction is committed, the dbFileSize variable indicates
46958 ** that the database file is larger than the database image (Pager.dbSize),
46959 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
46960 ** to measure the database file on disk, and then truncates it if required.
46961 ** dbFileSize is not used when rolling back a transaction. In this case
46962 ** pager_truncate() is called unconditionally (which means there may be
46963 ** a call to xFilesize() that is not strictly required). In either case,
46964 ** pager_truncate() may cause the file to become smaller or larger.
46965 **
46966 ** dbHintSize
46967 **
46968 ** The dbHintSize variable is used to limit the number of calls made to
46969 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
46970 **
46971 ** dbHintSize is set to a copy of the dbSize variable when a
46972 ** write-transaction is opened (at the same time as dbFileSize and
46973 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
46974 ** dbHintSize is increased to the number of pages that correspond to the
46975 ** size-hint passed to the method call. See pager_write_pagelist() for
46976 ** details.
46977 **
46978 ** errCode
46979 **
46980 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
46981 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
46982 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
46983 ** sub-codes.
46984 */
46985 struct Pager {
46986  sqlite3_vfs *pVfs; /* OS functions to use for IO */
46987  u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
46988  u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
46989  u8 useJournal; /* Use a rollback journal on this file */
46990  u8 noSync; /* Do not sync the journal if true */
46991  u8 fullSync; /* Do extra syncs of the journal for robustness */
46992  u8 extraSync; /* sync directory after journal delete */
46993  u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
46994  u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
46995  u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
46996  u8 tempFile; /* zFilename is a temporary or immutable file */
46997  u8 noLock; /* Do not lock (except in WAL mode) */
46998  u8 readOnly; /* True for a read-only database */
46999  u8 memDb; /* True to inhibit all file I/O */
47000 
47001  /**************************************************************************
47002  ** The following block contains those class members that change during
47003  ** routine operation. Class members not in this block are either fixed
47004  ** when the pager is first created or else only change when there is a
47005  ** significant mode change (such as changing the page_size, locking_mode,
47006  ** or the journal_mode). From another view, these class members describe
47007  ** the "state" of the pager, while other class members describe the
47008  ** "configuration" of the pager.
47009  */
47010  u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
47011  u8 eLock; /* Current lock held on database file */
47012  u8 changeCountDone; /* Set after incrementing the change-counter */
47013  u8 setMaster; /* True if a m-j name has been written to jrnl */
47014  u8 doNotSpill; /* Do not spill the cache when non-zero */
47015  u8 subjInMemory; /* True to use in-memory sub-journals */
47016  u8 bUseFetch; /* True to use xFetch() */
47017  u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
47018  Pgno dbSize; /* Number of pages in the database */
47019  Pgno dbOrigSize; /* dbSize before the current transaction */
47020  Pgno dbFileSize; /* Number of pages in the database file */
47021  Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
47022  int errCode; /* One of several kinds of errors */
47023  int nRec; /* Pages journalled since last j-header written */
47024  u32 cksumInit; /* Quasi-random value added to every checksum */
47025  u32 nSubRec; /* Number of records written to sub-journal */
47026  Bitvec *pInJournal; /* One bit for each page in the database file */
47027  sqlite3_file *fd; /* File descriptor for database */
47028  sqlite3_file *jfd; /* File descriptor for main journal */
47029  sqlite3_file *sjfd; /* File descriptor for sub-journal */
47030  i64 journalOff; /* Current write offset in the journal file */
47031  i64 journalHdr; /* Byte offset to previous journal header */
47032  sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
47033  PagerSavepoint *aSavepoint; /* Array of active savepoints */
47034  int nSavepoint; /* Number of elements in aSavepoint[] */
47035  u32 iDataVersion; /* Changes whenever database content changes */
47036  char dbFileVers[16]; /* Changes whenever database file changes */
47037 
47038  int nMmapOut; /* Number of mmap pages currently outstanding */
47039  sqlite3_int64 szMmap; /* Desired maximum mmap size */
47040  PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
47041  /*
47042  ** End of the routinely-changing class members
47043  ***************************************************************************/
47044 
47045  u16 nExtra; /* Add this many bytes to each in-memory page */
47046  i16 nReserve; /* Number of unused bytes at end of each page */
47047  u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
47048  u32 sectorSize; /* Assumed sector size during rollback */
47049  int pageSize; /* Number of bytes in a page */
47050  Pgno mxPgno; /* Maximum allowed size of the database */
47051  i64 journalSizeLimit; /* Size limit for persistent journal files */
47052  char *zFilename; /* Name of the database file */
47053  char *zJournal; /* Name of the journal file */
47054  int (*xBusyHandler)(void*); /* Function to call when busy */
47055  void *pBusyHandlerArg; /* Context argument for xBusyHandler */
47056  int aStat[3]; /* Total cache hits, misses and writes */
47057 #ifdef SQLITE_TEST
47058  int nRead; /* Database pages read */
47059 #endif
47060  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
47061 #ifdef SQLITE_HAS_CODEC
47062  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
47063  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
47064  void (*xCodecFree)(void*); /* Destructor for the codec */
47065  void *pCodec; /* First argument to xCodec... methods */
47066 #endif
47067  char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
47068  PCache *pPCache; /* Pointer to page cache object */
47069 #ifndef SQLITE_OMIT_WAL
47070  Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
47071  char *zWal; /* File name for write-ahead log */
47072 #endif
47073 };
47074 
47075 /*
47076 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
47077 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
47078 ** or CACHE_WRITE to sqlite3_db_status().
47079 */
47080 #define PAGER_STAT_HIT 0
47081 #define PAGER_STAT_MISS 1
47082 #define PAGER_STAT_WRITE 2
47083 
47084 /*
47085 ** The following global variables hold counters used for
47086 ** testing purposes only. These variables do not exist in
47087 ** a non-testing build. These variables are not thread-safe.
47088 */
47089 #ifdef SQLITE_TEST
47090 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
47091 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
47092 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
47093 # define PAGER_INCR(v) v++
47094 #else
47095 # define PAGER_INCR(v)
47096 #endif
47097 
47098 
47099 
47100 /*
47101 ** Journal files begin with the following magic string. The data
47102 ** was obtained from /dev/random. It is used only as a sanity check.
47103 **
47104 ** Since version 2.8.0, the journal format contains additional sanity
47105 ** checking information. If the power fails while the journal is being
47106 ** written, semi-random garbage data might appear in the journal
47107 ** file after power is restored. If an attempt is then made
47108 ** to roll the journal back, the database could be corrupted. The additional
47109 ** sanity checking data is an attempt to discover the garbage in the
47110 ** journal and ignore it.
47111 **
47112 ** The sanity checking information for the new journal format consists
47113 ** of a 32-bit checksum on each page of data. The checksum covers both
47114 ** the page number and the pPager->pageSize bytes of data for the page.
47115 ** This cksum is initialized to a 32-bit random value that appears in the
47116 ** journal file right after the header. The random initializer is important,
47117 ** because garbage data that appears at the end of a journal is likely
47118 ** data that was once in other files that have now been deleted. If the
47119 ** garbage data came from an obsolete journal file, the checksums might
47120 ** be correct. But by initializing the checksum to random value which
47121 ** is different for every journal, we minimize that risk.
47122 */
47123 static const unsigned char aJournalMagic[] = {
47124  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
47125 };
47126 
47127 /*
47128 ** The size of the of each page record in the journal is given by
47129 ** the following macro.
47130 */
47131 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
47132 
47133 /*
47134 ** The journal header size for this pager. This is usually the same
47135 ** size as a single disk sector. See also setSectorSize().
47136 */
47137 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
47138 
47139 /*
47140 ** The macro MEMDB is true if we are dealing with an in-memory database.
47141 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
47142 ** the value of MEMDB will be a constant and the compiler will optimize
47143 ** out code that would never execute.
47144 */
47145 #ifdef SQLITE_OMIT_MEMORYDB
47146 # define MEMDB 0
47147 #else
47148 # define MEMDB pPager->memDb
47149 #endif
47150 
47151 /*
47152 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
47153 ** interfaces to access the database using memory-mapped I/O.
47154 */
47155 #if SQLITE_MAX_MMAP_SIZE>0
47156 # define USEFETCH(x) ((x)->bUseFetch)
47157 #else
47158 # define USEFETCH(x) 0
47159 #endif
47160 
47161 /*
47162 ** The maximum legal page number is (2^31 - 1).
47163 */
47164 #define PAGER_MAX_PGNO 2147483647
47165 
47166 /*
47167 ** The argument to this macro is a file descriptor (type sqlite3_file*).
47168 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
47169 **
47170 ** This is so that expressions can be written as:
47171 **
47172 ** if( isOpen(pPager->jfd) ){ ...
47173 **
47174 ** instead of
47175 **
47176 ** if( pPager->jfd->pMethods ){ ...
47177 */
47178 #define isOpen(pFd) ((pFd)->pMethods!=0)
47179 
47180 /*
47181 ** Return true if this pager uses a write-ahead log instead of the usual
47182 ** rollback journal. Otherwise false.
47183 */
47184 #ifndef SQLITE_OMIT_WAL
47186  return (pPager->pWal!=0);
47187 }
47188 # define pagerUseWal(x) sqlite3PagerUseWal(x)
47189 #else
47190 # define pagerUseWal(x) 0
47191 # define pagerRollbackWal(x) 0
47192 # define pagerWalFrames(v,w,x,y) 0
47193 # define pagerOpenWalIfPresent(z) SQLITE_OK
47194 # define pagerBeginReadTransaction(z) SQLITE_OK
47195 #endif
47196 
47197 #ifndef NDEBUG
47198 /*
47199 ** Usage:
47200 **
47201 ** assert( assert_pager_state(pPager) );
47202 **
47203 ** This function runs many asserts to try to find inconsistencies in
47204 ** the internal state of the Pager object.
47205 */
47206 static int assert_pager_state(Pager *p){
47207  Pager *pPager = p;
47208 
47209  /* State must be valid. */
47210  assert( p->eState==PAGER_OPEN
47211  || p->eState==PAGER_READER
47214  || p->eState==PAGER_WRITER_DBMOD
47216  || p->eState==PAGER_ERROR
47217  );
47218 
47219  /* Regardless of the current state, a temp-file connection always behaves
47220  ** as if it has an exclusive lock on the database file. It never updates
47221  ** the change-counter field, so the changeCountDone flag is always set.
47222  */
47223  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
47224  assert( p->tempFile==0 || pPager->changeCountDone );
47225 
47226  /* If the useJournal flag is clear, the journal-mode must be "OFF".
47227  ** And if the journal-mode is "OFF", the journal file must not be open.
47228  */
47229  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
47230  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
47231 
47232  /* Check that MEMDB implies noSync. And an in-memory journal. Since
47233  ** this means an in-memory pager performs no IO at all, it cannot encounter
47234  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
47235  ** a journal file. (although the in-memory journal implementation may
47236  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
47237  ** is therefore not possible for an in-memory pager to enter the ERROR
47238  ** state.
47239  */
47240  if( MEMDB ){
47241  assert( !isOpen(p->fd) );
47242  assert( p->noSync );
47243  assert( p->journalMode==PAGER_JOURNALMODE_OFF
47245  );
47246  assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
47247  assert( pagerUseWal(p)==0 );
47248  }
47249 
47250  /* If changeCountDone is set, a RESERVED lock or greater must be held
47251  ** on the file.
47252  */
47253  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
47254  assert( p->eLock!=PENDING_LOCK );
47255 
47256  switch( p->eState ){
47257  case PAGER_OPEN:
47258  assert( !MEMDB );
47259  assert( pPager->errCode==SQLITE_OK );
47260  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
47261  break;
47262 
47263  case PAGER_READER:
47264  assert( pPager->errCode==SQLITE_OK );
47265  assert( p->eLock!=UNKNOWN_LOCK );
47266  assert( p->eLock>=SHARED_LOCK );
47267  break;
47268 
47269  case PAGER_WRITER_LOCKED:
47270  assert( p->eLock!=UNKNOWN_LOCK );
47271  assert( pPager->errCode==SQLITE_OK );
47272  if( !pagerUseWal(pPager) ){
47273  assert( p->eLock>=RESERVED_LOCK );
47274  }
47275  assert( pPager->dbSize==pPager->dbOrigSize );
47276  assert( pPager->dbOrigSize==pPager->dbFileSize );
47277  assert( pPager->dbOrigSize==pPager->dbHintSize );
47278  assert( pPager->setMaster==0 );
47279  break;
47280 
47281  case PAGER_WRITER_CACHEMOD:
47282  assert( p->eLock!=UNKNOWN_LOCK );
47283  assert( pPager->errCode==SQLITE_OK );
47284  if( !pagerUseWal(pPager) ){
47285  /* It is possible that if journal_mode=wal here that neither the
47286  ** journal file nor the WAL file are open. This happens during
47287  ** a rollback transaction that switches from journal_mode=off
47288  ** to journal_mode=wal.
47289  */
47290  assert( p->eLock>=RESERVED_LOCK );
47291  assert( isOpen(p->jfd)
47294  );
47295  }
47296  assert( pPager->dbOrigSize==pPager->dbFileSize );
47297  assert( pPager->dbOrigSize==pPager->dbHintSize );
47298  break;
47299 
47300  case PAGER_WRITER_DBMOD:
47301  assert( p->eLock==EXCLUSIVE_LOCK );
47302  assert( pPager->errCode==SQLITE_OK );
47303  assert( !pagerUseWal(pPager) );
47304  assert( p->eLock>=EXCLUSIVE_LOCK );
47305  assert( isOpen(p->jfd)
47308  );
47309  assert( pPager->dbOrigSize<=pPager->dbHintSize );
47310  break;
47311 
47312  case PAGER_WRITER_FINISHED:
47313  assert( p->eLock==EXCLUSIVE_LOCK );
47314  assert( pPager->errCode==SQLITE_OK );
47315  assert( !pagerUseWal(pPager) );
47316  assert( isOpen(p->jfd)
47319  );
47320  break;
47321 
47322  case PAGER_ERROR:
47323  /* There must be at least one outstanding reference to the pager if
47324  ** in ERROR state. Otherwise the pager should have already dropped
47325  ** back to OPEN state.
47326  */
47327  assert( pPager->errCode!=SQLITE_OK );
47328  assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
47329  break;
47330  }
47331 
47332  return 1;
47333 }
47334 #endif /* ifndef NDEBUG */
47335 
47336 #ifdef SQLITE_DEBUG
47337 /*
47338 ** Return a pointer to a human readable string in a static buffer
47339 ** containing the state of the Pager object passed as an argument. This
47340 ** is intended to be used within debuggers. For example, as an alternative
47341 ** to "print *pPager" in gdb:
47342 **
47343 ** (gdb) printf "%s", print_pager_state(pPager)
47344 */
47345 static char *print_pager_state(Pager *p){
47346  static char zRet[1024];
47347 
47348  sqlite3_snprintf(1024, zRet,
47349  "Filename: %s\n"
47350  "State: %s errCode=%d\n"
47351  "Lock: %s\n"
47352  "Locking mode: locking_mode=%s\n"
47353  "Journal mode: journal_mode=%s\n"
47354  "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
47355  "Journal: journalOff=%lld journalHdr=%lld\n"
47356  "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
47357  , p->zFilename
47358  , p->eState==PAGER_OPEN ? "OPEN" :
47359  p->eState==PAGER_READER ? "READER" :
47360  p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
47361  p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
47362  p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
47363  p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
47364  p->eState==PAGER_ERROR ? "ERROR" : "?error?"
47365  , (int)p->errCode
47366  , p->eLock==NO_LOCK ? "NO_LOCK" :
47367  p->eLock==RESERVED_LOCK ? "RESERVED" :
47368  p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
47369  p->eLock==SHARED_LOCK ? "SHARED" :
47370  p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
47371  , p->exclusiveMode ? "exclusive" : "normal"
47372  , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
47373  p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
47374  p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
47375  p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
47376  p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
47377  p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
47378  , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
47379  , p->journalOff, p->journalHdr
47380  , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
47381  );
47382 
47383  return zRet;
47384 }
47385 #endif
47386 
47387 /*
47388 ** Return true if it is necessary to write page *pPg into the sub-journal.
47389 ** A page needs to be written into the sub-journal if there exists one
47390 ** or more open savepoints for which:
47391 **
47392 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
47393 ** * The bit corresponding to the page-number is not set in
47394 ** PagerSavepoint.pInSavepoint.
47395 */
47396 static int subjRequiresPage(PgHdr *pPg){
47397  Pager *pPager = pPg->pPager;
47398  PagerSavepoint *p;
47399  Pgno pgno = pPg->pgno;
47400  int i;
47401  for(i=0; i<pPager->nSavepoint; i++){
47402  p = &pPager->aSavepoint[i];
47403  if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
47404  return 1;
47405  }
47406  }
47407  return 0;
47408 }
47409 
47410 #ifdef SQLITE_DEBUG
47411 /*
47412 ** Return true if the page is already in the journal file.
47413 */
47414 static int pageInJournal(Pager *pPager, PgHdr *pPg){
47415  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
47416 }
47417 #endif
47418 
47419 /*
47420 ** Read a 32-bit integer from the given file descriptor. Store the integer
47421 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
47422 ** error code is something goes wrong.
47423 **
47424 ** All values are stored on disk as big-endian.
47425 */
47426 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
47427  unsigned char ac[4];
47428  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
47429  if( rc==SQLITE_OK ){
47430  *pRes = sqlite3Get4byte(ac);
47431  }
47432  return rc;
47433 }
47434 
47435 /*
47436 ** Write a 32-bit integer into a string buffer in big-endian byte order.
47437 */
47438 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
47439 
47440 
47441 /*
47442 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
47443 ** on success or an error code is something goes wrong.
47444 */
47445 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
47446  char ac[4];
47447  put32bits(ac, val);
47448  return sqlite3OsWrite(fd, ac, 4, offset);
47449 }
47450 
47451 /*
47452 ** Unlock the database file to level eLock, which must be either NO_LOCK
47453 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
47454 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
47455 **
47456 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47457 ** called, do not modify it. See the comment above the #define of
47458 ** UNKNOWN_LOCK for an explanation of this.
47459 */
47460 static int pagerUnlockDb(Pager *pPager, int eLock){
47461  int rc = SQLITE_OK;
47462 
47463  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
47464  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
47465  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
47466  if( isOpen(pPager->fd) ){
47467  assert( pPager->eLock>=eLock );
47468  rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
47469  if( pPager->eLock!=UNKNOWN_LOCK ){
47470  pPager->eLock = (u8)eLock;
47471  }
47472  IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
47473  }
47474  return rc;
47475 }
47476 
47477 /*
47478 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
47479 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
47480 ** Pager.eLock variable to the new locking state.
47481 **
47482 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47483 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
47484 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
47485 ** of this.
47486 */
47487 static int pagerLockDb(Pager *pPager, int eLock){
47488  int rc = SQLITE_OK;
47489 
47490  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
47491  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
47492  rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
47493  if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
47494  pPager->eLock = (u8)eLock;
47495  IOTRACE(("LOCK %p %d\n", pPager, eLock))
47496  }
47497  }
47498  return rc;
47499 }
47500 
47501 /*
47502 ** This function determines whether or not the atomic-write optimization
47503 ** can be used with this pager. The optimization can be used if:
47504 **
47505 ** (a) the value returned by OsDeviceCharacteristics() indicates that
47506 ** a database page may be written atomically, and
47507 ** (b) the value returned by OsSectorSize() is less than or equal
47508 ** to the page size.
47509 **
47510 ** The optimization is also always enabled for temporary files. It is
47511 ** an error to call this function if pPager is opened on an in-memory
47512 ** database.
47513 **
47514 ** If the optimization cannot be used, 0 is returned. If it can be used,
47515 ** then the value returned is the size of the journal file when it
47516 ** contains rollback data for exactly one page.
47517 */
47518 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47519 static int jrnlBufferSize(Pager *pPager){
47520  assert( !MEMDB );
47521  if( !pPager->tempFile ){
47522  int dc; /* Device characteristics */
47523  int nSector; /* Sector size */
47524  int szPage; /* Page size */
47525 
47526  assert( isOpen(pPager->fd) );
47527  dc = sqlite3OsDeviceCharacteristics(pPager->fd);
47528  nSector = pPager->sectorSize;
47529  szPage = pPager->pageSize;
47530 
47531  assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
47532  assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
47533  if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
47534  return 0;
47535  }
47536  }
47537 
47538  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
47539 }
47540 #else
47541 # define jrnlBufferSize(x) 0
47542 #endif
47543 
47544 /*
47545 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
47546 ** on the cache using a hash function. This is used for testing
47547 ** and debugging only.
47548 */
47549 #ifdef SQLITE_CHECK_PAGES
47550 /*
47551 ** Return a 32-bit hash of the page data for pPage.
47552 */
47553 static u32 pager_datahash(int nByte, unsigned char *pData){
47554  u32 hash = 0;
47555  int i;
47556  for(i=0; i<nByte; i++){
47557  hash = (hash*1039) + pData[i];
47558  }
47559  return hash;
47560 }
47561 static u32 pager_pagehash(PgHdr *pPage){
47562  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
47563 }
47564 static void pager_set_pagehash(PgHdr *pPage){
47565  pPage->pageHash = pager_pagehash(pPage);
47566 }
47567 
47568 /*
47569 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
47570 ** is defined, and NDEBUG is not defined, an assert() statement checks
47571 ** that the page is either dirty or still matches the calculated page-hash.
47572 */
47573 #define CHECK_PAGE(x) checkPage(x)
47574 static void checkPage(PgHdr *pPg){
47575  Pager *pPager = pPg->pPager;
47576  assert( pPager->eState!=PAGER_ERROR );
47577  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
47578 }
47579 
47580 #else
47581 #define pager_datahash(X,Y) 0
47582 #define pager_pagehash(X) 0
47583 #define pager_set_pagehash(X)
47584 #define CHECK_PAGE(x)
47585 #endif /* SQLITE_CHECK_PAGES */
47586 
47587 /*
47588 ** When this is called the journal file for pager pPager must be open.
47589 ** This function attempts to read a master journal file name from the
47590 ** end of the file and, if successful, copies it into memory supplied
47591 ** by the caller. See comments above writeMasterJournal() for the format
47592 ** used to store a master journal file name at the end of a journal file.
47593 **
47594 ** zMaster must point to a buffer of at least nMaster bytes allocated by
47595 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
47596 ** enough space to write the master journal name). If the master journal
47597 ** name in the journal is longer than nMaster bytes (including a
47598 ** nul-terminator), then this is handled as if no master journal name
47599 ** were present in the journal.
47600 **
47601 ** If a master journal file name is present at the end of the journal
47602 ** file, then it is copied into the buffer pointed to by zMaster. A
47603 ** nul-terminator byte is appended to the buffer following the master
47604 ** journal file name.
47605 **
47606 ** If it is determined that no master journal file name is present
47607 ** zMaster[0] is set to 0 and SQLITE_OK returned.
47608 **
47609 ** If an error occurs while reading from the journal file, an SQLite
47610 ** error code is returned.
47611 */
47612 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
47613  int rc; /* Return code */
47614  u32 len; /* Length in bytes of master journal name */
47615  i64 szJ; /* Total size in bytes of journal file pJrnl */
47616  u32 cksum; /* MJ checksum value read from journal */
47617  u32 u; /* Unsigned loop counter */
47618  unsigned char aMagic[8]; /* A buffer to hold the magic header */
47619  zMaster[0] = '\0';
47620 
47621  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
47622  || szJ<16
47623  || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
47624  || len>=nMaster
47625  || len==0
47626  || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
47627  || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
47628  || memcmp(aMagic, aJournalMagic, 8)
47629  || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
47630  ){
47631  return rc;
47632  }
47633 
47634  /* See if the checksum matches the master journal name */
47635  for(u=0; u<len; u++){
47636  cksum -= zMaster[u];
47637  }
47638  if( cksum ){
47639  /* If the checksum doesn't add up, then one or more of the disk sectors
47640  ** containing the master journal filename is corrupted. This means
47641  ** definitely roll back, so just return SQLITE_OK and report a (nul)
47642  ** master-journal filename.
47643  */
47644  len = 0;
47645  }
47646  zMaster[len] = '\0';
47647 
47648  return SQLITE_OK;
47649 }
47650 
47651 /*
47652 ** Return the offset of the sector boundary at or immediately
47653 ** following the value in pPager->journalOff, assuming a sector
47654 ** size of pPager->sectorSize bytes.
47655 **
47656 ** i.e for a sector size of 512:
47657 **
47658 ** Pager.journalOff Return value
47659 ** ---------------------------------------
47660 ** 0 0
47661 ** 512 512
47662 ** 100 512
47663 ** 2000 2048
47664 **
47665 */
47666 static i64 journalHdrOffset(Pager *pPager){
47667  i64 offset = 0;
47668  i64 c = pPager->journalOff;
47669  if( c ){
47670  offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
47671  }
47672  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
47673  assert( offset>=c );
47674  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
47675  return offset;
47676 }
47677 
47678 /*
47679 ** The journal file must be open when this function is called.
47680 **
47681 ** This function is a no-op if the journal file has not been written to
47682 ** within the current transaction (i.e. if Pager.journalOff==0).
47683 **
47684 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
47685 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
47686 ** zero the 28-byte header at the start of the journal file. In either case,
47687 ** if the pager is not in no-sync mode, sync the journal file immediately
47688 ** after writing or truncating it.
47689 **
47690 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
47691 ** following the truncation or zeroing described above the size of the
47692 ** journal file in bytes is larger than this value, then truncate the
47693 ** journal file to Pager.journalSizeLimit bytes. The journal file does
47694 ** not need to be synced following this operation.
47695 **
47696 ** If an IO error occurs, abandon processing and return the IO error code.
47697 ** Otherwise, return SQLITE_OK.
47698 */
47699 static int zeroJournalHdr(Pager *pPager, int doTruncate){
47700  int rc = SQLITE_OK; /* Return code */
47701  assert( isOpen(pPager->jfd) );
47702  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
47703  if( pPager->journalOff ){
47704  const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
47705 
47706  IOTRACE(("JZEROHDR %p\n", pPager))
47707  if( doTruncate || iLimit==0 ){
47708  rc = sqlite3OsTruncate(pPager->jfd, 0);
47709  }else{
47710  static const char zeroHdr[28] = {0};
47711  rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
47712  }
47713  if( rc==SQLITE_OK && !pPager->noSync ){
47714  rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
47715  }
47716 
47717  /* At this point the transaction is committed but the write lock
47718  ** is still held on the file. If there is a size limit configured for
47719  ** the persistent journal and the journal file currently consumes more
47720  ** space than that limit allows for, truncate it now. There is no need
47721  ** to sync the file following this operation.
47722  */
47723  if( rc==SQLITE_OK && iLimit>0 ){
47724  i64 sz;
47725  rc = sqlite3OsFileSize(pPager->jfd, &sz);
47726  if( rc==SQLITE_OK && sz>iLimit ){
47727  rc = sqlite3OsTruncate(pPager->jfd, iLimit);
47728  }
47729  }
47730  }
47731  return rc;
47732 }
47733 
47734 /*
47735 ** The journal file must be open when this routine is called. A journal
47736 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
47737 ** current location.
47738 **
47739 ** The format for the journal header is as follows:
47740 ** - 8 bytes: Magic identifying journal format.
47741 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
47742 ** - 4 bytes: Random number used for page hash.
47743 ** - 4 bytes: Initial database page count.
47744 ** - 4 bytes: Sector size used by the process that wrote this journal.
47745 ** - 4 bytes: Database page size.
47746 **
47747 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
47748 */
47749 static int writeJournalHdr(Pager *pPager){
47750  int rc = SQLITE_OK; /* Return code */
47751  char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
47752  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
47753  u32 nWrite; /* Bytes of header sector written */
47754  int ii; /* Loop counter */
47755 
47756  assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
47757 
47758  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
47759  nHeader = JOURNAL_HDR_SZ(pPager);
47760  }
47761 
47762  /* If there are active savepoints and any of them were created
47763  ** since the most recent journal header was written, update the
47764  ** PagerSavepoint.iHdrOffset fields now.
47765  */
47766  for(ii=0; ii<pPager->nSavepoint; ii++){
47767  if( pPager->aSavepoint[ii].iHdrOffset==0 ){
47768  pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
47769  }
47770  }
47771 
47772  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
47773 
47774  /*
47775  ** Write the nRec Field - the number of page records that follow this
47776  ** journal header. Normally, zero is written to this value at this time.
47777  ** After the records are added to the journal (and the journal synced,
47778  ** if in full-sync mode), the zero is overwritten with the true number
47779  ** of records (see syncJournal()).
47780  **
47781  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
47782  ** reading the journal this value tells SQLite to assume that the
47783  ** rest of the journal file contains valid page records. This assumption
47784  ** is dangerous, as if a failure occurred whilst writing to the journal
47785  ** file it may contain some garbage data. There are two scenarios
47786  ** where this risk can be ignored:
47787  **
47788  ** * When the pager is in no-sync mode. Corruption can follow a
47789  ** power failure in this case anyway.
47790  **
47791  ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
47792  ** that garbage data is never appended to the journal file.
47793  */
47794  assert( isOpen(pPager->fd) || pPager->noSync );
47795  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
47797  ){
47798  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47799  put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
47800  }else{
47801  memset(zHeader, 0, sizeof(aJournalMagic)+4);
47802  }
47803 
47804  /* The random check-hash initializer */
47805  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
47806  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
47807  /* The initial database size */
47808  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
47809  /* The assumed sector size for this process */
47810  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
47811 
47812  /* The page size */
47813  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
47814 
47815  /* Initializing the tail of the buffer is not necessary. Everything
47816  ** works find if the following memset() is omitted. But initializing
47817  ** the memory prevents valgrind from complaining, so we are willing to
47818  ** take the performance hit.
47819  */
47820  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
47821  nHeader-(sizeof(aJournalMagic)+20));
47822 
47823  /* In theory, it is only necessary to write the 28 bytes that the
47824  ** journal header consumes to the journal file here. Then increment the
47825  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
47826  ** record is written to the following sector (leaving a gap in the file
47827  ** that will be implicitly filled in by the OS).
47828  **
47829  ** However it has been discovered that on some systems this pattern can
47830  ** be significantly slower than contiguously writing data to the file,
47831  ** even if that means explicitly writing data to the block of
47832  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
47833  ** is done.
47834  **
47835  ** The loop is required here in case the sector-size is larger than the
47836  ** database page size. Since the zHeader buffer is only Pager.pageSize
47837  ** bytes in size, more than one call to sqlite3OsWrite() may be required
47838  ** to populate the entire journal header sector.
47839  */
47840  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
47841  IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
47842  rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
47843  assert( pPager->journalHdr <= pPager->journalOff );
47844  pPager->journalOff += nHeader;
47845  }
47846 
47847  return rc;
47848 }
47849 
47850 /*
47851 ** The journal file must be open when this is called. A journal header file
47852 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
47853 ** file. The current location in the journal file is given by
47854 ** pPager->journalOff. See comments above function writeJournalHdr() for
47855 ** a description of the journal header format.
47856 **
47857 ** If the header is read successfully, *pNRec is set to the number of
47858 ** page records following this header and *pDbSize is set to the size of the
47859 ** database before the transaction began, in pages. Also, pPager->cksumInit
47860 ** is set to the value read from the journal header. SQLITE_OK is returned
47861 ** in this case.
47862 **
47863 ** If the journal header file appears to be corrupted, SQLITE_DONE is
47864 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
47865 ** cannot be read from the journal file an error code is returned.
47866 */
47867 static int readJournalHdr(
47868  Pager *pPager, /* Pager object */
47869  int isHot,
47870  i64 journalSize, /* Size of the open journal file in bytes */
47871  u32 *pNRec, /* OUT: Value read from the nRec field */
47872  u32 *pDbSize /* OUT: Value of original database size field */
47873 ){
47874  int rc; /* Return code */
47875  unsigned char aMagic[8]; /* A buffer to hold the magic header */
47876  i64 iHdrOff; /* Offset of journal header being read */
47877 
47878  assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
47879 
47880  /* Advance Pager.journalOff to the start of the next sector. If the
47881  ** journal file is too small for there to be a header stored at this
47882  ** point, return SQLITE_DONE.
47883  */
47884  pPager->journalOff = journalHdrOffset(pPager);
47885  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
47886  return SQLITE_DONE;
47887  }
47888  iHdrOff = pPager->journalOff;
47889 
47890  /* Read in the first 8 bytes of the journal header. If they do not match
47891  ** the magic string found at the start of each journal header, return
47892  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
47893  ** proceed.
47894  */
47895  if( isHot || iHdrOff!=pPager->journalHdr ){
47896  rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
47897  if( rc ){
47898  return rc;
47899  }
47900  if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
47901  return SQLITE_DONE;
47902  }
47903  }
47904 
47905  /* Read the first three 32-bit fields of the journal header: The nRec
47906  ** field, the checksum-initializer and the database size at the start
47907  ** of the transaction. Return an error code if anything goes wrong.
47908  */
47909  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
47910  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
47911  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
47912  ){
47913  return rc;
47914  }
47915 
47916  if( pPager->journalOff==0 ){
47917  u32 iPageSize; /* Page-size field of journal header */
47918  u32 iSectorSize; /* Sector-size field of journal header */
47919 
47920  /* Read the page-size and sector-size journal header fields. */
47921  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
47922  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
47923  ){
47924  return rc;
47925  }
47926 
47927  /* Versions of SQLite prior to 3.5.8 set the page-size field of the
47928  ** journal header to zero. In this case, assume that the Pager.pageSize
47929  ** variable is already set to the correct page size.
47930  */
47931  if( iPageSize==0 ){
47932  iPageSize = pPager->pageSize;
47933  }
47934 
47935  /* Check that the values read from the page-size and sector-size fields
47936  ** are within range. To be 'in range', both values need to be a power
47937  ** of two greater than or equal to 512 or 32, and not greater than their
47938  ** respective compile time maximum limits.
47939  */
47940  if( iPageSize<512 || iSectorSize<32
47941  || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
47942  || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
47943  ){
47944  /* If the either the page-size or sector-size in the journal-header is
47945  ** invalid, then the process that wrote the journal-header must have
47946  ** crashed before the header was synced. In this case stop reading
47947  ** the journal file here.
47948  */
47949  return SQLITE_DONE;
47950  }
47951 
47952  /* Update the page-size to match the value read from the journal.
47953  ** Use a testcase() macro to make sure that malloc failure within
47954  ** PagerSetPagesize() is tested.
47955  */
47956  rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
47957  testcase( rc!=SQLITE_OK );
47958 
47959  /* Update the assumed sector-size to match the value used by
47960  ** the process that created this journal. If this journal was
47961  ** created by a process other than this one, then this routine
47962  ** is being called from within pager_playback(). The local value
47963  ** of Pager.sectorSize is restored at the end of that routine.
47964  */
47965  pPager->sectorSize = iSectorSize;
47966  }
47967 
47968  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
47969  return rc;
47970 }
47971 
47972 
47973 /*
47974 ** Write the supplied master journal name into the journal file for pager
47975 ** pPager at the current location. The master journal name must be the last
47976 ** thing written to a journal file. If the pager is in full-sync mode, the
47977 ** journal file descriptor is advanced to the next sector boundary before
47978 ** anything is written. The format is:
47979 **
47980 ** + 4 bytes: PAGER_MJ_PGNO.
47981 ** + N bytes: Master journal filename in utf-8.
47982 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
47983 ** + 4 bytes: Master journal name checksum.
47984 ** + 8 bytes: aJournalMagic[].
47985 **
47986 ** The master journal page checksum is the sum of the bytes in the master
47987 ** journal name, where each byte is interpreted as a signed 8-bit integer.
47988 **
47989 ** If zMaster is a NULL pointer (occurs for a single database transaction),
47990 ** this call is a no-op.
47991 */
47992 static int writeMasterJournal(Pager *pPager, const char *zMaster){
47993  int rc; /* Return code */
47994  int nMaster; /* Length of string zMaster */
47995  i64 iHdrOff; /* Offset of header in journal file */
47996  i64 jrnlSize; /* Size of journal file on disk */
47997  u32 cksum = 0; /* Checksum of string zMaster */
47998 
47999  assert( pPager->setMaster==0 );
48000  assert( !pagerUseWal(pPager) );
48001 
48002  if( !zMaster
48004  || !isOpen(pPager->jfd)
48005  ){
48006  return SQLITE_OK;
48007  }
48008  pPager->setMaster = 1;
48009  assert( pPager->journalHdr <= pPager->journalOff );
48010 
48011  /* Calculate the length in bytes and the checksum of zMaster */
48012  for(nMaster=0; zMaster[nMaster]; nMaster++){
48013  cksum += zMaster[nMaster];
48014  }
48015 
48016  /* If in full-sync mode, advance to the next disk sector before writing
48017  ** the master journal name. This is in case the previous page written to
48018  ** the journal has already been synced.
48019  */
48020  if( pPager->fullSync ){
48021  pPager->journalOff = journalHdrOffset(pPager);
48022  }
48023  iHdrOff = pPager->journalOff;
48024 
48025  /* Write the master journal data to the end of the journal file. If
48026  ** an error occurs, return the error code to the caller.
48027  */
48028  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
48029  || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
48030  || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
48031  || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
48032  || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
48033  iHdrOff+4+nMaster+8)))
48034  ){
48035  return rc;
48036  }
48037  pPager->journalOff += (nMaster+20);
48038 
48039  /* If the pager is in peristent-journal mode, then the physical
48040  ** journal-file may extend past the end of the master-journal name
48041  ** and 8 bytes of magic data just written to the file. This is
48042  ** dangerous because the code to rollback a hot-journal file
48043  ** will not be able to find the master-journal name to determine
48044  ** whether or not the journal is hot.
48045  **
48046  ** Easiest thing to do in this scenario is to truncate the journal
48047  ** file to the required size.
48048  */
48049  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
48050  && jrnlSize>pPager->journalOff
48051  ){
48052  rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
48053  }
48054  return rc;
48055 }
48056 
48057 /*
48058 ** Discard the entire contents of the in-memory page-cache.
48059 */
48060 static void pager_reset(Pager *pPager){
48061  pPager->iDataVersion++;
48062  sqlite3BackupRestart(pPager->pBackup);
48063  sqlite3PcacheClear(pPager->pPCache);
48064 }
48065 
48066 /*
48067 ** Return the pPager->iDataVersion value
48068 */
48070  assert( pPager->eState>PAGER_OPEN );
48071  return pPager->iDataVersion;
48072 }
48073 
48074 /*
48075 ** Free all structures in the Pager.aSavepoint[] array and set both
48076 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
48077 ** if it is open and the pager is not in exclusive mode.
48078 */
48079 static void releaseAllSavepoints(Pager *pPager){
48080  int ii; /* Iterator for looping through Pager.aSavepoint */
48081  for(ii=0; ii<pPager->nSavepoint; ii++){
48083  }
48084  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
48085  sqlite3OsClose(pPager->sjfd);
48086  }
48087  sqlite3_free(pPager->aSavepoint);
48088  pPager->aSavepoint = 0;
48089  pPager->nSavepoint = 0;
48090  pPager->nSubRec = 0;
48091 }
48092 
48093 /*
48094 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
48095 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
48096 ** or SQLITE_NOMEM if a malloc failure occurs.
48097 */
48098 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
48099  int ii; /* Loop counter */
48100  int rc = SQLITE_OK; /* Result code */
48101 
48102  for(ii=0; ii<pPager->nSavepoint; ii++){
48103  PagerSavepoint *p = &pPager->aSavepoint[ii];
48104  if( pgno<=p->nOrig ){
48105  rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
48106  testcase( rc==SQLITE_NOMEM );
48107  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48108  }
48109  }
48110  return rc;
48111 }
48112 
48113 /*
48114 ** This function is a no-op if the pager is in exclusive mode and not
48115 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
48116 ** state.
48117 **
48118 ** If the pager is not in exclusive-access mode, the database file is
48119 ** completely unlocked. If the file is unlocked and the file-system does
48120 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
48121 ** closed (if it is open).
48122 **
48123 ** If the pager is in ERROR state when this function is called, the
48124 ** contents of the pager cache are discarded before switching back to
48125 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
48126 ** or not, any journal file left in the file-system will be treated
48127 ** as a hot-journal and rolled back the next time a read-transaction
48128 ** is opened (by this or by any other connection).
48129 */
48130 static void pager_unlock(Pager *pPager){
48131 
48132  assert( pPager->eState==PAGER_READER
48133  || pPager->eState==PAGER_OPEN
48134  || pPager->eState==PAGER_ERROR
48135  );
48136 
48138  pPager->pInJournal = 0;
48139  releaseAllSavepoints(pPager);
48140 
48141  if( pagerUseWal(pPager) ){
48142  assert( !isOpen(pPager->jfd) );
48144  pPager->eState = PAGER_OPEN;
48145  }else if( !pPager->exclusiveMode ){
48146  int rc; /* Error code returned by pagerUnlockDb() */
48147  int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
48148 
48149  /* If the operating system support deletion of open files, then
48150  ** close the journal file when dropping the database lock. Otherwise
48151  ** another connection with journal_mode=delete might delete the file
48152  ** out from under us.
48153  */
48154  assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
48155  assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
48156  assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
48157  assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
48158  assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48159  assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
48160  if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
48161  || 1!=(pPager->journalMode & 5)
48162  ){
48163  sqlite3OsClose(pPager->jfd);
48164  }
48165 
48166  /* If the pager is in the ERROR state and the call to unlock the database
48167  ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
48168  ** above the #define for UNKNOWN_LOCK for an explanation of why this
48169  ** is necessary.
48170  */
48171  rc = pagerUnlockDb(pPager, NO_LOCK);
48172  if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
48173  pPager->eLock = UNKNOWN_LOCK;
48174  }
48175 
48176  /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
48177  ** without clearing the error code. This is intentional - the error
48178  ** code is cleared and the cache reset in the block below.
48179  */
48180  assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
48181  pPager->changeCountDone = 0;
48182  pPager->eState = PAGER_OPEN;
48183  }
48184 
48185  /* If Pager.errCode is set, the contents of the pager cache cannot be
48186  ** trusted. Now that there are no outstanding references to the pager,
48187  ** it can safely move back to PAGER_OPEN state. This happens in both
48188  ** normal and exclusive-locking mode.
48189  */
48190  assert( pPager->errCode==SQLITE_OK || !MEMDB );
48191  if( pPager->errCode ){
48192  if( pPager->tempFile==0 ){
48193  pager_reset(pPager);
48194  pPager->changeCountDone = 0;
48195  pPager->eState = PAGER_OPEN;
48196  }else{
48197  pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
48198  }
48199  if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
48200  pPager->errCode = SQLITE_OK;
48201  }
48202 
48203  pPager->journalOff = 0;
48204  pPager->journalHdr = 0;
48205  pPager->setMaster = 0;
48206 }
48207 
48208 /*
48209 ** This function is called whenever an IOERR or FULL error that requires
48210 ** the pager to transition into the ERROR state may ahve occurred.
48211 ** The first argument is a pointer to the pager structure, the second
48212 ** the error-code about to be returned by a pager API function. The
48213 ** value returned is a copy of the second argument to this function.
48214 **
48215 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
48216 ** IOERR sub-codes, the pager enters the ERROR state and the error code
48217 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
48218 ** all major API calls on the Pager will immediately return Pager.errCode.
48219 **
48220 ** The ERROR state indicates that the contents of the pager-cache
48221 ** cannot be trusted. This state can be cleared by completely discarding
48222 ** the contents of the pager-cache. If a transaction was active when
48223 ** the persistent error occurred, then the rollback journal may need
48224 ** to be replayed to restore the contents of the database file (as if
48225 ** it were a hot-journal).
48226 */
48227 static int pager_error(Pager *pPager, int rc){
48228  int rc2 = rc & 0xff;
48229  assert( rc==SQLITE_OK || !MEMDB );
48230  assert(
48231  pPager->errCode==SQLITE_FULL ||
48232  pPager->errCode==SQLITE_OK ||
48233  (pPager->errCode & 0xff)==SQLITE_IOERR
48234  );
48235  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
48236  pPager->errCode = rc;
48237  pPager->eState = PAGER_ERROR;
48238  }
48239  return rc;
48240 }
48241 
48242 static int pager_truncate(Pager *pPager, Pgno nPage);
48243 
48244 /*
48245 ** The write transaction open on pPager is being committed (bCommit==1)
48246 ** or rolled back (bCommit==0).
48247 **
48248 ** Return TRUE if and only if all dirty pages should be flushed to disk.
48249 **
48250 ** Rules:
48251 **
48252 ** * For non-TEMP databases, always sync to disk. This is necessary
48253 ** for transactions to be durable.
48254 **
48255 ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
48256 ** file has been created already (via a spill on pagerStress()) and
48257 ** when the number of dirty pages in memory exceeds 25% of the total
48258 ** cache size.
48259 */
48260 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
48261  if( pPager->tempFile==0 ) return 1;
48262  if( !bCommit ) return 0;
48263  if( !isOpen(pPager->fd) ) return 0;
48264  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
48265 }
48266 
48267 /*
48268 ** This routine ends a transaction. A transaction is usually ended by
48269 ** either a COMMIT or a ROLLBACK operation. This routine may be called
48270 ** after rollback of a hot-journal, or if an error occurs while opening
48271 ** the journal file or writing the very first journal-header of a
48272 ** database transaction.
48273 **
48274 ** This routine is never called in PAGER_ERROR state. If it is called
48275 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
48276 ** exclusive than a RESERVED lock, it is a no-op.
48277 **
48278 ** Otherwise, any active savepoints are released.
48279 **
48280 ** If the journal file is open, then it is "finalized". Once a journal
48281 ** file has been finalized it is not possible to use it to roll back a
48282 ** transaction. Nor will it be considered to be a hot-journal by this
48283 ** or any other database connection. Exactly how a journal is finalized
48284 ** depends on whether or not the pager is running in exclusive mode and
48285 ** the current journal-mode (Pager.journalMode value), as follows:
48286 **
48287 ** journalMode==MEMORY
48288 ** Journal file descriptor is simply closed. This destroys an
48289 ** in-memory journal.
48290 **
48291 ** journalMode==TRUNCATE
48292 ** Journal file is truncated to zero bytes in size.
48293 **
48294 ** journalMode==PERSIST
48295 ** The first 28 bytes of the journal file are zeroed. This invalidates
48296 ** the first journal header in the file, and hence the entire journal
48297 ** file. An invalid journal file cannot be rolled back.
48298 **
48299 ** journalMode==DELETE
48300 ** The journal file is closed and deleted using sqlite3OsDelete().
48301 **
48302 ** If the pager is running in exclusive mode, this method of finalizing
48303 ** the journal file is never used. Instead, if the journalMode is
48304 ** DELETE and the pager is in exclusive mode, the method described under
48305 ** journalMode==PERSIST is used instead.
48306 **
48307 ** After the journal is finalized, the pager moves to PAGER_READER state.
48308 ** If running in non-exclusive rollback mode, the lock on the file is
48309 ** downgraded to a SHARED_LOCK.
48310 **
48311 ** SQLITE_OK is returned if no error occurs. If an error occurs during
48312 ** any of the IO operations to finalize the journal file or unlock the
48313 ** database then the IO error code is returned to the user. If the
48314 ** operation to finalize the journal file fails, then the code still
48315 ** tries to unlock the database file if not in exclusive mode. If the
48316 ** unlock operation fails as well, then the first error code related
48317 ** to the first error encountered (the journal finalization one) is
48318 ** returned.
48319 */
48320 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
48321  int rc = SQLITE_OK; /* Error code from journal finalization operation */
48322  int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
48323 
48324  /* Do nothing if the pager does not have an open write transaction
48325  ** or at least a RESERVED lock. This function may be called when there
48326  ** is no write-transaction active but a RESERVED or greater lock is
48327  ** held under two circumstances:
48328  **
48329  ** 1. After a successful hot-journal rollback, it is called with
48330  ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
48331  **
48332  ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
48333  ** lock switches back to locking_mode=normal and then executes a
48334  ** read-transaction, this function is called with eState==PAGER_READER
48335  ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
48336  */
48337  assert( assert_pager_state(pPager) );
48338  assert( pPager->eState!=PAGER_ERROR );
48339  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
48340  return SQLITE_OK;
48341  }
48342 
48343  releaseAllSavepoints(pPager);
48344  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
48345  if( isOpen(pPager->jfd) ){
48346  assert( !pagerUseWal(pPager) );
48347 
48348  /* Finalize the journal file. */
48349  if( sqlite3JournalIsInMemory(pPager->jfd) ){
48350  /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
48351  sqlite3OsClose(pPager->jfd);
48352  }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
48353  if( pPager->journalOff==0 ){
48354  rc = SQLITE_OK;
48355  }else{
48356  rc = sqlite3OsTruncate(pPager->jfd, 0);
48357  if( rc==SQLITE_OK && pPager->fullSync ){
48358  /* Make sure the new file size is written into the inode right away.
48359  ** Otherwise the journal might resurrect following a power loss and
48360  ** cause the last transaction to roll back. See
48361  ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
48362  */
48363  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
48364  }
48365  }
48366  pPager->journalOff = 0;
48367  }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
48368  || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
48369  ){
48370  rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
48371  pPager->journalOff = 0;
48372  }else{
48373  /* This branch may be executed with Pager.journalMode==MEMORY if
48374  ** a hot-journal was just rolled back. In this case the journal
48375  ** file should be closed and deleted. If this connection writes to
48376  ** the database file, it will do so using an in-memory journal.
48377  */
48378  int bDelete = !pPager->tempFile;
48379  assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
48380  assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
48382  || pPager->journalMode==PAGER_JOURNALMODE_WAL
48383  );
48384  sqlite3OsClose(pPager->jfd);
48385  if( bDelete ){
48386  rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
48387  }
48388  }
48389  }
48390 
48391 #ifdef SQLITE_CHECK_PAGES
48392  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
48393  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
48394  PgHdr *p = sqlite3PagerLookup(pPager, 1);
48395  if( p ){
48396  p->pageHash = 0;
48398  }
48399  }
48400 #endif
48401 
48403  pPager->pInJournal = 0;
48404  pPager->nRec = 0;
48405  if( rc==SQLITE_OK ){
48406  if( pagerFlushOnCommit(pPager, bCommit) ){
48407  sqlite3PcacheCleanAll(pPager->pPCache);
48408  }else{
48410  }
48411  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
48412  }
48413 
48414  if( pagerUseWal(pPager) ){
48415  /* Drop the WAL write-lock, if any. Also, if the connection was in
48416  ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
48417  ** lock held on the database file.
48418  */
48419  rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
48420  assert( rc2==SQLITE_OK );
48421  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
48422  /* This branch is taken when committing a transaction in rollback-journal
48423  ** mode if the database file on disk is larger than the database image.
48424  ** At this point the journal has been finalized and the transaction
48425  ** successfully committed, but the EXCLUSIVE lock is still held on the
48426  ** file. So it is safe to truncate the database file to its minimum
48427  ** required size. */
48428  assert( pPager->eLock==EXCLUSIVE_LOCK );
48429  rc = pager_truncate(pPager, pPager->dbSize);
48430  }
48431 
48432  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
48434  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
48435  }
48436 
48437  if( !pPager->exclusiveMode
48438  && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
48439  ){
48440  rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
48441  pPager->changeCountDone = 0;
48442  }
48443  pPager->eState = PAGER_READER;
48444  pPager->setMaster = 0;
48445 
48446  return (rc==SQLITE_OK?rc2:rc);
48447 }
48448 
48449 /*
48450 ** Execute a rollback if a transaction is active and unlock the
48451 ** database file.
48452 **
48453 ** If the pager has already entered the ERROR state, do not attempt
48454 ** the rollback at this time. Instead, pager_unlock() is called. The
48455 ** call to pager_unlock() will discard all in-memory pages, unlock
48456 ** the database file and move the pager back to OPEN state. If this
48457 ** means that there is a hot-journal left in the file-system, the next
48458 ** connection to obtain a shared lock on the pager (which may be this one)
48459 ** will roll it back.
48460 **
48461 ** If the pager has not already entered the ERROR state, but an IO or
48462 ** malloc error occurs during a rollback, then this will itself cause
48463 ** the pager to enter the ERROR state. Which will be cleared by the
48464 ** call to pager_unlock(), as described above.
48465 */
48466 static void pagerUnlockAndRollback(Pager *pPager){
48467  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
48468  assert( assert_pager_state(pPager) );
48469  if( pPager->eState>=PAGER_WRITER_LOCKED ){
48471  sqlite3PagerRollback(pPager);
48473  }else if( !pPager->exclusiveMode ){
48474  assert( pPager->eState==PAGER_READER );
48475  pager_end_transaction(pPager, 0, 0);
48476  }
48477  }
48478  pager_unlock(pPager);
48479 }
48480 
48481 /*
48482 ** Parameter aData must point to a buffer of pPager->pageSize bytes
48483 ** of data. Compute and return a checksum based ont the contents of the
48484 ** page of data and the current value of pPager->cksumInit.
48485 **
48486 ** This is not a real checksum. It is really just the sum of the
48487 ** random initial value (pPager->cksumInit) and every 200th byte
48488 ** of the page data, starting with byte offset (pPager->pageSize%200).
48489 ** Each byte is interpreted as an 8-bit unsigned integer.
48490 **
48491 ** Changing the formula used to compute this checksum results in an
48492 ** incompatible journal file format.
48493 **
48494 ** If journal corruption occurs due to a power failure, the most likely
48495 ** scenario is that one end or the other of the record will be changed.
48496 ** It is much less likely that the two ends of the journal record will be
48497 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
48498 ** though fast and simple, catches the mostly likely kind of corruption.
48499 */
48500 static u32 pager_cksum(Pager *pPager, const u8 *aData){
48501  u32 cksum = pPager->cksumInit; /* Checksum value to return */
48502  int i = pPager->pageSize-200; /* Loop counter */
48503  while( i>0 ){
48504  cksum += aData[i];
48505  i -= 200;
48506  }
48507  return cksum;
48508 }
48509 
48510 /*
48511 ** Report the current page size and number of reserved bytes back
48512 ** to the codec.
48513 */
48514 #ifdef SQLITE_HAS_CODEC
48515 static void pagerReportSize(Pager *pPager){
48516  if( pPager->xCodecSizeChng ){
48517  pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
48518  (int)pPager->nReserve);
48519  }
48520 }
48521 #else
48522 # define pagerReportSize(X) /* No-op if we do not support a codec */
48523 #endif
48524 
48525 #ifdef SQLITE_HAS_CODEC
48526 /*
48527 ** Make sure the number of reserved bits is the same in the destination
48528 ** pager as it is in the source. This comes up when a VACUUM changes the
48529 ** number of reserved bits to the "optimal" amount.
48530 */
48531 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
48532  if( pDest->nReserve!=pSrc->nReserve ){
48533  pDest->nReserve = pSrc->nReserve;
48534  pagerReportSize(pDest);
48535  }
48536 }
48537 #endif
48538 
48539 /*
48540 ** Read a single page from either the journal file (if isMainJrnl==1) or
48541 ** from the sub-journal (if isMainJrnl==0) and playback that page.
48542 ** The page begins at offset *pOffset into the file. The *pOffset
48543 ** value is increased to the start of the next page in the journal.
48544 **
48545 ** The main rollback journal uses checksums - the statement journal does
48546 ** not.
48547 **
48548 ** If the page number of the page record read from the (sub-)journal file
48549 ** is greater than the current value of Pager.dbSize, then playback is
48550 ** skipped and SQLITE_OK is returned.
48551 **
48552 ** If pDone is not NULL, then it is a record of pages that have already
48553 ** been played back. If the page at *pOffset has already been played back
48554 ** (if the corresponding pDone bit is set) then skip the playback.
48555 ** Make sure the pDone bit corresponding to the *pOffset page is set
48556 ** prior to returning.
48557 **
48558 ** If the page record is successfully read from the (sub-)journal file
48559 ** and played back, then SQLITE_OK is returned. If an IO error occurs
48560 ** while reading the record from the (sub-)journal file or while writing
48561 ** to the database file, then the IO error code is returned. If data
48562 ** is successfully read from the (sub-)journal file but appears to be
48563 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
48564 ** two circumstances:
48565 **
48566 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
48567 ** * If the record is being rolled back from the main journal file
48568 ** and the checksum field does not match the record content.
48569 **
48570 ** Neither of these two scenarios are possible during a savepoint rollback.
48571 **
48572 ** If this is a savepoint rollback, then memory may have to be dynamically
48573 ** allocated by this function. If this is the case and an allocation fails,
48574 ** SQLITE_NOMEM is returned.
48575 */
48577  Pager *pPager, /* The pager being played back */
48578  i64 *pOffset, /* Offset of record to playback */
48579  Bitvec *pDone, /* Bitvec of pages already played back */
48580  int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
48581  int isSavepnt /* True for a savepoint rollback */
48582 ){
48583  int rc;
48584  PgHdr *pPg; /* An existing page in the cache */
48585  Pgno pgno; /* The page number of a page in journal */
48586  u32 cksum; /* Checksum used for sanity checking */
48587  char *aData; /* Temporary storage for the page */
48588  sqlite3_file *jfd; /* The file descriptor for the journal file */
48589  int isSynced; /* True if journal page is synced */
48590 
48591  assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
48592  assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
48593  assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
48594  assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
48595 
48596  aData = pPager->pTmpSpace;
48597  assert( aData ); /* Temp storage must have already been allocated */
48598  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
48599 
48600  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
48601  ** or savepoint rollback done at the request of the caller) or this is
48602  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
48603  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
48604  ** only reads from the main journal, not the sub-journal.
48605  */
48606  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
48607  || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
48608  );
48609  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
48610 
48611  /* Read the page number and page data from the journal or sub-journal
48612  ** file. Return an error code to the caller if an IO error occurs.
48613  */
48614  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
48615  rc = read32bits(jfd, *pOffset, &pgno);
48616  if( rc!=SQLITE_OK ) return rc;
48617  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
48618  if( rc!=SQLITE_OK ) return rc;
48619  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
48620 
48621  /* Sanity checking on the page. This is more important that I originally
48622  ** thought. If a power failure occurs while the journal is being written,
48623  ** it could cause invalid data to be written into the journal. We need to
48624  ** detect this invalid data (with high probability) and ignore it.
48625  */
48626  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
48627  assert( !isSavepnt );
48628  return SQLITE_DONE;
48629  }
48630  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
48631  return SQLITE_OK;
48632  }
48633  if( isMainJrnl ){
48634  rc = read32bits(jfd, (*pOffset)-4, &cksum);
48635  if( rc ) return rc;
48636  if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
48637  return SQLITE_DONE;
48638  }
48639  }
48640 
48641  /* If this page has already been played back before during the current
48642  ** rollback, then don't bother to play it back again.
48643  */
48644  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
48645  return rc;
48646  }
48647 
48648  /* When playing back page 1, restore the nReserve setting
48649  */
48650  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
48651  pPager->nReserve = ((u8*)aData)[20];
48652  pagerReportSize(pPager);
48653  }
48654 
48655  /* If the pager is in CACHEMOD state, then there must be a copy of this
48656  ** page in the pager cache. In this case just update the pager cache,
48657  ** not the database file. The page is left marked dirty in this case.
48658  **
48659  ** An exception to the above rule: If the database is in no-sync mode
48660  ** and a page is moved during an incremental vacuum then the page may
48661  ** not be in the pager cache. Later: if a malloc() or IO error occurs
48662  ** during a Movepage() call, then the page may not be in the cache
48663  ** either. So the condition described in the above paragraph is not
48664  ** assert()able.
48665  **
48666  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
48667  ** pager cache if it exists and the main file. The page is then marked
48668  ** not dirty. Since this code is only executed in PAGER_OPEN state for
48669  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
48670  ** if the pager is in OPEN state.
48671  **
48672  ** Ticket #1171: The statement journal might contain page content that is
48673  ** different from the page content at the start of the transaction.
48674  ** This occurs when a page is changed prior to the start of a statement
48675  ** then changed again within the statement. When rolling back such a
48676  ** statement we must not write to the original database unless we know
48677  ** for certain that original page contents are synced into the main rollback
48678  ** journal. Otherwise, a power loss might leave modified data in the
48679  ** database file without an entry in the rollback journal that can
48680  ** restore the database to its original form. Two conditions must be
48681  ** met before writing to the database files. (1) the database must be
48682  ** locked. (2) we know that the original page content is fully synced
48683  ** in the main journal either because the page is not in cache or else
48684  ** the page is marked as needSync==0.
48685  **
48686  ** 2008-04-14: When attempting to vacuum a corrupt database file, it
48687  ** is possible to fail a statement on a database that does not yet exist.
48688  ** Do not attempt to write if database file has never been opened.
48689  */
48690  if( pagerUseWal(pPager) ){
48691  pPg = 0;
48692  }else{
48693  pPg = sqlite3PagerLookup(pPager, pgno);
48694  }
48695  assert( pPg || !MEMDB );
48696  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
48697  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
48698  PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
48699  (isMainJrnl?"main-journal":"sub-journal")
48700  ));
48701  if( isMainJrnl ){
48702  isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
48703  }else{
48704  isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
48705  }
48706  if( isOpen(pPager->fd)
48707  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48708  && isSynced
48709  ){
48710  i64 ofst = (pgno-1)*(i64)pPager->pageSize;
48711  testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
48712  assert( !pagerUseWal(pPager) );
48713  rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
48714  if( pgno>pPager->dbFileSize ){
48715  pPager->dbFileSize = pgno;
48716  }
48717  if( pPager->pBackup ){
48718  CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
48719  sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
48720  CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
48721  }
48722  }else if( !isMainJrnl && pPg==0 ){
48723  /* If this is a rollback of a savepoint and data was not written to
48724  ** the database and the page is not in-memory, there is a potential
48725  ** problem. When the page is next fetched by the b-tree layer, it
48726  ** will be read from the database file, which may or may not be
48727  ** current.
48728  **
48729  ** There are a couple of different ways this can happen. All are quite
48730  ** obscure. When running in synchronous mode, this can only happen
48731  ** if the page is on the free-list at the start of the transaction, then
48732  ** populated, then moved using sqlite3PagerMovepage().
48733  **
48734  ** The solution is to add an in-memory page to the cache containing
48735  ** the data just read from the sub-journal. Mark the page as dirty
48736  ** and if the pager requires a journal-sync, then mark the page as
48737  ** requiring a journal-sync before it is written.
48738  */
48739  assert( isSavepnt );
48740  assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
48741  pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
48742  rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
48743  assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
48744  pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
48745  if( rc!=SQLITE_OK ) return rc;
48747  }
48748  if( pPg ){
48749  /* No page should ever be explicitly rolled back that is in use, except
48750  ** for page 1 which is held in use in order to keep the lock on the
48751  ** database active. However such a page may be rolled back as a result
48752  ** of an internal error resulting in an automatic call to
48753  ** sqlite3PagerRollback().
48754  */
48755  void *pData;
48756  pData = pPg->pData;
48757  memcpy(pData, (u8*)aData, pPager->pageSize);
48758  pPager->xReiniter(pPg);
48759  /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
48760  ** that call was dangerous and had no detectable benefit since the cache
48761  ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48762  ** has been removed. */
48763  pager_set_pagehash(pPg);
48764 
48765  /* If this was page 1, then restore the value of Pager.dbFileVers.
48766  ** Do this before any decoding. */
48767  if( pgno==1 ){
48768  memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
48769  }
48770 
48771  /* Decode the page just read from disk */
48772  CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
48773  sqlite3PcacheRelease(pPg);
48774  }
48775  return rc;
48776 }
48777 
48778 /*
48779 ** Parameter zMaster is the name of a master journal file. A single journal
48780 ** file that referred to the master journal file has just been rolled back.
48781 ** This routine checks if it is possible to delete the master journal file,
48782 ** and does so if it is.
48783 **
48784 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
48785 ** available for use within this function.
48786 **
48787 ** When a master journal file is created, it is populated with the names
48788 ** of all of its child journals, one after another, formatted as utf-8
48789 ** encoded text. The end of each child journal file is marked with a
48790 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
48791 ** file for a transaction involving two databases might be:
48792 **
48793 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
48794 **
48795 ** A master journal file may only be deleted once all of its child
48796 ** journals have been rolled back.
48797 **
48798 ** This function reads the contents of the master-journal file into
48799 ** memory and loops through each of the child journal names. For
48800 ** each child journal, it checks if:
48801 **
48802 ** * if the child journal exists, and if so
48803 ** * if the child journal contains a reference to master journal
48804 ** file zMaster
48805 **
48806 ** If a child journal can be found that matches both of the criteria
48807 ** above, this function returns without doing anything. Otherwise, if
48808 ** no such child journal can be found, file zMaster is deleted from
48809 ** the file-system using sqlite3OsDelete().
48810 **
48811 ** If an IO error within this function, an error code is returned. This
48812 ** function allocates memory by calling sqlite3Malloc(). If an allocation
48813 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
48814 ** occur, SQLITE_OK is returned.
48815 **
48816 ** TODO: This function allocates a single block of memory to load
48817 ** the entire contents of the master journal file. This could be
48818 ** a couple of kilobytes or so - potentially larger than the page
48819 ** size.
48820 */
48821 static int pager_delmaster(Pager *pPager, const char *zMaster){
48822  sqlite3_vfs *pVfs = pPager->pVfs;
48823  int rc; /* Return code */
48824  sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
48825  sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
48826  char *zMasterJournal = 0; /* Contents of master journal file */
48827  i64 nMasterJournal; /* Size of master journal file */
48828  char *zJournal; /* Pointer to one journal within MJ file */
48829  char *zMasterPtr; /* Space to hold MJ filename from a journal file */
48830  int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
48831 
48832  /* Allocate space for both the pJournal and pMaster file descriptors.
48833  ** If successful, open the master journal file for reading.
48834  */
48835  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
48836  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
48837  if( !pMaster ){
48838  rc = SQLITE_NOMEM_BKPT;
48839  }else{
48841  rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
48842  }
48843  if( rc!=SQLITE_OK ) goto delmaster_out;
48844 
48845  /* Load the entire master journal file into space obtained from
48846  ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
48847  ** sufficient space (in zMasterPtr) to hold the names of master
48848  ** journal files extracted from regular rollback-journals.
48849  */
48850  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
48851  if( rc!=SQLITE_OK ) goto delmaster_out;
48852  nMasterPtr = pVfs->mxPathname+1;
48853  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
48854  if( !zMasterJournal ){
48855  rc = SQLITE_NOMEM_BKPT;
48856  goto delmaster_out;
48857  }
48858  zMasterPtr = &zMasterJournal[nMasterJournal+1];
48859  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
48860  if( rc!=SQLITE_OK ) goto delmaster_out;
48861  zMasterJournal[nMasterJournal] = 0;
48862 
48863  zJournal = zMasterJournal;
48864  while( (zJournal-zMasterJournal)<nMasterJournal ){
48865  int exists;
48866  rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
48867  if( rc!=SQLITE_OK ){
48868  goto delmaster_out;
48869  }
48870  if( exists ){
48871  /* One of the journals pointed to by the master journal exists.
48872  ** Open it and check if it points at the master journal. If
48873  ** so, return without deleting the master journal file.
48874  */
48875  int c;
48877  rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
48878  if( rc!=SQLITE_OK ){
48879  goto delmaster_out;
48880  }
48881 
48882  rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
48883  sqlite3OsClose(pJournal);
48884  if( rc!=SQLITE_OK ){
48885  goto delmaster_out;
48886  }
48887 
48888  c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
48889  if( c ){
48890  /* We have a match. Do not delete the master journal file. */
48891  goto delmaster_out;
48892  }
48893  }
48894  zJournal += (sqlite3Strlen30(zJournal)+1);
48895  }
48896 
48897  sqlite3OsClose(pMaster);
48898  rc = sqlite3OsDelete(pVfs, zMaster, 0);
48899 
48900 delmaster_out:
48901  sqlite3_free(zMasterJournal);
48902  if( pMaster ){
48903  sqlite3OsClose(pMaster);
48904  assert( !isOpen(pJournal) );
48905  sqlite3_free(pMaster);
48906  }
48907  return rc;
48908 }
48909 
48910 
48911 /*
48912 ** This function is used to change the actual size of the database
48913 ** file in the file-system. This only happens when committing a transaction,
48914 ** or rolling back a transaction (including rolling back a hot-journal).
48915 **
48916 ** If the main database file is not open, or the pager is not in either
48917 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
48918 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
48919 ** If the file on disk is currently larger than nPage pages, then use the VFS
48920 ** xTruncate() method to truncate it.
48921 **
48922 ** Or, it might be the case that the file on disk is smaller than
48923 ** nPage pages. Some operating system implementations can get confused if
48924 ** you try to truncate a file to some size that is larger than it
48925 ** currently is, so detect this case and write a single zero byte to
48926 ** the end of the new file instead.
48927 **
48928 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
48929 ** the database file, return the error code to the caller.
48930 */
48931 static int pager_truncate(Pager *pPager, Pgno nPage){
48932  int rc = SQLITE_OK;
48933  assert( pPager->eState!=PAGER_ERROR );
48934  assert( pPager->eState!=PAGER_READER );
48935 
48936  if( isOpen(pPager->fd)
48937  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48938  ){
48939  i64 currentSize, newSize;
48940  int szPage = pPager->pageSize;
48941  assert( pPager->eLock==EXCLUSIVE_LOCK );
48942  /* TODO: Is it safe to use Pager.dbFileSize here? */
48943  rc = sqlite3OsFileSize(pPager->fd, &currentSize);
48944  newSize = szPage*(i64)nPage;
48945  if( rc==SQLITE_OK && currentSize!=newSize ){
48946  if( currentSize>newSize ){
48947  rc = sqlite3OsTruncate(pPager->fd, newSize);
48948  }else if( (currentSize+szPage)<=newSize ){
48949  char *pTmp = pPager->pTmpSpace;
48950  memset(pTmp, 0, szPage);
48951  testcase( (newSize-szPage) == currentSize );
48952  testcase( (newSize-szPage) > currentSize );
48953  rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
48954  }
48955  if( rc==SQLITE_OK ){
48956  pPager->dbFileSize = nPage;
48957  }
48958  }
48959  }
48960  return rc;
48961 }
48962 
48963 /*
48964 ** Return a sanitized version of the sector-size of OS file pFile. The
48965 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
48966 */
48967 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
48968  int iRet = sqlite3OsSectorSize(pFile);
48969  if( iRet<32 ){
48970  iRet = 512;
48971  }else if( iRet>MAX_SECTOR_SIZE ){
48972  assert( MAX_SECTOR_SIZE>=512 );
48973  iRet = MAX_SECTOR_SIZE;
48974  }
48975  return iRet;
48976 }
48977 
48978 /*
48979 ** Set the value of the Pager.sectorSize variable for the given
48980 ** pager based on the value returned by the xSectorSize method
48981 ** of the open database file. The sector size will be used
48982 ** to determine the size and alignment of journal header and
48983 ** master journal pointers within created journal files.
48984 **
48985 ** For temporary files the effective sector size is always 512 bytes.
48986 **
48987 ** Otherwise, for non-temporary files, the effective sector size is
48988 ** the value returned by the xSectorSize() method rounded up to 32 if
48989 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
48990 ** is greater than MAX_SECTOR_SIZE.
48991 **
48992 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
48993 ** the effective sector size to its minimum value (512). The purpose of
48994 ** pPager->sectorSize is to define the "blast radius" of bytes that
48995 ** might change if a crash occurs while writing to a single byte in
48996 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
48997 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
48998 ** size. For backwards compatibility of the rollback journal file format,
48999 ** we cannot reduce the effective sector size below 512.
49000 */
49001 static void setSectorSize(Pager *pPager){
49002  assert( isOpen(pPager->fd) || pPager->tempFile );
49003 
49004  if( pPager->tempFile
49005  || (sqlite3OsDeviceCharacteristics(pPager->fd) &
49007  ){
49008  /* Sector size doesn't matter for temporary files. Also, the file
49009  ** may not have been opened yet, in which case the OsSectorSize()
49010  ** call will segfault. */
49011  pPager->sectorSize = 512;
49012  }else{
49013  pPager->sectorSize = sqlite3SectorSize(pPager->fd);
49014  }
49015 }
49016 
49017 /*
49018 ** Playback the journal and thus restore the database file to
49019 ** the state it was in before we started making changes.
49020 **
49021 ** The journal file format is as follows:
49022 **
49023 ** (1) 8 byte prefix. A copy of aJournalMagic[].
49024 ** (2) 4 byte big-endian integer which is the number of valid page records
49025 ** in the journal. If this value is 0xffffffff, then compute the
49026 ** number of page records from the journal size.
49027 ** (3) 4 byte big-endian integer which is the initial value for the
49028 ** sanity checksum.
49029 ** (4) 4 byte integer which is the number of pages to truncate the
49030 ** database to during a rollback.
49031 ** (5) 4 byte big-endian integer which is the sector size. The header
49032 ** is this many bytes in size.
49033 ** (6) 4 byte big-endian integer which is the page size.
49034 ** (7) zero padding out to the next sector size.
49035 ** (8) Zero or more pages instances, each as follows:
49036 ** + 4 byte page number.
49037 ** + pPager->pageSize bytes of data.
49038 ** + 4 byte checksum
49039 **
49040 ** When we speak of the journal header, we mean the first 7 items above.
49041 ** Each entry in the journal is an instance of the 8th item.
49042 **
49043 ** Call the value from the second bullet "nRec". nRec is the number of
49044 ** valid page entries in the journal. In most cases, you can compute the
49045 ** value of nRec from the size of the journal file. But if a power
49046 ** failure occurred while the journal was being written, it could be the
49047 ** case that the size of the journal file had already been increased but
49048 ** the extra entries had not yet made it safely to disk. In such a case,
49049 ** the value of nRec computed from the file size would be too large. For
49050 ** that reason, we always use the nRec value in the header.
49051 **
49052 ** If the nRec value is 0xffffffff it means that nRec should be computed
49053 ** from the file size. This value is used when the user selects the
49054 ** no-sync option for the journal. A power failure could lead to corruption
49055 ** in this case. But for things like temporary table (which will be
49056 ** deleted when the power is restored) we don't care.
49057 **
49058 ** If the file opened as the journal file is not a well-formed
49059 ** journal file then all pages up to the first corrupted page are rolled
49060 ** back (or no pages if the journal header is corrupted). The journal file
49061 ** is then deleted and SQLITE_OK returned, just as if no corruption had
49062 ** been encountered.
49063 **
49064 ** If an I/O or malloc() error occurs, the journal-file is not deleted
49065 ** and an error code is returned.
49066 **
49067 ** The isHot parameter indicates that we are trying to rollback a journal
49068 ** that might be a hot journal. Or, it could be that the journal is
49069 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
49070 ** If the journal really is hot, reset the pager cache prior rolling
49071 ** back any content. If the journal is merely persistent, no reset is
49072 ** needed.
49073 */
49074 static int pager_playback(Pager *pPager, int isHot){
49075  sqlite3_vfs *pVfs = pPager->pVfs;
49076  i64 szJ; /* Size of the journal file in bytes */
49077  u32 nRec; /* Number of Records in the journal */
49078  u32 u; /* Unsigned loop counter */
49079  Pgno mxPg = 0; /* Size of the original file in pages */
49080  int rc; /* Result code of a subroutine */
49081  int res = 1; /* Value returned by sqlite3OsAccess() */
49082  char *zMaster = 0; /* Name of master journal file if any */
49083  int needPagerReset; /* True to reset page prior to first page rollback */
49084  int nPlayback = 0; /* Total number of pages restored from journal */
49085 
49086  /* Figure out how many records are in the journal. Abort early if
49087  ** the journal is empty.
49088  */
49089  assert( isOpen(pPager->jfd) );
49090  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
49091  if( rc!=SQLITE_OK ){
49092  goto end_playback;
49093  }
49094 
49095  /* Read the master journal name from the journal, if it is present.
49096  ** If a master journal file name is specified, but the file is not
49097  ** present on disk, then the journal is not hot and does not need to be
49098  ** played back.
49099  **
49100  ** TODO: Technically the following is an error because it assumes that
49101  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
49102  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
49103  ** mxPathname is 512, which is the same as the minimum allowable value
49104  ** for pageSize.
49105  */
49106  zMaster = pPager->pTmpSpace;
49107  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49108  if( rc==SQLITE_OK && zMaster[0] ){
49109  rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49110  }
49111  zMaster = 0;
49112  if( rc!=SQLITE_OK || !res ){
49113  goto end_playback;
49114  }
49115  pPager->journalOff = 0;
49116  needPagerReset = isHot;
49117 
49118  /* This loop terminates either when a readJournalHdr() or
49119  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
49120  ** occurs.
49121  */
49122  while( 1 ){
49123  /* Read the next journal header from the journal file. If there are
49124  ** not enough bytes left in the journal file for a complete header, or
49125  ** it is corrupted, then a process must have failed while writing it.
49126  ** This indicates nothing more needs to be rolled back.
49127  */
49128  rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
49129  if( rc!=SQLITE_OK ){
49130  if( rc==SQLITE_DONE ){
49131  rc = SQLITE_OK;
49132  }
49133  goto end_playback;
49134  }
49135 
49136  /* If nRec is 0xffffffff, then this journal was created by a process
49137  ** working in no-sync mode. This means that the rest of the journal
49138  ** file consists of pages, there are no more journal headers. Compute
49139  ** the value of nRec based on this assumption.
49140  */
49141  if( nRec==0xffffffff ){
49142  assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
49143  nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
49144  }
49145 
49146  /* If nRec is 0 and this rollback is of a transaction created by this
49147  ** process and if this is the final header in the journal, then it means
49148  ** that this part of the journal was being filled but has not yet been
49149  ** synced to disk. Compute the number of pages based on the remaining
49150  ** size of the file.
49151  **
49152  ** The third term of the test was added to fix ticket #2565.
49153  ** When rolling back a hot journal, nRec==0 always means that the next
49154  ** chunk of the journal contains zero pages to be rolled back. But
49155  ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
49156  ** the journal, it means that the journal might contain additional
49157  ** pages that need to be rolled back and that the number of pages
49158  ** should be computed based on the journal file size.
49159  */
49160  if( nRec==0 && !isHot &&
49161  pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
49162  nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
49163  }
49164 
49165  /* If this is the first header read from the journal, truncate the
49166  ** database file back to its original size.
49167  */
49168  if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
49169  rc = pager_truncate(pPager, mxPg);
49170  if( rc!=SQLITE_OK ){
49171  goto end_playback;
49172  }
49173  pPager->dbSize = mxPg;
49174  }
49175 
49176  /* Copy original pages out of the journal and back into the
49177  ** database file and/or page cache.
49178  */
49179  for(u=0; u<nRec; u++){
49180  if( needPagerReset ){
49181  pager_reset(pPager);
49182  needPagerReset = 0;
49183  }
49184  rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
49185  if( rc==SQLITE_OK ){
49186  nPlayback++;
49187  }else{
49188  if( rc==SQLITE_DONE ){
49189  pPager->journalOff = szJ;
49190  break;
49191  }else if( rc==SQLITE_IOERR_SHORT_READ ){
49192  /* If the journal has been truncated, simply stop reading and
49193  ** processing the journal. This might happen if the journal was
49194  ** not completely written and synced prior to a crash. In that
49195  ** case, the database should have never been written in the
49196  ** first place so it is OK to simply abandon the rollback. */
49197  rc = SQLITE_OK;
49198  goto end_playback;
49199  }else{
49200  /* If we are unable to rollback, quit and return the error
49201  ** code. This will cause the pager to enter the error state
49202  ** so that no further harm will be done. Perhaps the next
49203  ** process to come along will be able to rollback the database.
49204  */
49205  goto end_playback;
49206  }
49207  }
49208  }
49209  }
49210  /*NOTREACHED*/
49211  assert( 0 );
49212 
49213 end_playback:
49214  /* Following a rollback, the database file should be back in its original
49215  ** state prior to the start of the transaction, so invoke the
49216  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
49217  ** assertion that the transaction counter was modified.
49218  */
49219 #ifdef SQLITE_DEBUG
49220  if( pPager->fd->pMethods ){
49222  }
49223 #endif
49224 
49225  /* If this playback is happening automatically as a result of an IO or
49226  ** malloc error that occurred after the change-counter was updated but
49227  ** before the transaction was committed, then the change-counter
49228  ** modification may just have been reverted. If this happens in exclusive
49229  ** mode, then subsequent transactions performed by the connection will not
49230  ** update the change-counter at all. This may lead to cache inconsistency
49231  ** problems for other processes at some point in the future. So, just
49232  ** in case this has happened, clear the changeCountDone flag now.
49233  */
49234  pPager->changeCountDone = pPager->tempFile;
49235 
49236  if( rc==SQLITE_OK ){
49237  zMaster = pPager->pTmpSpace;
49238  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49239  testcase( rc!=SQLITE_OK );
49240  }
49241  if( rc==SQLITE_OK
49242  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49243  ){
49244  rc = sqlite3PagerSync(pPager, 0);
49245  }
49246  if( rc==SQLITE_OK ){
49247  rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
49248  testcase( rc!=SQLITE_OK );
49249  }
49250  if( rc==SQLITE_OK && zMaster[0] && res ){
49251  /* If there was a master journal and this routine will return success,
49252  ** see if it is possible to delete the master journal.
49253  */
49254  rc = pager_delmaster(pPager, zMaster);
49255  testcase( rc!=SQLITE_OK );
49256  }
49257  if( isHot && nPlayback ){
49258  sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
49259  nPlayback, pPager->zJournal);
49260  }
49261 
49262  /* The Pager.sectorSize variable may have been updated while rolling
49263  ** back a journal created by a process with a different sector size
49264  ** value. Reset it to the correct value for this process.
49265  */
49266  setSectorSize(pPager);
49267  return rc;
49268 }
49269 
49270 
49271 /*
49272 ** Read the content for page pPg out of the database file and into
49273 ** pPg->pData. A shared lock or greater must be held on the database
49274 ** file before this function is called.
49275 **
49276 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
49277 ** the value read from the database file.
49278 **
49279 ** If an IO error occurs, then the IO error is returned to the caller.
49280 ** Otherwise, SQLITE_OK is returned.
49281 */
49282 static int readDbPage(PgHdr *pPg, u32 iFrame){
49283  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
49284  Pgno pgno = pPg->pgno; /* Page number to read */
49285  int rc = SQLITE_OK; /* Return code */
49286  int pgsz = pPager->pageSize; /* Number of bytes to read */
49287 
49288  assert( pPager->eState>=PAGER_READER && !MEMDB );
49289  assert( isOpen(pPager->fd) );
49290 
49291 #ifndef SQLITE_OMIT_WAL
49292  if( iFrame ){
49293  /* Try to pull the page from the write-ahead log. */
49294  rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
49295  }else
49296 #endif
49297  {
49298  i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
49299  rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
49300  if( rc==SQLITE_IOERR_SHORT_READ ){
49301  rc = SQLITE_OK;
49302  }
49303  }
49304 
49305  if( pgno==1 ){
49306  if( rc ){
49307  /* If the read is unsuccessful, set the dbFileVers[] to something
49308  ** that will never be a valid file version. dbFileVers[] is a copy
49309  ** of bytes 24..39 of the database. Bytes 28..31 should always be
49310  ** zero or the size of the database in page. Bytes 32..35 and 35..39
49311  ** should be page numbers which are never 0xffffffff. So filling
49312  ** pPager->dbFileVers[] with all 0xff bytes should suffice.
49313  **
49314  ** For an encrypted database, the situation is more complex: bytes
49315  ** 24..39 of the database are white noise. But the probability of
49316  ** white noise equaling 16 bytes of 0xff is vanishingly small so
49317  ** we should still be ok.
49318  */
49319  memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
49320  }else{
49321  u8 *dbFileVers = &((u8*)pPg->pData)[24];
49322  memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
49323  }
49324  }
49325  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
49326 
49327  PAGER_INCR(sqlite3_pager_readdb_count);
49328  PAGER_INCR(pPager->nRead);
49329  IOTRACE(("PGIN %p %d\n", pPager, pgno));
49330  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
49331  PAGERID(pPager), pgno, pager_pagehash(pPg)));
49332 
49333  return rc;
49334 }
49335 
49336 /*
49337 ** Update the value of the change-counter at offsets 24 and 92 in
49338 ** the header and the sqlite version number at offset 96.
49339 **
49340 ** This is an unconditional update. See also the pager_incr_changecounter()
49341 ** routine which only updates the change-counter if the update is actually
49342 ** needed, as determined by the pPager->changeCountDone state variable.
49343 */
49345  u32 change_counter;
49346 
49347  /* Increment the value just read and write it back to byte 24. */
49348  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
49349  put32bits(((char*)pPg->pData)+24, change_counter);
49350 
49351  /* Also store the SQLite version number in bytes 96..99 and in
49352  ** bytes 92..95 store the change counter for which the version number
49353  ** is valid. */
49354  put32bits(((char*)pPg->pData)+92, change_counter);
49355  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
49356 }
49357 
49358 #ifndef SQLITE_OMIT_WAL
49359 /*
49360 ** This function is invoked once for each page that has already been
49361 ** written into the log file when a WAL transaction is rolled back.
49362 ** Parameter iPg is the page number of said page. The pCtx argument
49363 ** is actually a pointer to the Pager structure.
49364 **
49365 ** If page iPg is present in the cache, and has no outstanding references,
49366 ** it is discarded. Otherwise, if there are one or more outstanding
49367 ** references, the page content is reloaded from the database. If the
49368 ** attempt to reload content from the database is required and fails,
49369 ** return an SQLite error code. Otherwise, SQLITE_OK.
49370 */
49371 static int pagerUndoCallback(void *pCtx, Pgno iPg){
49372  int rc = SQLITE_OK;
49373  Pager *pPager = (Pager *)pCtx;
49374  PgHdr *pPg;
49375 
49376  assert( pagerUseWal(pPager) );
49377  pPg = sqlite3PagerLookup(pPager, iPg);
49378  if( pPg ){
49379  if( sqlite3PcachePageRefcount(pPg)==1 ){
49380  sqlite3PcacheDrop(pPg);
49381  }else{
49382  u32 iFrame = 0;
49383  rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
49384  if( rc==SQLITE_OK ){
49385  rc = readDbPage(pPg, iFrame);
49386  }
49387  if( rc==SQLITE_OK ){
49388  pPager->xReiniter(pPg);
49389  }
49391  }
49392  }
49393 
49394  /* Normally, if a transaction is rolled back, any backup processes are
49395  ** updated as data is copied out of the rollback journal and into the
49396  ** database. This is not generally possible with a WAL database, as
49397  ** rollback involves simply truncating the log file. Therefore, if one
49398  ** or more frames have already been written to the log (and therefore
49399  ** also copied into the backup databases) as part of this transaction,
49400  ** the backups must be restarted.
49401  */
49402  sqlite3BackupRestart(pPager->pBackup);
49403 
49404  return rc;
49405 }
49406 
49407 /*
49408 ** This function is called to rollback a transaction on a WAL database.
49409 */
49410 static int pagerRollbackWal(Pager *pPager){
49411  int rc; /* Return Code */
49412  PgHdr *pList; /* List of dirty pages to revert */
49413 
49414  /* For all pages in the cache that are currently dirty or have already
49415  ** been written (but not committed) to the log file, do one of the
49416  ** following:
49417  **
49418  ** + Discard the cached page (if refcount==0), or
49419  ** + Reload page content from the database (if refcount>0).
49420  */
49421  pPager->dbSize = pPager->dbOrigSize;
49422  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
49423  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49424  while( pList && rc==SQLITE_OK ){
49425  PgHdr *pNext = pList->pDirty;
49426  rc = pagerUndoCallback((void *)pPager, pList->pgno);
49427  pList = pNext;
49428  }
49429 
49430  return rc;
49431 }
49432 
49433 /*
49434 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
49435 ** the contents of the list of pages headed by pList (connected by pDirty),
49436 ** this function notifies any active backup processes that the pages have
49437 ** changed.
49438 **
49439 ** The list of pages passed into this routine is always sorted by page number.
49440 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
49441 */
49442 static int pagerWalFrames(
49443  Pager *pPager, /* Pager object */
49444  PgHdr *pList, /* List of frames to log */
49445  Pgno nTruncate, /* Database size after this commit */
49446  int isCommit /* True if this is a commit */
49447 ){
49448  int rc; /* Return code */
49449  int nList; /* Number of pages in pList */
49450  PgHdr *p; /* For looping over pages */
49451 
49452  assert( pPager->pWal );
49453  assert( pList );
49454 #ifdef SQLITE_DEBUG
49455  /* Verify that the page list is in accending order */
49456  for(p=pList; p && p->pDirty; p=p->pDirty){
49457  assert( p->pgno < p->pDirty->pgno );
49458  }
49459 #endif
49460 
49461  assert( pList->pDirty==0 || isCommit );
49462  if( isCommit ){
49463  /* If a WAL transaction is being committed, there is no point in writing
49464  ** any pages with page numbers greater than nTruncate into the WAL file.
49465  ** They will never be read by any client. So remove them from the pDirty
49466  ** list here. */
49467  PgHdr **ppNext = &pList;
49468  nList = 0;
49469  for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
49470  if( p->pgno<=nTruncate ){
49471  ppNext = &p->pDirty;
49472  nList++;
49473  }
49474  }
49475  assert( pList );
49476  }else{
49477  nList = 1;
49478  }
49479  pPager->aStat[PAGER_STAT_WRITE] += nList;
49480 
49481  if( pList->pgno==1 ) pager_write_changecounter(pList);
49482  rc = sqlite3WalFrames(pPager->pWal,
49483  pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
49484  );
49485  if( rc==SQLITE_OK && pPager->pBackup ){
49486  for(p=pList; p; p=p->pDirty){
49487  sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
49488  }
49489  }
49490 
49491 #ifdef SQLITE_CHECK_PAGES
49492  pList = sqlite3PcacheDirtyList(pPager->pPCache);
49493  for(p=pList; p; p=p->pDirty){
49494  pager_set_pagehash(p);
49495  }
49496 #endif
49497 
49498  return rc;
49499 }
49500 
49501 /*
49502 ** Begin a read transaction on the WAL.
49503 **
49504 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
49505 ** makes a snapshot of the database at the current point in time and preserves
49506 ** that snapshot for use by the reader in spite of concurrently changes by
49507 ** other writers or checkpointers.
49508 */
49509 static int pagerBeginReadTransaction(Pager *pPager){
49510  int rc; /* Return code */
49511  int changed = 0; /* True if cache must be reset */
49512 
49513  assert( pagerUseWal(pPager) );
49514  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
49515 
49516  /* sqlite3WalEndReadTransaction() was not called for the previous
49517  ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
49518  ** are in locking_mode=NORMAL and EndRead() was previously called,
49519  ** the duplicate call is harmless.
49520  */
49522 
49523  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
49524  if( rc!=SQLITE_OK || changed ){
49525  pager_reset(pPager);
49526  if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
49527  }
49528 
49529  return rc;
49530 }
49531 #endif
49532 
49533 /*
49534 ** This function is called as part of the transition from PAGER_OPEN
49535 ** to PAGER_READER state to determine the size of the database file
49536 ** in pages (assuming the page size currently stored in Pager.pageSize).
49537 **
49538 ** If no error occurs, SQLITE_OK is returned and the size of the database
49539 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
49540 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
49541 */
49542 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
49543  Pgno nPage; /* Value to return via *pnPage */
49544 
49545  /* Query the WAL sub-system for the database size. The WalDbsize()
49546  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
49547  ** if the database size is not available. The database size is not
49548  ** available from the WAL sub-system if the log file is empty or
49549  ** contains no valid committed transactions.
49550  */
49551  assert( pPager->eState==PAGER_OPEN );
49552  assert( pPager->eLock>=SHARED_LOCK );
49553  assert( isOpen(pPager->fd) );
49554  assert( pPager->tempFile==0 );
49555  nPage = sqlite3WalDbsize(pPager->pWal);
49556 
49557  /* If the number of pages in the database is not available from the
49558  ** WAL sub-system, determine the page counte based on the size of
49559  ** the database file. If the size of the database file is not an
49560  ** integer multiple of the page-size, round up the result.
49561  */
49562  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
49563  i64 n = 0; /* Size of db file in bytes */
49564  int rc = sqlite3OsFileSize(pPager->fd, &n);
49565  if( rc!=SQLITE_OK ){
49566  return rc;
49567  }
49568  nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
49569  }
49570 
49571  /* If the current number of pages in the file is greater than the
49572  ** configured maximum pager number, increase the allowed limit so
49573  ** that the file can be read.
49574  */
49575  if( nPage>pPager->mxPgno ){
49576  pPager->mxPgno = (Pgno)nPage;
49577  }
49578 
49579  *pnPage = nPage;
49580  return SQLITE_OK;
49581 }
49582 
49583 #ifndef SQLITE_OMIT_WAL
49584 /*
49585 ** Check if the *-wal file that corresponds to the database opened by pPager
49586 ** exists if the database is not empy, or verify that the *-wal file does
49587 ** not exist (by deleting it) if the database file is empty.
49588 **
49589 ** If the database is not empty and the *-wal file exists, open the pager
49590 ** in WAL mode. If the database is empty or if no *-wal file exists and
49591 ** if no error occurs, make sure Pager.journalMode is not set to
49592 ** PAGER_JOURNALMODE_WAL.
49593 **
49594 ** Return SQLITE_OK or an error code.
49595 **
49596 ** The caller must hold a SHARED lock on the database file to call this
49597 ** function. Because an EXCLUSIVE lock on the db file is required to delete
49598 ** a WAL on a none-empty database, this ensures there is no race condition
49599 ** between the xAccess() below and an xDelete() being executed by some
49600 ** other connection.
49601 */
49602 static int pagerOpenWalIfPresent(Pager *pPager){
49603  int rc = SQLITE_OK;
49604  assert( pPager->eState==PAGER_OPEN );
49605  assert( pPager->eLock>=SHARED_LOCK );
49606 
49607  if( !pPager->tempFile ){
49608  int isWal; /* True if WAL file exists */
49609  Pgno nPage; /* Size of the database file */
49610 
49611  rc = pagerPagecount(pPager, &nPage);
49612  if( rc ) return rc;
49613  if( nPage==0 ){
49614  rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
49615  if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
49616  isWal = 0;
49617  }else{
49618  rc = sqlite3OsAccess(
49619  pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
49620  );
49621  }
49622  if( rc==SQLITE_OK ){
49623  if( isWal ){
49624  testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
49625  rc = sqlite3PagerOpenWal(pPager, 0);
49626  }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
49628  }
49629  }
49630  }
49631  return rc;
49632 }
49633 #endif
49634 
49635 /*
49636 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
49637 ** the entire master journal file. The case pSavepoint==NULL occurs when
49638 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
49639 ** savepoint.
49640 **
49641 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
49642 ** being rolled back), then the rollback consists of up to three stages,
49643 ** performed in the order specified:
49644 **
49645 ** * Pages are played back from the main journal starting at byte
49646 ** offset PagerSavepoint.iOffset and continuing to
49647 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
49648 ** file if PagerSavepoint.iHdrOffset is zero.
49649 **
49650 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
49651 ** back starting from the journal header immediately following
49652 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
49653 **
49654 ** * Pages are then played back from the sub-journal file, starting
49655 ** with the PagerSavepoint.iSubRec and continuing to the end of
49656 ** the journal file.
49657 **
49658 ** Throughout the rollback process, each time a page is rolled back, the
49659 ** corresponding bit is set in a bitvec structure (variable pDone in the
49660 ** implementation below). This is used to ensure that a page is only
49661 ** rolled back the first time it is encountered in either journal.
49662 **
49663 ** If pSavepoint is NULL, then pages are only played back from the main
49664 ** journal file. There is no need for a bitvec in this case.
49665 **
49666 ** In either case, before playback commences the Pager.dbSize variable
49667 ** is reset to the value that it held at the start of the savepoint
49668 ** (or transaction). No page with a page-number greater than this value
49669 ** is played back. If one is encountered it is simply skipped.
49670 */
49671 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
49672  i64 szJ; /* Effective size of the main journal */
49673  i64 iHdrOff; /* End of first segment of main-journal records */
49674  int rc = SQLITE_OK; /* Return code */
49675  Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
49676 
49677  assert( pPager->eState!=PAGER_ERROR );
49678  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49679 
49680  /* Allocate a bitvec to use to store the set of pages rolled back */
49681  if( pSavepoint ){
49682  pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
49683  if( !pDone ){
49684  return SQLITE_NOMEM_BKPT;
49685  }
49686  }
49687 
49688  /* Set the database size back to the value it was before the savepoint
49689  ** being reverted was opened.
49690  */
49691  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
49692  pPager->changeCountDone = pPager->tempFile;
49693 
49694  if( !pSavepoint && pagerUseWal(pPager) ){
49695  return pagerRollbackWal(pPager);
49696  }
49697 
49698  /* Use pPager->journalOff as the effective size of the main rollback
49699  ** journal. The actual file might be larger than this in
49700  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
49701  ** past pPager->journalOff is off-limits to us.
49702  */
49703  szJ = pPager->journalOff;
49704  assert( pagerUseWal(pPager)==0 || szJ==0 );
49705 
49706  /* Begin by rolling back records from the main journal starting at
49707  ** PagerSavepoint.iOffset and continuing to the next journal header.
49708  ** There might be records in the main journal that have a page number
49709  ** greater than the current database size (pPager->dbSize) but those
49710  ** will be skipped automatically. Pages are added to pDone as they
49711  ** are played back.
49712  */
49713  if( pSavepoint && !pagerUseWal(pPager) ){
49714  iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
49715  pPager->journalOff = pSavepoint->iOffset;
49716  while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
49717  rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49718  }
49719  assert( rc!=SQLITE_DONE );
49720  }else{
49721  pPager->journalOff = 0;
49722  }
49723 
49724  /* Continue rolling back records out of the main journal starting at
49725  ** the first journal header seen and continuing until the effective end
49726  ** of the main journal file. Continue to skip out-of-range pages and
49727  ** continue adding pages rolled back to pDone.
49728  */
49729  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
49730  u32 ii; /* Loop counter */
49731  u32 nJRec = 0; /* Number of Journal Records */
49732  u32 dummy;
49733  rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
49734  assert( rc!=SQLITE_DONE );
49735 
49736  /*
49737  ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
49738  ** test is related to ticket #2565. See the discussion in the
49739  ** pager_playback() function for additional information.
49740  */
49741  if( nJRec==0
49742  && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
49743  ){
49744  nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
49745  }
49746  for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
49747  rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49748  }
49749  assert( rc!=SQLITE_DONE );
49750  }
49751  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
49752 
49753  /* Finally, rollback pages from the sub-journal. Page that were
49754  ** previously rolled back out of the main journal (and are hence in pDone)
49755  ** will be skipped. Out-of-range pages are also skipped.
49756  */
49757  if( pSavepoint ){
49758  u32 ii; /* Loop counter */
49759  i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
49760 
49761  if( pagerUseWal(pPager) ){
49762  rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
49763  }
49764  for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
49765  assert( offset==(i64)ii*(4+pPager->pageSize) );
49766  rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
49767  }
49768  assert( rc!=SQLITE_DONE );
49769  }
49770 
49771  sqlite3BitvecDestroy(pDone);
49772  if( rc==SQLITE_OK ){
49773  pPager->journalOff = szJ;
49774  }
49775 
49776  return rc;
49777 }
49778 
49779 /*
49780 ** Change the maximum number of in-memory pages that are allowed
49781 ** before attempting to recycle clean and unused pages.
49782 */
49784  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
49785 }
49786 
49787 /*
49788 ** Change the maximum number of in-memory pages that are allowed
49789 ** before attempting to spill pages to journal.
49790 */
49792  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
49793 }
49794 
49795 /*
49796 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
49797 */
49798 static void pagerFixMaplimit(Pager *pPager){
49799 #if SQLITE_MAX_MMAP_SIZE>0
49800  sqlite3_file *fd = pPager->fd;
49801  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
49802  sqlite3_int64 sz;
49803  sz = pPager->szMmap;
49804  pPager->bUseFetch = (sz>0);
49806  }
49807 #endif
49808 }
49809 
49810 /*
49811 ** Change the maximum size of any memory mapping made of the database file.
49812 */
49813 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
49814  pPager->szMmap = szMmap;
49815  pagerFixMaplimit(pPager);
49816 }
49817 
49818 /*
49819 ** Free as much memory as possible from the pager.
49820 */
49822  sqlite3PcacheShrink(pPager->pPCache);
49823 }
49824 
49825 /*
49826 ** Adjust settings of the pager to those specified in the pgFlags parameter.
49827 **
49828 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
49829 ** of the database to damage due to OS crashes or power failures by
49830 ** changing the number of syncs()s when writing the journals.
49831 ** There are four levels:
49832 **
49833 ** OFF sqlite3OsSync() is never called. This is the default
49834 ** for temporary and transient files.
49835 **
49836 ** NORMAL The journal is synced once before writes begin on the
49837 ** database. This is normally adequate protection, but
49838 ** it is theoretically possible, though very unlikely,
49839 ** that an inopertune power failure could leave the journal
49840 ** in a state which would cause damage to the database
49841 ** when it is rolled back.
49842 **
49843 ** FULL The journal is synced twice before writes begin on the
49844 ** database (with some additional information - the nRec field
49845 ** of the journal header - being written in between the two
49846 ** syncs). If we assume that writing a
49847 ** single disk sector is atomic, then this mode provides
49848 ** assurance that the journal will not be corrupted to the
49849 ** point of causing damage to the database during rollback.
49850 **
49851 ** EXTRA This is like FULL except that is also syncs the directory
49852 ** that contains the rollback journal after the rollback
49853 ** journal is unlinked.
49854 **
49855 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
49856 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
49857 ** prior to the start of checkpoint and that the database file is synced
49858 ** at the conclusion of the checkpoint if the entire content of the WAL
49859 ** was written back into the database. But no sync operations occur for
49860 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
49861 ** file is synced following each commit operation, in addition to the
49862 ** syncs associated with NORMAL. There is no difference between FULL
49863 ** and EXTRA for WAL mode.
49864 **
49865 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
49866 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
49867 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
49868 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
49869 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
49870 ** synchronous=FULL versus synchronous=NORMAL setting determines when
49871 ** the xSync primitive is called and is relevant to all platforms.
49872 **
49873 ** Numeric values associated with these states are OFF==1, NORMAL=2,
49874 ** and FULL=3.
49875 */
49876 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49878  Pager *pPager, /* The pager to set safety level for */
49879  unsigned pgFlags /* Various flags */
49880 ){
49881  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
49882  if( pPager->tempFile ){
49883  pPager->noSync = 1;
49884  pPager->fullSync = 0;
49885  pPager->extraSync = 0;
49886  }else{
49887  pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
49888  pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
49889  pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
49890  }
49891  if( pPager->noSync ){
49892  pPager->syncFlags = 0;
49893  pPager->ckptSyncFlags = 0;
49894  }else if( pgFlags & PAGER_FULLFSYNC ){
49895  pPager->syncFlags = SQLITE_SYNC_FULL;
49896  pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49897  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
49898  pPager->syncFlags = SQLITE_SYNC_NORMAL;
49899  pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49900  }else{
49901  pPager->syncFlags = SQLITE_SYNC_NORMAL;
49903  }
49904  pPager->walSyncFlags = pPager->syncFlags;
49905  if( pPager->fullSync ){
49907  }
49908  if( pgFlags & PAGER_CACHESPILL ){
49909  pPager->doNotSpill &= ~SPILLFLAG_OFF;
49910  }else{
49911  pPager->doNotSpill |= SPILLFLAG_OFF;
49912  }
49913 }
49914 #endif
49915 
49916 /*
49917 ** The following global variable is incremented whenever the library
49918 ** attempts to open a temporary file. This information is used for
49919 ** testing and analysis only.
49920 */
49921 #ifdef SQLITE_TEST
49922 SQLITE_API int sqlite3_opentemp_count = 0;
49923 #endif
49924 
49925 /*
49926 ** Open a temporary file.
49927 **
49928 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
49929 ** or some other error code if we fail. The OS will automatically
49930 ** delete the temporary file when it is closed.
49931 **
49932 ** The flags passed to the VFS layer xOpen() call are those specified
49933 ** by parameter vfsFlags ORed with the following:
49934 **
49935 ** SQLITE_OPEN_READWRITE
49936 ** SQLITE_OPEN_CREATE
49937 ** SQLITE_OPEN_EXCLUSIVE
49938 ** SQLITE_OPEN_DELETEONCLOSE
49939 */
49940 static int pagerOpentemp(
49941  Pager *pPager, /* The pager object */
49942  sqlite3_file *pFile, /* Write the file descriptor here */
49943  int vfsFlags /* Flags passed through to the VFS */
49944 ){
49945  int rc; /* Return code */
49946 
49947 #ifdef SQLITE_TEST
49948  sqlite3_opentemp_count++; /* Used for testing and analysis only */
49949 #endif
49950 
49953  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
49954  assert( rc!=SQLITE_OK || isOpen(pFile) );
49955  return rc;
49956 }
49957 
49958 /*
49959 ** Set the busy handler function.
49960 **
49961 ** The pager invokes the busy-handler if sqlite3OsLock() returns
49962 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
49963 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
49964 ** lock. It does *not* invoke the busy handler when upgrading from
49965 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
49966 ** (which occurs during hot-journal rollback). Summary:
49967 **
49968 ** Transition | Invokes xBusyHandler
49969 ** --------------------------------------------------------
49970 ** NO_LOCK -> SHARED_LOCK | Yes
49971 ** SHARED_LOCK -> RESERVED_LOCK | No
49972 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
49973 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
49974 **
49975 ** If the busy-handler callback returns non-zero, the lock is
49976 ** retried. If it returns zero, then the SQLITE_BUSY error is
49977 ** returned to the caller of the pager API function.
49978 */
49980  Pager *pPager, /* Pager object */
49981  int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
49982  void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
49983 ){
49984  pPager->xBusyHandler = xBusyHandler;
49985  pPager->pBusyHandlerArg = pBusyHandlerArg;
49986 
49987  if( isOpen(pPager->fd) ){
49988  void **ap = (void **)&pPager->xBusyHandler;
49989  assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
49990  assert( ap[1]==pBusyHandlerArg );
49992  }
49993 }
49994 
49995 /*
49996 ** Change the page size used by the Pager object. The new page size
49997 ** is passed in *pPageSize.
49998 **
49999 ** If the pager is in the error state when this function is called, it
50000 ** is a no-op. The value returned is the error state error code (i.e.
50001 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
50002 **
50003 ** Otherwise, if all of the following are true:
50004 **
50005 ** * the new page size (value of *pPageSize) is valid (a power
50006 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
50007 **
50008 ** * there are no outstanding page references, and
50009 **
50010 ** * the database is either not an in-memory database or it is
50011 ** an in-memory database that currently consists of zero pages.
50012 **
50013 ** then the pager object page size is set to *pPageSize.
50014 **
50015 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
50016 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
50017 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
50018 ** In all other cases, SQLITE_OK is returned.
50019 **
50020 ** If the page size is not changed, either because one of the enumerated
50021 ** conditions above is not true, the pager was in error state when this
50022 ** function was called, or because the memory allocation attempt failed,
50023 ** then *pPageSize is set to the old, retained page size before returning.
50024 */
50025 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
50026  int rc = SQLITE_OK;
50027 
50028  /* It is not possible to do a full assert_pager_state() here, as this
50029  ** function may be called from within PagerOpen(), before the state
50030  ** of the Pager object is internally consistent.
50031  **
50032  ** At one point this function returned an error if the pager was in
50033  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
50034  ** there is at least one outstanding page reference, this function
50035  ** is a no-op for that case anyhow.
50036  */
50037 
50038  u32 pageSize = *pPageSize;
50039  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
50040  if( (pPager->memDb==0 || pPager->dbSize==0)
50041  && sqlite3PcacheRefCount(pPager->pPCache)==0
50042  && pageSize && pageSize!=(u32)pPager->pageSize
50043  ){
50044  char *pNew = NULL; /* New temp space */
50045  i64 nByte = 0;
50046 
50047  if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
50048  rc = sqlite3OsFileSize(pPager->fd, &nByte);
50049  }
50050  if( rc==SQLITE_OK ){
50051  pNew = (char *)sqlite3PageMalloc(pageSize);
50052  if( !pNew ) rc = SQLITE_NOMEM_BKPT;
50053  }
50054 
50055  if( rc==SQLITE_OK ){
50056  pager_reset(pPager);
50057  rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
50058  }
50059  if( rc==SQLITE_OK ){
50060  sqlite3PageFree(pPager->pTmpSpace);
50061  pPager->pTmpSpace = pNew;
50062  pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
50063  pPager->pageSize = pageSize;
50064  }else{
50065  sqlite3PageFree(pNew);
50066  }
50067  }
50068 
50069  *pPageSize = pPager->pageSize;
50070  if( rc==SQLITE_OK ){
50071  if( nReserve<0 ) nReserve = pPager->nReserve;
50072  assert( nReserve>=0 && nReserve<1000 );
50073  pPager->nReserve = (i16)nReserve;
50074  pagerReportSize(pPager);
50075  pagerFixMaplimit(pPager);
50076  }
50077  return rc;
50078 }
50079 
50080 /*
50081 ** Return a pointer to the "temporary page" buffer held internally
50082 ** by the pager. This is a buffer that is big enough to hold the
50083 ** entire content of a database page. This buffer is used internally
50084 ** during rollback and will be overwritten whenever a rollback
50085 ** occurs. But other modules are free to use it too, as long as
50086 ** no rollbacks are happening.
50087 */
50089  return pPager->pTmpSpace;
50090 }
50091 
50092 /*
50093 ** Attempt to set the maximum database page count if mxPage is positive.
50094 ** Make no changes if mxPage is zero or negative. And never reduce the
50095 ** maximum page count below the current size of the database.
50096 **
50097 ** Regardless of mxPage, return the current maximum page count.
50098 */
50100  if( mxPage>0 ){
50101  pPager->mxPgno = mxPage;
50102  }
50103  assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
50104  assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
50105  return pPager->mxPgno;
50106 }
50107 
50108 /*
50109 ** The following set of routines are used to disable the simulated
50110 ** I/O error mechanism. These routines are used to avoid simulated
50111 ** errors in places where we do not care about errors.
50112 **
50113 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
50114 ** and generate no code.
50115 */
50116 #ifdef SQLITE_TEST
50117 SQLITE_API extern int sqlite3_io_error_pending;
50118 SQLITE_API extern int sqlite3_io_error_hit;
50119 static int saved_cnt;
50120 void disable_simulated_io_errors(void){
50121  saved_cnt = sqlite3_io_error_pending;
50122  sqlite3_io_error_pending = -1;
50123 }
50124 void enable_simulated_io_errors(void){
50125  sqlite3_io_error_pending = saved_cnt;
50126 }
50127 #else
50128 # define disable_simulated_io_errors()
50129 # define enable_simulated_io_errors()
50130 #endif
50131 
50132 /*
50133 ** Read the first N bytes from the beginning of the file into memory
50134 ** that pDest points to.
50135 **
50136 ** If the pager was opened on a transient file (zFilename==""), or
50137 ** opened on a file less than N bytes in size, the output buffer is
50138 ** zeroed and SQLITE_OK returned. The rationale for this is that this
50139 ** function is used to read database headers, and a new transient or
50140 ** zero sized database has a header than consists entirely of zeroes.
50141 **
50142 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
50143 ** the error code is returned to the caller and the contents of the
50144 ** output buffer undefined.
50145 */
50146 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
50147  int rc = SQLITE_OK;
50148  memset(pDest, 0, N);
50149  assert( isOpen(pPager->fd) || pPager->tempFile );
50150 
50151  /* This routine is only called by btree immediately after creating
50152  ** the Pager object. There has not been an opportunity to transition
50153  ** to WAL mode yet.
50154  */
50155  assert( !pagerUseWal(pPager) );
50156 
50157  if( isOpen(pPager->fd) ){
50158  IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
50159  rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
50160  if( rc==SQLITE_IOERR_SHORT_READ ){
50161  rc = SQLITE_OK;
50162  }
50163  }
50164  return rc;
50165 }
50166 
50167 /*
50168 ** This function may only be called when a read-transaction is open on
50169 ** the pager. It returns the total number of pages in the database.
50170 **
50171 ** However, if the file is between 1 and <page-size> bytes in size, then
50172 ** this is considered a 1 page file.
50173 */
50174 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
50175  assert( pPager->eState>=PAGER_READER );
50176  assert( pPager->eState!=PAGER_WRITER_FINISHED );
50177  *pnPage = (int)pPager->dbSize;
50178 }
50179 
50180 
50181 /*
50182 ** Try to obtain a lock of type locktype on the database file. If
50183 ** a similar or greater lock is already held, this function is a no-op
50184 ** (returning SQLITE_OK immediately).
50185 **
50186 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
50187 ** the busy callback if the lock is currently not available. Repeat
50188 ** until the busy callback returns false or until the attempt to
50189 ** obtain the lock succeeds.
50190 **
50191 ** Return SQLITE_OK on success and an error code if we cannot obtain
50192 ** the lock. If the lock is obtained successfully, set the Pager.state
50193 ** variable to locktype before returning.
50194 */
50195 static int pager_wait_on_lock(Pager *pPager, int locktype){
50196  int rc; /* Return code */
50197 
50198  /* Check that this is either a no-op (because the requested lock is
50199  ** already held), or one of the transitions that the busy-handler
50200  ** may be invoked during, according to the comment above
50201  ** sqlite3PagerSetBusyhandler().
50202  */
50203  assert( (pPager->eLock>=locktype)
50204  || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
50205  || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
50206  );
50207 
50208  do {
50209  rc = pagerLockDb(pPager, locktype);
50210  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
50211  return rc;
50212 }
50213 
50214 /*
50215 ** Function assertTruncateConstraint(pPager) checks that one of the
50216 ** following is true for all dirty pages currently in the page-cache:
50217 **
50218 ** a) The page number is less than or equal to the size of the
50219 ** current database image, in pages, OR
50220 **
50221 ** b) if the page content were written at this time, it would not
50222 ** be necessary to write the current content out to the sub-journal
50223 ** (as determined by function subjRequiresPage()).
50224 **
50225 ** If the condition asserted by this function were not true, and the
50226 ** dirty page were to be discarded from the cache via the pagerStress()
50227 ** routine, pagerStress() would not write the current page content to
50228 ** the database file. If a savepoint transaction were rolled back after
50229 ** this happened, the correct behavior would be to restore the current
50230 ** content of the page. However, since this content is not present in either
50231 ** the database file or the portion of the rollback journal and
50232 ** sub-journal rolled back the content could not be restored and the
50233 ** database image would become corrupt. It is therefore fortunate that
50234 ** this circumstance cannot arise.
50235 */
50236 #if defined(SQLITE_DEBUG)
50237 static void assertTruncateConstraintCb(PgHdr *pPg){
50238  assert( pPg->flags&PGHDR_DIRTY );
50239  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
50240 }
50241 static void assertTruncateConstraint(Pager *pPager){
50242  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
50243 }
50244 #else
50245 # define assertTruncateConstraint(pPager)
50246 #endif
50247 
50248 /*
50249 ** Truncate the in-memory database file image to nPage pages. This
50250 ** function does not actually modify the database file on disk. It
50251 ** just sets the internal state of the pager object so that the
50252 ** truncation will be done when the current transaction is committed.
50253 **
50254 ** This function is only called right before committing a transaction.
50255 ** Once this function has been called, the transaction must either be
50256 ** rolled back or committed. It is not safe to call this function and
50257 ** then continue writing to the database.
50258 */
50260  assert( pPager->dbSize>=nPage );
50261  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
50262  pPager->dbSize = nPage;
50263 
50264  /* At one point the code here called assertTruncateConstraint() to
50265  ** ensure that all pages being truncated away by this operation are,
50266  ** if one or more savepoints are open, present in the savepoint
50267  ** journal so that they can be restored if the savepoint is rolled
50268  ** back. This is no longer necessary as this function is now only
50269  ** called right before committing a transaction. So although the
50270  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
50271  ** they cannot be rolled back. So the assertTruncateConstraint() call
50272  ** is no longer correct. */
50273 }
50274 
50275 
50276 /*
50277 ** This function is called before attempting a hot-journal rollback. It
50278 ** syncs the journal file to disk, then sets pPager->journalHdr to the
50279 ** size of the journal file so that the pager_playback() routine knows
50280 ** that the entire journal file has been synced.
50281 **
50282 ** Syncing a hot-journal to disk before attempting to roll it back ensures
50283 ** that if a power-failure occurs during the rollback, the process that
50284 ** attempts rollback following system recovery sees the same journal
50285 ** content as this process.
50286 **
50287 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
50288 ** an SQLite error code.
50289 */
50290 static int pagerSyncHotJournal(Pager *pPager){
50291  int rc = SQLITE_OK;
50292  if( !pPager->noSync ){
50293  rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
50294  }
50295  if( rc==SQLITE_OK ){
50296  rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
50297  }
50298  return rc;
50299 }
50300 
50301 /*
50302 ** Obtain a reference to a memory mapped page object for page number pgno.
50303 ** The new object will use the pointer pData, obtained from xFetch().
50304 ** If successful, set *ppPage to point to the new page reference
50305 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
50306 ** *ppPage to zero.
50307 **
50308 ** Page references obtained by calling this function should be released
50309 ** by calling pagerReleaseMapPage().
50310 */
50312  Pager *pPager, /* Pager object */
50313  Pgno pgno, /* Page number */
50314  void *pData, /* xFetch()'d data for this page */
50315  PgHdr **ppPage /* OUT: Acquired page object */
50316 ){
50317  PgHdr *p; /* Memory mapped page to return */
50318 
50319  if( pPager->pMmapFreelist ){
50320  *ppPage = p = pPager->pMmapFreelist;
50321  pPager->pMmapFreelist = p->pDirty;
50322  p->pDirty = 0;
50323  memset(p->pExtra, 0, pPager->nExtra);
50324  }else{
50325  *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
50326  if( p==0 ){
50327  sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
50328  return SQLITE_NOMEM_BKPT;
50329  }
50330  p->pExtra = (void *)&p[1];
50331  p->flags = PGHDR_MMAP;
50332  p->nRef = 1;
50333  p->pPager = pPager;
50334  }
50335 
50336  assert( p->pExtra==(void *)&p[1] );
50337  assert( p->pPage==0 );
50338  assert( p->flags==PGHDR_MMAP );
50339  assert( p->pPager==pPager );
50340  assert( p->nRef==1 );
50341 
50342  p->pgno = pgno;
50343  p->pData = pData;
50344  pPager->nMmapOut++;
50345 
50346  return SQLITE_OK;
50347 }
50348 
50349 /*
50350 ** Release a reference to page pPg. pPg must have been returned by an
50351 ** earlier call to pagerAcquireMapPage().
50352 */
50353 static void pagerReleaseMapPage(PgHdr *pPg){
50354  Pager *pPager = pPg->pPager;
50355  pPager->nMmapOut--;
50356  pPg->pDirty = pPager->pMmapFreelist;
50357  pPager->pMmapFreelist = pPg;
50358 
50359  assert( pPager->fd->pMethods->iVersion>=3 );
50360  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
50361 }
50362 
50363 /*
50364 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
50365 */
50366 static void pagerFreeMapHdrs(Pager *pPager){
50367  PgHdr *p;
50368  PgHdr *pNext;
50369  for(p=pPager->pMmapFreelist; p; p=pNext){
50370  pNext = p->pDirty;
50371  sqlite3_free(p);
50372  }
50373 }
50374 
50375 
50376 /*
50377 ** Shutdown the page cache. Free all memory and close all files.
50378 **
50379 ** If a transaction was in progress when this routine is called, that
50380 ** transaction is rolled back. All outstanding pages are invalidated
50381 ** and their memory is freed. Any attempt to use a page associated
50382 ** with this page cache after this function returns will likely
50383 ** result in a coredump.
50384 **
50385 ** This function always succeeds. If a transaction is active an attempt
50386 ** is made to roll it back. If an error occurs during the rollback
50387 ** a hot journal may be left in the filesystem but no error is returned
50388 ** to the caller.
50389 */
50391  u8 *pTmp = (u8 *)pPager->pTmpSpace;
50392 
50393  assert( assert_pager_state(pPager) );
50396  pagerFreeMapHdrs(pPager);
50397  /* pPager->errCode = 0; */
50398  pPager->exclusiveMode = 0;
50399 #ifndef SQLITE_OMIT_WAL
50400  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
50401  pPager->pWal = 0;
50402 #endif
50403  pager_reset(pPager);
50404  if( MEMDB ){
50405  pager_unlock(pPager);
50406  }else{
50407  /* If it is open, sync the journal file before calling UnlockAndRollback.
50408  ** If this is not done, then an unsynced portion of the open journal
50409  ** file may be played back into the database. If a power failure occurs
50410  ** while this is happening, the database could become corrupt.
50411  **
50412  ** If an error occurs while trying to sync the journal, shift the pager
50413  ** into the ERROR state. This causes UnlockAndRollback to unlock the
50414  ** database and close the journal file without attempting to roll it
50415  ** back or finalize it. The next database user will have to do hot-journal
50416  ** rollback before accessing the database file.
50417  */
50418  if( isOpen(pPager->jfd) ){
50419  pager_error(pPager, pagerSyncHotJournal(pPager));
50420  }
50421  pagerUnlockAndRollback(pPager);
50422  }
50425  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
50426  IOTRACE(("CLOSE %p\n", pPager))
50427  sqlite3OsClose(pPager->jfd);
50428  sqlite3OsClose(pPager->fd);
50429  sqlite3PageFree(pTmp);
50430  sqlite3PcacheClose(pPager->pPCache);
50431 
50432 #ifdef SQLITE_HAS_CODEC
50433  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
50434 #endif
50435 
50436  assert( !pPager->aSavepoint && !pPager->pInJournal );
50437  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
50438 
50439  sqlite3_free(pPager);
50440  return SQLITE_OK;
50441 }
50442 
50443 #if !defined(NDEBUG) || defined(SQLITE_TEST)
50444 /*
50445 ** Return the page number for page pPg.
50446 */
50447 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
50448  return pPg->pgno;
50449 }
50450 #endif
50451 
50452 /*
50453 ** Increment the reference count for page pPg.
50454 */
50456  sqlite3PcacheRef(pPg);
50457 }
50458 
50459 /*
50460 ** Sync the journal. In other words, make sure all the pages that have
50461 ** been written to the journal have actually reached the surface of the
50462 ** disk and can be restored in the event of a hot-journal rollback.
50463 **
50464 ** If the Pager.noSync flag is set, then this function is a no-op.
50465 ** Otherwise, the actions required depend on the journal-mode and the
50466 ** device characteristics of the file-system, as follows:
50467 **
50468 ** * If the journal file is an in-memory journal file, no action need
50469 ** be taken.
50470 **
50471 ** * Otherwise, if the device does not support the SAFE_APPEND property,
50472 ** then the nRec field of the most recently written journal header
50473 ** is updated to contain the number of journal records that have
50474 ** been written following it. If the pager is operating in full-sync
50475 ** mode, then the journal file is synced before this field is updated.
50476 **
50477 ** * If the device does not support the SEQUENTIAL property, then
50478 ** journal file is synced.
50479 **
50480 ** Or, in pseudo-code:
50481 **
50482 ** if( NOT <in-memory journal> ){
50483 ** if( NOT SAFE_APPEND ){
50484 ** if( <full-sync mode> ) xSync(<journal file>);
50485 ** <update nRec field>
50486 ** }
50487 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
50488 ** }
50489 **
50490 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
50491 ** page currently held in memory before returning SQLITE_OK. If an IO
50492 ** error is encountered, then the IO error code is returned to the caller.
50493 */
50494 static int syncJournal(Pager *pPager, int newHdr){
50495  int rc; /* Return code */
50496 
50497  assert( pPager->eState==PAGER_WRITER_CACHEMOD
50498  || pPager->eState==PAGER_WRITER_DBMOD
50499  );
50500  assert( assert_pager_state(pPager) );
50501  assert( !pagerUseWal(pPager) );
50502 
50503  rc = sqlite3PagerExclusiveLock(pPager);
50504  if( rc!=SQLITE_OK ) return rc;
50505 
50506  if( !pPager->noSync ){
50507  assert( !pPager->tempFile );
50508  if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
50509  const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50510  assert( isOpen(pPager->jfd) );
50511 
50512  if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50513  /* This block deals with an obscure problem. If the last connection
50514  ** that wrote to this database was operating in persistent-journal
50515  ** mode, then the journal file may at this point actually be larger
50516  ** than Pager.journalOff bytes. If the next thing in the journal
50517  ** file happens to be a journal-header (written as part of the
50518  ** previous connection's transaction), and a crash or power-failure
50519  ** occurs after nRec is updated but before this connection writes
50520  ** anything else to the journal file (or commits/rolls back its
50521  ** transaction), then SQLite may become confused when doing the
50522  ** hot-journal rollback following recovery. It may roll back all
50523  ** of this connections data, then proceed to rolling back the old,
50524  ** out-of-date data that follows it. Database corruption.
50525  **
50526  ** To work around this, if the journal file does appear to contain
50527  ** a valid header following Pager.journalOff, then write a 0x00
50528  ** byte to the start of it to prevent it from being recognized.
50529  **
50530  ** Variable iNextHdrOffset is set to the offset at which this
50531  ** problematic header will occur, if it exists. aMagic is used
50532  ** as a temporary buffer to inspect the first couple of bytes of
50533  ** the potential journal header.
50534  */
50535  i64 iNextHdrOffset;
50536  u8 aMagic[8];
50537  u8 zHeader[sizeof(aJournalMagic)+4];
50538 
50539  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
50540  put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
50541 
50542  iNextHdrOffset = journalHdrOffset(pPager);
50543  rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
50544  if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
50545  static const u8 zerobyte = 0;
50546  rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
50547  }
50548  if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
50549  return rc;
50550  }
50551 
50552  /* Write the nRec value into the journal file header. If in
50553  ** full-synchronous mode, sync the journal first. This ensures that
50554  ** all data has really hit the disk before nRec is updated to mark
50555  ** it as a candidate for rollback.
50556  **
50557  ** This is not required if the persistent media supports the
50558  ** SAFE_APPEND property. Because in this case it is not possible
50559  ** for garbage data to be appended to the file, the nRec field
50560  ** is populated with 0xFFFFFFFF when the journal header is written
50561  ** and never needs to be updated.
50562  */
50563  if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50564  PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50565  IOTRACE(("JSYNC %p\n", pPager))
50566  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
50567  if( rc!=SQLITE_OK ) return rc;
50568  }
50569  IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
50570  rc = sqlite3OsWrite(
50571  pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
50572  );
50573  if( rc!=SQLITE_OK ) return rc;
50574  }
50575  if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50576  PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50577  IOTRACE(("JSYNC %p\n", pPager))
50578  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
50580  );
50581  if( rc!=SQLITE_OK ) return rc;
50582  }
50583 
50584  pPager->journalHdr = pPager->journalOff;
50585  if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50586  pPager->nRec = 0;
50587  rc = writeJournalHdr(pPager);
50588  if( rc!=SQLITE_OK ) return rc;
50589  }
50590  }else{
50591  pPager->journalHdr = pPager->journalOff;
50592  }
50593  }
50594 
50595  /* Unless the pager is in noSync mode, the journal file was just
50596  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
50597  ** all pages.
50598  */
50600  pPager->eState = PAGER_WRITER_DBMOD;
50601  assert( assert_pager_state(pPager) );
50602  return SQLITE_OK;
50603 }
50604 
50605 /*
50606 ** The argument is the first in a linked list of dirty pages connected
50607 ** by the PgHdr.pDirty pointer. This function writes each one of the
50608 ** in-memory pages in the list to the database file. The argument may
50609 ** be NULL, representing an empty list. In this case this function is
50610 ** a no-op.
50611 **
50612 ** The pager must hold at least a RESERVED lock when this function
50613 ** is called. Before writing anything to the database file, this lock
50614 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
50615 ** SQLITE_BUSY is returned and no data is written to the database file.
50616 **
50617 ** If the pager is a temp-file pager and the actual file-system file
50618 ** is not yet open, it is created and opened before any data is
50619 ** written out.
50620 **
50621 ** Once the lock has been upgraded and, if necessary, the file opened,
50622 ** the pages are written out to the database file in list order. Writing
50623 ** a page is skipped if it meets either of the following criteria:
50624 **
50625 ** * The page number is greater than Pager.dbSize, or
50626 ** * The PGHDR_DONT_WRITE flag is set on the page.
50627 **
50628 ** If writing out a page causes the database file to grow, Pager.dbFileSize
50629 ** is updated accordingly. If page 1 is written out, then the value cached
50630 ** in Pager.dbFileVers[] is updated to match the new value stored in
50631 ** the database file.
50632 **
50633 ** If everything is successful, SQLITE_OK is returned. If an IO error
50634 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
50635 ** be obtained, SQLITE_BUSY is returned.
50636 */
50637 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
50638  int rc = SQLITE_OK; /* Return code */
50639 
50640  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
50641  assert( !pagerUseWal(pPager) );
50642  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
50643  assert( pPager->eLock==EXCLUSIVE_LOCK );
50644  assert( isOpen(pPager->fd) || pList->pDirty==0 );
50645 
50646  /* If the file is a temp-file has not yet been opened, open it now. It
50647  ** is not possible for rc to be other than SQLITE_OK if this branch
50648  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
50649  */
50650  if( !isOpen(pPager->fd) ){
50651  assert( pPager->tempFile && rc==SQLITE_OK );
50652  rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
50653  }
50654 
50655  /* Before the first write, give the VFS a hint of what the final
50656  ** file size will be.
50657  */
50658  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
50659  if( rc==SQLITE_OK
50660  && pPager->dbHintSize<pPager->dbSize
50661  && (pList->pDirty || pList->pgno>pPager->dbHintSize)
50662  ){
50663  sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
50665  pPager->dbHintSize = pPager->dbSize;
50666  }
50667 
50668  while( rc==SQLITE_OK && pList ){
50669  Pgno pgno = pList->pgno;
50670 
50671  /* If there are dirty pages in the page cache with page numbers greater
50672  ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
50673  ** make the file smaller (presumably by auto-vacuum code). Do not write
50674  ** any such pages to the file.
50675  **
50676  ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
50677  ** set (set by sqlite3PagerDontWrite()).
50678  */
50679  if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
50680  i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
50681  char *pData; /* Data to write */
50682 
50683  assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
50684  if( pList->pgno==1 ) pager_write_changecounter(pList);
50685 
50686  /* Encode the database */
50687  CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
50688 
50689  /* Write out the page data. */
50690  rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
50691 
50692  /* If page 1 was just written, update Pager.dbFileVers to match
50693  ** the value now stored in the database file. If writing this
50694  ** page caused the database file to grow, update dbFileSize.
50695  */
50696  if( pgno==1 ){
50697  memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
50698  }
50699  if( pgno>pPager->dbFileSize ){
50700  pPager->dbFileSize = pgno;
50701  }
50702  pPager->aStat[PAGER_STAT_WRITE]++;
50703 
50704  /* Update any backup objects copying the contents of this pager. */
50705  sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
50706 
50707  PAGERTRACE(("STORE %d page %d hash(%08x)\n",
50708  PAGERID(pPager), pgno, pager_pagehash(pList)));
50709  IOTRACE(("PGOUT %p %d\n", pPager, pgno));
50710  PAGER_INCR(sqlite3_pager_writedb_count);
50711  }else{
50712  PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
50713  }
50714  pager_set_pagehash(pList);
50715  pList = pList->pDirty;
50716  }
50717 
50718  return rc;
50719 }
50720 
50721 /*
50722 ** Ensure that the sub-journal file is open. If it is already open, this
50723 ** function is a no-op.
50724 **
50725 ** SQLITE_OK is returned if everything goes according to plan. An
50726 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
50727 ** fails.
50728 */
50729 static int openSubJournal(Pager *pPager){
50730  int rc = SQLITE_OK;
50731  if( !isOpen(pPager->sjfd) ){
50732  const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
50735  int nStmtSpill = sqlite3Config.nStmtSpill;
50736  if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
50737  nStmtSpill = -1;
50738  }
50739  rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
50740  }
50741  return rc;
50742 }
50743 
50744 /*
50745 ** Append a record of the current state of page pPg to the sub-journal.
50746 **
50747 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
50748 ** for all open savepoints before returning.
50749 **
50750 ** This function returns SQLITE_OK if everything is successful, an IO
50751 ** error code if the attempt to write to the sub-journal fails, or
50752 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
50753 ** bitvec.
50754 */
50755 static int subjournalPage(PgHdr *pPg){
50756  int rc = SQLITE_OK;
50757  Pager *pPager = pPg->pPager;
50758  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
50759 
50760  /* Open the sub-journal, if it has not already been opened */
50761  assert( pPager->useJournal );
50762  assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
50763  assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
50764  assert( pagerUseWal(pPager)
50765  || pageInJournal(pPager, pPg)
50766  || pPg->pgno>pPager->dbOrigSize
50767  );
50768  rc = openSubJournal(pPager);
50769 
50770  /* If the sub-journal was opened successfully (or was already open),
50771  ** write the journal record into the file. */
50772  if( rc==SQLITE_OK ){
50773  void *pData = pPg->pData;
50774  i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
50775  char *pData2;
50776 
50777  CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
50778  PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
50779  rc = write32bits(pPager->sjfd, offset, pPg->pgno);
50780  if( rc==SQLITE_OK ){
50781  rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
50782  }
50783  }
50784  }
50785  if( rc==SQLITE_OK ){
50786  pPager->nSubRec++;
50787  assert( pPager->nSavepoint>0 );
50788  rc = addToSavepointBitvecs(pPager, pPg->pgno);
50789  }
50790  return rc;
50791 }
50793  if( subjRequiresPage(pPg) ){
50794  return subjournalPage(pPg);
50795  }else{
50796  return SQLITE_OK;
50797  }
50798 }
50799 
50800 /*
50801 ** This function is called by the pcache layer when it has reached some
50802 ** soft memory limit. The first argument is a pointer to a Pager object
50803 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
50804 ** database). The second argument is a reference to a page that is
50805 ** currently dirty but has no outstanding references. The page
50806 ** is always associated with the Pager object passed as the first
50807 ** argument.
50808 **
50809 ** The job of this function is to make pPg clean by writing its contents
50810 ** out to the database file, if possible. This may involve syncing the
50811 ** journal file.
50812 **
50813 ** If successful, sqlite3PcacheMakeClean() is called on the page and
50814 ** SQLITE_OK returned. If an IO error occurs while trying to make the
50815 ** page clean, the IO error code is returned. If the page cannot be
50816 ** made clean for some other reason, but no error occurs, then SQLITE_OK
50817 ** is returned by sqlite3PcacheMakeClean() is not called.
50818 */
50819 static int pagerStress(void *p, PgHdr *pPg){
50820  Pager *pPager = (Pager *)p;
50821  int rc = SQLITE_OK;
50822 
50823  assert( pPg->pPager==pPager );
50824  assert( pPg->flags&PGHDR_DIRTY );
50825 
50826  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
50827  ** journal (and adding a new header) is not allowed. This occurs
50828  ** during calls to sqlite3PagerWrite() while trying to journal multiple
50829  ** pages belonging to the same sector.
50830  **
50831  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
50832  ** regardless of whether or not a sync is required. This is set during
50833  ** a rollback or by user request, respectively.
50834  **
50835  ** Spilling is also prohibited when in an error state since that could
50836  ** lead to database corruption. In the current implementation it
50837  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
50838  ** while in the error state, hence it is impossible for this routine to
50839  ** be called in the error state. Nevertheless, we include a NEVER()
50840  ** test for the error state as a safeguard against future changes.
50841  */
50842  if( NEVER(pPager->errCode) ) return SQLITE_OK;
50843  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
50844  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
50845  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
50846  if( pPager->doNotSpill
50847  && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
50848  || (pPg->flags & PGHDR_NEED_SYNC)!=0)
50849  ){
50850  return SQLITE_OK;
50851  }
50852 
50853  pPg->pDirty = 0;
50854  if( pagerUseWal(pPager) ){
50855  /* Write a single frame for this page to the log. */
50856  rc = subjournalPageIfRequired(pPg);
50857  if( rc==SQLITE_OK ){
50858  rc = pagerWalFrames(pPager, pPg, 0, 0);
50859  }
50860  }else{
50861 
50862  /* Sync the journal file if required. */
50863  if( pPg->flags&PGHDR_NEED_SYNC
50864  || pPager->eState==PAGER_WRITER_CACHEMOD
50865  ){
50866  rc = syncJournal(pPager, 1);
50867  }
50868 
50869  /* Write the contents of the page out to the database file. */
50870  if( rc==SQLITE_OK ){
50871  assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
50872  rc = pager_write_pagelist(pPager, pPg);
50873  }
50874  }
50875 
50876  /* Mark the page as clean. */
50877  if( rc==SQLITE_OK ){
50878  PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
50880  }
50881 
50882  return pager_error(pPager, rc);
50883 }
50884 
50885 /*
50886 ** Flush all unreferenced dirty pages to disk.
50887 */
50889  int rc = pPager->errCode;
50890  if( !MEMDB ){
50891  PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
50892  assert( assert_pager_state(pPager) );
50893  while( rc==SQLITE_OK && pList ){
50894  PgHdr *pNext = pList->pDirty;
50895  if( pList->nRef==0 ){
50896  rc = pagerStress((void*)pPager, pList);
50897  }
50898  pList = pNext;
50899  }
50900  }
50901 
50902  return rc;
50903 }
50904 
50905 /*
50906 ** Allocate and initialize a new Pager object and put a pointer to it
50907 ** in *ppPager. The pager should eventually be freed by passing it
50908 ** to sqlite3PagerClose().
50909 **
50910 ** The zFilename argument is the path to the database file to open.
50911 ** If zFilename is NULL then a randomly-named temporary file is created
50912 ** and used as the file to be cached. Temporary files are be deleted
50913 ** automatically when they are closed. If zFilename is ":memory:" then
50914 ** all information is held in cache. It is never written to disk.
50915 ** This can be used to implement an in-memory database.
50916 **
50917 ** The nExtra parameter specifies the number of bytes of space allocated
50918 ** along with each page reference. This space is available to the user
50919 ** via the sqlite3PagerGetExtra() API.
50920 **
50921 ** The flags argument is used to specify properties that affect the
50922 ** operation of the pager. It should be passed some bitwise combination
50923 ** of the PAGER_* flags.
50924 **
50925 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
50926 ** of the xOpen() method of the supplied VFS when opening files.
50927 **
50928 ** If the pager object is allocated and the specified file opened
50929 ** successfully, SQLITE_OK is returned and *ppPager set to point to
50930 ** the new pager object. If an error occurs, *ppPager is set to NULL
50931 ** and error code returned. This function may return SQLITE_NOMEM
50932 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
50933 ** various SQLITE_IO_XXX errors.
50934 */
50936  sqlite3_vfs *pVfs, /* The virtual file system to use */
50937  Pager **ppPager, /* OUT: Return the Pager structure here */
50938  const char *zFilename, /* Name of the database file to open */
50939  int nExtra, /* Extra bytes append to each in-memory page */
50940  int flags, /* flags controlling this file */
50941  int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
50942  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
50943 ){
50944  u8 *pPtr;
50945  Pager *pPager = 0; /* Pager object to allocate and return */
50946  int rc = SQLITE_OK; /* Return code */
50947  int tempFile = 0; /* True for temp files (incl. in-memory files) */
50948  int memDb = 0; /* True if this is an in-memory file */
50949  int readOnly = 0; /* True if this is a read-only file */
50950  int journalFileSize; /* Bytes to allocate for each journal fd */
50951  char *zPathname = 0; /* Full path to database file */
50952  int nPathname = 0; /* Number of bytes in zPathname */
50953  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
50954  int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
50955  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
50956  const char *zUri = 0; /* URI args to copy */
50957  int nUri = 0; /* Number of bytes of URI args at *zUri */
50958 
50959  /* Figure out how much space is required for each journal file-handle
50960  ** (there are two of them, the main journal and the sub-journal). */
50961  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
50962 
50963  /* Set the output variable to NULL in case an error occurs. */
50964  *ppPager = 0;
50965 
50966 #ifndef SQLITE_OMIT_MEMORYDB
50967  if( flags & PAGER_MEMORY ){
50968  memDb = 1;
50969  if( zFilename && zFilename[0] ){
50970  zPathname = sqlite3DbStrDup(0, zFilename);
50971  if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
50972  nPathname = sqlite3Strlen30(zPathname);
50973  zFilename = 0;
50974  }
50975  }
50976 #endif
50977 
50978  /* Compute and store the full pathname in an allocated buffer pointed
50979  ** to by zPathname, length nPathname. Or, if this is a temporary file,
50980  ** leave both nPathname and zPathname set to 0.
50981  */
50982  if( zFilename && zFilename[0] ){
50983  const char *z;
50984  nPathname = pVfs->mxPathname+1;
50985  zPathname = sqlite3DbMallocRaw(0, nPathname*2);
50986  if( zPathname==0 ){
50987  return SQLITE_NOMEM_BKPT;
50988  }
50989  zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
50990  rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
50991  nPathname = sqlite3Strlen30(zPathname);
50992  z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
50993  while( *z ){
50994  z += sqlite3Strlen30(z)+1;
50995  z += sqlite3Strlen30(z)+1;
50996  }
50997  nUri = (int)(&z[1] - zUri);
50998  assert( nUri>=0 );
50999  if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
51000  /* This branch is taken when the journal path required by
51001  ** the database being opened will be more than pVfs->mxPathname
51002  ** bytes in length. This means the database cannot be opened,
51003  ** as it will not be possible to open the journal file or even
51004  ** check for a hot-journal before reading.
51005  */
51006  rc = SQLITE_CANTOPEN_BKPT;
51007  }
51008  if( rc!=SQLITE_OK ){
51009  sqlite3DbFree(0, zPathname);
51010  return rc;
51011  }
51012  }
51013 
51014  /* Allocate memory for the Pager structure, PCache object, the
51015  ** three file descriptors, the database file name and the journal
51016  ** file name. The layout in memory is as follows:
51017  **
51018  ** Pager object (sizeof(Pager) bytes)
51019  ** PCache object (sqlite3PcacheSize() bytes)
51020  ** Database file handle (pVfs->szOsFile bytes)
51021  ** Sub-journal file handle (journalFileSize bytes)
51022  ** Main journal file handle (journalFileSize bytes)
51023  ** Database file name (nPathname+1 bytes)
51024  ** Journal file name (nPathname+8+1 bytes)
51025  */
51026  pPtr = (u8 *)sqlite3MallocZero(
51027  ROUND8(sizeof(*pPager)) + /* Pager structure */
51028  ROUND8(pcacheSize) + /* PCache object */
51029  ROUND8(pVfs->szOsFile) + /* The main db file */
51030  journalFileSize * 2 + /* The two journal files */
51031  nPathname + 1 + nUri + /* zFilename */
51032  nPathname + 8 + 2 /* zJournal */
51033 #ifndef SQLITE_OMIT_WAL
51034  + nPathname + 4 + 2 /* zWal */
51035 #endif
51036  );
51037  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
51038  if( !pPtr ){
51039  sqlite3DbFree(0, zPathname);
51040  return SQLITE_NOMEM_BKPT;
51041  }
51042  pPager = (Pager*)(pPtr);
51043  pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
51044  pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
51045  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
51046  pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
51047  pPager->zFilename = (char*)(pPtr += journalFileSize);
51048  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
51049 
51050  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
51051  if( zPathname ){
51052  assert( nPathname>0 );
51053  pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
51054  memcpy(pPager->zFilename, zPathname, nPathname);
51055  if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
51056  memcpy(pPager->zJournal, zPathname, nPathname);
51057  memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
51058  sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
51059 #ifndef SQLITE_OMIT_WAL
51060  pPager->zWal = &pPager->zJournal[nPathname+8+1];
51061  memcpy(pPager->zWal, zPathname, nPathname);
51062  memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
51063  sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
51064 #endif
51065  sqlite3DbFree(0, zPathname);
51066  }
51067  pPager->pVfs = pVfs;
51068  pPager->vfsFlags = vfsFlags;
51069 
51070  /* Open the pager file.
51071  */
51072  if( zFilename && zFilename[0] ){
51073  int fout = 0; /* VFS flags returned by xOpen() */
51074  rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
51075  assert( !memDb );
51076  readOnly = (fout&SQLITE_OPEN_READONLY);
51077 
51078  /* If the file was successfully opened for read/write access,
51079  ** choose a default page size in case we have to create the
51080  ** database file. The default page size is the maximum of:
51081  **
51082  ** + SQLITE_DEFAULT_PAGE_SIZE,
51083  ** + The value returned by sqlite3OsSectorSize()
51084  ** + The largest page size that can be written atomically.
51085  */
51086  if( rc==SQLITE_OK ){
51087  int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
51088  if( !readOnly ){
51089  setSectorSize(pPager);
51091  if( szPageDflt<pPager->sectorSize ){
51093  szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
51094  }else{
51095  szPageDflt = (u32)pPager->sectorSize;
51096  }
51097  }
51098 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
51099  {
51100  int ii;
51101  assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
51102  assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
51103  assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
51104  for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
51105  if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
51106  szPageDflt = ii;
51107  }
51108  }
51109  }
51110 #endif
51111  }
51112  pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
51113  if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
51114  || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
51115  vfsFlags |= SQLITE_OPEN_READONLY;
51116  goto act_like_temp_file;
51117  }
51118  }
51119  }else{
51120  /* If a temporary file is requested, it is not opened immediately.
51121  ** In this case we accept the default page size and delay actually
51122  ** opening the file until the first call to OsWrite().
51123  **
51124  ** This branch is also run for an in-memory database. An in-memory
51125  ** database is the same as a temp-file that is never written out to
51126  ** disk and uses an in-memory rollback journal.
51127  **
51128  ** This branch also runs for files marked as immutable.
51129  */
51130 act_like_temp_file:
51131  tempFile = 1;
51132  pPager->eState = PAGER_READER; /* Pretend we already have a lock */
51133  pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
51134  pPager->noLock = 1; /* Do no locking */
51135  readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
51136  }
51137 
51138  /* The following call to PagerSetPagesize() serves to set the value of
51139  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
51140  */
51141  if( rc==SQLITE_OK ){
51142  assert( pPager->memDb==0 );
51143  rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
51144  testcase( rc!=SQLITE_OK );
51145  }
51146 
51147  /* Initialize the PCache object. */
51148  if( rc==SQLITE_OK ){
51149  assert( nExtra<1000 );
51150  nExtra = ROUND8(nExtra);
51151  rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
51152  !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
51153  }
51154 
51155  /* If an error occurred above, free the Pager structure and close the file.
51156  */
51157  if( rc!=SQLITE_OK ){
51158  sqlite3OsClose(pPager->fd);
51159  sqlite3PageFree(pPager->pTmpSpace);
51160  sqlite3_free(pPager);
51161  return rc;
51162  }
51163 
51164  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
51165  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
51166 
51167  pPager->useJournal = (u8)useJournal;
51168  /* pPager->stmtOpen = 0; */
51169  /* pPager->stmtInUse = 0; */
51170  /* pPager->nRef = 0; */
51171  /* pPager->stmtSize = 0; */
51172  /* pPager->stmtJSize = 0; */
51173  /* pPager->nPage = 0; */
51174  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
51175  /* pPager->state = PAGER_UNLOCK; */
51176  /* pPager->errMask = 0; */
51177  pPager->tempFile = (u8)tempFile;
51178  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
51179  || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
51180  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
51181  pPager->exclusiveMode = (u8)tempFile;
51182  pPager->changeCountDone = pPager->tempFile;
51183  pPager->memDb = (u8)memDb;
51184  pPager->readOnly = (u8)readOnly;
51185  assert( useJournal || pPager->tempFile );
51186  pPager->noSync = pPager->tempFile;
51187  if( pPager->noSync ){
51188  assert( pPager->fullSync==0 );
51189  assert( pPager->extraSync==0 );
51190  assert( pPager->syncFlags==0 );
51191  assert( pPager->walSyncFlags==0 );
51192  assert( pPager->ckptSyncFlags==0 );
51193  }else{
51194  pPager->fullSync = 1;
51195  pPager->extraSync = 0;
51196  pPager->syncFlags = SQLITE_SYNC_NORMAL;
51199  }
51200  /* pPager->pFirst = 0; */
51201  /* pPager->pFirstSynced = 0; */
51202  /* pPager->pLast = 0; */
51203  pPager->nExtra = (u16)nExtra;
51205  assert( isOpen(pPager->fd) || tempFile );
51206  setSectorSize(pPager);
51207  if( !useJournal ){
51209  }else if( memDb ){
51211  }
51212  /* pPager->xBusyHandler = 0; */
51213  /* pPager->pBusyHandlerArg = 0; */
51214  pPager->xReiniter = xReinit;
51215  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
51216  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
51217 
51218  *ppPager = pPager;
51219  return SQLITE_OK;
51220 }
51221 
51222 
51223 /* Verify that the database file has not be deleted or renamed out from
51224 ** under the pager. Return SQLITE_OK if the database is still were it ought
51225 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
51226 ** code from sqlite3OsAccess()) if the database has gone missing.
51227 */
51228 static int databaseIsUnmoved(Pager *pPager){
51229  int bHasMoved = 0;
51230  int rc;
51231 
51232  if( pPager->tempFile ) return SQLITE_OK;
51233  if( pPager->dbSize==0 ) return SQLITE_OK;
51234  assert( pPager->zFilename && pPager->zFilename[0] );
51235  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
51236  if( rc==SQLITE_NOTFOUND ){
51237  /* If the HAS_MOVED file-control is unimplemented, assume that the file
51238  ** has not been moved. That is the historical behavior of SQLite: prior to
51239  ** version 3.8.3, it never checked */
51240  rc = SQLITE_OK;
51241  }else if( rc==SQLITE_OK && bHasMoved ){
51243  }
51244  return rc;
51245 }
51246 
51247 
51248 /*
51249 ** This function is called after transitioning from PAGER_UNLOCK to
51250 ** PAGER_SHARED state. It tests if there is a hot journal present in
51251 ** the file-system for the given pager. A hot journal is one that
51252 ** needs to be played back. According to this function, a hot-journal
51253 ** file exists if the following criteria are met:
51254 **
51255 ** * The journal file exists in the file system, and
51256 ** * No process holds a RESERVED or greater lock on the database file, and
51257 ** * The database file itself is greater than 0 bytes in size, and
51258 ** * The first byte of the journal file exists and is not 0x00.
51259 **
51260 ** If the current size of the database file is 0 but a journal file
51261 ** exists, that is probably an old journal left over from a prior
51262 ** database with the same name. In this case the journal file is
51263 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
51264 ** is returned.
51265 **
51266 ** This routine does not check if there is a master journal filename
51267 ** at the end of the file. If there is, and that master journal file
51268 ** does not exist, then the journal file is not really hot. In this
51269 ** case this routine will return a false-positive. The pager_playback()
51270 ** routine will discover that the journal file is not really hot and
51271 ** will not roll it back.
51272 **
51273 ** If a hot-journal file is found to exist, *pExists is set to 1 and
51274 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
51275 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
51276 ** to determine whether or not a hot-journal file exists, the IO error
51277 ** code is returned and the value of *pExists is undefined.
51278 */
51279 static int hasHotJournal(Pager *pPager, int *pExists){
51280  sqlite3_vfs * const pVfs = pPager->pVfs;
51281  int rc = SQLITE_OK; /* Return code */
51282  int exists = 1; /* True if a journal file is present */
51283  int jrnlOpen = !!isOpen(pPager->jfd);
51284 
51285  assert( pPager->useJournal );
51286  assert( isOpen(pPager->fd) );
51287  assert( pPager->eState==PAGER_OPEN );
51288 
51289  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
51291  ));
51292 
51293  *pExists = 0;
51294  if( !jrnlOpen ){
51295  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
51296  }
51297  if( rc==SQLITE_OK && exists ){
51298  int locked = 0; /* True if some process holds a RESERVED lock */
51299 
51300  /* Race condition here: Another process might have been holding the
51301  ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
51302  ** call above, but then delete the journal and drop the lock before
51303  ** we get to the following sqlite3OsCheckReservedLock() call. If that
51304  ** is the case, this routine might think there is a hot journal when
51305  ** in fact there is none. This results in a false-positive which will
51306  ** be dealt with by the playback routine. Ticket #3883.
51307  */
51308  rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
51309  if( rc==SQLITE_OK && !locked ){
51310  Pgno nPage; /* Number of pages in database file */
51311 
51312  assert( pPager->tempFile==0 );
51313  rc = pagerPagecount(pPager, &nPage);
51314  if( rc==SQLITE_OK ){
51315  /* If the database is zero pages in size, that means that either (1) the
51316  ** journal is a remnant from a prior database with the same name where
51317  ** the database file but not the journal was deleted, or (2) the initial
51318  ** transaction that populates a new database is being rolled back.
51319  ** In either case, the journal file can be deleted. However, take care
51320  ** not to delete the journal file if it is already open due to
51321  ** journal_mode=PERSIST.
51322  */
51323  if( nPage==0 && !jrnlOpen ){
51325  if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
51326  sqlite3OsDelete(pVfs, pPager->zJournal, 0);
51327  if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
51328  }
51330  }else{
51331  /* The journal file exists and no other connection has a reserved
51332  ** or greater lock on the database file. Now check that there is
51333  ** at least one non-zero bytes at the start of the journal file.
51334  ** If there is, then we consider this journal to be hot. If not,
51335  ** it can be ignored.
51336  */
51337  if( !jrnlOpen ){
51339  rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
51340  }
51341  if( rc==SQLITE_OK ){
51342  u8 first = 0;
51343  rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
51344  if( rc==SQLITE_IOERR_SHORT_READ ){
51345  rc = SQLITE_OK;
51346  }
51347  if( !jrnlOpen ){
51348  sqlite3OsClose(pPager->jfd);
51349  }
51350  *pExists = (first!=0);
51351  }else if( rc==SQLITE_CANTOPEN ){
51352  /* If we cannot open the rollback journal file in order to see if
51353  ** it has a zero header, that might be due to an I/O error, or
51354  ** it might be due to the race condition described above and in
51355  ** ticket #3883. Either way, assume that the journal is hot.
51356  ** This might be a false positive. But if it is, then the
51357  ** automatic journal playback and recovery mechanism will deal
51358  ** with it under an EXCLUSIVE lock where we do not need to
51359  ** worry so much with race conditions.
51360  */
51361  *pExists = 1;
51362  rc = SQLITE_OK;
51363  }
51364  }
51365  }
51366  }
51367  }
51368 
51369  return rc;
51370 }
51371 
51372 /*
51373 ** This function is called to obtain a shared lock on the database file.
51374 ** It is illegal to call sqlite3PagerGet() until after this function
51375 ** has been successfully called. If a shared-lock is already held when
51376 ** this function is called, it is a no-op.
51377 **
51378 ** The following operations are also performed by this function.
51379 **
51380 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
51381 ** on the database file), then an attempt is made to obtain a
51382 ** SHARED lock on the database file. Immediately after obtaining
51383 ** the SHARED lock, the file-system is checked for a hot-journal,
51384 ** which is played back if present. Following any hot-journal
51385 ** rollback, the contents of the cache are validated by checking
51386 ** the 'change-counter' field of the database file header and
51387 ** discarded if they are found to be invalid.
51388 **
51389 ** 2) If the pager is running in exclusive-mode, and there are currently
51390 ** no outstanding references to any pages, and is in the error state,
51391 ** then an attempt is made to clear the error state by discarding
51392 ** the contents of the page cache and rolling back any open journal
51393 ** file.
51394 **
51395 ** If everything is successful, SQLITE_OK is returned. If an IO error
51396 ** occurs while locking the database, checking for a hot-journal file or
51397 ** rolling back a journal file, the IO error code is returned.
51398 */
51400  int rc = SQLITE_OK; /* Return code */
51401 
51402  /* This routine is only called from b-tree and only when there are no
51403  ** outstanding pages. This implies that the pager state should either
51404  ** be OPEN or READER. READER is only possible if the pager is or was in
51405  ** exclusive access mode. */
51406  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
51407  assert( assert_pager_state(pPager) );
51408  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
51409  assert( pPager->errCode==SQLITE_OK );
51410 
51411  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
51412  int bHotJournal = 1; /* True if there exists a hot journal-file */
51413 
51414  assert( !MEMDB );
51415  assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
51416 
51417  rc = pager_wait_on_lock(pPager, SHARED_LOCK);
51418  if( rc!=SQLITE_OK ){
51419  assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
51420  goto failed;
51421  }
51422 
51423  /* If a journal file exists, and there is no RESERVED lock on the
51424  ** database file, then it either needs to be played back or deleted.
51425  */
51426  if( pPager->eLock<=SHARED_LOCK ){
51427  rc = hasHotJournal(pPager, &bHotJournal);
51428  }
51429  if( rc!=SQLITE_OK ){
51430  goto failed;
51431  }
51432  if( bHotJournal ){
51433  if( pPager->readOnly ){
51435  goto failed;
51436  }
51437 
51438  /* Get an EXCLUSIVE lock on the database file. At this point it is
51439  ** important that a RESERVED lock is not obtained on the way to the
51440  ** EXCLUSIVE lock. If it were, another process might open the
51441  ** database file, detect the RESERVED lock, and conclude that the
51442  ** database is safe to read while this process is still rolling the
51443  ** hot-journal back.
51444  **
51445  ** Because the intermediate RESERVED lock is not requested, any
51446  ** other process attempting to access the database file will get to
51447  ** this point in the code and fail to obtain its own EXCLUSIVE lock
51448  ** on the database file.
51449  **
51450  ** Unless the pager is in locking_mode=exclusive mode, the lock is
51451  ** downgraded to SHARED_LOCK before this function returns.
51452  */
51453  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51454  if( rc!=SQLITE_OK ){
51455  goto failed;
51456  }
51457 
51458  /* If it is not already open and the file exists on disk, open the
51459  ** journal for read/write access. Write access is required because
51460  ** in exclusive-access mode the file descriptor will be kept open
51461  ** and possibly used for a transaction later on. Also, write-access
51462  ** is usually required to finalize the journal in journal_mode=persist
51463  ** mode (and also for journal_mode=truncate on some systems).
51464  **
51465  ** If the journal does not exist, it usually means that some
51466  ** other connection managed to get in and roll it back before
51467  ** this connection obtained the exclusive lock above. Or, it
51468  ** may mean that the pager was in the error-state when this
51469  ** function was called and the journal file does not exist.
51470  */
51471  if( !isOpen(pPager->jfd) ){
51472  sqlite3_vfs * const pVfs = pPager->pVfs;
51473  int bExists; /* True if journal file exists */
51474  rc = sqlite3OsAccess(
51475  pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
51476  if( rc==SQLITE_OK && bExists ){
51477  int fout = 0;
51479  assert( !pPager->tempFile );
51480  rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
51481  assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51482  if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
51483  rc = SQLITE_CANTOPEN_BKPT;
51484  sqlite3OsClose(pPager->jfd);
51485  }
51486  }
51487  }
51488 
51489  /* Playback and delete the journal. Drop the database write
51490  ** lock and reacquire the read lock. Purge the cache before
51491  ** playing back the hot-journal so that we don't end up with
51492  ** an inconsistent cache. Sync the hot journal before playing
51493  ** it back since the process that crashed and left the hot journal
51494  ** probably did not sync it and we are required to always sync
51495  ** the journal before playing it back.
51496  */
51497  if( isOpen(pPager->jfd) ){
51498  assert( rc==SQLITE_OK );
51499  rc = pagerSyncHotJournal(pPager);
51500  if( rc==SQLITE_OK ){
51501  rc = pager_playback(pPager, !pPager->tempFile);
51502  pPager->eState = PAGER_OPEN;
51503  }
51504  }else if( !pPager->exclusiveMode ){
51505  pagerUnlockDb(pPager, SHARED_LOCK);
51506  }
51507 
51508  if( rc!=SQLITE_OK ){
51509  /* This branch is taken if an error occurs while trying to open
51510  ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
51511  ** pager_unlock() routine will be called before returning to unlock
51512  ** the file. If the unlock attempt fails, then Pager.eLock must be
51513  ** set to UNKNOWN_LOCK (see the comment above the #define for
51514  ** UNKNOWN_LOCK above for an explanation).
51515  **
51516  ** In order to get pager_unlock() to do this, set Pager.eState to
51517  ** PAGER_ERROR now. This is not actually counted as a transition
51518  ** to ERROR state in the state diagram at the top of this file,
51519  ** since we know that the same call to pager_unlock() will very
51520  ** shortly transition the pager object to the OPEN state. Calling
51521  ** assert_pager_state() would fail now, as it should not be possible
51522  ** to be in ERROR state when there are zero outstanding page
51523  ** references.
51524  */
51525  pager_error(pPager, rc);
51526  goto failed;
51527  }
51528 
51529  assert( pPager->eState==PAGER_OPEN );
51530  assert( (pPager->eLock==SHARED_LOCK)
51531  || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
51532  );
51533  }
51534 
51535  if( !pPager->tempFile && pPager->hasHeldSharedLock ){
51536  /* The shared-lock has just been acquired then check to
51537  ** see if the database has been modified. If the database has changed,
51538  ** flush the cache. The hasHeldSharedLock flag prevents this from
51539  ** occurring on the very first access to a file, in order to save a
51540  ** single unnecessary sqlite3OsRead() call at the start-up.
51541  **
51542  ** Database changes are detected by looking at 15 bytes beginning
51543  ** at offset 24 into the file. The first 4 of these 16 bytes are
51544  ** a 32-bit counter that is incremented with each change. The
51545  ** other bytes change randomly with each file change when
51546  ** a codec is in use.
51547  **
51548  ** There is a vanishingly small chance that a change will not be
51549  ** detected. The chance of an undetected change is so small that
51550  ** it can be neglected.
51551  */
51552  Pgno nPage = 0;
51553  char dbFileVers[sizeof(pPager->dbFileVers)];
51554 
51555  rc = pagerPagecount(pPager, &nPage);
51556  if( rc ) goto failed;
51557 
51558  if( nPage>0 ){
51559  IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
51560  rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
51561  if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51562  goto failed;
51563  }
51564  }else{
51565  memset(dbFileVers, 0, sizeof(dbFileVers));
51566  }
51567 
51568  if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
51569  pager_reset(pPager);
51570 
51571  /* Unmap the database file. It is possible that external processes
51572  ** may have truncated the database file and then extended it back
51573  ** to its original size while this process was not holding a lock.
51574  ** In this case there may exist a Pager.pMap mapping that appears
51575  ** to be the right size but is not actually valid. Avoid this
51576  ** possibility by unmapping the db here. */
51577  if( USEFETCH(pPager) ){
51578  sqlite3OsUnfetch(pPager->fd, 0, 0);
51579  }
51580  }
51581  }
51582 
51583  /* If there is a WAL file in the file-system, open this database in WAL
51584  ** mode. Otherwise, the following function call is a no-op.
51585  */
51586  rc = pagerOpenWalIfPresent(pPager);
51587 #ifndef SQLITE_OMIT_WAL
51588  assert( pPager->pWal==0 || rc==SQLITE_OK );
51589 #endif
51590  }
51591 
51592  if( pagerUseWal(pPager) ){
51593  assert( rc==SQLITE_OK );
51594  rc = pagerBeginReadTransaction(pPager);
51595  }
51596 
51597  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51598  rc = pagerPagecount(pPager, &pPager->dbSize);
51599  }
51600 
51601  failed:
51602  if( rc!=SQLITE_OK ){
51603  assert( !MEMDB );
51604  pager_unlock(pPager);
51605  assert( pPager->eState==PAGER_OPEN );
51606  }else{
51607  pPager->eState = PAGER_READER;
51608  pPager->hasHeldSharedLock = 1;
51609  }
51610  return rc;
51611 }
51612 
51613 /*
51614 ** If the reference count has reached zero, rollback any active
51615 ** transaction and unlock the pager.
51616 **
51617 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
51618 ** the rollback journal, the unlock is not performed and there is
51619 ** nothing to rollback, so this routine is a no-op.
51620 */
51621 static void pagerUnlockIfUnused(Pager *pPager){
51622  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
51623  pagerUnlockAndRollback(pPager);
51624  }
51625 }
51626 
51627 /*
51628 ** Acquire a reference to page number pgno in pager pPager (a page
51629 ** reference has type DbPage*). If the requested reference is
51630 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
51631 **
51632 ** If the requested page is already in the cache, it is returned.
51633 ** Otherwise, a new page object is allocated and populated with data
51634 ** read from the database file. In some cases, the pcache module may
51635 ** choose not to allocate a new page object and may reuse an existing
51636 ** object with no outstanding references.
51637 **
51638 ** The extra data appended to a page is always initialized to zeros the
51639 ** first time a page is loaded into memory. If the page requested is
51640 ** already in the cache when this function is called, then the extra
51641 ** data is left as it was when the page object was last used.
51642 **
51643 ** If the database image is smaller than the requested page or if a
51644 ** non-zero value is passed as the noContent parameter and the
51645 ** requested page is not already stored in the cache, then no
51646 ** actual disk read occurs. In this case the memory image of the
51647 ** page is initialized to all zeros.
51648 **
51649 ** If noContent is true, it means that we do not care about the contents
51650 ** of the page. This occurs in two scenarios:
51651 **
51652 ** a) When reading a free-list leaf page from the database, and
51653 **
51654 ** b) When a savepoint is being rolled back and we need to load
51655 ** a new page into the cache to be filled with the data read
51656 ** from the savepoint journal.
51657 **
51658 ** If noContent is true, then the data returned is zeroed instead of
51659 ** being read from the database. Additionally, the bits corresponding
51660 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
51661 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
51662 ** savepoints are set. This means if the page is made writable at any
51663 ** point in the future, using a call to sqlite3PagerWrite(), its contents
51664 ** will not be journaled. This saves IO.
51665 **
51666 ** The acquisition might fail for several reasons. In all cases,
51667 ** an appropriate error code is returned and *ppPage is set to NULL.
51668 **
51669 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
51670 ** to find a page in the in-memory cache first. If the page is not already
51671 ** in memory, this routine goes to disk to read it in whereas Lookup()
51672 ** just returns 0. This routine acquires a read-lock the first time it
51673 ** has to go to disk, and could also playback an old journal if necessary.
51674 ** Since Lookup() never goes to disk, it never has to deal with locks
51675 ** or journal files.
51676 */
51678  Pager *pPager, /* The pager open on the database file */
51679  Pgno pgno, /* Page number to fetch */
51680  DbPage **ppPage, /* Write a pointer to the page here */
51681  int flags /* PAGER_GET_XXX flags */
51682 ){
51683  int rc = SQLITE_OK;
51684  PgHdr *pPg = 0;
51685  u32 iFrame = 0; /* Frame to read from WAL file */
51686  const int noContent = (flags & PAGER_GET_NOCONTENT);
51687 
51688  /* It is acceptable to use a read-only (mmap) page for any page except
51689  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
51690  ** flag was specified by the caller. And so long as the db is not a
51691  ** temporary or in-memory database. */
51692  const int bMmapOk = (pgno>1 && USEFETCH(pPager)
51693  && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
51694 #ifdef SQLITE_HAS_CODEC
51695  && pPager->xCodec==0
51696 #endif
51697  );
51698 
51699  /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
51700  ** allows the compiler optimizer to reuse the results of the "pgno>1"
51701  ** test in the previous statement, and avoid testing pgno==0 in the
51702  ** common case where pgno is large. */
51703  if( pgno<=1 && pgno==0 ){
51704  return SQLITE_CORRUPT_BKPT;
51705  }
51706  assert( pPager->eState>=PAGER_READER );
51707  assert( assert_pager_state(pPager) );
51708  assert( noContent==0 || bMmapOk==0 );
51709 
51710  assert( pPager->hasHeldSharedLock==1 );
51711 
51712  /* If the pager is in the error state, return an error immediately.
51713  ** Otherwise, request the page from the PCache layer. */
51714  if( pPager->errCode!=SQLITE_OK ){
51715  rc = pPager->errCode;
51716  }else{
51717  if( bMmapOk && pagerUseWal(pPager) ){
51718  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51719  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51720  }
51721 
51722  if( bMmapOk && iFrame==0 ){
51723  void *pData = 0;
51724 
51725  rc = sqlite3OsFetch(pPager->fd,
51726  (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
51727  );
51728 
51729  if( rc==SQLITE_OK && pData ){
51730  if( pPager->eState>PAGER_READER || pPager->tempFile ){
51731  pPg = sqlite3PagerLookup(pPager, pgno);
51732  }
51733  if( pPg==0 ){
51734  rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
51735  }else{
51736  sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
51737  }
51738  if( pPg ){
51739  assert( rc==SQLITE_OK );
51740  *ppPage = pPg;
51741  return SQLITE_OK;
51742  }
51743  }
51744  if( rc!=SQLITE_OK ){
51745  goto pager_acquire_err;
51746  }
51747  }
51748 
51749  {
51750  sqlite3_pcache_page *pBase;
51751  pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
51752  if( pBase==0 ){
51753  rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
51754  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51755  if( pBase==0 ){
51756  pPg = *ppPage = 0;
51757  rc = SQLITE_NOMEM_BKPT;
51758  goto pager_acquire_err;
51759  }
51760  }
51761  pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
51762  assert( pPg!=0 );
51763  }
51764  }
51765 
51766  if( rc!=SQLITE_OK ){
51767  /* Either the call to sqlite3PcacheFetch() returned an error or the
51768  ** pager was already in the error-state when this function was called.
51769  ** Set pPg to 0 and jump to the exception handler. */
51770  pPg = 0;
51771  goto pager_acquire_err;
51772  }
51773  assert( pPg==(*ppPage) );
51774  assert( pPg->pgno==pgno );
51775  assert( pPg->pPager==pPager || pPg->pPager==0 );
51776 
51777  if( pPg->pPager && !noContent ){
51778  /* In this case the pcache already contains an initialized copy of
51779  ** the page. Return without further ado. */
51780  assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
51781  pPager->aStat[PAGER_STAT_HIT]++;
51782  return SQLITE_OK;
51783 
51784  }else{
51785  /* The pager cache has created a new page. Its content needs to
51786  ** be initialized. */
51787 
51788  pPg->pPager = pPager;
51789 
51790  /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
51791  ** number greater than this, or the unused locking-page, is requested. */
51792  if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
51793  rc = SQLITE_CORRUPT_BKPT;
51794  goto pager_acquire_err;
51795  }
51796 
51797  assert( !isOpen(pPager->fd) || !MEMDB );
51798  if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
51799  if( pgno>pPager->mxPgno ){
51800  rc = SQLITE_FULL;
51801  goto pager_acquire_err;
51802  }
51803  if( noContent ){
51804  /* Failure to set the bits in the InJournal bit-vectors is benign.
51805  ** It merely means that we might do some extra work to journal a
51806  ** page that does not need to be journaled. Nevertheless, be sure
51807  ** to test the case where a malloc error occurs while trying to set
51808  ** a bit in a bit vector.
51809  */
51811  if( pgno<=pPager->dbOrigSize ){
51812  TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
51813  testcase( rc==SQLITE_NOMEM );
51814  }
51815  TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
51816  testcase( rc==SQLITE_NOMEM );
51818  }
51819  memset(pPg->pData, 0, pPager->pageSize);
51820  IOTRACE(("ZERO %p %d\n", pPager, pgno));
51821  }else{
51822  if( pagerUseWal(pPager) && bMmapOk==0 ){
51823  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51824  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51825  }
51826  assert( pPg->pPager==pPager );
51827  pPager->aStat[PAGER_STAT_MISS]++;
51828  rc = readDbPage(pPg, iFrame);
51829  if( rc!=SQLITE_OK ){
51830  goto pager_acquire_err;
51831  }
51832  }
51833  pager_set_pagehash(pPg);
51834  }
51835 
51836  return SQLITE_OK;
51837 
51838 pager_acquire_err:
51839  assert( rc!=SQLITE_OK );
51840  if( pPg ){
51841  sqlite3PcacheDrop(pPg);
51842  }
51843  pagerUnlockIfUnused(pPager);
51844 
51845  *ppPage = 0;
51846  return rc;
51847 }
51848 
51849 /*
51850 ** Acquire a page if it is already in the in-memory cache. Do
51851 ** not read the page from disk. Return a pointer to the page,
51852 ** or 0 if the page is not in cache.
51853 **
51854 ** See also sqlite3PagerGet(). The difference between this routine
51855 ** and sqlite3PagerGet() is that _get() will go to the disk and read
51856 ** in the page if the page is not already in cache. This routine
51857 ** returns NULL if the page is not in cache or if a disk I/O error
51858 ** has ever happened.
51859 */
51861  sqlite3_pcache_page *pPage;
51862  assert( pPager!=0 );
51863  assert( pgno!=0 );
51864  assert( pPager->pPCache!=0 );
51865  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
51866  assert( pPage==0 || pPager->hasHeldSharedLock );
51867  if( pPage==0 ) return 0;
51868  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
51869 }
51870 
51871 /*
51872 ** Release a page reference.
51873 **
51874 ** If the number of references to the page drop to zero, then the
51875 ** page is added to the LRU list. When all references to all pages
51876 ** are released, a rollback occurs and the lock on the database is
51877 ** removed.
51878 */
51880  Pager *pPager;
51881  assert( pPg!=0 );
51882  pPager = pPg->pPager;
51883  if( pPg->flags & PGHDR_MMAP ){
51884  pagerReleaseMapPage(pPg);
51885  }else{
51886  sqlite3PcacheRelease(pPg);
51887  }
51888  pagerUnlockIfUnused(pPager);
51889 }
51891  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
51892 }
51893 
51894 /*
51895 ** This function is called at the start of every write transaction.
51896 ** There must already be a RESERVED or EXCLUSIVE lock on the database
51897 ** file when this routine is called.
51898 **
51899 ** Open the journal file for pager pPager and write a journal header
51900 ** to the start of it. If there are active savepoints, open the sub-journal
51901 ** as well. This function is only used when the journal file is being
51902 ** opened to write a rollback log for a transaction. It is not used
51903 ** when opening a hot journal file to roll it back.
51904 **
51905 ** If the journal file is already open (as it may be in exclusive mode),
51906 ** then this function just writes a journal header to the start of the
51907 ** already open file.
51908 **
51909 ** Whether or not the journal file is opened by this function, the
51910 ** Pager.pInJournal bitvec structure is allocated.
51911 **
51912 ** Return SQLITE_OK if everything is successful. Otherwise, return
51913 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
51914 ** an IO error code if opening or writing the journal file fails.
51915 */
51916 static int pager_open_journal(Pager *pPager){
51917  int rc = SQLITE_OK; /* Return code */
51918  sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
51919 
51920  assert( pPager->eState==PAGER_WRITER_LOCKED );
51921  assert( assert_pager_state(pPager) );
51922  assert( pPager->pInJournal==0 );
51923 
51924  /* If already in the error state, this function is a no-op. But on
51925  ** the other hand, this routine is never called if we are already in
51926  ** an error state. */
51927  if( NEVER(pPager->errCode) ) return pPager->errCode;
51928 
51929  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51930  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
51931  if( pPager->pInJournal==0 ){
51932  return SQLITE_NOMEM_BKPT;
51933  }
51934 
51935  /* Open the journal file if it is not already open. */
51936  if( !isOpen(pPager->jfd) ){
51937  if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
51938  sqlite3MemJournalOpen(pPager->jfd);
51939  }else{
51941  int nSpill;
51942 
51943  if( pPager->tempFile ){
51945  nSpill = sqlite3Config.nStmtSpill;
51946  }else{
51947  flags |= SQLITE_OPEN_MAIN_JOURNAL;
51948  nSpill = jrnlBufferSize(pPager);
51949  }
51950 
51951  /* Verify that the database still has the same name as it did when
51952  ** it was originally opened. */
51953  rc = databaseIsUnmoved(pPager);
51954  if( rc==SQLITE_OK ){
51955  rc = sqlite3JournalOpen (
51956  pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
51957  );
51958  }
51959  }
51960  assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51961  }
51962 
51963 
51964  /* Write the first journal header to the journal file and open
51965  ** the sub-journal if necessary.
51966  */
51967  if( rc==SQLITE_OK ){
51968  /* TODO: Check if all of these are really required. */
51969  pPager->nRec = 0;
51970  pPager->journalOff = 0;
51971  pPager->setMaster = 0;
51972  pPager->journalHdr = 0;
51973  rc = writeJournalHdr(pPager);
51974  }
51975  }
51976 
51977  if( rc!=SQLITE_OK ){
51979  pPager->pInJournal = 0;
51980  }else{
51981  assert( pPager->eState==PAGER_WRITER_LOCKED );
51982  pPager->eState = PAGER_WRITER_CACHEMOD;
51983  }
51984 
51985  return rc;
51986 }
51987 
51988 /*
51989 ** Begin a write-transaction on the specified pager object. If a
51990 ** write-transaction has already been opened, this function is a no-op.
51991 **
51992 ** If the exFlag argument is false, then acquire at least a RESERVED
51993 ** lock on the database file. If exFlag is true, then acquire at least
51994 ** an EXCLUSIVE lock. If such a lock is already held, no locking
51995 ** functions need be called.
51996 **
51997 ** If the subjInMemory argument is non-zero, then any sub-journal opened
51998 ** within this transaction will be opened as an in-memory file. This
51999 ** has no effect if the sub-journal is already opened (as it may be when
52000 ** running in exclusive mode) or if the transaction does not require a
52001 ** sub-journal. If the subjInMemory argument is zero, then any required
52002 ** sub-journal is implemented in-memory if pPager is an in-memory database,
52003 ** or using a temporary file otherwise.
52004 */
52005 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
52006  int rc = SQLITE_OK;
52007 
52008  if( pPager->errCode ) return pPager->errCode;
52009  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
52010  pPager->subjInMemory = (u8)subjInMemory;
52011 
52012  if( ALWAYS(pPager->eState==PAGER_READER) ){
52013  assert( pPager->pInJournal==0 );
52014 
52015  if( pagerUseWal(pPager) ){
52016  /* If the pager is configured to use locking_mode=exclusive, and an
52017  ** exclusive lock on the database is not already held, obtain it now.
52018  */
52019  if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
52020  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
52021  if( rc!=SQLITE_OK ){
52022  return rc;
52023  }
52024  (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
52025  }
52026 
52027  /* Grab the write lock on the log file. If successful, upgrade to
52028  ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
52029  ** The busy-handler is not invoked if another connection already
52030  ** holds the write-lock. If possible, the upper layer will call it.
52031  */
52032  rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
52033  }else{
52034  /* Obtain a RESERVED lock on the database file. If the exFlag parameter
52035  ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
52036  ** busy-handler callback can be used when upgrading to the EXCLUSIVE
52037  ** lock, but not when obtaining the RESERVED lock.
52038  */
52039  rc = pagerLockDb(pPager, RESERVED_LOCK);
52040  if( rc==SQLITE_OK && exFlag ){
52041  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52042  }
52043  }
52044 
52045  if( rc==SQLITE_OK ){
52046  /* Change to WRITER_LOCKED state.
52047  **
52048  ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
52049  ** when it has an open transaction, but never to DBMOD or FINISHED.
52050  ** This is because in those states the code to roll back savepoint
52051  ** transactions may copy data from the sub-journal into the database
52052  ** file as well as into the page cache. Which would be incorrect in
52053  ** WAL mode.
52054  */
52055  pPager->eState = PAGER_WRITER_LOCKED;
52056  pPager->dbHintSize = pPager->dbSize;
52057  pPager->dbFileSize = pPager->dbSize;
52058  pPager->dbOrigSize = pPager->dbSize;
52059  pPager->journalOff = 0;
52060  }
52061 
52062  assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
52063  assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
52064  assert( assert_pager_state(pPager) );
52065  }
52066 
52067  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
52068  return rc;
52069 }
52070 
52071 /*
52072 ** Write page pPg onto the end of the rollback journal.
52073 */
52075  Pager *pPager = pPg->pPager;
52076  int rc;
52077  u32 cksum;
52078  char *pData2;
52079  i64 iOff = pPager->journalOff;
52080 
52081  /* We should never write to the journal file the page that
52082  ** contains the database locks. The following assert verifies
52083  ** that we do not. */
52084  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
52085 
52086  assert( pPager->journalHdr<=pPager->journalOff );
52087  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
52088  cksum = pager_cksum(pPager, (u8*)pData2);
52089 
52090  /* Even if an IO or diskfull error occurs while journalling the
52091  ** page in the block above, set the need-sync flag for the page.
52092  ** Otherwise, when the transaction is rolled back, the logic in
52093  ** playback_one_page() will think that the page needs to be restored
52094  ** in the database file. And if an IO error occurs while doing so,
52095  ** then corruption may follow.
52096  */
52097  pPg->flags |= PGHDR_NEED_SYNC;
52098 
52099  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
52100  if( rc!=SQLITE_OK ) return rc;
52101  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
52102  if( rc!=SQLITE_OK ) return rc;
52103  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
52104  if( rc!=SQLITE_OK ) return rc;
52105 
52106  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
52107  pPager->journalOff, pPager->pageSize));
52108  PAGER_INCR(sqlite3_pager_writej_count);
52109  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
52110  PAGERID(pPager), pPg->pgno,
52111  ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
52112 
52113  pPager->journalOff += 8 + pPager->pageSize;
52114  pPager->nRec++;
52115  assert( pPager->pInJournal!=0 );
52116  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
52117  testcase( rc==SQLITE_NOMEM );
52118  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52119  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
52120  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52121  return rc;
52122 }
52123 
52124 /*
52125 ** Mark a single data page as writeable. The page is written into the
52126 ** main journal or sub-journal as required. If the page is written into
52127 ** one of the journals, the corresponding bit is set in the
52128 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
52129 ** of any open savepoints as appropriate.
52130 */
52131 static int pager_write(PgHdr *pPg){
52132  Pager *pPager = pPg->pPager;
52133  int rc = SQLITE_OK;
52134 
52135  /* This routine is not called unless a write-transaction has already
52136  ** been started. The journal file may or may not be open at this point.
52137  ** It is never called in the ERROR state.
52138  */
52139  assert( pPager->eState==PAGER_WRITER_LOCKED
52140  || pPager->eState==PAGER_WRITER_CACHEMOD
52141  || pPager->eState==PAGER_WRITER_DBMOD
52142  );
52143  assert( assert_pager_state(pPager) );
52144  assert( pPager->errCode==0 );
52145  assert( pPager->readOnly==0 );
52146  CHECK_PAGE(pPg);
52147 
52148  /* The journal file needs to be opened. Higher level routines have already
52149  ** obtained the necessary locks to begin the write-transaction, but the
52150  ** rollback journal might not yet be open. Open it now if this is the case.
52151  **
52152  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
52153  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
52154  ** an error might occur and the pager would end up in WRITER_LOCKED state
52155  ** with pages marked as dirty in the cache.
52156  */
52157  if( pPager->eState==PAGER_WRITER_LOCKED ){
52158  rc = pager_open_journal(pPager);
52159  if( rc!=SQLITE_OK ) return rc;
52160  }
52161  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
52162  assert( assert_pager_state(pPager) );
52163 
52164  /* Mark the page that is about to be modified as dirty. */
52166 
52167  /* If a rollback journal is in use, them make sure the page that is about
52168  ** to change is in the rollback journal, or if the page is a new page off
52169  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
52170  */
52171  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
52172  if( pPager->pInJournal!=0
52173  && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
52174  ){
52175  assert( pagerUseWal(pPager)==0 );
52176  if( pPg->pgno<=pPager->dbOrigSize ){
52178  if( rc!=SQLITE_OK ){
52179  return rc;
52180  }
52181  }else{
52182  if( pPager->eState!=PAGER_WRITER_DBMOD ){
52183  pPg->flags |= PGHDR_NEED_SYNC;
52184  }
52185  PAGERTRACE(("APPEND %d page %d needSync=%d\n",
52186  PAGERID(pPager), pPg->pgno,
52187  ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
52188  }
52189  }
52190 
52191  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
52192  ** and before writing the page into the rollback journal. Wait until now,
52193  ** after the page has been successfully journalled, before setting the
52194  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
52195  */
52196  pPg->flags |= PGHDR_WRITEABLE;
52197 
52198  /* If the statement journal is open and the page is not in it,
52199  ** then write the page into the statement journal.
52200  */
52201  if( pPager->nSavepoint>0 ){
52202  rc = subjournalPageIfRequired(pPg);
52203  }
52204 
52205  /* Update the database size and return. */
52206  if( pPager->dbSize<pPg->pgno ){
52207  pPager->dbSize = pPg->pgno;
52208  }
52209  return rc;
52210 }
52211 
52212 /*
52213 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
52214 ** is larger than the page size. SQLite makes the (reasonable) assumption that
52215 ** all bytes of a sector are written together by hardware. Hence, all bytes of
52216 ** a sector need to be journalled in case of a power loss in the middle of
52217 ** a write.
52218 **
52219 ** Usually, the sector size is less than or equal to the page size, in which
52220 ** case pages can be individually written. This routine only runs in the
52221 ** exceptional case where the page size is smaller than the sector size.
52222 */
52224  int rc = SQLITE_OK; /* Return code */
52225  Pgno nPageCount; /* Total number of pages in database file */
52226  Pgno pg1; /* First page of the sector pPg is located on. */
52227  int nPage = 0; /* Number of pages starting at pg1 to journal */
52228  int ii; /* Loop counter */
52229  int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
52230  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
52231  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
52232 
52233  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
52234  ** a journal header to be written between the pages journaled by
52235  ** this function.
52236  */
52237  assert( !MEMDB );
52238  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
52239  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
52240 
52241  /* This trick assumes that both the page-size and sector-size are
52242  ** an integer power of 2. It sets variable pg1 to the identifier
52243  ** of the first page of the sector pPg is located on.
52244  */
52245  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
52246 
52247  nPageCount = pPager->dbSize;
52248  if( pPg->pgno>nPageCount ){
52249  nPage = (pPg->pgno - pg1)+1;
52250  }else if( (pg1+nPagePerSector-1)>nPageCount ){
52251  nPage = nPageCount+1-pg1;
52252  }else{
52253  nPage = nPagePerSector;
52254  }
52255  assert(nPage>0);
52256  assert(pg1<=pPg->pgno);
52257  assert((pg1+nPage)>pPg->pgno);
52258 
52259  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
52260  Pgno pg = pg1+ii;
52261  PgHdr *pPage;
52262  if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
52263  if( pg!=PAGER_MJ_PGNO(pPager) ){
52264  rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
52265  if( rc==SQLITE_OK ){
52266  rc = pager_write(pPage);
52267  if( pPage->flags&PGHDR_NEED_SYNC ){
52268  needSync = 1;
52269  }
52270  sqlite3PagerUnrefNotNull(pPage);
52271  }
52272  }
52273  }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
52274  if( pPage->flags&PGHDR_NEED_SYNC ){
52275  needSync = 1;
52276  }
52277  sqlite3PagerUnrefNotNull(pPage);
52278  }
52279  }
52280 
52281  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
52282  ** starting at pg1, then it needs to be set for all of them. Because
52283  ** writing to any of these nPage pages may damage the others, the
52284  ** journal file must contain sync()ed copies of all of them
52285  ** before any of them can be written out to the database file.
52286  */
52287  if( rc==SQLITE_OK && needSync ){
52288  assert( !MEMDB );
52289  for(ii=0; ii<nPage; ii++){
52290  PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
52291  if( pPage ){
52292  pPage->flags |= PGHDR_NEED_SYNC;
52293  sqlite3PagerUnrefNotNull(pPage);
52294  }
52295  }
52296  }
52297 
52298  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
52299  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
52300  return rc;
52301 }
52302 
52303 /*
52304 ** Mark a data page as writeable. This routine must be called before
52305 ** making changes to a page. The caller must check the return value
52306 ** of this function and be careful not to change any page data unless
52307 ** this routine returns SQLITE_OK.
52308 **
52309 ** The difference between this function and pager_write() is that this
52310 ** function also deals with the special case where 2 or more pages
52311 ** fit on a single disk sector. In this case all co-resident pages
52312 ** must have been written to the journal file before returning.
52313 **
52314 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
52315 ** as appropriate. Otherwise, SQLITE_OK.
52316 */
52318  Pager *pPager = pPg->pPager;
52319  assert( (pPg->flags & PGHDR_MMAP)==0 );
52320  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52321  assert( assert_pager_state(pPager) );
52322  if( pPager->errCode ){
52323  return pPager->errCode;
52324  }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
52325  if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
52326  return SQLITE_OK;
52327  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
52328  assert( pPager->tempFile==0 );
52329  return pagerWriteLargeSector(pPg);
52330  }else{
52331  return pager_write(pPg);
52332  }
52333 }
52334 
52335 /*
52336 ** Return TRUE if the page given in the argument was previously passed
52337 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
52338 ** to change the content of the page.
52339 */
52340 #ifndef NDEBUG
52341 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
52342  return pPg->flags & PGHDR_WRITEABLE;
52343 }
52344 #endif
52345 
52346 /*
52347 ** A call to this routine tells the pager that it is not necessary to
52348 ** write the information on page pPg back to the disk, even though
52349 ** that page might be marked as dirty. This happens, for example, when
52350 ** the page has been added as a leaf of the freelist and so its
52351 ** content no longer matters.
52352 **
52353 ** The overlying software layer calls this routine when all of the data
52354 ** on the given page is unused. The pager marks the page as clean so
52355 ** that it does not get written to disk.
52356 **
52357 ** Tests show that this optimization can quadruple the speed of large
52358 ** DELETE operations.
52359 **
52360 ** This optimization cannot be used with a temp-file, as the page may
52361 ** have been dirty at the start of the transaction. In that case, if
52362 ** memory pressure forces page pPg out of the cache, the data does need
52363 ** to be written out to disk so that it may be read back in if the
52364 ** current transaction is rolled back.
52365 */
52367  Pager *pPager = pPg->pPager;
52368  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
52369  PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
52370  IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
52371  pPg->flags |= PGHDR_DONT_WRITE;
52372  pPg->flags &= ~PGHDR_WRITEABLE;
52373  testcase( pPg->flags & PGHDR_NEED_SYNC );
52374  pager_set_pagehash(pPg);
52375  }
52376 }
52377 
52378 /*
52379 ** This routine is called to increment the value of the database file
52380 ** change-counter, stored as a 4-byte big-endian integer starting at
52381 ** byte offset 24 of the pager file. The secondary change counter at
52382 ** 92 is also updated, as is the SQLite version number at offset 96.
52383 **
52384 ** But this only happens if the pPager->changeCountDone flag is false.
52385 ** To avoid excess churning of page 1, the update only happens once.
52386 ** See also the pager_write_changecounter() routine that does an
52387 ** unconditional update of the change counters.
52388 **
52389 ** If the isDirectMode flag is zero, then this is done by calling
52390 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
52391 ** page data. In this case the file will be updated when the current
52392 ** transaction is committed.
52393 **
52394 ** The isDirectMode flag may only be non-zero if the library was compiled
52395 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
52396 ** if isDirect is non-zero, then the database file is updated directly
52397 ** by writing an updated version of page 1 using a call to the
52398 ** sqlite3OsWrite() function.
52399 */
52400 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
52401  int rc = SQLITE_OK;
52402 
52403  assert( pPager->eState==PAGER_WRITER_CACHEMOD
52404  || pPager->eState==PAGER_WRITER_DBMOD
52405  );
52406  assert( assert_pager_state(pPager) );
52407 
52408  /* Declare and initialize constant integer 'isDirect'. If the
52409  ** atomic-write optimization is enabled in this build, then isDirect
52410  ** is initialized to the value passed as the isDirectMode parameter
52411  ** to this function. Otherwise, it is always set to zero.
52412  **
52413  ** The idea is that if the atomic-write optimization is not
52414  ** enabled at compile time, the compiler can omit the tests of
52415  ** 'isDirect' below, as well as the block enclosed in the
52416  ** "if( isDirect )" condition.
52417  */
52418 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
52419 # define DIRECT_MODE 0
52420  assert( isDirectMode==0 );
52421  UNUSED_PARAMETER(isDirectMode);
52422 #else
52423 # define DIRECT_MODE isDirectMode
52424 #endif
52425 
52426  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
52427  PgHdr *pPgHdr; /* Reference to page 1 */
52428 
52429  assert( !pPager->tempFile && isOpen(pPager->fd) );
52430 
52431  /* Open page 1 of the file for writing. */
52432  rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
52433  assert( pPgHdr==0 || rc==SQLITE_OK );
52434 
52435  /* If page one was fetched successfully, and this function is not
52436  ** operating in direct-mode, make page 1 writable. When not in
52437  ** direct mode, page 1 is always held in cache and hence the PagerGet()
52438  ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
52439  */
52440  if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
52441  rc = sqlite3PagerWrite(pPgHdr);
52442  }
52443 
52444  if( rc==SQLITE_OK ){
52445  /* Actually do the update of the change counter */
52446  pager_write_changecounter(pPgHdr);
52447 
52448  /* If running in direct mode, write the contents of page 1 to the file. */
52449  if( DIRECT_MODE ){
52450  const void *zBuf;
52451  assert( pPager->dbFileSize>0 );
52452  CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
52453  if( rc==SQLITE_OK ){
52454  rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
52455  pPager->aStat[PAGER_STAT_WRITE]++;
52456  }
52457  if( rc==SQLITE_OK ){
52458  /* Update the pager's copy of the change-counter. Otherwise, the
52459  ** next time a read transaction is opened the cache will be
52460  ** flushed (as the change-counter values will not match). */
52461  const void *pCopy = (const void *)&((const char *)zBuf)[24];
52462  memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
52463  pPager->changeCountDone = 1;
52464  }
52465  }else{
52466  pPager->changeCountDone = 1;
52467  }
52468  }
52469 
52470  /* Release the page reference. */
52471  sqlite3PagerUnref(pPgHdr);
52472  }
52473  return rc;
52474 }
52475 
52476 /*
52477 ** Sync the database file to disk. This is a no-op for in-memory databases
52478 ** or pages with the Pager.noSync flag set.
52479 **
52480 ** If successful, or if called on a pager for which it is a no-op, this
52481 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
52482 */
52483 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
52484  int rc = SQLITE_OK;
52485 
52486  if( isOpen(pPager->fd) ){
52487  void *pArg = (void*)zMaster;
52488  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
52489  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
52490  }
52491  if( rc==SQLITE_OK && !pPager->noSync ){
52492  assert( !MEMDB );
52493  rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
52494  }
52495  return rc;
52496 }
52497 
52498 /*
52499 ** This function may only be called while a write-transaction is active in
52500 ** rollback. If the connection is in WAL mode, this call is a no-op.
52501 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
52502 ** the database file, an attempt is made to obtain one.
52503 **
52504 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
52505 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
52506 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
52507 ** returned.
52508 */
52510  int rc = pPager->errCode;
52511  assert( assert_pager_state(pPager) );
52512  if( rc==SQLITE_OK ){
52513  assert( pPager->eState==PAGER_WRITER_CACHEMOD
52514  || pPager->eState==PAGER_WRITER_DBMOD
52515  || pPager->eState==PAGER_WRITER_LOCKED
52516  );
52517  assert( assert_pager_state(pPager) );
52518  if( 0==pagerUseWal(pPager) ){
52519  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52520  }
52521  }
52522  return rc;
52523 }
52524 
52525 /*
52526 ** Sync the database file for the pager pPager. zMaster points to the name
52527 ** of a master journal file that should be written into the individual
52528 ** journal file. zMaster may be NULL, which is interpreted as no master
52529 ** journal (a single database transaction).
52530 **
52531 ** This routine ensures that:
52532 **
52533 ** * The database file change-counter is updated,
52534 ** * the journal is synced (unless the atomic-write optimization is used),
52535 ** * all dirty pages are written to the database file,
52536 ** * the database file is truncated (if required), and
52537 ** * the database file synced.
52538 **
52539 ** The only thing that remains to commit the transaction is to finalize
52540 ** (delete, truncate or zero the first part of) the journal file (or
52541 ** delete the master journal file if specified).
52542 **
52543 ** Note that if zMaster==NULL, this does not overwrite a previous value
52544 ** passed to an sqlite3PagerCommitPhaseOne() call.
52545 **
52546 ** If the final parameter - noSync - is true, then the database file itself
52547 ** is not synced. The caller must call sqlite3PagerSync() directly to
52548 ** sync the database file before calling CommitPhaseTwo() to delete the
52549 ** journal file in this case.
52550 */
52552  Pager *pPager, /* Pager object */
52553  const char *zMaster, /* If not NULL, the master journal name */
52554  int noSync /* True to omit the xSync on the db file */
52555 ){
52556  int rc = SQLITE_OK; /* Return code */
52557 
52558  assert( pPager->eState==PAGER_WRITER_LOCKED
52559  || pPager->eState==PAGER_WRITER_CACHEMOD
52560  || pPager->eState==PAGER_WRITER_DBMOD
52561  || pPager->eState==PAGER_ERROR
52562  );
52563  assert( assert_pager_state(pPager) );
52564 
52565  /* If a prior error occurred, report that error again. */
52566  if( NEVER(pPager->errCode) ) return pPager->errCode;
52567 
52568  /* Provide the ability to easily simulate an I/O error during testing */
52569  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
52570 
52571  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
52572  pPager->zFilename, zMaster, pPager->dbSize));
52573 
52574  /* If no database changes have been made, return early. */
52575  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
52576 
52577  assert( MEMDB==0 || pPager->tempFile );
52578  assert( isOpen(pPager->fd) || pPager->tempFile );
52579  if( 0==pagerFlushOnCommit(pPager, 1) ){
52580  /* If this is an in-memory db, or no pages have been written to, or this
52581  ** function has already been called, it is mostly a no-op. However, any
52582  ** backup in progress needs to be restarted. */
52583  sqlite3BackupRestart(pPager->pBackup);
52584  }else{
52585  if( pagerUseWal(pPager) ){
52586  PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52587  PgHdr *pPageOne = 0;
52588  if( pList==0 ){
52589  /* Must have at least one page for the WAL commit flag.
52590  ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
52591  rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
52592  pList = pPageOne;
52593  pList->pDirty = 0;
52594  }
52595  assert( rc==SQLITE_OK );
52596  if( ALWAYS(pList) ){
52597  rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
52598  }
52599  sqlite3PagerUnref(pPageOne);
52600  if( rc==SQLITE_OK ){
52601  sqlite3PcacheCleanAll(pPager->pPCache);
52602  }
52603  }else{
52604  /* The following block updates the change-counter. Exactly how it
52605  ** does this depends on whether or not the atomic-update optimization
52606  ** was enabled at compile time, and if this transaction meets the
52607  ** runtime criteria to use the operation:
52608  **
52609  ** * The file-system supports the atomic-write property for
52610  ** blocks of size page-size, and
52611  ** * This commit is not part of a multi-file transaction, and
52612  ** * Exactly one page has been modified and store in the journal file.
52613  **
52614  ** If the optimization was not enabled at compile time, then the
52615  ** pager_incr_changecounter() function is called to update the change
52616  ** counter in 'indirect-mode'. If the optimization is compiled in but
52617  ** is not applicable to this transaction, call sqlite3JournalCreate()
52618  ** to make sure the journal file has actually been created, then call
52619  ** pager_incr_changecounter() to update the change-counter in indirect
52620  ** mode.
52621  **
52622  ** Otherwise, if the optimization is both enabled and applicable,
52623  ** then call pager_incr_changecounter() to update the change-counter
52624  ** in 'direct' mode. In this case the journal file will never be
52625  ** created for this transaction.
52626  */
52627  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
52628  PgHdr *pPg;
52629  assert( isOpen(pPager->jfd)
52630  || pPager->journalMode==PAGER_JOURNALMODE_OFF
52631  || pPager->journalMode==PAGER_JOURNALMODE_WAL
52632  );
52633  if( !zMaster && isOpen(pPager->jfd)
52634  && pPager->journalOff==jrnlBufferSize(pPager)
52635  && pPager->dbSize>=pPager->dbOrigSize
52636  && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
52637  ){
52638  /* Update the db file change counter via the direct-write method. The
52639  ** following call will modify the in-memory representation of page 1
52640  ** to include the updated change counter and then write page 1
52641  ** directly to the database file. Because of the atomic-write
52642  ** property of the host file-system, this is safe.
52643  */
52644  rc = pager_incr_changecounter(pPager, 1);
52645  }else{
52646  rc = sqlite3JournalCreate(pPager->jfd);
52647  if( rc==SQLITE_OK ){
52648  rc = pager_incr_changecounter(pPager, 0);
52649  }
52650  }
52651  #else
52652  rc = pager_incr_changecounter(pPager, 0);
52653  #endif
52654  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52655 
52656  /* Write the master journal name into the journal file. If a master
52657  ** journal file name has already been written to the journal file,
52658  ** or if zMaster is NULL (no master journal), then this call is a no-op.
52659  */
52660  rc = writeMasterJournal(pPager, zMaster);
52661  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52662 
52663  /* Sync the journal file and write all dirty pages to the database.
52664  ** If the atomic-update optimization is being used, this sync will not
52665  ** create the journal file or perform any real IO.
52666  **
52667  ** Because the change-counter page was just modified, unless the
52668  ** atomic-update optimization is used it is almost certain that the
52669  ** journal requires a sync here. However, in locking_mode=exclusive
52670  ** on a system under memory pressure it is just possible that this is
52671  ** not the case. In this case it is likely enough that the redundant
52672  ** xSync() call will be changed to a no-op by the OS anyhow.
52673  */
52674  rc = syncJournal(pPager, 0);
52675  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52676 
52677  rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
52678  if( rc!=SQLITE_OK ){
52679  assert( rc!=SQLITE_IOERR_BLOCKED );
52680  goto commit_phase_one_exit;
52681  }
52682  sqlite3PcacheCleanAll(pPager->pPCache);
52683 
52684  /* If the file on disk is smaller than the database image, use
52685  ** pager_truncate to grow the file here. This can happen if the database
52686  ** image was extended as part of the current transaction and then the
52687  ** last page in the db image moved to the free-list. In this case the
52688  ** last page is never written out to disk, leaving the database file
52689  ** undersized. Fix this now if it is the case. */
52690  if( pPager->dbSize>pPager->dbFileSize ){
52691  Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
52692  assert( pPager->eState==PAGER_WRITER_DBMOD );
52693  rc = pager_truncate(pPager, nNew);
52694  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52695  }
52696 
52697  /* Finally, sync the database file. */
52698  if( !noSync ){
52699  rc = sqlite3PagerSync(pPager, zMaster);
52700  }
52701  IOTRACE(("DBSYNC %p\n", pPager))
52702  }
52703  }
52704 
52705 commit_phase_one_exit:
52706  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
52707  pPager->eState = PAGER_WRITER_FINISHED;
52708  }
52709  return rc;
52710 }
52711 
52712 
52713 /*
52714 ** When this function is called, the database file has been completely
52715 ** updated to reflect the changes made by the current transaction and
52716 ** synced to disk. The journal file still exists in the file-system
52717 ** though, and if a failure occurs at this point it will eventually
52718 ** be used as a hot-journal and the current transaction rolled back.
52719 **
52720 ** This function finalizes the journal file, either by deleting,
52721 ** truncating or partially zeroing it, so that it cannot be used
52722 ** for hot-journal rollback. Once this is done the transaction is
52723 ** irrevocably committed.
52724 **
52725 ** If an error occurs, an IO error code is returned and the pager
52726 ** moves into the error state. Otherwise, SQLITE_OK is returned.
52727 */
52729  int rc = SQLITE_OK; /* Return code */
52730 
52731  /* This routine should not be called if a prior error has occurred.
52732  ** But if (due to a coding error elsewhere in the system) it does get
52733  ** called, just return the same error code without doing anything. */
52734  if( NEVER(pPager->errCode) ) return pPager->errCode;
52735 
52736  assert( pPager->eState==PAGER_WRITER_LOCKED
52737  || pPager->eState==PAGER_WRITER_FINISHED
52738  || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
52739  );
52740  assert( assert_pager_state(pPager) );
52741 
52742  /* An optimization. If the database was not actually modified during
52743  ** this transaction, the pager is running in exclusive-mode and is
52744  ** using persistent journals, then this function is a no-op.
52745  **
52746  ** The start of the journal file currently contains a single journal
52747  ** header with the nRec field set to 0. If such a journal is used as
52748  ** a hot-journal during hot-journal rollback, 0 changes will be made
52749  ** to the database file. So there is no need to zero the journal
52750  ** header. Since the pager is in exclusive mode, there is no need
52751  ** to drop any locks either.
52752  */
52753  if( pPager->eState==PAGER_WRITER_LOCKED
52754  && pPager->exclusiveMode
52756  ){
52757  assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
52758  pPager->eState = PAGER_READER;
52759  return SQLITE_OK;
52760  }
52761 
52762  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
52763  pPager->iDataVersion++;
52764  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
52765  return pager_error(pPager, rc);
52766 }
52767 
52768 /*
52769 ** If a write transaction is open, then all changes made within the
52770 ** transaction are reverted and the current write-transaction is closed.
52771 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
52772 ** state if an error occurs.
52773 **
52774 ** If the pager is already in PAGER_ERROR state when this function is called,
52775 ** it returns Pager.errCode immediately. No work is performed in this case.
52776 **
52777 ** Otherwise, in rollback mode, this function performs two functions:
52778 **
52779 ** 1) It rolls back the journal file, restoring all database file and
52780 ** in-memory cache pages to the state they were in when the transaction
52781 ** was opened, and
52782 **
52783 ** 2) It finalizes the journal file, so that it is not used for hot
52784 ** rollback at any point in the future.
52785 **
52786 ** Finalization of the journal file (task 2) is only performed if the
52787 ** rollback is successful.
52788 **
52789 ** In WAL mode, all cache-entries containing data modified within the
52790 ** current transaction are either expelled from the cache or reverted to
52791 ** their pre-transaction state by re-reading data from the database or
52792 ** WAL files. The WAL transaction is then closed.
52793 */
52795  int rc = SQLITE_OK; /* Return code */
52796  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
52797 
52798  /* PagerRollback() is a no-op if called in READER or OPEN state. If
52799  ** the pager is already in the ERROR state, the rollback is not
52800  ** attempted here. Instead, the error code is returned to the caller.
52801  */
52802  assert( assert_pager_state(pPager) );
52803  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
52804  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
52805 
52806  if( pagerUseWal(pPager) ){
52807  int rc2;
52808  rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
52809  rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
52810  if( rc==SQLITE_OK ) rc = rc2;
52811  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
52812  int eState = pPager->eState;
52813  rc = pager_end_transaction(pPager, 0, 0);
52814  if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
52815  /* This can happen using journal_mode=off. Move the pager to the error
52816  ** state to indicate that the contents of the cache may not be trusted.
52817  ** Any active readers will get SQLITE_ABORT.
52818  */
52819  pPager->errCode = SQLITE_ABORT;
52820  pPager->eState = PAGER_ERROR;
52821  return rc;
52822  }
52823  }else{
52824  rc = pager_playback(pPager, 0);
52825  }
52826 
52827  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
52828  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
52829  || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
52830  || rc==SQLITE_CANTOPEN
52831  );
52832 
52833  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
52834  ** cache. So call pager_error() on the way out to make any error persistent.
52835  */
52836  return pager_error(pPager, rc);
52837 }
52838 
52839 /*
52840 ** Return TRUE if the database file is opened read-only. Return FALSE
52841 ** if the database is (in theory) writable.
52842 */
52844  return pPager->readOnly;
52845 }
52846 
52847 #ifdef SQLITE_DEBUG
52848 /*
52849 ** Return the sum of the reference counts for all pages held by pPager.
52850 */
52851 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
52852  return sqlite3PcacheRefCount(pPager->pPCache);
52853 }
52854 #endif
52855 
52856 /*
52857 ** Return the approximate number of bytes of memory currently
52858 ** used by the pager and its associated cache.
52859 */
52861  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
52862  + 5*sizeof(void*);
52863  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
52864  + sqlite3MallocSize(pPager)
52865  + pPager->pageSize;
52866 }
52867 
52868 /*
52869 ** Return the number of references to the specified page.
52870 */
52872  return sqlite3PcachePageRefcount(pPage);
52873 }
52874 
52875 #ifdef SQLITE_TEST
52876 /*
52877 ** This routine is used for testing and analysis only.
52878 */
52879 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
52880  static int a[11];
52881  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
52882  a[1] = sqlite3PcachePagecount(pPager->pPCache);
52883  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
52884  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
52885  a[4] = pPager->eState;
52886  a[5] = pPager->errCode;
52887  a[6] = pPager->aStat[PAGER_STAT_HIT];
52888  a[7] = pPager->aStat[PAGER_STAT_MISS];
52889  a[8] = 0; /* Used to be pPager->nOvfl */
52890  a[9] = pPager->nRead;
52891  a[10] = pPager->aStat[PAGER_STAT_WRITE];
52892  return a;
52893 }
52894 #endif
52895 
52896 /*
52897 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
52898 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
52899 ** current cache hit or miss count, according to the value of eStat. If the
52900 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
52901 ** returning.
52902 */
52903 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
52904 
52905  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
52906  || eStat==SQLITE_DBSTATUS_CACHE_MISS
52907  || eStat==SQLITE_DBSTATUS_CACHE_WRITE
52908  );
52909 
52912  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
52913 
52914  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
52915  if( reset ){
52916  pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
52917  }
52918 }
52919 
52920 /*
52921 ** Return true if this is an in-memory or temp-file backed pager.
52922 */
52924  return pPager->tempFile;
52925 }
52926 
52927 /*
52928 ** Check that there are at least nSavepoint savepoints open. If there are
52929 ** currently less than nSavepoints open, then open one or more savepoints
52930 ** to make up the difference. If the number of savepoints is already
52931 ** equal to nSavepoint, then this function is a no-op.
52932 **
52933 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
52934 ** occurs while opening the sub-journal file, then an IO error code is
52935 ** returned. Otherwise, SQLITE_OK.
52936 */
52937 static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
52938  int rc = SQLITE_OK; /* Return code */
52939  int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
52940  int ii; /* Iterator variable */
52941  PagerSavepoint *aNew; /* New Pager.aSavepoint array */
52942 
52943  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52944  assert( assert_pager_state(pPager) );
52945  assert( nSavepoint>nCurrent && pPager->useJournal );
52946 
52947  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
52948  ** if the allocation fails. Otherwise, zero the new portion in case a
52949  ** malloc failure occurs while populating it in the for(...) loop below.
52950  */
52951  aNew = (PagerSavepoint *)sqlite3Realloc(
52952  pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
52953  );
52954  if( !aNew ){
52955  return SQLITE_NOMEM_BKPT;
52956  }
52957  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
52958  pPager->aSavepoint = aNew;
52959 
52960  /* Populate the PagerSavepoint structures just allocated. */
52961  for(ii=nCurrent; ii<nSavepoint; ii++){
52962  aNew[ii].nOrig = pPager->dbSize;
52963  if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
52964  aNew[ii].iOffset = pPager->journalOff;
52965  }else{
52966  aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
52967  }
52968  aNew[ii].iSubRec = pPager->nSubRec;
52969  aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
52970  if( !aNew[ii].pInSavepoint ){
52971  return SQLITE_NOMEM_BKPT;
52972  }
52973  if( pagerUseWal(pPager) ){
52974  sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
52975  }
52976  pPager->nSavepoint = ii+1;
52977  }
52978  assert( pPager->nSavepoint==nSavepoint );
52979  assertTruncateConstraint(pPager);
52980  return rc;
52981 }
52982 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
52983  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52984  assert( assert_pager_state(pPager) );
52985 
52986  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
52987  return pagerOpenSavepoint(pPager, nSavepoint);
52988  }else{
52989  return SQLITE_OK;
52990  }
52991 }
52992 
52993 
52994 /*
52995 ** This function is called to rollback or release (commit) a savepoint.
52996 ** The savepoint to release or rollback need not be the most recently
52997 ** created savepoint.
52998 **
52999 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
53000 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
53001 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
53002 ** that have occurred since the specified savepoint was created.
53003 **
53004 ** The savepoint to rollback or release is identified by parameter
53005 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
53006 ** (the first created). A value of (Pager.nSavepoint-1) means operate
53007 ** on the most recently created savepoint. If iSavepoint is greater than
53008 ** (Pager.nSavepoint-1), then this function is a no-op.
53009 **
53010 ** If a negative value is passed to this function, then the current
53011 ** transaction is rolled back. This is different to calling
53012 ** sqlite3PagerRollback() because this function does not terminate
53013 ** the transaction or unlock the database, it just restores the
53014 ** contents of the database to its original state.
53015 **
53016 ** In any case, all savepoints with an index greater than iSavepoint
53017 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
53018 ** then savepoint iSavepoint is also destroyed.
53019 **
53020 ** This function may return SQLITE_NOMEM if a memory allocation fails,
53021 ** or an IO error code if an IO error occurs while rolling back a
53022 ** savepoint. If no errors occur, SQLITE_OK is returned.
53023 */
53024 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
53025  int rc = pPager->errCode;
53026 
53027 #ifdef SQLITE_ENABLE_ZIPVFS
53028  if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
53029 #endif
53030 
53031  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53032  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
53033 
53034  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
53035  int ii; /* Iterator variable */
53036  int nNew; /* Number of remaining savepoints after this op. */
53037 
53038  /* Figure out how many savepoints will still be active after this
53039  ** operation. Store this value in nNew. Then free resources associated
53040  ** with any savepoints that are destroyed by this operation.
53041  */
53042  nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
53043  for(ii=nNew; ii<pPager->nSavepoint; ii++){
53045  }
53046  pPager->nSavepoint = nNew;
53047 
53048  /* If this is a release of the outermost savepoint, truncate
53049  ** the sub-journal to zero bytes in size. */
53050  if( op==SAVEPOINT_RELEASE ){
53051  if( nNew==0 && isOpen(pPager->sjfd) ){
53052  /* Only truncate if it is an in-memory sub-journal. */
53053  if( sqlite3JournalIsInMemory(pPager->sjfd) ){
53054  rc = sqlite3OsTruncate(pPager->sjfd, 0);
53055  assert( rc==SQLITE_OK );
53056  }
53057  pPager->nSubRec = 0;
53058  }
53059  }
53060  /* Else this is a rollback operation, playback the specified savepoint.
53061  ** If this is a temp-file, it is possible that the journal file has
53062  ** not yet been opened. In this case there have been no changes to
53063  ** the database file, so the playback operation can be skipped.
53064  */
53065  else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
53066  PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
53067  rc = pagerPlaybackSavepoint(pPager, pSavepoint);
53068  assert(rc!=SQLITE_DONE);
53069  }
53070 
53071 #ifdef SQLITE_ENABLE_ZIPVFS
53072  /* If the cache has been modified but the savepoint cannot be rolled
53073  ** back journal_mode=off, put the pager in the error state. This way,
53074  ** if the VFS used by this pager includes ZipVFS, the entire transaction
53075  ** can be rolled back at the ZipVFS level. */
53076  else if(
53078  && pPager->eState>=PAGER_WRITER_CACHEMOD
53079  ){
53080  pPager->errCode = SQLITE_ABORT;
53081  pPager->eState = PAGER_ERROR;
53082  }
53083 #endif
53084  }
53085 
53086  return rc;
53087 }
53088 
53089 /*
53090 ** Return the full pathname of the database file.
53091 **
53092 ** Except, if the pager is in-memory only, then return an empty string if
53093 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
53094 ** used to report the filename to the user, for compatibility with legacy
53095 ** behavior. But when the Btree needs to know the filename for matching to
53096 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
53097 ** participate in shared-cache.
53098 */
53099 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
53100  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
53101 }
53102 
53103 /*
53104 ** Return the VFS structure for the pager.
53105 */
53106 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
53107  return pPager->pVfs;
53108 }
53109 
53110 /*
53111 ** Return the file handle for the database file associated
53112 ** with the pager. This might return NULL if the file has
53113 ** not yet been opened.
53114 */
53115 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
53116  return pPager->fd;
53117 }
53118 
53119 /*
53120 ** Return the file handle for the journal file (if it exists).
53121 ** This will be either the rollback journal or the WAL file.
53122 */
53124 #if SQLITE_OMIT_WAL
53125  return pPager->jfd;
53126 #else
53127  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
53128 #endif
53129 }
53130 
53131 /*
53132 ** Return the full pathname of the journal file.
53133 */
53135  return pPager->zJournal;
53136 }
53137 
53138 #ifdef SQLITE_HAS_CODEC
53139 /*
53140 ** Set or retrieve the codec for this pager
53141 */
53142 SQLITE_PRIVATE void sqlite3PagerSetCodec(
53143  Pager *pPager,
53144  void *(*xCodec)(void*,void*,Pgno,int),
53145  void (*xCodecSizeChng)(void*,int,int),
53146  void (*xCodecFree)(void*),
53147  void *pCodec
53148 ){
53149  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
53150  pPager->xCodec = pPager->memDb ? 0 : xCodec;
53151  pPager->xCodecSizeChng = xCodecSizeChng;
53152  pPager->xCodecFree = xCodecFree;
53153  pPager->pCodec = pCodec;
53154  pagerReportSize(pPager);
53155 }
53156 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
53157  return pPager->pCodec;
53158 }
53159 
53160 /*
53161 ** This function is called by the wal module when writing page content
53162 ** into the log file.
53163 **
53164 ** This function returns a pointer to a buffer containing the encrypted
53165 ** page content. If a malloc fails, this function may return NULL.
53166 */
53167 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
53168  void *aData = 0;
53169  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
53170  return aData;
53171 }
53172 
53173 /*
53174 ** Return the current pager state
53175 */
53176 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
53177  return pPager->eState;
53178 }
53179 #endif /* SQLITE_HAS_CODEC */
53180 
53181 #ifndef SQLITE_OMIT_AUTOVACUUM
53182 /*
53183 ** Move the page pPg to location pgno in the file.
53184 **
53185 ** There must be no references to the page previously located at
53186 ** pgno (which we call pPgOld) though that page is allowed to be
53187 ** in cache. If the page previously located at pgno is not already
53188 ** in the rollback journal, it is not put there by by this routine.
53189 **
53190 ** References to the page pPg remain valid. Updating any
53191 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
53192 ** allocated along with the page) is the responsibility of the caller.
53193 **
53194 ** A transaction must be active when this routine is called. It used to be
53195 ** required that a statement transaction was not active, but this restriction
53196 ** has been removed (CREATE INDEX needs to move a page when a statement
53197 ** transaction is active).
53198 **
53199 ** If the fourth argument, isCommit, is non-zero, then this page is being
53200 ** moved as part of a database reorganization just before the transaction
53201 ** is being committed. In this case, it is guaranteed that the database page
53202 ** pPg refers to will not be written to again within this transaction.
53203 **
53204 ** This function may return SQLITE_NOMEM or an IO error code if an error
53205 ** occurs. Otherwise, it returns SQLITE_OK.
53206 */
53207 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
53208  PgHdr *pPgOld; /* The page being overwritten. */
53209  Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
53210  int rc; /* Return code */
53211  Pgno origPgno; /* The original page number */
53212 
53213  assert( pPg->nRef>0 );
53214  assert( pPager->eState==PAGER_WRITER_CACHEMOD
53215  || pPager->eState==PAGER_WRITER_DBMOD
53216  );
53217  assert( assert_pager_state(pPager) );
53218 
53219  /* In order to be able to rollback, an in-memory database must journal
53220  ** the page we are moving from.
53221  */
53222  assert( pPager->tempFile || !MEMDB );
53223  if( pPager->tempFile ){
53224  rc = sqlite3PagerWrite(pPg);
53225  if( rc ) return rc;
53226  }
53227 
53228  /* If the page being moved is dirty and has not been saved by the latest
53229  ** savepoint, then save the current contents of the page into the
53230  ** sub-journal now. This is required to handle the following scenario:
53231  **
53232  ** BEGIN;
53233  ** <journal page X, then modify it in memory>
53234  ** SAVEPOINT one;
53235  ** <Move page X to location Y>
53236  ** ROLLBACK TO one;
53237  **
53238  ** If page X were not written to the sub-journal here, it would not
53239  ** be possible to restore its contents when the "ROLLBACK TO one"
53240  ** statement were is processed.
53241  **
53242  ** subjournalPage() may need to allocate space to store pPg->pgno into
53243  ** one or more savepoint bitvecs. This is the reason this function
53244  ** may return SQLITE_NOMEM.
53245  */
53246  if( (pPg->flags & PGHDR_DIRTY)!=0
53247  && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
53248  ){
53249  return rc;
53250  }
53251 
53252  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
53253  PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
53254  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
53255 
53256  /* If the journal needs to be sync()ed before page pPg->pgno can
53257  ** be written to, store pPg->pgno in local variable needSyncPgno.
53258  **
53259  ** If the isCommit flag is set, there is no need to remember that
53260  ** the journal needs to be sync()ed before database page pPg->pgno
53261  ** can be written to. The caller has already promised not to write to it.
53262  */
53263  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
53264  needSyncPgno = pPg->pgno;
53265  assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
53266  pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
53267  assert( pPg->flags&PGHDR_DIRTY );
53268  }
53269 
53270  /* If the cache contains a page with page-number pgno, remove it
53271  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
53272  ** page pgno before the 'move' operation, it needs to be retained
53273  ** for the page moved there.
53274  */
53275  pPg->flags &= ~PGHDR_NEED_SYNC;
53276  pPgOld = sqlite3PagerLookup(pPager, pgno);
53277  assert( !pPgOld || pPgOld->nRef==1 );
53278  if( pPgOld ){
53279  pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
53280  if( pPager->tempFile ){
53281  /* Do not discard pages from an in-memory database since we might
53282  ** need to rollback later. Just move the page out of the way. */
53283  sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
53284  }else{
53285  sqlite3PcacheDrop(pPgOld);
53286  }
53287  }
53288 
53289  origPgno = pPg->pgno;
53290  sqlite3PcacheMove(pPg, pgno);
53292 
53293  /* For an in-memory database, make sure the original page continues
53294  ** to exist, in case the transaction needs to roll back. Use pPgOld
53295  ** as the original page since it has already been allocated.
53296  */
53297  if( pPager->tempFile && pPgOld ){
53298  sqlite3PcacheMove(pPgOld, origPgno);
53299  sqlite3PagerUnrefNotNull(pPgOld);
53300  }
53301 
53302  if( needSyncPgno ){
53303  /* If needSyncPgno is non-zero, then the journal file needs to be
53304  ** sync()ed before any data is written to database file page needSyncPgno.
53305  ** Currently, no such page exists in the page-cache and the
53306  ** "is journaled" bitvec flag has been set. This needs to be remedied by
53307  ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
53308  ** flag.
53309  **
53310  ** If the attempt to load the page into the page-cache fails, (due
53311  ** to a malloc() or IO failure), clear the bit in the pInJournal[]
53312  ** array. Otherwise, if the page is loaded and written again in
53313  ** this transaction, it may be written to the database file before
53314  ** it is synced into the journal file. This way, it may end up in
53315  ** the journal file twice, but that is not a problem.
53316  */
53317  PgHdr *pPgHdr;
53318  rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
53319  if( rc!=SQLITE_OK ){
53320  if( needSyncPgno<=pPager->dbOrigSize ){
53321  assert( pPager->pTmpSpace!=0 );
53322  sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
53323  }
53324  return rc;
53325  }
53326  pPgHdr->flags |= PGHDR_NEED_SYNC;
53327  sqlite3PcacheMakeDirty(pPgHdr);
53328  sqlite3PagerUnrefNotNull(pPgHdr);
53329  }
53330 
53331  return SQLITE_OK;
53332 }
53333 #endif
53334 
53335 /*
53336 ** The page handle passed as the first argument refers to a dirty page
53337 ** with a page number other than iNew. This function changes the page's
53338 ** page number to iNew and sets the value of the PgHdr.flags field to
53339 ** the value passed as the third parameter.
53340 */
53341 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
53342  assert( pPg->pgno!=iNew );
53343  pPg->flags = flags;
53344  sqlite3PcacheMove(pPg, iNew);
53345 }
53346 
53347 /*
53348 ** Return a pointer to the data for the specified page.
53349 */
53351  assert( pPg->nRef>0 || pPg->pPager->memDb );
53352  return pPg->pData;
53353 }
53354 
53355 /*
53356 ** Return a pointer to the Pager.nExtra bytes of "extra" space
53357 ** allocated along with the specified page.
53358 */
53360  return pPg->pExtra;
53361 }
53362 
53363 /*
53364 ** Get/set the locking-mode for this pager. Parameter eMode must be one
53365 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
53366 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
53367 ** the locking-mode is set to the value specified.
53368 **
53369 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
53370 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
53371 ** locking-mode.
53372 */
53374  assert( eMode==PAGER_LOCKINGMODE_QUERY
53375  || eMode==PAGER_LOCKINGMODE_NORMAL
53376  || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
53377  assert( PAGER_LOCKINGMODE_QUERY<0 );
53379  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
53380  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
53381  pPager->exclusiveMode = (u8)eMode;
53382  }
53383  return (int)pPager->exclusiveMode;
53384 }
53385 
53386 /*
53387 ** Set the journal-mode for this pager. Parameter eMode must be one of:
53388 **
53389 ** PAGER_JOURNALMODE_DELETE
53390 ** PAGER_JOURNALMODE_TRUNCATE
53391 ** PAGER_JOURNALMODE_PERSIST
53392 ** PAGER_JOURNALMODE_OFF
53393 ** PAGER_JOURNALMODE_MEMORY
53394 ** PAGER_JOURNALMODE_WAL
53395 **
53396 ** The journalmode is set to the value specified if the change is allowed.
53397 ** The change may be disallowed for the following reasons:
53398 **
53399 ** * An in-memory database can only have its journal_mode set to _OFF
53400 ** or _MEMORY.
53401 **
53402 ** * Temporary databases cannot have _WAL journalmode.
53403 **
53404 ** The returned indicate the current (possibly updated) journal-mode.
53405 */
53407  u8 eOld = pPager->journalMode; /* Prior journalmode */
53408 
53409 #ifdef SQLITE_DEBUG
53410  /* The print_pager_state() routine is intended to be used by the debugger
53411  ** only. We invoke it once here to suppress a compiler warning. */
53412  print_pager_state(pPager);
53413 #endif
53414 
53415 
53416  /* The eMode parameter is always valid */
53417  assert( eMode==PAGER_JOURNALMODE_DELETE
53418  || eMode==PAGER_JOURNALMODE_TRUNCATE
53419  || eMode==PAGER_JOURNALMODE_PERSIST
53420  || eMode==PAGER_JOURNALMODE_OFF
53421  || eMode==PAGER_JOURNALMODE_WAL
53422  || eMode==PAGER_JOURNALMODE_MEMORY );
53423 
53424  /* This routine is only called from the OP_JournalMode opcode, and
53425  ** the logic there will never allow a temporary file to be changed
53426  ** to WAL mode.
53427  */
53428  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
53429 
53430  /* Do allow the journalmode of an in-memory database to be set to
53431  ** anything other than MEMORY or OFF
53432  */
53433  if( MEMDB ){
53434  assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
53435  if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
53436  eMode = eOld;
53437  }
53438  }
53439 
53440  if( eMode!=eOld ){
53441 
53442  /* Change the journal mode. */
53443  assert( pPager->eState!=PAGER_ERROR );
53444  pPager->journalMode = (u8)eMode;
53445 
53446  /* When transistioning from TRUNCATE or PERSIST to any other journal
53447  ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
53448  ** delete the journal file.
53449  */
53450  assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
53451  assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
53452  assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
53453  assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
53454  assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
53455  assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
53456 
53457  assert( isOpen(pPager->fd) || pPager->exclusiveMode );
53458  if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
53459 
53460  /* In this case we would like to delete the journal file. If it is
53461  ** not possible, then that is not a problem. Deleting the journal file
53462  ** here is an optimization only.
53463  **
53464  ** Before deleting the journal file, obtain a RESERVED lock on the
53465  ** database file. This ensures that the journal file is not deleted
53466  ** while it is in use by some other client.
53467  */
53468  sqlite3OsClose(pPager->jfd);
53469  if( pPager->eLock>=RESERVED_LOCK ){
53470  sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53471  }else{
53472  int rc = SQLITE_OK;
53473  int state = pPager->eState;
53474  assert( state==PAGER_OPEN || state==PAGER_READER );
53475  if( state==PAGER_OPEN ){
53476  rc = sqlite3PagerSharedLock(pPager);
53477  }
53478  if( pPager->eState==PAGER_READER ){
53479  assert( rc==SQLITE_OK );
53480  rc = pagerLockDb(pPager, RESERVED_LOCK);
53481  }
53482  if( rc==SQLITE_OK ){
53483  sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53484  }
53485  if( rc==SQLITE_OK && state==PAGER_READER ){
53486  pagerUnlockDb(pPager, SHARED_LOCK);
53487  }else if( state==PAGER_OPEN ){
53488  pager_unlock(pPager);
53489  }
53490  assert( state==pPager->eState );
53491  }
53492  }else if( eMode==PAGER_JOURNALMODE_OFF ){
53493  sqlite3OsClose(pPager->jfd);
53494  }
53495  }
53496 
53497  /* Return the new journal mode */
53498  return (int)pPager->journalMode;
53499 }
53500 
53501 /*
53502 ** Return the current journal mode.
53503 */
53505  return (int)pPager->journalMode;
53506 }
53507 
53508 /*
53509 ** Return TRUE if the pager is in a state where it is OK to change the
53510 ** journalmode. Journalmode changes can only happen when the database
53511 ** is unmodified.
53512 */
53514  assert( assert_pager_state(pPager) );
53515  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
53516  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
53517  return 1;
53518 }
53519 
53520 /*
53521 ** Get/set the size-limit used for persistent journal files.
53522 **
53523 ** Setting the size limit to -1 means no limit is enforced.
53524 ** An attempt to set a limit smaller than -1 is a no-op.
53525 */
53527  if( iLimit>=-1 ){
53528  pPager->journalSizeLimit = iLimit;
53529  sqlite3WalLimit(pPager->pWal, iLimit);
53530  }
53531  return pPager->journalSizeLimit;
53532 }
53533 
53534 /*
53535 ** Return a pointer to the pPager->pBackup variable. The backup module
53536 ** in backup.c maintains the content of this variable. This module
53537 ** uses it opaquely as an argument to sqlite3BackupRestart() and
53538 ** sqlite3BackupUpdate() only.
53539 */
53541  return &pPager->pBackup;
53542 }
53543 
53544 #ifndef SQLITE_OMIT_VACUUM
53545 /*
53546 ** Unless this is an in-memory or temporary database, clear the pager cache.
53547 */
53549  assert( MEMDB==0 || pPager->tempFile );
53550  if( pPager->tempFile==0 ) pager_reset(pPager);
53551 }
53552 #endif
53553 
53554 
53555 #ifndef SQLITE_OMIT_WAL
53556 /*
53557 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
53558 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
53559 ** or wal_blocking_checkpoint() API functions.
53560 **
53561 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
53562 */
53563 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
53564  int rc = SQLITE_OK;
53565  if( pPager->pWal ){
53566  rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
53567  (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
53568  pPager->pBusyHandlerArg,
53569  pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
53570  pnLog, pnCkpt
53571  );
53572  }
53573  return rc;
53574 }
53575 
53577  return sqlite3WalCallback(pPager->pWal);
53578 }
53579 
53580 /*
53581 ** Return true if the underlying VFS for the given pager supports the
53582 ** primitives necessary for write-ahead logging.
53583 */
53585  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
53586  if( pPager->noLock ) return 0;
53587  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
53588 }
53589 
53590 /*
53591 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
53592 ** is obtained instead, immediately release it.
53593 */
53594 static int pagerExclusiveLock(Pager *pPager){
53595  int rc; /* Return code */
53596 
53597  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53598  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53599  if( rc!=SQLITE_OK ){
53600  /* If the attempt to grab the exclusive lock failed, release the
53601  ** pending lock that may have been obtained instead. */
53602  pagerUnlockDb(pPager, SHARED_LOCK);
53603  }
53604 
53605  return rc;
53606 }
53607 
53608 /*
53609 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
53610 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
53611 ** lock on the database file and use heap-memory to store the wal-index
53612 ** in. Otherwise, use the normal shared-memory.
53613 */
53614 static int pagerOpenWal(Pager *pPager){
53615  int rc = SQLITE_OK;
53616 
53617  assert( pPager->pWal==0 && pPager->tempFile==0 );
53618  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53619 
53620  /* If the pager is already in exclusive-mode, the WAL module will use
53621  ** heap-memory for the wal-index instead of the VFS shared-memory
53622  ** implementation. Take the exclusive lock now, before opening the WAL
53623  ** file, to make sure this is safe.
53624  */
53625  if( pPager->exclusiveMode ){
53626  rc = pagerExclusiveLock(pPager);
53627  }
53628 
53629  /* Open the connection to the log file. If this operation fails,
53630  ** (e.g. due to malloc() failure), return an error code.
53631  */
53632  if( rc==SQLITE_OK ){
53633  rc = sqlite3WalOpen(pPager->pVfs,
53634  pPager->fd, pPager->zWal, pPager->exclusiveMode,
53635  pPager->journalSizeLimit, &pPager->pWal
53636  );
53637  }
53638  pagerFixMaplimit(pPager);
53639 
53640  return rc;
53641 }
53642 
53643 
53644 /*
53645 ** The caller must be holding a SHARED lock on the database file to call
53646 ** this function.
53647 **
53648 ** If the pager passed as the first argument is open on a real database
53649 ** file (not a temp file or an in-memory database), and the WAL file
53650 ** is not already open, make an attempt to open it now. If successful,
53651 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
53652 ** not support the xShmXXX() methods, return an error code. *pbOpen is
53653 ** not modified in either case.
53654 **
53655 ** If the pager is open on a temp-file (or in-memory database), or if
53656 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
53657 ** without doing anything.
53658 */
53660  Pager *pPager, /* Pager object */
53661  int *pbOpen /* OUT: Set to true if call is a no-op */
53662 ){
53663  int rc = SQLITE_OK; /* Return code */
53664 
53665  assert( assert_pager_state(pPager) );
53666  assert( pPager->eState==PAGER_OPEN || pbOpen );
53667  assert( pPager->eState==PAGER_READER || !pbOpen );
53668  assert( pbOpen==0 || *pbOpen==0 );
53669  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
53670 
53671  if( !pPager->tempFile && !pPager->pWal ){
53672  if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
53673 
53674  /* Close any rollback journal previously open */
53675  sqlite3OsClose(pPager->jfd);
53676 
53677  rc = pagerOpenWal(pPager);
53678  if( rc==SQLITE_OK ){
53680  pPager->eState = PAGER_OPEN;
53681  }
53682  }else{
53683  *pbOpen = 1;
53684  }
53685 
53686  return rc;
53687 }
53688 
53689 /*
53690 ** This function is called to close the connection to the log file prior
53691 ** to switching from WAL to rollback mode.
53692 **
53693 ** Before closing the log file, this function attempts to take an
53694 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
53695 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
53696 ** If successful, the EXCLUSIVE lock is not released before returning.
53697 */
53699  int rc = SQLITE_OK;
53700 
53701  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
53702 
53703  /* If the log file is not already open, but does exist in the file-system,
53704  ** it may need to be checkpointed before the connection can switch to
53705  ** rollback mode. Open it now so this can happen.
53706  */
53707  if( !pPager->pWal ){
53708  int logexists = 0;
53709  rc = pagerLockDb(pPager, SHARED_LOCK);
53710  if( rc==SQLITE_OK ){
53711  rc = sqlite3OsAccess(
53712  pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
53713  );
53714  }
53715  if( rc==SQLITE_OK && logexists ){
53716  rc = pagerOpenWal(pPager);
53717  }
53718  }
53719 
53720  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
53721  ** the database file, the log and log-summary files will be deleted.
53722  */
53723  if( rc==SQLITE_OK && pPager->pWal ){
53724  rc = pagerExclusiveLock(pPager);
53725  if( rc==SQLITE_OK ){
53726  rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
53727  pPager->pageSize, (u8*)pPager->pTmpSpace);
53728  pPager->pWal = 0;
53729  pagerFixMaplimit(pPager);
53730  if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
53731  }
53732  }
53733  return rc;
53734 }
53735 
53736 #ifdef SQLITE_ENABLE_SNAPSHOT
53737 /*
53738 ** If this is a WAL database, obtain a snapshot handle for the snapshot
53739 ** currently open. Otherwise, return an error.
53740 */
53741 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
53742  int rc = SQLITE_ERROR;
53743  if( pPager->pWal ){
53744  rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
53745  }
53746  return rc;
53747 }
53748 
53749 /*
53750 ** If this is a WAL database, store a pointer to pSnapshot. Next time a
53751 ** read transaction is opened, attempt to read from the snapshot it
53752 ** identifies. If this is not a WAL database, return an error.
53753 */
53754 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
53755  int rc = SQLITE_OK;
53756  if( pPager->pWal ){
53757  sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
53758  }else{
53759  rc = SQLITE_ERROR;
53760  }
53761  return rc;
53762 }
53763 #endif /* SQLITE_ENABLE_SNAPSHOT */
53764 #endif /* !SQLITE_OMIT_WAL */
53765 
53766 #ifdef SQLITE_ENABLE_ZIPVFS
53767 /*
53768 ** A read-lock must be held on the pager when this function is called. If
53769 ** the pager is in WAL mode and the WAL file currently contains one or more
53770 ** frames, return the size in bytes of the page images stored within the
53771 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
53772 ** is empty, return 0.
53773 */
53774 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
53775  assert( pPager->eState>=PAGER_READER );
53776  return sqlite3WalFramesize(pPager->pWal);
53777 }
53778 #endif
53779 
53780 #endif /* SQLITE_OMIT_DISKIO */
53781 
53782 /************** End of pager.c ***********************************************/
53783 /************** Begin file wal.c *********************************************/
53784 /*
53785 ** 2010 February 1
53786 **
53787 ** The author disclaims copyright to this source code. In place of
53788 ** a legal notice, here is a blessing:
53789 **
53790 ** May you do good and not evil.
53791 ** May you find forgiveness for yourself and forgive others.
53792 ** May you share freely, never taking more than you give.
53793 **
53794 *************************************************************************
53795 **
53796 ** This file contains the implementation of a write-ahead log (WAL) used in
53797 ** "journal_mode=WAL" mode.
53798 **
53799 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
53800 **
53801 ** A WAL file consists of a header followed by zero or more "frames".
53802 ** Each frame records the revised content of a single page from the
53803 ** database file. All changes to the database are recorded by writing
53804 ** frames into the WAL. Transactions commit when a frame is written that
53805 ** contains a commit marker. A single WAL can and usually does record
53806 ** multiple transactions. Periodically, the content of the WAL is
53807 ** transferred back into the database file in an operation called a
53808 ** "checkpoint".
53809 **
53810 ** A single WAL file can be used multiple times. In other words, the
53811 ** WAL can fill up with frames and then be checkpointed and then new
53812 ** frames can overwrite the old ones. A WAL always grows from beginning
53813 ** toward the end. Checksums and counters attached to each frame are
53814 ** used to determine which frames within the WAL are valid and which
53815 ** are leftovers from prior checkpoints.
53816 **
53817 ** The WAL header is 32 bytes in size and consists of the following eight
53818 ** big-endian 32-bit unsigned integer values:
53819 **
53820 ** 0: Magic number. 0x377f0682 or 0x377f0683
53821 ** 4: File format version. Currently 3007000
53822 ** 8: Database page size. Example: 1024
53823 ** 12: Checkpoint sequence number
53824 ** 16: Salt-1, random integer incremented with each checkpoint
53825 ** 20: Salt-2, a different random integer changing with each ckpt
53826 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
53827 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
53828 **
53829 ** Immediately following the wal-header are zero or more frames. Each
53830 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
53831 ** of page data. The frame-header is six big-endian 32-bit unsigned
53832 ** integer values, as follows:
53833 **
53834 ** 0: Page number.
53835 ** 4: For commit records, the size of the database image in pages
53836 ** after the commit. For all other records, zero.
53837 ** 8: Salt-1 (copied from the header)
53838 ** 12: Salt-2 (copied from the header)
53839 ** 16: Checksum-1.
53840 ** 20: Checksum-2.
53841 **
53842 ** A frame is considered valid if and only if the following conditions are
53843 ** true:
53844 **
53845 ** (1) The salt-1 and salt-2 values in the frame-header match
53846 ** salt values in the wal-header
53847 **
53848 ** (2) The checksum values in the final 8 bytes of the frame-header
53849 ** exactly match the checksum computed consecutively on the
53850 ** WAL header and the first 8 bytes and the content of all frames
53851 ** up to and including the current frame.
53852 **
53853 ** The checksum is computed using 32-bit big-endian integers if the
53854 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
53855 ** is computed using little-endian if the magic number is 0x377f0682.
53856 ** The checksum values are always stored in the frame header in a
53857 ** big-endian format regardless of which byte order is used to compute
53858 ** the checksum. The checksum is computed by interpreting the input as
53859 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
53860 ** algorithm used for the checksum is as follows:
53861 **
53862 ** for i from 0 to n-1 step 2:
53863 ** s0 += x[i] + s1;
53864 ** s1 += x[i+1] + s0;
53865 ** endfor
53866 **
53867 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
53868 ** in reverse order (the largest fibonacci weight occurs on the first element
53869 ** of the sequence being summed.) The s1 value spans all 32-bit
53870 ** terms of the sequence whereas s0 omits the final term.
53871 **
53872 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
53873 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
53874 ** The VFS.xSync operations serve as write barriers - all writes launched
53875 ** before the xSync must complete before any write that launches after the
53876 ** xSync begins.
53877 **
53878 ** After each checkpoint, the salt-1 value is incremented and the salt-2
53879 ** value is randomized. This prevents old and new frames in the WAL from
53880 ** being considered valid at the same time and being checkpointing together
53881 ** following a crash.
53882 **
53883 ** READER ALGORITHM
53884 **
53885 ** To read a page from the database (call it page number P), a reader
53886 ** first checks the WAL to see if it contains page P. If so, then the
53887 ** last valid instance of page P that is a followed by a commit frame
53888 ** or is a commit frame itself becomes the value read. If the WAL
53889 ** contains no copies of page P that are valid and which are a commit
53890 ** frame or are followed by a commit frame, then page P is read from
53891 ** the database file.
53892 **
53893 ** To start a read transaction, the reader records the index of the last
53894 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
53895 ** for all subsequent read operations. New transactions can be appended
53896 ** to the WAL, but as long as the reader uses its original mxFrame value
53897 ** and ignores the newly appended content, it will see a consistent snapshot
53898 ** of the database from a single point in time. This technique allows
53899 ** multiple concurrent readers to view different versions of the database
53900 ** content simultaneously.
53901 **
53902 ** The reader algorithm in the previous paragraphs works correctly, but
53903 ** because frames for page P can appear anywhere within the WAL, the
53904 ** reader has to scan the entire WAL looking for page P frames. If the
53905 ** WAL is large (multiple megabytes is typical) that scan can be slow,
53906 ** and read performance suffers. To overcome this problem, a separate
53907 ** data structure called the wal-index is maintained to expedite the
53908 ** search for frames of a particular page.
53909 **
53910 ** WAL-INDEX FORMAT
53911 **
53912 ** Conceptually, the wal-index is shared memory, though VFS implementations
53913 ** might choose to implement the wal-index using a mmapped file. Because
53914 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
53915 ** on a network filesystem. All users of the database must be able to
53916 ** share memory.
53917 **
53918 ** The wal-index is transient. After a crash, the wal-index can (and should
53919 ** be) reconstructed from the original WAL file. In fact, the VFS is required
53920 ** to either truncate or zero the header of the wal-index when the last
53921 ** connection to it closes. Because the wal-index is transient, it can
53922 ** use an architecture-specific format; it does not have to be cross-platform.
53923 ** Hence, unlike the database and WAL file formats which store all values
53924 ** as big endian, the wal-index can store multi-byte values in the native
53925 ** byte order of the host computer.
53926 **
53927 ** The purpose of the wal-index is to answer this question quickly: Given
53928 ** a page number P and a maximum frame index M, return the index of the
53929 ** last frame in the wal before frame M for page P in the WAL, or return
53930 ** NULL if there are no frames for page P in the WAL prior to M.
53931 **
53932 ** The wal-index consists of a header region, followed by an one or
53933 ** more index blocks.
53934 **
53935 ** The wal-index header contains the total number of frames within the WAL
53936 ** in the mxFrame field.
53937 **
53938 ** Each index block except for the first contains information on
53939 ** HASHTABLE_NPAGE frames. The first index block contains information on
53940 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
53941 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
53942 ** first index block are the same size as all other index blocks in the
53943 ** wal-index.
53944 **
53945 ** Each index block contains two sections, a page-mapping that contains the
53946 ** database page number associated with each wal frame, and a hash-table
53947 ** that allows readers to query an index block for a specific page number.
53948 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
53949 ** for the first index block) 32-bit page numbers. The first entry in the
53950 ** first index-block contains the database page number corresponding to the
53951 ** first frame in the WAL file. The first entry in the second index block
53952 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
53953 ** the log, and so on.
53954 **
53955 ** The last index block in a wal-index usually contains less than the full
53956 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
53957 ** depending on the contents of the WAL file. This does not change the
53958 ** allocated size of the page-mapping array - the page-mapping array merely
53959 ** contains unused entries.
53960 **
53961 ** Even without using the hash table, the last frame for page P
53962 ** can be found by scanning the page-mapping sections of each index block
53963 ** starting with the last index block and moving toward the first, and
53964 ** within each index block, starting at the end and moving toward the
53965 ** beginning. The first entry that equals P corresponds to the frame
53966 ** holding the content for that page.
53967 **
53968 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
53969 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
53970 ** hash table for each page number in the mapping section, so the hash
53971 ** table is never more than half full. The expected number of collisions
53972 ** prior to finding a match is 1. Each entry of the hash table is an
53973 ** 1-based index of an entry in the mapping section of the same
53974 ** index block. Let K be the 1-based index of the largest entry in
53975 ** the mapping section. (For index blocks other than the last, K will
53976 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
53977 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
53978 ** contain a value of 0.
53979 **
53980 ** To look for page P in the hash table, first compute a hash iKey on
53981 ** P as follows:
53982 **
53983 ** iKey = (P * 383) % HASHTABLE_NSLOT
53984 **
53985 ** Then start scanning entries of the hash table, starting with iKey
53986 ** (wrapping around to the beginning when the end of the hash table is
53987 ** reached) until an unused hash slot is found. Let the first unused slot
53988 ** be at index iUnused. (iUnused might be less than iKey if there was
53989 ** wrap-around.) Because the hash table is never more than half full,
53990 ** the search is guaranteed to eventually hit an unused entry. Let
53991 ** iMax be the value between iKey and iUnused, closest to iUnused,
53992 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
53993 ** no hash slot such that aHash[i]==p) then page P is not in the
53994 ** current index block. Otherwise the iMax-th mapping entry of the
53995 ** current index block corresponds to the last entry that references
53996 ** page P.
53997 **
53998 ** A hash search begins with the last index block and moves toward the
53999 ** first index block, looking for entries corresponding to page P. On
54000 ** average, only two or three slots in each index block need to be
54001 ** examined in order to either find the last entry for page P, or to
54002 ** establish that no such entry exists in the block. Each index block
54003 ** holds over 4000 entries. So two or three index blocks are sufficient
54004 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
54005 ** comparisons (on average) suffice to either locate a frame in the
54006 ** WAL or to establish that the frame does not exist in the WAL. This
54007 ** is much faster than scanning the entire 10MB WAL.
54008 **
54009 ** Note that entries are added in order of increasing K. Hence, one
54010 ** reader might be using some value K0 and a second reader that started
54011 ** at a later time (after additional transactions were added to the WAL
54012 ** and to the wal-index) might be using a different value K1, where K1>K0.
54013 ** Both readers can use the same hash table and mapping section to get
54014 ** the correct result. There may be entries in the hash table with
54015 ** K>K0 but to the first reader, those entries will appear to be unused
54016 ** slots in the hash table and so the first reader will get an answer as
54017 ** if no values greater than K0 had ever been inserted into the hash table
54018 ** in the first place - which is what reader one wants. Meanwhile, the
54019 ** second reader using K1 will see additional values that were inserted
54020 ** later, which is exactly what reader two wants.
54021 **
54022 ** When a rollback occurs, the value of K is decreased. Hash table entries
54023 ** that correspond to frames greater than the new K value are removed
54024 ** from the hash table at this point.
54025 */
54026 #ifndef SQLITE_OMIT_WAL
54027 
54028 /* #include "wal.h" */
54029 
54030 /*
54031 ** Trace output macros
54032 */
54033 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54034 SQLITE_PRIVATE int sqlite3WalTrace = 0;
54035 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
54036 #else
54037 # define WALTRACE(X)
54038 #endif
54039 
54040 /*
54041 ** The maximum (and only) versions of the wal and wal-index formats
54042 ** that may be interpreted by this version of SQLite.
54043 **
54044 ** If a client begins recovering a WAL file and finds that (a) the checksum
54045 ** values in the wal-header are correct and (b) the version field is not
54046 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
54047 **
54048 ** Similarly, if a client successfully reads a wal-index header (i.e. the
54049 ** checksum test is successful) and finds that the version field is not
54050 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
54051 ** returns SQLITE_CANTOPEN.
54052 */
54053 #define WAL_MAX_VERSION 3007000
54054 #define WALINDEX_MAX_VERSION 3007000
54055 
54056 /*
54057 ** Indices of various locking bytes. WAL_NREADER is the number
54058 ** of available reader locks and should be at least 3. The default
54059 ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
54060 */
54061 #define WAL_WRITE_LOCK 0
54062 #define WAL_ALL_BUT_WRITE 1
54063 #define WAL_CKPT_LOCK 1
54064 #define WAL_RECOVER_LOCK 2
54065 #define WAL_READ_LOCK(I) (3+(I))
54066 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
54067 
54068 
54069 /* Object declarations */
54070 typedef struct WalIndexHdr WalIndexHdr;
54071 typedef struct WalIterator WalIterator;
54072 typedef struct WalCkptInfo WalCkptInfo;
54073 
54074 
54075 /*
54076 ** The following object holds a copy of the wal-index header content.
54077 **
54078 ** The actual header in the wal-index consists of two copies of this
54079 ** object followed by one instance of the WalCkptInfo object.
54080 ** For all versions of SQLite through 3.10.0 and probably beyond,
54081 ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
54082 ** the total header size is 136 bytes.
54083 **
54084 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
54085 ** Or it can be 1 to represent a 65536-byte page. The latter case was
54086 ** added in 3.7.1 when support for 64K pages was added.
54087 */
54088 struct WalIndexHdr {
54089  u32 iVersion; /* Wal-index version */
54090  u32 unused; /* Unused (padding) field */
54091  u32 iChange; /* Counter incremented each transaction */
54092  u8 isInit; /* 1 when initialized */
54093  u8 bigEndCksum; /* True if checksums in WAL are big-endian */
54094  u16 szPage; /* Database page size in bytes. 1==64K */
54095  u32 mxFrame; /* Index of last valid frame in the WAL */
54096  u32 nPage; /* Size of database in pages */
54097  u32 aFrameCksum[2]; /* Checksum of last frame in log */
54098  u32 aSalt[2]; /* Two salt values copied from WAL header */
54099  u32 aCksum[2]; /* Checksum over all prior fields */
54100 };
54101 
54102 /*
54103 ** A copy of the following object occurs in the wal-index immediately
54104 ** following the second copy of the WalIndexHdr. This object stores
54105 ** information used by checkpoint.
54106 **
54107 ** nBackfill is the number of frames in the WAL that have been written
54108 ** back into the database. (We call the act of moving content from WAL to
54109 ** database "backfilling".) The nBackfill number is never greater than
54110 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
54111 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
54112 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
54113 ** mxFrame back to zero when the WAL is reset.
54114 **
54115 ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
54116 ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
54117 ** the nBackfillAttempted is set before any backfilling is done and the
54118 ** nBackfill is only set after all backfilling completes. So if a checkpoint
54119 ** crashes, nBackfillAttempted might be larger than nBackfill. The
54120 ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
54121 **
54122 ** The aLock[] field is a set of bytes used for locking. These bytes should
54123 ** never be read or written.
54124 **
54125 ** There is one entry in aReadMark[] for each reader lock. If a reader
54126 ** holds read-lock K, then the value in aReadMark[K] is no greater than
54127 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
54128 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
54129 ** a special case; its value is never used and it exists as a place-holder
54130 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
54131 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
54132 ** directly from the database.
54133 **
54134 ** The value of aReadMark[K] may only be changed by a thread that
54135 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
54136 ** aReadMark[K] cannot changed while there is a reader is using that mark
54137 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
54138 **
54139 ** The checkpointer may only transfer frames from WAL to database where
54140 ** the frame numbers are less than or equal to every aReadMark[] that is
54141 ** in use (that is, every aReadMark[j] for which there is a corresponding
54142 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
54143 ** largest value and will increase an unused aReadMark[] to mxFrame if there
54144 ** is not already an aReadMark[] equal to mxFrame. The exception to the
54145 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
54146 ** in the WAL has been backfilled into the database) then new readers
54147 ** will choose aReadMark[0] which has value 0 and hence such reader will
54148 ** get all their all content directly from the database file and ignore
54149 ** the WAL.
54150 **
54151 ** Writers normally append new frames to the end of the WAL. However,
54152 ** if nBackfill equals mxFrame (meaning that all WAL content has been
54153 ** written back into the database) and if no readers are using the WAL
54154 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
54155 ** the writer will first "reset" the WAL back to the beginning and start
54156 ** writing new content beginning at frame 1.
54157 **
54158 ** We assume that 32-bit loads are atomic and so no locks are needed in
54159 ** order to read from any aReadMark[] entries.
54160 */
54161 struct WalCkptInfo {
54162  u32 nBackfill; /* Number of WAL frames backfilled into DB */
54163  u32 aReadMark[WAL_NREADER]; /* Reader marks */
54164  u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
54165  u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
54166  u32 notUsed0; /* Available for future enhancements */
54167 };
54168 #define READMARK_NOT_USED 0xffffffff
54169 
54170 
54171 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
54172 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
54173 ** only support mandatory file-locks, we do not read or write data
54174 ** from the region of the file on which locks are applied.
54175 */
54176 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
54177 #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
54178 
54179 /* Size of header before each frame in wal */
54180 #define WAL_FRAME_HDRSIZE 24
54181 
54182 /* Size of write ahead log header, including checksum. */
54183 /* #define WAL_HDRSIZE 24 */
54184 #define WAL_HDRSIZE 32
54185 
54186 /* WAL magic value. Either this value, or the same value with the least
54187 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
54188 ** big-endian format in the first 4 bytes of a WAL file.
54189 **
54190 ** If the LSB is set, then the checksums for each frame within the WAL
54191 ** file are calculated by treating all data as an array of 32-bit
54192 ** big-endian words. Otherwise, they are calculated by interpreting
54193 ** all data as 32-bit little-endian words.
54194 */
54195 #define WAL_MAGIC 0x377f0682
54196 
54197 /*
54198 ** Return the offset of frame iFrame in the write-ahead log file,
54199 ** assuming a database page size of szPage bytes. The offset returned
54200 ** is to the start of the write-ahead log frame-header.
54201 */
54202 #define walFrameOffset(iFrame, szPage) ( \
54203  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
54204 )
54205 
54206 /*
54207 ** An open write-ahead log file is represented by an instance of the
54208 ** following object.
54209 */
54210 struct Wal {
54211  sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
54212  sqlite3_file *pDbFd; /* File handle for the database file */
54213  sqlite3_file *pWalFd; /* File handle for WAL file */
54214  u32 iCallback; /* Value to pass to log callback (or 0) */
54215  i64 mxWalSize; /* Truncate WAL to this size upon reset */
54216  int nWiData; /* Size of array apWiData */
54217  int szFirstBlock; /* Size of first block written to WAL file */
54218  volatile u32 **apWiData; /* Pointer to wal-index content in memory */
54219  u32 szPage; /* Database page size */
54220  i16 readLock; /* Which read lock is being held. -1 for none */
54221  u8 syncFlags; /* Flags to use to sync header writes */
54222  u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
54223  u8 writeLock; /* True if in a write transaction */
54224  u8 ckptLock; /* True if holding a checkpoint lock */
54225  u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
54226  u8 truncateOnCommit; /* True to truncate WAL file on commit */
54227  u8 syncHeader; /* Fsync the WAL header if true */
54228  u8 padToSectorBoundary; /* Pad transactions out to the next sector */
54229  WalIndexHdr hdr; /* Wal-index header for current transaction */
54230  u32 minFrame; /* Ignore wal frames before this one */
54231  u32 iReCksum; /* On commit, recalculate checksums from here */
54232  const char *zWalName; /* Name of WAL file */
54233  u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
54234 #ifdef SQLITE_DEBUG
54235  u8 lockError; /* True if a locking error has occurred */
54236 #endif
54237 #ifdef SQLITE_ENABLE_SNAPSHOT
54238  WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
54239 #endif
54240 };
54241 
54242 /*
54243 ** Candidate values for Wal.exclusiveMode.
54244 */
54245 #define WAL_NORMAL_MODE 0
54246 #define WAL_EXCLUSIVE_MODE 1
54247 #define WAL_HEAPMEMORY_MODE 2
54248 
54249 /*
54250 ** Possible values for WAL.readOnly
54251 */
54252 #define WAL_RDWR 0 /* Normal read/write connection */
54253 #define WAL_RDONLY 1 /* The WAL file is readonly */
54254 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
54255 
54256 /*
54257 ** Each page of the wal-index mapping contains a hash-table made up of
54258 ** an array of HASHTABLE_NSLOT elements of the following type.
54259 */
54260 typedef u16 ht_slot;
54261 
54262 /*
54263 ** This structure is used to implement an iterator that loops through
54264 ** all frames in the WAL in database page order. Where two or more frames
54265 ** correspond to the same database page, the iterator visits only the
54266 ** frame most recently written to the WAL (in other words, the frame with
54267 ** the largest index).
54268 **
54269 ** The internals of this structure are only accessed by:
54270 **
54271 ** walIteratorInit() - Create a new iterator,
54272 ** walIteratorNext() - Step an iterator,
54273 ** walIteratorFree() - Free an iterator.
54274 **
54275 ** This functionality is used by the checkpoint code (see walCheckpoint()).
54276 */
54277 struct WalIterator {
54278  int iPrior; /* Last result returned from the iterator */
54279  int nSegment; /* Number of entries in aSegment[] */
54280  struct WalSegment {
54281  int iNext; /* Next slot in aIndex[] not yet returned */
54282  ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
54283  u32 *aPgno; /* Array of page numbers. */
54284  int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
54285  int iZero; /* Frame number associated with aPgno[0] */
54286  } aSegment[1]; /* One for every 32KB page in the wal-index */
54287 };
54288 
54289 /*
54290 ** Define the parameters of the hash tables in the wal-index file. There
54291 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
54292 ** wal-index.
54293 **
54294 ** Changing any of these constants will alter the wal-index format and
54295 ** create incompatibilities.
54296 */
54297 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
54298 #define HASHTABLE_HASH_1 383 /* Should be prime */
54299 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
54300 
54301 /*
54302 ** The block of page numbers associated with the first hash-table in a
54303 ** wal-index is smaller than usual. This is so that there is a complete
54304 ** hash-table on each aligned 32KB page of the wal-index.
54305 */
54306 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
54307 
54308 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
54309 #define WALINDEX_PGSZ ( \
54310  sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
54311 )
54312 
54313 /*
54314 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
54315 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
54316 ** numbered from zero.
54317 **
54318 ** If this call is successful, *ppPage is set to point to the wal-index
54319 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
54320 ** then an SQLite error code is returned and *ppPage is set to 0.
54321 */
54322 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
54323  int rc = SQLITE_OK;
54324 
54325  /* Enlarge the pWal->apWiData[] array if required */
54326  if( pWal->nWiData<=iPage ){
54327  int nByte = sizeof(u32*)*(iPage+1);
54328  volatile u32 **apNew;
54329  apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
54330  if( !apNew ){
54331  *ppPage = 0;
54332  return SQLITE_NOMEM_BKPT;
54333  }
54334  memset((void*)&apNew[pWal->nWiData], 0,
54335  sizeof(u32*)*(iPage+1-pWal->nWiData));
54336  pWal->apWiData = apNew;
54337  pWal->nWiData = iPage+1;
54338  }
54339 
54340  /* Request a pointer to the required page from the VFS */
54341  if( pWal->apWiData[iPage]==0 ){
54342  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54343  pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
54344  if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
54345  }else{
54346  rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
54347  pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
54348  );
54349  if( rc==SQLITE_READONLY ){
54350  pWal->readOnly |= WAL_SHM_RDONLY;
54351  rc = SQLITE_OK;
54352  }
54353  }
54354  }
54355 
54356  *ppPage = pWal->apWiData[iPage];
54357  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
54358  return rc;
54359 }
54360 
54361 /*
54362 ** Return a pointer to the WalCkptInfo structure in the wal-index.
54363 */
54364 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
54365  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54366  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
54367 }
54368 
54369 /*
54370 ** Return a pointer to the WalIndexHdr structure in the wal-index.
54371 */
54372 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
54373  assert( pWal->nWiData>0 && pWal->apWiData[0] );
54374  return (volatile WalIndexHdr*)pWal->apWiData[0];
54375 }
54376 
54377 /*
54378 ** The argument to this macro must be of type u32. On a little-endian
54379 ** architecture, it returns the u32 value that results from interpreting
54380 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
54381 ** returns the value that would be produced by interpreting the 4 bytes
54382 ** of the input value as a little-endian integer.
54383 */
54384 #define BYTESWAP32(x) ( \
54385  (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
54386  + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
54387 )
54388 
54389 /*
54390 ** Generate or extend an 8 byte checksum based on the data in
54391 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
54392 ** initial values of 0 and 0 if aIn==NULL).
54393 **
54394 ** The checksum is written back into aOut[] before returning.
54395 **
54396 ** nByte must be a positive multiple of 8.
54397 */
54398 static void walChecksumBytes(
54399  int nativeCksum, /* True for native byte-order, false for non-native */
54400  u8 *a, /* Content to be checksummed */
54401  int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
54402  const u32 *aIn, /* Initial checksum value input */
54403  u32 *aOut /* OUT: Final checksum value output */
54404 ){
54405  u32 s1, s2;
54406  u32 *aData = (u32 *)a;
54407  u32 *aEnd = (u32 *)&a[nByte];
54408 
54409  if( aIn ){
54410  s1 = aIn[0];
54411  s2 = aIn[1];
54412  }else{
54413  s1 = s2 = 0;
54414  }
54415 
54416  assert( nByte>=8 );
54417  assert( (nByte&0x00000007)==0 );
54418 
54419  if( nativeCksum ){
54420  do {
54421  s1 += *aData++ + s2;
54422  s2 += *aData++ + s1;
54423  }while( aData<aEnd );
54424  }else{
54425  do {
54426  s1 += BYTESWAP32(aData[0]) + s2;
54427  s2 += BYTESWAP32(aData[1]) + s1;
54428  aData += 2;
54429  }while( aData<aEnd );
54430  }
54431 
54432  aOut[0] = s1;
54433  aOut[1] = s2;
54434 }
54435 
54436 static void walShmBarrier(Wal *pWal){
54437  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
54438  sqlite3OsShmBarrier(pWal->pDbFd);
54439  }
54440 }
54441 
54442 /*
54443 ** Write the header information in pWal->hdr into the wal-index.
54444 **
54445 ** The checksum on pWal->hdr is updated before it is written.
54446 */
54447 static void walIndexWriteHdr(Wal *pWal){
54448  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
54449  const int nCksum = offsetof(WalIndexHdr, aCksum);
54450 
54451  assert( pWal->writeLock );
54452  pWal->hdr.isInit = 1;
54454  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
54455  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54456  walShmBarrier(pWal);
54457  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54458 }
54459 
54460 /*
54461 ** This function encodes a single frame header and writes it to a buffer
54462 ** supplied by the caller. A frame-header is made up of a series of
54463 ** 4-byte big-endian integers, as follows:
54464 **
54465 ** 0: Page number.
54466 ** 4: For commit records, the size of the database image in pages
54467 ** after the commit. For all other records, zero.
54468 ** 8: Salt-1 (copied from the wal-header)
54469 ** 12: Salt-2 (copied from the wal-header)
54470 ** 16: Checksum-1.
54471 ** 20: Checksum-2.
54472 */
54473 static void walEncodeFrame(
54474  Wal *pWal, /* The write-ahead log */
54475  u32 iPage, /* Database page number for frame */
54476  u32 nTruncate, /* New db size (or 0 for non-commit frames) */
54477  u8 *aData, /* Pointer to page data */
54478  u8 *aFrame /* OUT: Write encoded frame here */
54479 ){
54480  int nativeCksum; /* True for native byte-order checksums */
54481  u32 *aCksum = pWal->hdr.aFrameCksum;
54482  assert( WAL_FRAME_HDRSIZE==24 );
54483  sqlite3Put4byte(&aFrame[0], iPage);
54484  sqlite3Put4byte(&aFrame[4], nTruncate);
54485  if( pWal->iReCksum==0 ){
54486  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
54487 
54488  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54489  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54490  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54491 
54492  sqlite3Put4byte(&aFrame[16], aCksum[0]);
54493  sqlite3Put4byte(&aFrame[20], aCksum[1]);
54494  }else{
54495  memset(&aFrame[8], 0, 16);
54496  }
54497 }
54498 
54499 /*
54500 ** Check to see if the frame with header in aFrame[] and content
54501 ** in aData[] is valid. If it is a valid frame, fill *piPage and
54502 ** *pnTruncate and return true. Return if the frame is not valid.
54503 */
54504 static int walDecodeFrame(
54505  Wal *pWal, /* The write-ahead log */
54506  u32 *piPage, /* OUT: Database page number for frame */
54507  u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
54508  u8 *aData, /* Pointer to page data (for checksum) */
54509  u8 *aFrame /* Frame data */
54510 ){
54511  int nativeCksum; /* True for native byte-order checksums */
54512  u32 *aCksum = pWal->hdr.aFrameCksum;
54513  u32 pgno; /* Page number of the frame */
54514  assert( WAL_FRAME_HDRSIZE==24 );
54515 
54516  /* A frame is only valid if the salt values in the frame-header
54517  ** match the salt values in the wal-header.
54518  */
54519  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
54520  return 0;
54521  }
54522 
54523  /* A frame is only valid if the page number is creater than zero.
54524  */
54525  pgno = sqlite3Get4byte(&aFrame[0]);
54526  if( pgno==0 ){
54527  return 0;
54528  }
54529 
54530  /* A frame is only valid if a checksum of the WAL header,
54531  ** all prior frams, the first 16 bytes of this frame-header,
54532  ** and the frame-data matches the checksum in the last 8
54533  ** bytes of this frame-header.
54534  */
54535  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54536  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54537  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54538  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
54539  || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
54540  ){
54541  /* Checksum failed. */
54542  return 0;
54543  }
54544 
54545  /* If we reach this point, the frame is valid. Return the page number
54546  ** and the new database size.
54547  */
54548  *piPage = pgno;
54549  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
54550  return 1;
54551 }
54552 
54553 
54554 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54555 /*
54556 ** Names of locks. This routine is used to provide debugging output and is not
54557 ** a part of an ordinary build.
54558 */
54559 static const char *walLockName(int lockIdx){
54560  if( lockIdx==WAL_WRITE_LOCK ){
54561  return "WRITE-LOCK";
54562  }else if( lockIdx==WAL_CKPT_LOCK ){
54563  return "CKPT-LOCK";
54564  }else if( lockIdx==WAL_RECOVER_LOCK ){
54565  return "RECOVER-LOCK";
54566  }else{
54567  static char zName[15];
54568  sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
54569  lockIdx-WAL_READ_LOCK(0));
54570  return zName;
54571  }
54572 }
54573 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
54574 
54575 
54576 /*
54577 ** Set or release locks on the WAL. Locks are either shared or exclusive.
54578 ** A lock cannot be moved directly between shared and exclusive - it must go
54579 ** through the unlocked state first.
54580 **
54581 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
54582 */
54583 static int walLockShared(Wal *pWal, int lockIdx){
54584  int rc;
54585  if( pWal->exclusiveMode ) return SQLITE_OK;
54586  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54588  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
54589  walLockName(lockIdx), rc ? "failed" : "ok"));
54590  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54591  return rc;
54592 }
54593 static void walUnlockShared(Wal *pWal, int lockIdx){
54594  if( pWal->exclusiveMode ) return;
54595  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54597  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
54598 }
54599 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
54600  int rc;
54601  if( pWal->exclusiveMode ) return SQLITE_OK;
54602  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54604  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
54605  walLockName(lockIdx), n, rc ? "failed" : "ok"));
54606  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54607  return rc;
54608 }
54609 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
54610  if( pWal->exclusiveMode ) return;
54611  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54613  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
54614  walLockName(lockIdx), n));
54615 }
54616 
54617 /*
54618 ** Compute a hash on a page number. The resulting hash value must land
54619 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
54620 ** the hash to the next value in the event of a collision.
54621 */
54622 static int walHash(u32 iPage){
54623  assert( iPage>0 );
54624  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
54625  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
54626 }
54627 static int walNextHash(int iPriorHash){
54628  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
54629 }
54630 
54631 /*
54632 ** Return pointers to the hash table and page number array stored on
54633 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
54634 ** numbered starting from 0.
54635 **
54636 ** Set output variable *paHash to point to the start of the hash table
54637 ** in the wal-index file. Set *piZero to one less than the frame
54638 ** number of the first frame indexed by this hash table. If a
54639 ** slot in the hash table is set to N, it refers to frame number
54640 ** (*piZero+N) in the log.
54641 **
54642 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
54643 ** first frame indexed by the hash table, frame (*piZero+1).
54644 */
54645 static int walHashGet(
54646  Wal *pWal, /* WAL handle */
54647  int iHash, /* Find the iHash'th table */
54648  volatile ht_slot **paHash, /* OUT: Pointer to hash index */
54649  volatile u32 **paPgno, /* OUT: Pointer to page number array */
54650  u32 *piZero /* OUT: Frame associated with *paPgno[0] */
54651 ){
54652  int rc; /* Return code */
54653  volatile u32 *aPgno;
54654 
54655  rc = walIndexPage(pWal, iHash, &aPgno);
54656  assert( rc==SQLITE_OK || iHash>0 );
54657 
54658  if( rc==SQLITE_OK ){
54659  u32 iZero;
54660  volatile ht_slot *aHash;
54661 
54662  aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
54663  if( iHash==0 ){
54664  aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
54665  iZero = 0;
54666  }else{
54667  iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
54668  }
54669 
54670  *paPgno = &aPgno[-1];
54671  *paHash = aHash;
54672  *piZero = iZero;
54673  }
54674  return rc;
54675 }
54676 
54677 /*
54678 ** Return the number of the wal-index page that contains the hash-table
54679 ** and page-number array that contain entries corresponding to WAL frame
54680 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
54681 ** are numbered starting from 0.
54682 */
54683 static int walFramePage(u32 iFrame){
54684  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
54685  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
54686  && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
54687  && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
54688  && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
54689  && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
54690  );
54691  return iHash;
54692 }
54693 
54694 /*
54695 ** Return the page number associated with frame iFrame in this WAL.
54696 */
54697 static u32 walFramePgno(Wal *pWal, u32 iFrame){
54698  int iHash = walFramePage(iFrame);
54699  if( iHash==0 ){
54700  return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
54701  }
54702  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
54703 }
54704 
54705 /*
54706 ** Remove entries from the hash table that point to WAL slots greater
54707 ** than pWal->hdr.mxFrame.
54708 **
54709 ** This function is called whenever pWal->hdr.mxFrame is decreased due
54710 ** to a rollback or savepoint.
54711 **
54712 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
54713 ** updated. Any later hash tables will be automatically cleared when
54714 ** pWal->hdr.mxFrame advances to the point where those hash tables are
54715 ** actually needed.
54716 */
54717 static void walCleanupHash(Wal *pWal){
54718  volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
54719  volatile u32 *aPgno = 0; /* Page number array for hash table */
54720  u32 iZero = 0; /* frame == (aHash[x]+iZero) */
54721  int iLimit = 0; /* Zero values greater than this */
54722  int nByte; /* Number of bytes to zero in aPgno[] */
54723  int i; /* Used to iterate through aHash[] */
54724 
54725  assert( pWal->writeLock );
54729 
54730  if( pWal->hdr.mxFrame==0 ) return;
54731 
54732  /* Obtain pointers to the hash-table and page-number array containing
54733  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
54734  ** that the page said hash-table and array reside on is already mapped.
54735  */
54736  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
54737  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
54738  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
54739 
54740  /* Zero all hash-table entries that correspond to frame numbers greater
54741  ** than pWal->hdr.mxFrame.
54742  */
54743  iLimit = pWal->hdr.mxFrame - iZero;
54744  assert( iLimit>0 );
54745  for(i=0; i<HASHTABLE_NSLOT; i++){
54746  if( aHash[i]>iLimit ){
54747  aHash[i] = 0;
54748  }
54749  }
54750 
54751  /* Zero the entries in the aPgno array that correspond to frames with
54752  ** frame numbers greater than pWal->hdr.mxFrame.
54753  */
54754  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
54755  memset((void *)&aPgno[iLimit+1], 0, nByte);
54756 
54757 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54758  /* Verify that the every entry in the mapping region is still reachable
54759  ** via the hash table even after the cleanup.
54760  */
54761  if( iLimit ){
54762  int j; /* Loop counter */
54763  int iKey; /* Hash key */
54764  for(j=1; j<=iLimit; j++){
54765  for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
54766  if( aHash[iKey]==j ) break;
54767  }
54768  assert( aHash[iKey]==j );
54769  }
54770  }
54771 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54772 }
54773 
54774 
54775 /*
54776 ** Set an entry in the wal-index that will map database page number
54777 ** pPage into WAL frame iFrame.
54778 */
54779 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
54780  int rc; /* Return code */
54781  u32 iZero = 0; /* One less than frame number of aPgno[1] */
54782  volatile u32 *aPgno = 0; /* Page number array */
54783  volatile ht_slot *aHash = 0; /* Hash table */
54784 
54785  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
54786 
54787  /* Assuming the wal-index file was successfully mapped, populate the
54788  ** page number array and hash table entry.
54789  */
54790  if( rc==SQLITE_OK ){
54791  int iKey; /* Hash table key */
54792  int idx; /* Value to write to hash-table slot */
54793  int nCollide; /* Number of hash collisions */
54794 
54795  idx = iFrame - iZero;
54796  assert( idx <= HASHTABLE_NSLOT/2 + 1 );
54797 
54798  /* If this is the first entry to be added to this hash-table, zero the
54799  ** entire hash table and aPgno[] array before proceeding.
54800  */
54801  if( idx==1 ){
54802  int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
54803  memset((void*)&aPgno[1], 0, nByte);
54804  }
54805 
54806  /* If the entry in aPgno[] is already set, then the previous writer
54807  ** must have exited unexpectedly in the middle of a transaction (after
54808  ** writing one or more dirty pages to the WAL to free up memory).
54809  ** Remove the remnants of that writers uncommitted transaction from
54810  ** the hash-table before writing any new entries.
54811  */
54812  if( aPgno[idx] ){
54813  walCleanupHash(pWal);
54814  assert( !aPgno[idx] );
54815  }
54816 
54817  /* Write the aPgno[] array entry and the hash-table slot. */
54818  nCollide = idx;
54819  for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
54820  if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
54821  }
54822  aPgno[idx] = iPage;
54823  aHash[iKey] = (ht_slot)idx;
54824 
54825 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54826  /* Verify that the number of entries in the hash table exactly equals
54827  ** the number of entries in the mapping region.
54828  */
54829  {
54830  int i; /* Loop counter */
54831  int nEntry = 0; /* Number of entries in the hash table */
54832  for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
54833  assert( nEntry==idx );
54834  }
54835 
54836  /* Verify that the every entry in the mapping region is reachable
54837  ** via the hash table. This turns out to be a really, really expensive
54838  ** thing to check, so only do this occasionally - not on every
54839  ** iteration.
54840  */
54841  if( (idx&0x3ff)==0 ){
54842  int i; /* Loop counter */
54843  for(i=1; i<=idx; i++){
54844  for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
54845  if( aHash[iKey]==i ) break;
54846  }
54847  assert( aHash[iKey]==i );
54848  }
54849  }
54850 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54851  }
54852 
54853 
54854  return rc;
54855 }
54856 
54857 
54858 /*
54859 ** Recover the wal-index by reading the write-ahead log file.
54860 **
54861 ** This routine first tries to establish an exclusive lock on the
54862 ** wal-index to prevent other threads/processes from doing anything
54863 ** with the WAL or wal-index while recovery is running. The
54864 ** WAL_RECOVER_LOCK is also held so that other threads will know
54865 ** that this thread is running recovery. If unable to establish
54866 ** the necessary locks, this routine returns SQLITE_BUSY.
54867 */
54868 static int walIndexRecover(Wal *pWal){
54869  int rc; /* Return Code */
54870  i64 nSize; /* Size of log file */
54871  u32 aFrameCksum[2] = {0, 0};
54872  int iLock; /* Lock offset to lock for checkpoint */
54873  int nLock; /* Number of locks to hold */
54874 
54875  /* Obtain an exclusive lock on all byte in the locking range not already
54876  ** locked by the caller. The caller is guaranteed to have locked the
54877  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
54878  ** If successful, the same bytes that are locked here are unlocked before
54879  ** this function returns.
54880  */
54881  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
54882  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
54883  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
54884  assert( pWal->writeLock );
54885  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
54886  nLock = SQLITE_SHM_NLOCK - iLock;
54887  rc = walLockExclusive(pWal, iLock, nLock);
54888  if( rc ){
54889  return rc;
54890  }
54891  WALTRACE(("WAL%p: recovery begin...\n", pWal));
54892 
54893  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
54894 
54895  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
54896  if( rc!=SQLITE_OK ){
54897  goto recovery_error;
54898  }
54899 
54900  if( nSize>WAL_HDRSIZE ){
54901  u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
54902  u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
54903  int szFrame; /* Number of bytes in buffer aFrame[] */
54904  u8 *aData; /* Pointer to data part of aFrame buffer */
54905  int iFrame; /* Index of last frame read */
54906  i64 iOffset; /* Next offset to read from log file */
54907  int szPage; /* Page size according to the log */
54908  u32 magic; /* Magic value read from WAL header */
54909  u32 version; /* Magic value read from WAL header */
54910  int isValid; /* True if this frame is valid */
54911 
54912  /* Read in the WAL header. */
54913  rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
54914  if( rc!=SQLITE_OK ){
54915  goto recovery_error;
54916  }
54917 
54918  /* If the database page size is not a power of two, or is greater than
54919  ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
54920  ** data. Similarly, if the 'magic' value is invalid, ignore the whole
54921  ** WAL file.
54922  */
54923  magic = sqlite3Get4byte(&aBuf[0]);
54924  szPage = sqlite3Get4byte(&aBuf[8]);
54925  if( (magic&0xFFFFFFFE)!=WAL_MAGIC
54926  || szPage&(szPage-1)
54927  || szPage>SQLITE_MAX_PAGE_SIZE
54928  || szPage<512
54929  ){
54930  goto finished;
54931  }
54932  pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
54933  pWal->szPage = szPage;
54934  pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
54935  memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
54936 
54937  /* Verify that the WAL header checksum is correct */
54939  aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
54940  );
54941  if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
54942  || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
54943  ){
54944  goto finished;
54945  }
54946 
54947  /* Verify that the version number on the WAL format is one that
54948  ** are able to understand */
54949  version = sqlite3Get4byte(&aBuf[4]);
54950  if( version!=WAL_MAX_VERSION ){
54951  rc = SQLITE_CANTOPEN_BKPT;
54952  goto finished;
54953  }
54954 
54955  /* Malloc a buffer to read frames into. */
54956  szFrame = szPage + WAL_FRAME_HDRSIZE;
54957  aFrame = (u8 *)sqlite3_malloc64(szFrame);
54958  if( !aFrame ){
54959  rc = SQLITE_NOMEM_BKPT;
54960  goto recovery_error;
54961  }
54962  aData = &aFrame[WAL_FRAME_HDRSIZE];
54963 
54964  /* Read all frames from the log file. */
54965  iFrame = 0;
54966  for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
54967  u32 pgno; /* Database page number for frame */
54968  u32 nTruncate; /* dbsize field from frame header */
54969 
54970  /* Read and decode the next log frame. */
54971  iFrame++;
54972  rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
54973  if( rc!=SQLITE_OK ) break;
54974  isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
54975  if( !isValid ) break;
54976  rc = walIndexAppend(pWal, iFrame, pgno);
54977  if( rc!=SQLITE_OK ) break;
54978 
54979  /* If nTruncate is non-zero, this is a commit record. */
54980  if( nTruncate ){
54981  pWal->hdr.mxFrame = iFrame;
54982  pWal->hdr.nPage = nTruncate;
54983  pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
54984  testcase( szPage<=32768 );
54985  testcase( szPage>=65536 );
54986  aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
54987  aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
54988  }
54989  }
54990 
54991  sqlite3_free(aFrame);
54992  }
54993 
54994 finished:
54995  if( rc==SQLITE_OK ){
54996  volatile WalCkptInfo *pInfo;
54997  int i;
54998  pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
54999  pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
55000  walIndexWriteHdr(pWal);
55001 
55002  /* Reset the checkpoint-header. This is safe because this thread is
55003  ** currently holding locks that exclude all other readers, writers and
55004  ** checkpointers.
55005  */
55006  pInfo = walCkptInfo(pWal);
55007  pInfo->nBackfill = 0;
55008  pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
55009  pInfo->aReadMark[0] = 0;
55010  for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55011  if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
55012 
55013  /* If more than one frame was recovered from the log file, report an
55014  ** event via sqlite3_log(). This is to help with identifying performance
55015  ** problems caused by applications routinely shutting down without
55016  ** checkpointing the log file.
55017  */
55018  if( pWal->hdr.nPage ){
55020  "recovered %d frames from WAL file %s",
55021  pWal->hdr.mxFrame, pWal->zWalName
55022  );
55023  }
55024  }
55025 
55026 recovery_error:
55027  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
55028  walUnlockExclusive(pWal, iLock, nLock);
55029  return rc;
55030 }
55031 
55032 /*
55033 ** Close an open wal-index.
55034 */
55035 static void walIndexClose(Wal *pWal, int isDelete){
55036  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
55037  int i;
55038  for(i=0; i<pWal->nWiData; i++){
55039  sqlite3_free((void *)pWal->apWiData[i]);
55040  pWal->apWiData[i] = 0;
55041  }
55042  }else{
55043  sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
55044  }
55045 }
55046 
55047 /*
55048 ** Open a connection to the WAL file zWalName. The database file must
55049 ** already be opened on connection pDbFd. The buffer that zWalName points
55050 ** to must remain valid for the lifetime of the returned Wal* handle.
55051 **
55052 ** A SHARED lock should be held on the database file when this function
55053 ** is called. The purpose of this SHARED lock is to prevent any other
55054 ** client from unlinking the WAL or wal-index file. If another process
55055 ** were to do this just after this client opened one of these files, the
55056 ** system would be badly broken.
55057 **
55058 ** If the log file is successfully opened, SQLITE_OK is returned and
55059 ** *ppWal is set to point to a new WAL handle. If an error occurs,
55060 ** an SQLite error code is returned and *ppWal is left unmodified.
55061 */
55063  sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
55064  sqlite3_file *pDbFd, /* The open database file */
55065  const char *zWalName, /* Name of the WAL file */
55066  int bNoShm, /* True to run in heap-memory mode */
55067  i64 mxWalSize, /* Truncate WAL to this size on reset */
55068  Wal **ppWal /* OUT: Allocated Wal handle */
55069 ){
55070  int rc; /* Return Code */
55071  Wal *pRet; /* Object to allocate and return */
55072  int flags; /* Flags passed to OsOpen() */
55073 
55074  assert( zWalName && zWalName[0] );
55075  assert( pDbFd );
55076 
55077  /* In the amalgamation, the os_unix.c and os_win.c source files come before
55078  ** this source file. Verify that the #defines of the locking byte offsets
55079  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
55080  ** For that matter, if the lock offset ever changes from its initial design
55081  ** value of 120, we need to know that so there is an assert() to check it.
55082  */
55083  assert( 120==WALINDEX_LOCK_OFFSET );
55084  assert( 136==WALINDEX_HDR_SIZE );
55085 #ifdef WIN_SHM_BASE
55086  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
55087 #endif
55088 #ifdef UNIX_SHM_BASE
55090 #endif
55091 
55092 
55093  /* Allocate an instance of struct Wal to return. */
55094  *ppWal = 0;
55095  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
55096  if( !pRet ){
55097  return SQLITE_NOMEM_BKPT;
55098  }
55099 
55100  pRet->pVfs = pVfs;
55101  pRet->pWalFd = (sqlite3_file *)&pRet[1];
55102  pRet->pDbFd = pDbFd;
55103  pRet->readLock = -1;
55104  pRet->mxWalSize = mxWalSize;
55105  pRet->zWalName = zWalName;
55106  pRet->syncHeader = 1;
55107  pRet->padToSectorBoundary = 1;
55109 
55110  /* Open file handle on the write-ahead log file. */
55112  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
55113  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
55114  pRet->readOnly = WAL_RDONLY;
55115  }
55116 
55117  if( rc!=SQLITE_OK ){
55118  walIndexClose(pRet, 0);
55119  sqlite3OsClose(pRet->pWalFd);
55120  sqlite3_free(pRet);
55121  }else{
55122  int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
55123  if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
55125  pRet->padToSectorBoundary = 0;
55126  }
55127  *ppWal = pRet;
55128  WALTRACE(("WAL%d: opened\n", pRet));
55129  }
55130  return rc;
55131 }
55132 
55133 /*
55134 ** Change the size to which the WAL file is trucated on each reset.
55135 */
55136 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
55137  if( pWal ) pWal->mxWalSize = iLimit;
55138 }
55139 
55140 /*
55141 ** Find the smallest page number out of all pages held in the WAL that
55142 ** has not been returned by any prior invocation of this method on the
55143 ** same WalIterator object. Write into *piFrame the frame index where
55144 ** that page was last written into the WAL. Write into *piPage the page
55145 ** number.
55146 **
55147 ** Return 0 on success. If there are no pages in the WAL with a page
55148 ** number larger than *piPage, then return 1.
55149 */
55150 static int walIteratorNext(
55151  WalIterator *p, /* Iterator */
55152  u32 *piPage, /* OUT: The page number of the next page */
55153  u32 *piFrame /* OUT: Wal frame index of next page */
55154 ){
55155  u32 iMin; /* Result pgno must be greater than iMin */
55156  u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
55157  int i; /* For looping through segments */
55158 
55159  iMin = p->iPrior;
55160  assert( iMin<0xffffffff );
55161  for(i=p->nSegment-1; i>=0; i--){
55162  struct WalSegment *pSegment = &p->aSegment[i];
55163  while( pSegment->iNext<pSegment->nEntry ){
55164  u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
55165  if( iPg>iMin ){
55166  if( iPg<iRet ){
55167  iRet = iPg;
55168  *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
55169  }
55170  break;
55171  }
55172  pSegment->iNext++;
55173  }
55174  }
55175 
55176  *piPage = p->iPrior = iRet;
55177  return (iRet==0xFFFFFFFF);
55178 }
55179 
55180 /*
55181 ** This function merges two sorted lists into a single sorted list.
55182 **
55183 ** aLeft[] and aRight[] are arrays of indices. The sort key is
55184 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
55185 ** is guaranteed for all J<K:
55186 **
55187 ** aContent[aLeft[J]] < aContent[aLeft[K]]
55188 ** aContent[aRight[J]] < aContent[aRight[K]]
55189 **
55190 ** This routine overwrites aRight[] with a new (probably longer) sequence
55191 ** of indices such that the aRight[] contains every index that appears in
55192 ** either aLeft[] or the old aRight[] and such that the second condition
55193 ** above is still met.
55194 **
55195 ** The aContent[aLeft[X]] values will be unique for all X. And the
55196 ** aContent[aRight[X]] values will be unique too. But there might be
55197 ** one or more combinations of X and Y such that
55198 **
55199 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
55200 **
55201 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
55202 */
55203 static void walMerge(
55204  const u32 *aContent, /* Pages in wal - keys for the sort */
55205  ht_slot *aLeft, /* IN: Left hand input list */
55206  int nLeft, /* IN: Elements in array *paLeft */
55207  ht_slot **paRight, /* IN/OUT: Right hand input list */
55208  int *pnRight, /* IN/OUT: Elements in *paRight */
55209  ht_slot *aTmp /* Temporary buffer */
55210 ){
55211  int iLeft = 0; /* Current index in aLeft */
55212  int iRight = 0; /* Current index in aRight */
55213  int iOut = 0; /* Current index in output buffer */
55214  int nRight = *pnRight;
55215  ht_slot *aRight = *paRight;
55216 
55217  assert( nLeft>0 && nRight>0 );
55218  while( iRight<nRight || iLeft<nLeft ){
55219  ht_slot logpage;
55220  Pgno dbpage;
55221 
55222  if( (iLeft<nLeft)
55223  && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
55224  ){
55225  logpage = aLeft[iLeft++];
55226  }else{
55227  logpage = aRight[iRight++];
55228  }
55229  dbpage = aContent[logpage];
55230 
55231  aTmp[iOut++] = logpage;
55232  if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
55233 
55234  assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
55235  assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
55236  }
55237 
55238  *paRight = aLeft;
55239  *pnRight = iOut;
55240  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
55241 }
55242 
55243 /*
55244 ** Sort the elements in list aList using aContent[] as the sort key.
55245 ** Remove elements with duplicate keys, preferring to keep the
55246 ** larger aList[] values.
55247 **
55248 ** The aList[] entries are indices into aContent[]. The values in
55249 ** aList[] are to be sorted so that for all J<K:
55250 **
55251 ** aContent[aList[J]] < aContent[aList[K]]
55252 **
55253 ** For any X and Y such that
55254 **
55255 ** aContent[aList[X]] == aContent[aList[Y]]
55256 **
55257 ** Keep the larger of the two values aList[X] and aList[Y] and discard
55258 ** the smaller.
55259 */
55260 static void walMergesort(
55261  const u32 *aContent, /* Pages in wal */
55262  ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
55263  ht_slot *aList, /* IN/OUT: List to sort */
55264  int *pnList /* IN/OUT: Number of elements in aList[] */
55265 ){
55266  struct Sublist {
55267  int nList; /* Number of elements in aList */
55268  ht_slot *aList; /* Pointer to sub-list content */
55269  };
55270 
55271  const int nList = *pnList; /* Size of input list */
55272  int nMerge = 0; /* Number of elements in list aMerge */
55273  ht_slot *aMerge = 0; /* List to be merged */
55274  int iList; /* Index into input list */
55275  u32 iSub = 0; /* Index into aSub array */
55276  struct Sublist aSub[13]; /* Array of sub-lists */
55277 
55278  memset(aSub, 0, sizeof(aSub));
55279  assert( nList<=HASHTABLE_NPAGE && nList>0 );
55280  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
55281 
55282  for(iList=0; iList<nList; iList++){
55283  nMerge = 1;
55284  aMerge = &aList[iList];
55285  for(iSub=0; iList & (1<<iSub); iSub++){
55286  struct Sublist *p;
55287  assert( iSub<ArraySize(aSub) );
55288  p = &aSub[iSub];
55289  assert( p->aList && p->nList<=(1<<iSub) );
55290  assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
55291  walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55292  }
55293  aSub[iSub].aList = aMerge;
55294  aSub[iSub].nList = nMerge;
55295  }
55296 
55297  for(iSub++; iSub<ArraySize(aSub); iSub++){
55298  if( nList & (1<<iSub) ){
55299  struct Sublist *p;
55300  assert( iSub<ArraySize(aSub) );
55301  p = &aSub[iSub];
55302  assert( p->nList<=(1<<iSub) );
55303  assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
55304  walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55305  }
55306  }
55307  assert( aMerge==aList );
55308  *pnList = nMerge;
55309 
55310 #ifdef SQLITE_DEBUG
55311  {
55312  int i;
55313  for(i=1; i<*pnList; i++){
55314  assert( aContent[aList[i]] > aContent[aList[i-1]] );
55315  }
55316  }
55317 #endif
55318 }
55319 
55320 /*
55321 ** Free an iterator allocated by walIteratorInit().
55322 */
55324  sqlite3_free(p);
55325 }
55326 
55327 /*
55328 ** Construct a WalInterator object that can be used to loop over all
55329 ** pages in the WAL in ascending order. The caller must hold the checkpoint
55330 ** lock.
55331 **
55332 ** On success, make *pp point to the newly allocated WalInterator object
55333 ** return SQLITE_OK. Otherwise, return an error code. If this routine
55334 ** returns an error, the value of *pp is undefined.
55335 **
55336 ** The calling routine should invoke walIteratorFree() to destroy the
55337 ** WalIterator object when it has finished with it.
55338 */
55339 static int walIteratorInit(Wal *pWal, WalIterator **pp){
55340  WalIterator *p; /* Return value */
55341  int nSegment; /* Number of segments to merge */
55342  u32 iLast; /* Last frame in log */
55343  int nByte; /* Number of bytes to allocate */
55344  int i; /* Iterator variable */
55345  ht_slot *aTmp; /* Temp space used by merge-sort */
55346  int rc = SQLITE_OK; /* Return Code */
55347 
55348  /* This routine only runs while holding the checkpoint lock. And
55349  ** it only runs if there is actually content in the log (mxFrame>0).
55350  */
55351  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
55352  iLast = pWal->hdr.mxFrame;
55353 
55354  /* Allocate space for the WalIterator object. */
55355  nSegment = walFramePage(iLast) + 1;
55356  nByte = sizeof(WalIterator)
55357  + (nSegment-1)*sizeof(struct WalSegment)
55358  + iLast*sizeof(ht_slot);
55359  p = (WalIterator *)sqlite3_malloc64(nByte);
55360  if( !p ){
55361  return SQLITE_NOMEM_BKPT;
55362  }
55363  memset(p, 0, nByte);
55364  p->nSegment = nSegment;
55365 
55366  /* Allocate temporary space used by the merge-sort routine. This block
55367  ** of memory will be freed before this function returns.
55368  */
55369  aTmp = (ht_slot *)sqlite3_malloc64(
55370  sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
55371  );
55372  if( !aTmp ){
55373  rc = SQLITE_NOMEM_BKPT;
55374  }
55375 
55376  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
55377  volatile ht_slot *aHash;
55378  u32 iZero;
55379  volatile u32 *aPgno;
55380 
55381  rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
55382  if( rc==SQLITE_OK ){
55383  int j; /* Counter variable */
55384  int nEntry; /* Number of entries in this segment */
55385  ht_slot *aIndex; /* Sorted index for this segment */
55386 
55387  aPgno++;
55388  if( (i+1)==nSegment ){
55389  nEntry = (int)(iLast - iZero);
55390  }else{
55391  nEntry = (int)((u32*)aHash - (u32*)aPgno);
55392  }
55393  aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
55394  iZero++;
55395 
55396  for(j=0; j<nEntry; j++){
55397  aIndex[j] = (ht_slot)j;
55398  }
55399  walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
55400  p->aSegment[i].iZero = iZero;
55401  p->aSegment[i].nEntry = nEntry;
55402  p->aSegment[i].aIndex = aIndex;
55403  p->aSegment[i].aPgno = (u32 *)aPgno;
55404  }
55405  }
55406  sqlite3_free(aTmp);
55407 
55408  if( rc!=SQLITE_OK ){
55409  walIteratorFree(p);
55410  }
55411  *pp = p;
55412  return rc;
55413 }
55414 
55415 /*
55416 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
55417 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
55418 ** busy-handler function. Invoke it and retry the lock until either the
55419 ** lock is successfully obtained or the busy-handler returns 0.
55420 */
55421 static int walBusyLock(
55422  Wal *pWal, /* WAL connection */
55423  int (*xBusy)(void*), /* Function to call when busy */
55424  void *pBusyArg, /* Context argument for xBusyHandler */
55425  int lockIdx, /* Offset of first byte to lock */
55426  int n /* Number of bytes to lock */
55427 ){
55428  int rc;
55429  do {
55430  rc = walLockExclusive(pWal, lockIdx, n);
55431  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
55432  return rc;
55433 }
55434 
55435 /*
55436 ** The cache of the wal-index header must be valid to call this function.
55437 ** Return the page-size in bytes used by the database.
55438 */
55439 static int walPagesize(Wal *pWal){
55440  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55441 }
55442 
55443 /*
55444 ** The following is guaranteed when this function is called:
55445 **
55446 ** a) the WRITER lock is held,
55447 ** b) the entire log file has been checkpointed, and
55448 ** c) any existing readers are reading exclusively from the database
55449 ** file - there are no readers that may attempt to read a frame from
55450 ** the log file.
55451 **
55452 ** This function updates the shared-memory structures so that the next
55453 ** client to write to the database (which may be this one) does so by
55454 ** writing frames into the start of the log file.
55455 **
55456 ** The value of parameter salt1 is used as the aSalt[1] value in the
55457 ** new wal-index header. It should be passed a pseudo-random value (i.e.
55458 ** one obtained from sqlite3_randomness()).
55459 */
55460 static void walRestartHdr(Wal *pWal, u32 salt1){
55461  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
55462  int i; /* Loop counter */
55463  u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
55464  pWal->nCkpt++;
55465  pWal->hdr.mxFrame = 0;
55466  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
55467  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
55468  walIndexWriteHdr(pWal);
55469  pInfo->nBackfill = 0;
55470  pInfo->nBackfillAttempted = 0;
55471  pInfo->aReadMark[1] = 0;
55472  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55473  assert( pInfo->aReadMark[0]==0 );
55474 }
55475 
55476 /*
55477 ** Copy as much content as we can from the WAL back into the database file
55478 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
55479 **
55480 ** The amount of information copies from WAL to database might be limited
55481 ** by active readers. This routine will never overwrite a database page
55482 ** that a concurrent reader might be using.
55483 **
55484 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
55485 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
55486 ** checkpoints are always run by a background thread or background
55487 ** process, foreground threads will never block on a lengthy fsync call.
55488 **
55489 ** Fsync is called on the WAL before writing content out of the WAL and
55490 ** into the database. This ensures that if the new content is persistent
55491 ** in the WAL and can be recovered following a power-loss or hard reset.
55492 **
55493 ** Fsync is also called on the database file if (and only if) the entire
55494 ** WAL content is copied into the database file. This second fsync makes
55495 ** it safe to delete the WAL since the new content will persist in the
55496 ** database file.
55497 **
55498 ** This routine uses and updates the nBackfill field of the wal-index header.
55499 ** This is the only routine that will increase the value of nBackfill.
55500 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
55501 ** its value.)
55502 **
55503 ** The caller must be holding sufficient locks to ensure that no other
55504 ** checkpoint is running (in any other thread or process) at the same
55505 ** time.
55506 */
55507 static int walCheckpoint(
55508  Wal *pWal, /* Wal connection */
55509  int eMode, /* One of PASSIVE, FULL or RESTART */
55510  int (*xBusy)(void*), /* Function to call when busy */
55511  void *pBusyArg, /* Context argument for xBusyHandler */
55512  int sync_flags, /* Flags for OsSync() (or 0) */
55513  u8 *zBuf /* Temporary buffer to use */
55514 ){
55515  int rc = SQLITE_OK; /* Return code */
55516  int szPage; /* Database page-size */
55517  WalIterator *pIter = 0; /* Wal iterator context */
55518  u32 iDbpage = 0; /* Next database page to write */
55519  u32 iFrame = 0; /* Wal frame containing data for iDbpage */
55520  u32 mxSafeFrame; /* Max frame that can be backfilled */
55521  u32 mxPage; /* Max database page to write */
55522  int i; /* Loop counter */
55523  volatile WalCkptInfo *pInfo; /* The checkpoint status information */
55524 
55525  szPage = walPagesize(pWal);
55526  testcase( szPage<=32768 );
55527  testcase( szPage>=65536 );
55528  pInfo = walCkptInfo(pWal);
55529  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55530 
55531  /* Allocate the iterator */
55532  rc = walIteratorInit(pWal, &pIter);
55533  if( rc!=SQLITE_OK ){
55534  return rc;
55535  }
55536  assert( pIter );
55537 
55538  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
55539  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
55540  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
55541 
55542  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
55543  ** safe to write into the database. Frames beyond mxSafeFrame might
55544  ** overwrite database pages that are in use by active readers and thus
55545  ** cannot be backfilled from the WAL.
55546  */
55547  mxSafeFrame = pWal->hdr.mxFrame;
55548  mxPage = pWal->hdr.nPage;
55549  for(i=1; i<WAL_NREADER; i++){
55550  /* Thread-sanitizer reports that the following is an unsafe read,
55551  ** as some other thread may be in the process of updating the value
55552  ** of the aReadMark[] slot. The assumption here is that if that is
55553  ** happening, the other client may only be increasing the value,
55554  ** not decreasing it. So assuming either that either the "old" or
55555  ** "new" version of the value is read, and not some arbitrary value
55556  ** that would never be written by a real client, things are still
55557  ** safe. */
55558  u32 y = pInfo->aReadMark[i];
55559  if( mxSafeFrame>y ){
55560  assert( y<=pWal->hdr.mxFrame );
55561  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
55562  if( rc==SQLITE_OK ){
55563  pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
55564  walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55565  }else if( rc==SQLITE_BUSY ){
55566  mxSafeFrame = y;
55567  xBusy = 0;
55568  }else{
55569  goto walcheckpoint_out;
55570  }
55571  }
55572  }
55573 
55574  if( pInfo->nBackfill<mxSafeFrame
55575  && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
55576  ){
55577  i64 nSize; /* Current size of database file */
55578  u32 nBackfill = pInfo->nBackfill;
55579 
55580  pInfo->nBackfillAttempted = mxSafeFrame;
55581 
55582  /* Sync the WAL to disk */
55583  if( sync_flags ){
55584  rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
55585  }
55586 
55587  /* If the database may grow as a result of this checkpoint, hint
55588  ** about the eventual size of the db file to the VFS layer.
55589  */
55590  if( rc==SQLITE_OK ){
55591  i64 nReq = ((i64)mxPage * szPage);
55592  rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
55593  if( rc==SQLITE_OK && nSize<nReq ){
55595  }
55596  }
55597 
55598 
55599  /* Iterate through the contents of the WAL, copying data to the db file */
55600  while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
55601  i64 iOffset;
55602  assert( walFramePgno(pWal, iFrame)==iDbpage );
55603  if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
55604  continue;
55605  }
55606  iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
55607  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
55608  rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
55609  if( rc!=SQLITE_OK ) break;
55610  iOffset = (iDbpage-1)*(i64)szPage;
55611  testcase( IS_BIG_INT(iOffset) );
55612  rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
55613  if( rc!=SQLITE_OK ) break;
55614  }
55615 
55616  /* If work was actually accomplished... */
55617  if( rc==SQLITE_OK ){
55618  if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
55619  i64 szDb = pWal->hdr.nPage*(i64)szPage;
55620  testcase( IS_BIG_INT(szDb) );
55621  rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
55622  if( rc==SQLITE_OK && sync_flags ){
55623  rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
55624  }
55625  }
55626  if( rc==SQLITE_OK ){
55627  pInfo->nBackfill = mxSafeFrame;
55628  }
55629  }
55630 
55631  /* Release the reader lock held while backfilling */
55632  walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
55633  }
55634 
55635  if( rc==SQLITE_BUSY ){
55636  /* Reset the return code so as not to report a checkpoint failure
55637  ** just because there are active readers. */
55638  rc = SQLITE_OK;
55639  }
55640  }
55641 
55642  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
55643  ** entire wal file has been copied into the database file, then block
55644  ** until all readers have finished using the wal file. This ensures that
55645  ** the next process to write to the database restarts the wal file.
55646  */
55647  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
55648  assert( pWal->writeLock );
55649  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55650  rc = SQLITE_BUSY;
55651  }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
55652  u32 salt1;
55653  sqlite3_randomness(4, &salt1);
55654  assert( pInfo->nBackfill==pWal->hdr.mxFrame );
55655  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
55656  if( rc==SQLITE_OK ){
55657  if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
55658  /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
55659  ** SQLITE_CHECKPOINT_RESTART with the addition that it also
55660  ** truncates the log file to zero bytes just prior to a
55661  ** successful return.
55662  **
55663  ** In theory, it might be safe to do this without updating the
55664  ** wal-index header in shared memory, as all subsequent reader or
55665  ** writer clients should see that the entire log file has been
55666  ** checkpointed and behave accordingly. This seems unsafe though,
55667  ** as it would leave the system in a state where the contents of
55668  ** the wal-index header do not match the contents of the
55669  ** file-system. To avoid this, update the wal-index header to
55670  ** indicate that the log file contains zero valid frames. */
55671  walRestartHdr(pWal, salt1);
55672  rc = sqlite3OsTruncate(pWal->pWalFd, 0);
55673  }
55675  }
55676  }
55677  }
55678 
55679  walcheckpoint_out:
55680  walIteratorFree(pIter);
55681  return rc;
55682 }
55683 
55684 /*
55685 ** If the WAL file is currently larger than nMax bytes in size, truncate
55686 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
55687 */
55688 static void walLimitSize(Wal *pWal, i64 nMax){
55689  i64 sz;
55690  int rx;
55692  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
55693  if( rx==SQLITE_OK && (sz > nMax ) ){
55694  rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
55695  }
55697  if( rx ){
55698  sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
55699  }
55700 }
55701 
55702 /*
55703 ** Close a connection to a log file.
55704 */
55706  Wal *pWal, /* Wal to close */
55707  int sync_flags, /* Flags to pass to OsSync() (or 0) */
55708  int nBuf,
55709  u8 *zBuf /* Buffer of at least nBuf bytes */
55710 ){
55711  int rc = SQLITE_OK;
55712  if( pWal ){
55713  int isDelete = 0; /* True to unlink wal and wal-index files */
55714 
55715  /* If an EXCLUSIVE lock can be obtained on the database file (using the
55716  ** ordinary, rollback-mode locking methods, this guarantees that the
55717  ** connection associated with this log file is the only connection to
55718  ** the database. In this case checkpoint the database and unlink both
55719  ** the wal and wal-index files.
55720  **
55721  ** The EXCLUSIVE lock is not released before returning.
55722  */
55724  if( rc==SQLITE_OK ){
55725  if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
55727  }
55728  rc = sqlite3WalCheckpoint(
55729  pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
55730  );
55731  if( rc==SQLITE_OK ){
55732  int bPersist = -1;
55734  pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
55735  );
55736  if( bPersist!=1 ){
55737  /* Try to delete the WAL file if the checkpoint completed and
55738  ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
55739  ** mode (!bPersist) */
55740  isDelete = 1;
55741  }else if( pWal->mxWalSize>=0 ){
55742  /* Try to truncate the WAL file to zero bytes if the checkpoint
55743  ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
55744  ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
55745  ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
55746  ** to zero bytes as truncating to the journal_size_limit might
55747  ** leave a corrupt WAL file on disk. */
55748  walLimitSize(pWal, 0);
55749  }
55750  }
55751  }
55752 
55753  walIndexClose(pWal, isDelete);
55754  sqlite3OsClose(pWal->pWalFd);
55755  if( isDelete ){
55757  sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
55759  }
55760  WALTRACE(("WAL%p: closed\n", pWal));
55761  sqlite3_free((void *)pWal->apWiData);
55762  sqlite3_free(pWal);
55763  }
55764  return rc;
55765 }
55766 
55767 /*
55768 ** Try to read the wal-index header. Return 0 on success and 1 if
55769 ** there is a problem.
55770 **
55771 ** The wal-index is in shared memory. Another thread or process might
55772 ** be writing the header at the same time this procedure is trying to
55773 ** read it, which might result in inconsistency. A dirty read is detected
55774 ** by verifying that both copies of the header are the same and also by
55775 ** a checksum on the header.
55776 **
55777 ** If and only if the read is consistent and the header is different from
55778 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
55779 ** and *pChanged is set to 1.
55780 **
55781 ** If the checksum cannot be verified return non-zero. If the header
55782 ** is read successfully and the checksum verified, return zero.
55783 */
55784 static int walIndexTryHdr(Wal *pWal, int *pChanged){
55785  u32 aCksum[2]; /* Checksum on the header content */
55786  WalIndexHdr h1, h2; /* Two copies of the header content */
55787  WalIndexHdr volatile *aHdr; /* Header in shared memory */
55788 
55789  /* The first page of the wal-index must be mapped at this point. */
55790  assert( pWal->nWiData>0 && pWal->apWiData[0] );
55791 
55792  /* Read the header. This might happen concurrently with a write to the
55793  ** same area of shared memory on a different CPU in a SMP,
55794  ** meaning it is possible that an inconsistent snapshot is read
55795  ** from the file. If this happens, return non-zero.
55796  **
55797  ** There are two copies of the header at the beginning of the wal-index.
55798  ** When reading, read [0] first then [1]. Writes are in the reverse order.
55799  ** Memory barriers are used to prevent the compiler or the hardware from
55800  ** reordering the reads and writes.
55801  */
55802  aHdr = walIndexHdr(pWal);
55803  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
55804  walShmBarrier(pWal);
55805  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
55806 
55807  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
55808  return 1; /* Dirty read */
55809  }
55810  if( h1.isInit==0 ){
55811  return 1; /* Malformed header - probably all zeros */
55812  }
55813  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
55814  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
55815  return 1; /* Checksum does not match */
55816  }
55817 
55818  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
55819  *pChanged = 1;
55820  memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
55821  pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55822  testcase( pWal->szPage<=32768 );
55823  testcase( pWal->szPage>=65536 );
55824  }
55825 
55826  /* The header was successfully read. Return zero. */
55827  return 0;
55828 }
55829 
55830 /*
55831 ** Read the wal-index header from the wal-index and into pWal->hdr.
55832 ** If the wal-header appears to be corrupt, try to reconstruct the
55833 ** wal-index from the WAL before returning.
55834 **
55835 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
55836 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
55837 ** to 0.
55838 **
55839 ** If the wal-index header is successfully read, return SQLITE_OK.
55840 ** Otherwise an SQLite error code.
55841 */
55842 static int walIndexReadHdr(Wal *pWal, int *pChanged){
55843  int rc; /* Return code */
55844  int badHdr; /* True if a header read failed */
55845  volatile u32 *page0; /* Chunk of wal-index containing header */
55846 
55847  /* Ensure that page 0 of the wal-index (the page that contains the
55848  ** wal-index header) is mapped. Return early if an error occurs here.
55849  */
55850  assert( pChanged );
55851  rc = walIndexPage(pWal, 0, &page0);
55852  if( rc!=SQLITE_OK ){
55853  return rc;
55854  };
55855  assert( page0 || pWal->writeLock==0 );
55856 
55857  /* If the first page of the wal-index has been mapped, try to read the
55858  ** wal-index header immediately, without holding any lock. This usually
55859  ** works, but may fail if the wal-index header is corrupt or currently
55860  ** being modified by another thread or process.
55861  */
55862  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
55863 
55864  /* If the first attempt failed, it might have been due to a race
55865  ** with a writer. So get a WRITE lock and try again.
55866  */
55867  assert( badHdr==0 || pWal->writeLock==0 );
55868  if( badHdr ){
55869  if( pWal->readOnly & WAL_SHM_RDONLY ){
55870  if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
55873  }
55874  }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
55875  pWal->writeLock = 1;
55876  if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
55877  badHdr = walIndexTryHdr(pWal, pChanged);
55878  if( badHdr ){
55879  /* If the wal-index header is still malformed even while holding
55880  ** a WRITE lock, it can only mean that the header is corrupted and
55881  ** needs to be reconstructed. So run recovery to do exactly that.
55882  */
55883  rc = walIndexRecover(pWal);
55884  *pChanged = 1;
55885  }
55886  }
55887  pWal->writeLock = 0;
55889  }
55890  }
55891 
55892  /* If the header is read successfully, check the version number to make
55893  ** sure the wal-index was not constructed with some future format that
55894  ** this version of SQLite cannot understand.
55895  */
55896  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
55897  rc = SQLITE_CANTOPEN_BKPT;
55898  }
55899 
55900  return rc;
55901 }
55902 
55903 /*
55904 ** This is the value that walTryBeginRead returns when it needs to
55905 ** be retried.
55906 */
55907 #define WAL_RETRY (-1)
55908 
55909 /*
55910 ** Attempt to start a read transaction. This might fail due to a race or
55911 ** other transient condition. When that happens, it returns WAL_RETRY to
55912 ** indicate to the caller that it is safe to retry immediately.
55913 **
55914 ** On success return SQLITE_OK. On a permanent failure (such an
55915 ** I/O error or an SQLITE_BUSY because another process is running
55916 ** recovery) return a positive error code.
55917 **
55918 ** The useWal parameter is true to force the use of the WAL and disable
55919 ** the case where the WAL is bypassed because it has been completely
55920 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
55921 ** to make a copy of the wal-index header into pWal->hdr. If the
55922 ** wal-index header has changed, *pChanged is set to 1 (as an indication
55923 ** to the caller that the local paget cache is obsolete and needs to be
55924 ** flushed.) When useWal==1, the wal-index header is assumed to already
55925 ** be loaded and the pChanged parameter is unused.
55926 **
55927 ** The caller must set the cnt parameter to the number of prior calls to
55928 ** this routine during the current read attempt that returned WAL_RETRY.
55929 ** This routine will start taking more aggressive measures to clear the
55930 ** race conditions after multiple WAL_RETRY returns, and after an excessive
55931 ** number of errors will ultimately return SQLITE_PROTOCOL. The
55932 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
55933 ** and is not honoring the locking protocol. There is a vanishingly small
55934 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
55935 ** bad luck when there is lots of contention for the wal-index, but that
55936 ** possibility is so small that it can be safely neglected, we believe.
55937 **
55938 ** On success, this routine obtains a read lock on
55939 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
55940 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
55941 ** that means the Wal does not hold any read lock. The reader must not
55942 ** access any database page that is modified by a WAL frame up to and
55943 ** including frame number aReadMark[pWal->readLock]. The reader will
55944 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
55945 ** Or if pWal->readLock==0, then the reader will ignore the WAL
55946 ** completely and get all content directly from the database file.
55947 ** If the useWal parameter is 1 then the WAL will never be ignored and
55948 ** this routine will always set pWal->readLock>0 on success.
55949 ** When the read transaction is completed, the caller must release the
55950 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
55951 **
55952 ** This routine uses the nBackfill and aReadMark[] fields of the header
55953 ** to select a particular WAL_READ_LOCK() that strives to let the
55954 ** checkpoint process do as much work as possible. This routine might
55955 ** update values of the aReadMark[] array in the header, but if it does
55956 ** so it takes care to hold an exclusive lock on the corresponding
55957 ** WAL_READ_LOCK() while changing values.
55958 */
55959 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
55960  volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
55961  u32 mxReadMark; /* Largest aReadMark[] value */
55962  int mxI; /* Index of largest aReadMark[] value */
55963  int i; /* Loop counter */
55964  int rc = SQLITE_OK; /* Return code */
55965  u32 mxFrame; /* Wal frame to lock to */
55966 
55967  assert( pWal->readLock<0 ); /* Not currently locked */
55968 
55969  /* Take steps to avoid spinning forever if there is a protocol error.
55970  **
55971  ** Circumstances that cause a RETRY should only last for the briefest
55972  ** instances of time. No I/O or other system calls are done while the
55973  ** locks are held, so the locks should not be held for very long. But
55974  ** if we are unlucky, another process that is holding a lock might get
55975  ** paged out or take a page-fault that is time-consuming to resolve,
55976  ** during the few nanoseconds that it is holding the lock. In that case,
55977  ** it might take longer than normal for the lock to free.
55978  **
55979  ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
55980  ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
55981  ** is more of a scheduler yield than an actual delay. But on the 10th
55982  ** an subsequent retries, the delays start becoming longer and longer,
55983  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
55984  ** The total delay time before giving up is less than 10 seconds.
55985  */
55986  if( cnt>5 ){
55987  int nDelay = 1; /* Pause time in microseconds */
55988  if( cnt>100 ){
55989  VVA_ONLY( pWal->lockError = 1; )
55990  return SQLITE_PROTOCOL;
55991  }
55992  if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
55993  sqlite3OsSleep(pWal->pVfs, nDelay);
55994  }
55995 
55996  if( !useWal ){
55997  rc = walIndexReadHdr(pWal, pChanged);
55998  if( rc==SQLITE_BUSY ){
55999  /* If there is not a recovery running in another thread or process
56000  ** then convert BUSY errors to WAL_RETRY. If recovery is known to
56001  ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
56002  ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
56003  ** would be technically correct. But the race is benign since with
56004  ** WAL_RETRY this routine will be called again and will probably be
56005  ** right on the second iteration.
56006  */
56007  if( pWal->apWiData[0]==0 ){
56008  /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
56009  ** We assume this is a transient condition, so return WAL_RETRY. The
56010  ** xShmMap() implementation used by the default unix and win32 VFS
56011  ** modules may return SQLITE_BUSY due to a race condition in the
56012  ** code that determines whether or not the shared-memory region
56013  ** must be zeroed before the requested page is returned.
56014  */
56015  rc = WAL_RETRY;
56016  }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
56018  rc = WAL_RETRY;
56019  }else if( rc==SQLITE_BUSY ){
56020  rc = SQLITE_BUSY_RECOVERY;
56021  }
56022  }
56023  if( rc!=SQLITE_OK ){
56024  return rc;
56025  }
56026  }
56027 
56028  pInfo = walCkptInfo(pWal);
56029  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
56030 #ifdef SQLITE_ENABLE_SNAPSHOT
56031  && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
56032  || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
56033 #endif
56034  ){
56035  /* The WAL has been completely backfilled (or it is empty).
56036  ** and can be safely ignored.
56037  */
56038  rc = walLockShared(pWal, WAL_READ_LOCK(0));
56039  walShmBarrier(pWal);
56040  if( rc==SQLITE_OK ){
56041  if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
56042  /* It is not safe to allow the reader to continue here if frames
56043  ** may have been appended to the log before READ_LOCK(0) was obtained.
56044  ** When holding READ_LOCK(0), the reader ignores the entire log file,
56045  ** which implies that the database file contains a trustworthy
56046  ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
56047  ** happening, this is usually correct.
56048  **
56049  ** However, if frames have been appended to the log (or if the log
56050  ** is wrapped and written for that matter) before the READ_LOCK(0)
56051  ** is obtained, that is not necessarily true. A checkpointer may
56052  ** have started to backfill the appended frames but crashed before
56053  ** it finished. Leaving a corrupt image in the database file.
56054  */
56055  walUnlockShared(pWal, WAL_READ_LOCK(0));
56056  return WAL_RETRY;
56057  }
56058  pWal->readLock = 0;
56059  return SQLITE_OK;
56060  }else if( rc!=SQLITE_BUSY ){
56061  return rc;
56062  }
56063  }
56064 
56065  /* If we get this far, it means that the reader will want to use
56066  ** the WAL to get at content from recent commits. The job now is
56067  ** to select one of the aReadMark[] entries that is closest to
56068  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
56069  */
56070  mxReadMark = 0;
56071  mxI = 0;
56072  mxFrame = pWal->hdr.mxFrame;
56073 #ifdef SQLITE_ENABLE_SNAPSHOT
56074  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
56075  mxFrame = pWal->pSnapshot->mxFrame;
56076  }
56077 #endif
56078  for(i=1; i<WAL_NREADER; i++){
56079  u32 thisMark = pInfo->aReadMark[i];
56080  if( mxReadMark<=thisMark && thisMark<=mxFrame ){
56081  assert( thisMark!=READMARK_NOT_USED );
56082  mxReadMark = thisMark;
56083  mxI = i;
56084  }
56085  }
56086  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
56087  && (mxReadMark<mxFrame || mxI==0)
56088  ){
56089  for(i=1; i<WAL_NREADER; i++){
56090  rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
56091  if( rc==SQLITE_OK ){
56092  mxReadMark = pInfo->aReadMark[i] = mxFrame;
56093  mxI = i;
56094  walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
56095  break;
56096  }else if( rc!=SQLITE_BUSY ){
56097  return rc;
56098  }
56099  }
56100  }
56101  if( mxI==0 ){
56102  assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
56104  }
56105 
56106  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
56107  if( rc ){
56108  return rc==SQLITE_BUSY ? WAL_RETRY : rc;
56109  }
56110  /* Now that the read-lock has been obtained, check that neither the
56111  ** value in the aReadMark[] array or the contents of the wal-index
56112  ** header have changed.
56113  **
56114  ** It is necessary to check that the wal-index header did not change
56115  ** between the time it was read and when the shared-lock was obtained
56116  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
56117  ** that the log file may have been wrapped by a writer, or that frames
56118  ** that occur later in the log than pWal->hdr.mxFrame may have been
56119  ** copied into the database by a checkpointer. If either of these things
56120  ** happened, then reading the database with the current value of
56121  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
56122  ** instead.
56123  **
56124  ** Before checking that the live wal-index header has not changed
56125  ** since it was read, set Wal.minFrame to the first frame in the wal
56126  ** file that has not yet been checkpointed. This client will not need
56127  ** to read any frames earlier than minFrame from the wal file - they
56128  ** can be safely read directly from the database file.
56129  **
56130  ** Because a ShmBarrier() call is made between taking the copy of
56131  ** nBackfill and checking that the wal-header in shared-memory still
56132  ** matches the one cached in pWal->hdr, it is guaranteed that the
56133  ** checkpointer that set nBackfill was not working with a wal-index
56134  ** header newer than that cached in pWal->hdr. If it were, that could
56135  ** cause a problem. The checkpointer could omit to checkpoint
56136  ** a version of page X that lies before pWal->minFrame (call that version
56137  ** A) on the basis that there is a newer version (version B) of the same
56138  ** page later in the wal file. But if version B happens to like past
56139  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
56140  ** that it can read version A from the database file. However, since
56141  ** we can guarantee that the checkpointer that set nBackfill could not
56142  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
56143  */
56144  pWal->minFrame = pInfo->nBackfill+1;
56145  walShmBarrier(pWal);
56146  if( pInfo->aReadMark[mxI]!=mxReadMark
56147  || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
56148  ){
56149  walUnlockShared(pWal, WAL_READ_LOCK(mxI));
56150  return WAL_RETRY;
56151  }else{
56152  assert( mxReadMark<=pWal->hdr.mxFrame );
56153  pWal->readLock = (i16)mxI;
56154  }
56155  return rc;
56156 }
56157 
56158 /*
56159 ** Begin a read transaction on the database.
56160 **
56161 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
56162 ** it takes a snapshot of the state of the WAL and wal-index for the current
56163 ** instant in time. The current thread will continue to use this snapshot.
56164 ** Other threads might append new content to the WAL and wal-index but
56165 ** that extra content is ignored by the current thread.
56166 **
56167 ** If the database contents have changes since the previous read
56168 ** transaction, then *pChanged is set to 1 before returning. The
56169 ** Pager layer will use this to know that is cache is stale and
56170 ** needs to be flushed.
56171 */
56173  int rc; /* Return code */
56174  int cnt = 0; /* Number of TryBeginRead attempts */
56175 
56176 #ifdef SQLITE_ENABLE_SNAPSHOT
56177  int bChanged = 0;
56178  WalIndexHdr *pSnapshot = pWal->pSnapshot;
56179  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56180  bChanged = 1;
56181  }
56182 #endif
56183 
56184  do{
56185  rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
56186  }while( rc==WAL_RETRY );
56187  testcase( (rc&0xff)==SQLITE_BUSY );
56188  testcase( (rc&0xff)==SQLITE_IOERR );
56189  testcase( rc==SQLITE_PROTOCOL );
56190  testcase( rc==SQLITE_OK );
56191 
56192 #ifdef SQLITE_ENABLE_SNAPSHOT
56193  if( rc==SQLITE_OK ){
56194  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56195  /* At this point the client has a lock on an aReadMark[] slot holding
56196  ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
56197  ** is populated with the wal-index header corresponding to the head
56198  ** of the wal file. Verify that pSnapshot is still valid before
56199  ** continuing. Reasons why pSnapshot might no longer be valid:
56200  **
56201  ** (1) The WAL file has been reset since the snapshot was taken.
56202  ** In this case, the salt will have changed.
56203  **
56204  ** (2) A checkpoint as been attempted that wrote frames past
56205  ** pSnapshot->mxFrame into the database file. Note that the
56206  ** checkpoint need not have completed for this to cause problems.
56207  */
56208  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56209 
56210  assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
56211  assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
56212 
56213  /* It is possible that there is a checkpointer thread running
56214  ** concurrent with this code. If this is the case, it may be that the
56215  ** checkpointer has already determined that it will checkpoint
56216  ** snapshot X, where X is later in the wal file than pSnapshot, but
56217  ** has not yet set the pInfo->nBackfillAttempted variable to indicate
56218  ** its intent. To avoid the race condition this leads to, ensure that
56219  ** there is no checkpointer process by taking a shared CKPT lock
56220  ** before checking pInfo->nBackfillAttempted. */
56221  rc = walLockShared(pWal, WAL_CKPT_LOCK);
56222 
56223  if( rc==SQLITE_OK ){
56224  /* Check that the wal file has not been wrapped. Assuming that it has
56225  ** not, also check that no checkpointer has attempted to checkpoint any
56226  ** frames beyond pSnapshot->mxFrame. If either of these conditions are
56227  ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
56228  ** with *pSnapshot and set *pChanged as appropriate for opening the
56229  ** snapshot. */
56230  if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
56231  && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
56232  ){
56233  assert( pWal->readLock>0 );
56234  memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
56235  *pChanged = bChanged;
56236  }else{
56237  rc = SQLITE_BUSY_SNAPSHOT;
56238  }
56239 
56240  /* Release the shared CKPT lock obtained above. */
56242  }
56243 
56244 
56245  if( rc!=SQLITE_OK ){
56247  }
56248  }
56249  }
56250 #endif
56251  return rc;
56252 }
56253 
56254 /*
56255 ** Finish with a read transaction. All this does is release the
56256 ** read-lock.
56257 */
56260  if( pWal->readLock>=0 ){
56261  walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
56262  pWal->readLock = -1;
56263  }
56264 }
56265 
56266 /*
56267 ** Search the wal file for page pgno. If found, set *piRead to the frame that
56268 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
56269 ** to zero.
56270 **
56271 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
56272 ** error does occur, the final value of *piRead is undefined.
56273 */
56275  Wal *pWal, /* WAL handle */
56276  Pgno pgno, /* Database page number to read data for */
56277  u32 *piRead /* OUT: Frame number (or zero) */
56278 ){
56279  u32 iRead = 0; /* If !=0, WAL frame to return data from */
56280  u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
56281  int iHash; /* Used to loop through N hash tables */
56282  int iMinHash;
56283 
56284  /* This routine is only be called from within a read transaction. */
56285  assert( pWal->readLock>=0 || pWal->lockError );
56286 
56287  /* If the "last page" field of the wal-index header snapshot is 0, then
56288  ** no data will be read from the wal under any circumstances. Return early
56289  ** in this case as an optimization. Likewise, if pWal->readLock==0,
56290  ** then the WAL is ignored by the reader so return early, as if the
56291  ** WAL were empty.
56292  */
56293  if( iLast==0 || pWal->readLock==0 ){
56294  *piRead = 0;
56295  return SQLITE_OK;
56296  }
56297 
56298  /* Search the hash table or tables for an entry matching page number
56299  ** pgno. Each iteration of the following for() loop searches one
56300  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
56301  **
56302  ** This code might run concurrently to the code in walIndexAppend()
56303  ** that adds entries to the wal-index (and possibly to this hash
56304  ** table). This means the value just read from the hash
56305  ** slot (aHash[iKey]) may have been added before or after the
56306  ** current read transaction was opened. Values added after the
56307  ** read transaction was opened may have been written incorrectly -
56308  ** i.e. these slots may contain garbage data. However, we assume
56309  ** that any slots written before the current read transaction was
56310  ** opened remain unmodified.
56311  **
56312  ** For the reasons above, the if(...) condition featured in the inner
56313  ** loop of the following block is more stringent that would be required
56314  ** if we had exclusive access to the hash-table:
56315  **
56316  ** (aPgno[iFrame]==pgno):
56317  ** This condition filters out normal hash-table collisions.
56318  **
56319  ** (iFrame<=iLast):
56320  ** This condition filters out entries that were added to the hash
56321  ** table after the current read-transaction had started.
56322  */
56323  iMinHash = walFramePage(pWal->minFrame);
56324  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
56325  volatile ht_slot *aHash; /* Pointer to hash table */
56326  volatile u32 *aPgno; /* Pointer to array of page numbers */
56327  u32 iZero; /* Frame number corresponding to aPgno[0] */
56328  int iKey; /* Hash slot index */
56329  int nCollide; /* Number of hash collisions remaining */
56330  int rc; /* Error code */
56331 
56332  rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
56333  if( rc!=SQLITE_OK ){
56334  return rc;
56335  }
56336  nCollide = HASHTABLE_NSLOT;
56337  for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
56338  u32 iFrame = aHash[iKey] + iZero;
56339  if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
56340  assert( iFrame>iRead || CORRUPT_DB );
56341  iRead = iFrame;
56342  }
56343  if( (nCollide--)==0 ){
56344  return SQLITE_CORRUPT_BKPT;
56345  }
56346  }
56347  }
56348 
56349 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56350  /* If expensive assert() statements are available, do a linear search
56351  ** of the wal-index file content. Make sure the results agree with the
56352  ** result obtained using the hash indexes above. */
56353  {
56354  u32 iRead2 = 0;
56355  u32 iTest;
56356  assert( pWal->minFrame>0 );
56357  for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
56358  if( walFramePgno(pWal, iTest)==pgno ){
56359  iRead2 = iTest;
56360  break;
56361  }
56362  }
56363  assert( iRead==iRead2 );
56364  }
56365 #endif
56366 
56367  *piRead = iRead;
56368  return SQLITE_OK;
56369 }
56370 
56371 /*
56372 ** Read the contents of frame iRead from the wal file into buffer pOut
56373 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
56374 ** error code otherwise.
56375 */
56377  Wal *pWal, /* WAL handle */
56378  u32 iRead, /* Frame to read */
56379  int nOut, /* Size of buffer pOut in bytes */
56380  u8 *pOut /* Buffer to write page data to */
56381 ){
56382  int sz;
56383  i64 iOffset;
56384  sz = pWal->hdr.szPage;
56385  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
56386  testcase( sz<=32768 );
56387  testcase( sz>=65536 );
56388  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
56389  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
56390  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
56391 }
56392 
56393 /*
56394 ** Return the size of the database in pages (or zero, if unknown).
56395 */
56397  if( pWal && ALWAYS(pWal->readLock>=0) ){
56398  return pWal->hdr.nPage;
56399  }
56400  return 0;
56401 }
56402 
56403 
56404 /*
56405 ** This function starts a write transaction on the WAL.
56406 **
56407 ** A read transaction must have already been started by a prior call
56408 ** to sqlite3WalBeginReadTransaction().
56409 **
56410 ** If another thread or process has written into the database since
56411 ** the read transaction was started, then it is not possible for this
56412 ** thread to write as doing so would cause a fork. So this routine
56413 ** returns SQLITE_BUSY in that case and no write transaction is started.
56414 **
56415 ** There can only be a single writer active at a time.
56416 */
56418  int rc;
56419 
56420  /* Cannot start a write transaction without first holding a read
56421  ** transaction. */
56422  assert( pWal->readLock>=0 );
56423  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
56424 
56425  if( pWal->readOnly ){
56426  return SQLITE_READONLY;
56427  }
56428 
56429  /* Only one writer allowed at a time. Get the write lock. Return
56430  ** SQLITE_BUSY if unable.
56431  */
56432  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
56433  if( rc ){
56434  return rc;
56435  }
56436  pWal->writeLock = 1;
56437 
56438  /* If another connection has written to the database file since the
56439  ** time the read transaction on this connection was started, then
56440  ** the write is disallowed.
56441  */
56442  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
56444  pWal->writeLock = 0;
56445  rc = SQLITE_BUSY_SNAPSHOT;
56446  }
56447 
56448  return rc;
56449 }
56450 
56451 /*
56452 ** End a write transaction. The commit has already been done. This
56453 ** routine merely releases the lock.
56454 */
56456  if( pWal->writeLock ){
56458  pWal->writeLock = 0;
56459  pWal->iReCksum = 0;
56460  pWal->truncateOnCommit = 0;
56461  }
56462  return SQLITE_OK;
56463 }
56464 
56465 /*
56466 ** If any data has been written (but not committed) to the log file, this
56467 ** function moves the write-pointer back to the start of the transaction.
56468 **
56469 ** Additionally, the callback function is invoked for each frame written
56470 ** to the WAL since the start of the transaction. If the callback returns
56471 ** other than SQLITE_OK, it is not invoked again and the error code is
56472 ** returned to the caller.
56473 **
56474 ** Otherwise, if the callback function does not return an error, this
56475 ** function returns SQLITE_OK.
56476 */
56477 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
56478  int rc = SQLITE_OK;
56479  if( ALWAYS(pWal->writeLock) ){
56480  Pgno iMax = pWal->hdr.mxFrame;
56481  Pgno iFrame;
56482 
56483  /* Restore the clients cache of the wal-index header to the state it
56484  ** was in before the client began writing to the database.
56485  */
56486  memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
56487 
56488  for(iFrame=pWal->hdr.mxFrame+1;
56489  ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
56490  iFrame++
56491  ){
56492  /* This call cannot fail. Unless the page for which the page number
56493  ** is passed as the second argument is (a) in the cache and
56494  ** (b) has an outstanding reference, then xUndo is either a no-op
56495  ** (if (a) is false) or simply expels the page from the cache (if (b)
56496  ** is false).
56497  **
56498  ** If the upper layer is doing a rollback, it is guaranteed that there
56499  ** are no outstanding references to any page other than page 1. And
56500  ** page 1 is never written to the log until the transaction is
56501  ** committed. As a result, the call to xUndo may not fail.
56502  */
56503  assert( walFramePgno(pWal, iFrame)!=1 );
56504  rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
56505  }
56506  if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
56507  }
56508  return rc;
56509 }
56510 
56511 /*
56512 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
56513 ** values. This function populates the array with values required to
56514 ** "rollback" the write position of the WAL handle back to the current
56515 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
56516 */
56517 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
56518  assert( pWal->writeLock );
56519  aWalData[0] = pWal->hdr.mxFrame;
56520  aWalData[1] = pWal->hdr.aFrameCksum[0];
56521  aWalData[2] = pWal->hdr.aFrameCksum[1];
56522  aWalData[3] = pWal->nCkpt;
56523 }
56524 
56525 /*
56526 ** Move the write position of the WAL back to the point identified by
56527 ** the values in the aWalData[] array. aWalData must point to an array
56528 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
56529 ** by a call to WalSavepoint().
56530 */
56531 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
56532  int rc = SQLITE_OK;
56533 
56534  assert( pWal->writeLock );
56535  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
56536 
56537  if( aWalData[3]!=pWal->nCkpt ){
56538  /* This savepoint was opened immediately after the write-transaction
56539  ** was started. Right after that, the writer decided to wrap around
56540  ** to the start of the log. Update the savepoint values to match.
56541  */
56542  aWalData[0] = 0;
56543  aWalData[3] = pWal->nCkpt;
56544  }
56545 
56546  if( aWalData[0]<pWal->hdr.mxFrame ){
56547  pWal->hdr.mxFrame = aWalData[0];
56548  pWal->hdr.aFrameCksum[0] = aWalData[1];
56549  pWal->hdr.aFrameCksum[1] = aWalData[2];
56550  walCleanupHash(pWal);
56551  }
56552 
56553  return rc;
56554 }
56555 
56556 /*
56557 ** This function is called just before writing a set of frames to the log
56558 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
56559 ** to the current log file, it is possible to overwrite the start of the
56560 ** existing log file with the new frames (i.e. "reset" the log). If so,
56561 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
56562 ** unchanged.
56563 **
56564 ** SQLITE_OK is returned if no error is encountered (regardless of whether
56565 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
56566 ** if an error occurs.
56567 */
56568 static int walRestartLog(Wal *pWal){
56569  int rc = SQLITE_OK;
56570  int cnt;
56571 
56572  if( pWal->readLock==0 ){
56573  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56574  assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56575  if( pInfo->nBackfill>0 ){
56576  u32 salt1;
56577  sqlite3_randomness(4, &salt1);
56578  rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56579  if( rc==SQLITE_OK ){
56580  /* If all readers are using WAL_READ_LOCK(0) (in other words if no
56581  ** readers are currently using the WAL), then the transactions
56582  ** frames will overwrite the start of the existing log. Update the
56583  ** wal-index header to reflect this.
56584  **
56585  ** In theory it would be Ok to update the cache of the header only
56586  ** at this point. But updating the actual wal-index header is also
56587  ** safe and means there is no special case for sqlite3WalUndo()
56588  ** to handle if this transaction is rolled back. */
56589  walRestartHdr(pWal, salt1);
56591  }else if( rc!=SQLITE_BUSY ){
56592  return rc;
56593  }
56594  }
56595  walUnlockShared(pWal, WAL_READ_LOCK(0));
56596  pWal->readLock = -1;
56597  cnt = 0;
56598  do{
56599  int notUsed;
56600  rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
56601  }while( rc==WAL_RETRY );
56602  assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
56603  testcase( (rc&0xff)==SQLITE_IOERR );
56604  testcase( rc==SQLITE_PROTOCOL );
56605  testcase( rc==SQLITE_OK );
56606  }
56607  return rc;
56608 }
56609 
56610 /*
56611 ** Information about the current state of the WAL file and where
56612 ** the next fsync should occur - passed from sqlite3WalFrames() into
56613 ** walWriteToLog().
56614 */
56615 typedef struct WalWriter {
56616  Wal *pWal; /* The complete WAL information */
56617  sqlite3_file *pFd; /* The WAL file to which we write */
56618  sqlite3_int64 iSyncPoint; /* Fsync at this offset */
56619  int syncFlags; /* Flags for the fsync */
56620  int szPage; /* Size of one page */
56621 } WalWriter;
56622 
56623 /*
56624 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
56625 ** Do a sync when crossing the p->iSyncPoint boundary.
56626 **
56627 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
56628 ** first write the part before iSyncPoint, then sync, then write the
56629 ** rest.
56630 */
56631 static int walWriteToLog(
56632  WalWriter *p, /* WAL to write to */
56633  void *pContent, /* Content to be written */
56634  int iAmt, /* Number of bytes to write */
56635  sqlite3_int64 iOffset /* Start writing at this offset */
56636 ){
56637  int rc;
56638  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
56639  int iFirstAmt = (int)(p->iSyncPoint - iOffset);
56640  rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
56641  if( rc ) return rc;
56642  iOffset += iFirstAmt;
56643  iAmt -= iFirstAmt;
56644  pContent = (void*)(iFirstAmt + (char*)pContent);
56647  if( iAmt==0 || rc ) return rc;
56648  }
56649  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
56650  return rc;
56651 }
56652 
56653 /*
56654 ** Write out a single frame of the WAL
56655 */
56656 static int walWriteOneFrame(
56657  WalWriter *p, /* Where to write the frame */
56658  PgHdr *pPage, /* The page of the frame to be written */
56659  int nTruncate, /* The commit flag. Usually 0. >0 for commit */
56660  sqlite3_int64 iOffset /* Byte offset at which to write */
56661 ){
56662  int rc; /* Result code from subfunctions */
56663  void *pData; /* Data actually written */
56664  u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
56665 #if defined(SQLITE_HAS_CODEC)
56666  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
56667 #else
56668  pData = pPage->pData;
56669 #endif
56670  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
56671  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
56672  if( rc ) return rc;
56673  /* Write the page data */
56674  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
56675  return rc;
56676 }
56677 
56678 /*
56679 ** This function is called as part of committing a transaction within which
56680 ** one or more frames have been overwritten. It updates the checksums for
56681 ** all frames written to the wal file by the current transaction starting
56682 ** with the earliest to have been overwritten.
56683 **
56684 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
56685 */
56686 static int walRewriteChecksums(Wal *pWal, u32 iLast){
56687  const int szPage = pWal->szPage;/* Database page size */
56688  int rc = SQLITE_OK; /* Return code */
56689  u8 *aBuf; /* Buffer to load data from wal file into */
56690  u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
56691  u32 iRead; /* Next frame to read from wal file */
56692  i64 iCksumOff;
56693 
56694  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
56695  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
56696 
56697  /* Find the checksum values to use as input for the recalculating the
56698  ** first checksum. If the first frame is frame 1 (implying that the current
56699  ** transaction restarted the wal file), these values must be read from the
56700  ** wal-file header. Otherwise, read them from the frame header of the
56701  ** previous frame. */
56702  assert( pWal->iReCksum>0 );
56703  if( pWal->iReCksum==1 ){
56704  iCksumOff = 24;
56705  }else{
56706  iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
56707  }
56708  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
56709  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
56710  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
56711 
56712  iRead = pWal->iReCksum;
56713  pWal->iReCksum = 0;
56714  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
56715  i64 iOff = walFrameOffset(iRead, szPage);
56716  rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
56717  if( rc==SQLITE_OK ){
56718  u32 iPgno, nDbSize;
56719  iPgno = sqlite3Get4byte(aBuf);
56720  nDbSize = sqlite3Get4byte(&aBuf[4]);
56721 
56722  walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
56723  rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
56724  }
56725  }
56726 
56727  sqlite3_free(aBuf);
56728  return rc;
56729 }
56730 
56731 /*
56732 ** Write a set of frames to the log. The caller must hold the write-lock
56733 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
56734 */
56736  Wal *pWal, /* Wal handle to write to */
56737  int szPage, /* Database page-size in bytes */
56738  PgHdr *pList, /* List of dirty pages to write */
56739  Pgno nTruncate, /* Database size after this commit */
56740  int isCommit, /* True if this is a commit */
56741  int sync_flags /* Flags to pass to OsSync() (or 0) */
56742 ){
56743  int rc; /* Used to catch return codes */
56744  u32 iFrame; /* Next frame address */
56745  PgHdr *p; /* Iterator to run through pList with. */
56746  PgHdr *pLast = 0; /* Last frame in list */
56747  int nExtra = 0; /* Number of extra copies of last page */
56748  int szFrame; /* The size of a single frame */
56749  i64 iOffset; /* Next byte to write in WAL file */
56750  WalWriter w; /* The writer */
56751  u32 iFirst = 0; /* First frame that may be overwritten */
56752  WalIndexHdr *pLive; /* Pointer to shared header */
56753 
56754  assert( pList );
56755  assert( pWal->writeLock );
56756 
56757  /* If this frame set completes a transaction, then nTruncate>0. If
56758  ** nTruncate==0 then this frame set does not complete the transaction. */
56759  assert( (isCommit!=0)==(nTruncate!=0) );
56760 
56761 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
56762  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
56763  WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
56764  pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
56765  }
56766 #endif
56767 
56768  pLive = (WalIndexHdr*)walIndexHdr(pWal);
56769  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
56770  iFirst = pLive->mxFrame+1;
56771  }
56772 
56773  /* See if it is possible to write these frames into the start of the
56774  ** log file, instead of appending to it at pWal->hdr.mxFrame.
56775  */
56776  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
56777  return rc;
56778  }
56779 
56780  /* If this is the first frame written into the log, write the WAL
56781  ** header to the start of the WAL file. See comments at the top of
56782  ** this source file for a description of the WAL header format.
56783  */
56784  iFrame = pWal->hdr.mxFrame;
56785  if( iFrame==0 ){
56786  u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
56787  u32 aCksum[2]; /* Checksum for wal-header */
56788 
56789  sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
56790  sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
56791  sqlite3Put4byte(&aWalHdr[8], szPage);
56792  sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
56793  if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
56794  memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
56795  walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
56796  sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
56797  sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
56798 
56799  pWal->szPage = szPage;
56801  pWal->hdr.aFrameCksum[0] = aCksum[0];
56802  pWal->hdr.aFrameCksum[1] = aCksum[1];
56803  pWal->truncateOnCommit = 1;
56804 
56805  rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
56806  WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
56807  if( rc!=SQLITE_OK ){
56808  return rc;
56809  }
56810 
56811  /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
56812  ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
56813  ** an out-of-order write following a WAL restart could result in
56814  ** database corruption. See the ticket:
56815  **
56816  ** http://localhost:591/sqlite/info/ff5be73dee
56817  */
56818  if( pWal->syncHeader && sync_flags ){
56819  rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
56820  if( rc ) return rc;
56821  }
56822  }
56823  assert( (int)pWal->szPage==szPage );
56824 
56825  /* Setup information needed to write frames into the WAL */
56826  w.pWal = pWal;
56827  w.pFd = pWal->pWalFd;
56828  w.iSyncPoint = 0;
56829  w.syncFlags = sync_flags;
56830  w.szPage = szPage;
56831  iOffset = walFrameOffset(iFrame+1, szPage);
56832  szFrame = szPage + WAL_FRAME_HDRSIZE;
56833 
56834  /* Write all frames into the log file exactly once */
56835  for(p=pList; p; p=p->pDirty){
56836  int nDbSize; /* 0 normally. Positive == commit flag */
56837 
56838  /* Check if this page has already been written into the wal file by
56839  ** the current transaction. If so, overwrite the existing frame and
56840  ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
56841  ** checksums must be recomputed when the transaction is committed. */
56842  if( iFirst && (p->pDirty || isCommit==0) ){
56843  u32 iWrite = 0;
56844  VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
56845  assert( rc==SQLITE_OK || iWrite==0 );
56846  if( iWrite>=iFirst ){
56847  i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
56848  void *pData;
56849  if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
56850  pWal->iReCksum = iWrite;
56851  }
56852 #if defined(SQLITE_HAS_CODEC)
56853  if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
56854 #else
56855  pData = p->pData;
56856 #endif
56857  rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
56858  if( rc ) return rc;
56859  p->flags &= ~PGHDR_WAL_APPEND;
56860  continue;
56861  }
56862  }
56863 
56864  iFrame++;
56865  assert( iOffset==walFrameOffset(iFrame, szPage) );
56866  nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
56867  rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
56868  if( rc ) return rc;
56869  pLast = p;
56870  iOffset += szFrame;
56871  p->flags |= PGHDR_WAL_APPEND;
56872  }
56873 
56874  /* Recalculate checksums within the wal file if required. */
56875  if( isCommit && pWal->iReCksum ){
56876  rc = walRewriteChecksums(pWal, iFrame);
56877  if( rc ) return rc;
56878  }
56879 
56880  /* If this is the end of a transaction, then we might need to pad
56881  ** the transaction and/or sync the WAL file.
56882  **
56883  ** Padding and syncing only occur if this set of frames complete a
56884  ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
56885  ** or synchronous==OFF, then no padding or syncing are needed.
56886  **
56887  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
56888  ** needed and only the sync is done. If padding is needed, then the
56889  ** final frame is repeated (with its commit mark) until the next sector
56890  ** boundary is crossed. Only the part of the WAL prior to the last
56891  ** sector boundary is synced; the part of the last frame that extends
56892  ** past the sector boundary is written after the sync.
56893  */
56894  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
56895  int bSync = 1;
56896  if( pWal->padToSectorBoundary ){
56897  int sectorSize = sqlite3SectorSize(pWal->pWalFd);
56898  w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
56899  bSync = (w.iSyncPoint==iOffset);
56900  testcase( bSync );
56901  while( iOffset<w.iSyncPoint ){
56902  rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
56903  if( rc ) return rc;
56904  iOffset += szFrame;
56905  nExtra++;
56906  }
56907  }
56908  if( bSync ){
56909  assert( rc==SQLITE_OK );
56910  rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
56911  }
56912  }
56913 
56914  /* If this frame set completes the first transaction in the WAL and
56915  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
56916  ** journal size limit, if possible.
56917  */
56918  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
56919  i64 sz = pWal->mxWalSize;
56920  if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
56921  sz = walFrameOffset(iFrame+nExtra+1, szPage);
56922  }
56923  walLimitSize(pWal, sz);
56924  pWal->truncateOnCommit = 0;
56925  }
56926 
56927  /* Append data to the wal-index. It is not necessary to lock the
56928  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
56929  ** guarantees that there are no other writers, and no data that may
56930  ** be in use by existing readers is being overwritten.
56931  */
56932  iFrame = pWal->hdr.mxFrame;
56933  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
56934  if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
56935  iFrame++;
56936  rc = walIndexAppend(pWal, iFrame, p->pgno);
56937  }
56938  while( rc==SQLITE_OK && nExtra>0 ){
56939  iFrame++;
56940  nExtra--;
56941  rc = walIndexAppend(pWal, iFrame, pLast->pgno);
56942  }
56943 
56944  if( rc==SQLITE_OK ){
56945  /* Update the private copy of the header. */
56946  pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56947  testcase( szPage<=32768 );
56948  testcase( szPage>=65536 );
56949  pWal->hdr.mxFrame = iFrame;
56950  if( isCommit ){
56951  pWal->hdr.iChange++;
56952  pWal->hdr.nPage = nTruncate;
56953  }
56954  /* If this is a commit, update the wal-index header too. */
56955  if( isCommit ){
56956  walIndexWriteHdr(pWal);
56957  pWal->iCallback = iFrame;
56958  }
56959  }
56960 
56961  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
56962  return rc;
56963 }
56964 
56965 /*
56966 ** This routine is called to implement sqlite3_wal_checkpoint() and
56967 ** related interfaces.
56968 **
56969 ** Obtain a CHECKPOINT lock and then backfill as much information as
56970 ** we can from WAL into the database.
56971 **
56972 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
56973 ** callback. In this case this function runs a blocking checkpoint.
56974 */
56976  Wal *pWal, /* Wal connection */
56977  int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
56978  int (*xBusy)(void*), /* Function to call when busy */
56979  void *pBusyArg, /* Context argument for xBusyHandler */
56980  int sync_flags, /* Flags to sync db file with (or 0) */
56981  int nBuf, /* Size of temporary buffer */
56982  u8 *zBuf, /* Temporary buffer to use */
56983  int *pnLog, /* OUT: Number of frames in WAL */
56984  int *pnCkpt /* OUT: Number of backfilled frames in WAL */
56985 ){
56986  int rc; /* Return code */
56987  int isChanged = 0; /* True if a new wal-index header is loaded */
56988  int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
56989  int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
56990 
56991  assert( pWal->ckptLock==0 );
56992  assert( pWal->writeLock==0 );
56993 
56994  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56995  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56996  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56997 
56998  if( pWal->readOnly ) return SQLITE_READONLY;
56999  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
57000 
57001  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
57002  ** "checkpoint" lock on the database file. */
57003  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
57004  if( rc ){
57005  /* EVIDENCE-OF: R-10421-19736 If any other process is running a
57006  ** checkpoint operation at the same time, the lock cannot be obtained and
57007  ** SQLITE_BUSY is returned.
57008  ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
57009  ** it will not be invoked in this case.
57010  */
57011  testcase( rc==SQLITE_BUSY );
57012  testcase( xBusy!=0 );
57013  return rc;
57014  }
57015  pWal->ckptLock = 1;
57016 
57017  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
57018  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
57019  ** file.
57020  **
57021  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
57022  ** immediately, and a busy-handler is configured, it is invoked and the
57023  ** writer lock retried until either the busy-handler returns 0 or the
57024  ** lock is successfully obtained.
57025  */
57026  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
57027  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
57028  if( rc==SQLITE_OK ){
57029  pWal->writeLock = 1;
57030  }else if( rc==SQLITE_BUSY ){
57031  eMode2 = SQLITE_CHECKPOINT_PASSIVE;
57032  xBusy2 = 0;
57033  rc = SQLITE_OK;
57034  }
57035  }
57036 
57037  /* Read the wal-index header. */
57038  if( rc==SQLITE_OK ){
57039  rc = walIndexReadHdr(pWal, &isChanged);
57040  if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
57041  sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
57042  }
57043  }
57044 
57045  /* Copy data from the log to the database file. */
57046  if( rc==SQLITE_OK ){
57047 
57048  if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
57049  rc = SQLITE_CORRUPT_BKPT;
57050  }else{
57051  rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
57052  }
57053 
57054  /* If no error occurred, set the output variables. */
57055  if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
57056  if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
57057  if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
57058  }
57059  }
57060 
57061  if( isChanged ){
57062  /* If a new wal-index header was loaded before the checkpoint was
57063  ** performed, then the pager-cache associated with pWal is now
57064  ** out of date. So zero the cached wal-index header to ensure that
57065  ** next time the pager opens a snapshot on this database it knows that
57066  ** the cache needs to be reset.
57067  */
57068  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
57069  }
57070 
57071  /* Release the locks. */
57074  pWal->ckptLock = 0;
57075  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
57076  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
57077 }
57078 
57079 /* Return the value to pass to a sqlite3_wal_hook callback, the
57080 ** number of frames in the WAL at the point of the last commit since
57081 ** sqlite3WalCallback() was called. If no commits have occurred since
57082 ** the last call, then return 0.
57083 */
57085  u32 ret = 0;
57086  if( pWal ){
57087  ret = pWal->iCallback;
57088  pWal->iCallback = 0;
57089  }
57090  return (int)ret;
57091 }
57092 
57093 /*
57094 ** This function is called to change the WAL subsystem into or out
57095 ** of locking_mode=EXCLUSIVE.
57096 **
57097 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
57098 ** into locking_mode=NORMAL. This means that we must acquire a lock
57099 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
57100 ** or if the acquisition of the lock fails, then return 0. If the
57101 ** transition out of exclusive-mode is successful, return 1. This
57102 ** operation must occur while the pager is still holding the exclusive
57103 ** lock on the main database file.
57104 **
57105 ** If op is one, then change from locking_mode=NORMAL into
57106 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
57107 ** be released. Return 1 if the transition is made and 0 if the
57108 ** WAL is already in exclusive-locking mode - meaning that this
57109 ** routine is a no-op. The pager must already hold the exclusive lock
57110 ** on the main database file before invoking this operation.
57111 **
57112 ** If op is negative, then do a dry-run of the op==1 case but do
57113 ** not actually change anything. The pager uses this to see if it
57114 ** should acquire the database exclusive lock prior to invoking
57115 ** the op==1 case.
57116 */
57118  int rc;
57119  assert( pWal->writeLock==0 );
57120  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
57121 
57122  /* pWal->readLock is usually set, but might be -1 if there was a
57123  ** prior error while attempting to acquire are read-lock. This cannot
57124  ** happen if the connection is actually in exclusive mode (as no xShmLock
57125  ** locks are taken in this case). Nor should the pager attempt to
57126  ** upgrade to exclusive-mode following such an error.
57127  */
57128  assert( pWal->readLock>=0 || pWal->lockError );
57129  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
57130 
57131  if( op==0 ){
57132  if( pWal->exclusiveMode ){
57133  pWal->exclusiveMode = 0;
57134  if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
57135  pWal->exclusiveMode = 1;
57136  }
57137  rc = pWal->exclusiveMode==0;
57138  }else{
57139  /* Already in locking_mode=NORMAL */
57140  rc = 0;
57141  }
57142  }else if( op>0 ){
57143  assert( pWal->exclusiveMode==0 );
57144  assert( pWal->readLock>=0 );
57145  walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57146  pWal->exclusiveMode = 1;
57147  rc = 1;
57148  }else{
57149  rc = pWal->exclusiveMode==0;
57150  }
57151  return rc;
57152 }
57153 
57154 /*
57155 ** Return true if the argument is non-NULL and the WAL module is using
57156 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
57157 ** WAL module is using shared-memory, return false.
57158 */
57160  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
57161 }
57162 
57163 #ifdef SQLITE_ENABLE_SNAPSHOT
57164 /* Create a snapshot object. The content of a snapshot is opaque to
57165 ** every other subsystem, so the WAL module can put whatever it needs
57166 ** in the object.
57167 */
57168 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
57169  int rc = SQLITE_OK;
57170  WalIndexHdr *pRet;
57171 
57172  assert( pWal->readLock>=0 && pWal->writeLock==0 );
57173 
57174  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
57175  if( pRet==0 ){
57176  rc = SQLITE_NOMEM_BKPT;
57177  }else{
57178  memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
57179  *ppSnapshot = (sqlite3_snapshot*)pRet;
57180  }
57181 
57182  return rc;
57183 }
57184 
57185 /* Try to open on pSnapshot when the next read-transaction starts
57186 */
57187 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
57188  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
57189 }
57190 
57191 /*
57192 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
57193 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
57194 */
57196  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
57197  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
57198 
57199  /* aSalt[0] is a copy of the value stored in the wal file header. It
57200  ** is incremented each time the wal file is restarted. */
57201  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
57202  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
57203  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
57204  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
57205  return 0;
57206 }
57207 #endif /* SQLITE_ENABLE_SNAPSHOT */
57208 
57209 #ifdef SQLITE_ENABLE_ZIPVFS
57210 /*
57211 ** If the argument is not NULL, it points to a Wal object that holds a
57212 ** read-lock. This function returns the database page-size if it is known,
57213 ** or zero if it is not (or if pWal is NULL).
57214 */
57215 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
57216  assert( pWal==0 || pWal->readLock>=0 );
57217  return (pWal ? pWal->szPage : 0);
57218 }
57219 #endif
57220 
57221 /* Return the sqlite3_file object for the WAL file
57222 */
57223 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
57224  return pWal->pWalFd;
57225 }
57226 
57227 #endif /* #ifndef SQLITE_OMIT_WAL */
57228 
57229 /************** End of wal.c *************************************************/
57230 /************** Begin file btmutex.c *****************************************/
57231 /*
57232 ** 2007 August 27
57233 **
57234 ** The author disclaims copyright to this source code. In place of
57235 ** a legal notice, here is a blessing:
57236 **
57237 ** May you do good and not evil.
57238 ** May you find forgiveness for yourself and forgive others.
57239 ** May you share freely, never taking more than you give.
57240 **
57241 *************************************************************************
57242 **
57243 ** This file contains code used to implement mutexes on Btree objects.
57244 ** This code really belongs in btree.c. But btree.c is getting too
57245 ** big and we want to break it down some. This packaged seemed like
57246 ** a good breakout.
57247 */
57248 /************** Include btreeInt.h in the middle of btmutex.c ****************/
57249 /************** Begin file btreeInt.h ****************************************/
57250 /*
57251 ** 2004 April 6
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 ** This file implements an external (disk-based) database using BTrees.
57262 ** For a detailed discussion of BTrees, refer to
57263 **
57264 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
57265 ** "Sorting And Searching", pages 473-480. Addison-Wesley
57266 ** Publishing Company, Reading, Massachusetts.
57267 **
57268 ** The basic idea is that each page of the file contains N database
57269 ** entries and N+1 pointers to subpages.
57270 **
57271 ** ----------------------------------------------------------------
57272 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
57273 ** ----------------------------------------------------------------
57274 **
57275 ** All of the keys on the page that Ptr(0) points to have values less
57276 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
57277 ** values greater than Key(0) and less than Key(1). All of the keys
57278 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
57279 ** so forth.
57280 **
57281 ** Finding a particular key requires reading O(log(M)) pages from the
57282 ** disk where M is the number of entries in the tree.
57283 **
57284 ** In this implementation, a single file can hold one or more separate
57285 ** BTrees. Each BTree is identified by the index of its root page. The
57286 ** key and data for any entry are combined to form the "payload". A
57287 ** fixed amount of payload can be carried directly on the database
57288 ** page. If the payload is larger than the preset amount then surplus
57289 ** bytes are stored on overflow pages. The payload for an entry
57290 ** and the preceding pointer are combined to form a "Cell". Each
57291 ** page has a small header which contains the Ptr(N) pointer and other
57292 ** information such as the size of key and data.
57293 **
57294 ** FORMAT DETAILS
57295 **
57296 ** The file is divided into pages. The first page is called page 1,
57297 ** the second is page 2, and so forth. A page number of zero indicates
57298 ** "no such page". The page size can be any power of 2 between 512 and 65536.
57299 ** Each page can be either a btree page, a freelist page, an overflow
57300 ** page, or a pointer-map page.
57301 **
57302 ** The first page is always a btree page. The first 100 bytes of the first
57303 ** page contain a special header (the "file header") that describes the file.
57304 ** The format of the file header is as follows:
57305 **
57306 ** OFFSET SIZE DESCRIPTION
57307 ** 0 16 Header string: "SQLite format 3\000"
57308 ** 16 2 Page size in bytes. (1 means 65536)
57309 ** 18 1 File format write version
57310 ** 19 1 File format read version
57311 ** 20 1 Bytes of unused space at the end of each page
57312 ** 21 1 Max embedded payload fraction (must be 64)
57313 ** 22 1 Min embedded payload fraction (must be 32)
57314 ** 23 1 Min leaf payload fraction (must be 32)
57315 ** 24 4 File change counter
57316 ** 28 4 Reserved for future use
57317 ** 32 4 First freelist page
57318 ** 36 4 Number of freelist pages in the file
57319 ** 40 60 15 4-byte meta values passed to higher layers
57320 **
57321 ** 40 4 Schema cookie
57322 ** 44 4 File format of schema layer
57323 ** 48 4 Size of page cache
57324 ** 52 4 Largest root-page (auto/incr_vacuum)
57325 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
57326 ** 60 4 User version
57327 ** 64 4 Incremental vacuum mode
57328 ** 68 4 Application-ID
57329 ** 72 20 unused
57330 ** 92 4 The version-valid-for number
57331 ** 96 4 SQLITE_VERSION_NUMBER
57332 **
57333 ** All of the integer values are big-endian (most significant byte first).
57334 **
57335 ** The file change counter is incremented when the database is changed
57336 ** This counter allows other processes to know when the file has changed
57337 ** and thus when they need to flush their cache.
57338 **
57339 ** The max embedded payload fraction is the amount of the total usable
57340 ** space in a page that can be consumed by a single cell for standard
57341 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
57342 ** is to limit the maximum cell size so that at least 4 cells will fit
57343 ** on one page. Thus the default max embedded payload fraction is 64.
57344 **
57345 ** If the payload for a cell is larger than the max payload, then extra
57346 ** payload is spilled to overflow pages. Once an overflow page is allocated,
57347 ** as many bytes as possible are moved into the overflow pages without letting
57348 ** the cell size drop below the min embedded payload fraction.
57349 **
57350 ** The min leaf payload fraction is like the min embedded payload fraction
57351 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
57352 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
57353 ** not specified in the header.
57354 **
57355 ** Each btree pages is divided into three sections: The header, the
57356 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
57357 ** file header that occurs before the page header.
57358 **
57359 ** |----------------|
57360 ** | file header | 100 bytes. Page 1 only.
57361 ** |----------------|
57362 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
57363 ** |----------------|
57364 ** | cell pointer | | 2 bytes per cell. Sorted order.
57365 ** | array | | Grows downward
57366 ** | | v
57367 ** |----------------|
57368 ** | unallocated |
57369 ** | space |
57370 ** |----------------| ^ Grows upwards
57371 ** | cell content | | Arbitrary order interspersed with freeblocks.
57372 ** | area | | and free space fragments.
57373 ** |----------------|
57374 **
57375 ** The page headers looks like this:
57376 **
57377 ** OFFSET SIZE DESCRIPTION
57378 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
57379 ** 1 2 byte offset to the first freeblock
57380 ** 3 2 number of cells on this page
57381 ** 5 2 first byte of the cell content area
57382 ** 7 1 number of fragmented free bytes
57383 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
57384 **
57385 ** The flags define the format of this btree page. The leaf flag means that
57386 ** this page has no children. The zerodata flag means that this page carries
57387 ** only keys and no data. The intkey flag means that the key is an integer
57388 ** which is stored in the key size entry of the cell header rather than in
57389 ** the payload area.
57390 **
57391 ** The cell pointer array begins on the first byte after the page header.
57392 ** The cell pointer array contains zero or more 2-byte numbers which are
57393 ** offsets from the beginning of the page to the cell content in the cell
57394 ** content area. The cell pointers occur in sorted order. The system strives
57395 ** to keep free space after the last cell pointer so that new cells can
57396 ** be easily added without having to defragment the page.
57397 **
57398 ** Cell content is stored at the very end of the page and grows toward the
57399 ** beginning of the page.
57400 **
57401 ** Unused space within the cell content area is collected into a linked list of
57402 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
57403 ** to the first freeblock is given in the header. Freeblocks occur in
57404 ** increasing order. Because a freeblock must be at least 4 bytes in size,
57405 ** any group of 3 or fewer unused bytes in the cell content area cannot
57406 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
57407 ** a fragment. The total number of bytes in all fragments is recorded.
57408 ** in the page header at offset 7.
57409 **
57410 ** SIZE DESCRIPTION
57411 ** 2 Byte offset of the next freeblock
57412 ** 2 Bytes in this freeblock
57413 **
57414 ** Cells are of variable length. Cells are stored in the cell content area at
57415 ** the end of the page. Pointers to the cells are in the cell pointer array
57416 ** that immediately follows the page header. Cells is not necessarily
57417 ** contiguous or in order, but cell pointers are contiguous and in order.
57418 **
57419 ** Cell content makes use of variable length integers. A variable
57420 ** length integer is 1 to 9 bytes where the lower 7 bits of each
57421 ** byte are used. The integer consists of all bytes that have bit 8 set and
57422 ** the first byte with bit 8 clear. The most significant byte of the integer
57423 ** appears first. A variable-length integer may not be more than 9 bytes long.
57424 ** As a special case, all 8 bytes of the 9th byte are used as data. This
57425 ** allows a 64-bit integer to be encoded in 9 bytes.
57426 **
57427 ** 0x00 becomes 0x00000000
57428 ** 0x7f becomes 0x0000007f
57429 ** 0x81 0x00 becomes 0x00000080
57430 ** 0x82 0x00 becomes 0x00000100
57431 ** 0x80 0x7f becomes 0x0000007f
57432 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
57433 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
57434 **
57435 ** Variable length integers are used for rowids and to hold the number of
57436 ** bytes of key and data in a btree cell.
57437 **
57438 ** The content of a cell looks like this:
57439 **
57440 ** SIZE DESCRIPTION
57441 ** 4 Page number of the left child. Omitted if leaf flag is set.
57442 ** var Number of bytes of data. Omitted if the zerodata flag is set.
57443 ** var Number of bytes of key. Or the key itself if intkey flag is set.
57444 ** * Payload
57445 ** 4 First page of the overflow chain. Omitted if no overflow
57446 **
57447 ** Overflow pages form a linked list. Each page except the last is completely
57448 ** filled with data (pagesize - 4 bytes). The last page can have as little
57449 ** as 1 byte of data.
57450 **
57451 ** SIZE DESCRIPTION
57452 ** 4 Page number of next overflow page
57453 ** * Data
57454 **
57455 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
57456 ** file header points to the first in a linked list of trunk page. Each trunk
57457 ** page points to multiple leaf pages. The content of a leaf page is
57458 ** unspecified. A trunk page looks like this:
57459 **
57460 ** SIZE DESCRIPTION
57461 ** 4 Page number of next trunk page
57462 ** 4 Number of leaf pointers on this page
57463 ** * zero or more pages numbers of leaves
57464 */
57465 /* #include "sqliteInt.h" */
57466 
57467 
57468 /* The following value is the maximum cell size assuming a maximum page
57469 ** size give above.
57470 */
57471 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
57472 
57473 /* The maximum number of cells on a single page of the database. This
57474 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
57475 ** plus 2 bytes for the index to the cell in the page header). Such
57476 ** small cells will be rare, but they are possible.
57477 */
57478 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
57479 
57480 /* Forward declarations */
57481 typedef struct MemPage MemPage;
57482 typedef struct BtLock BtLock;
57483 typedef struct CellInfo CellInfo;
57484 
57485 /*
57486 ** This is a magic string that appears at the beginning of every
57487 ** SQLite database in order to identify the file as a real database.
57488 **
57489 ** You can change this value at compile-time by specifying a
57490 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
57491 ** header must be exactly 16 bytes including the zero-terminator so
57492 ** the string itself should be 15 characters long. If you change
57493 ** the header, then your custom library will not be able to read
57494 ** databases generated by the standard tools and the standard tools
57495 ** will not be able to read databases created by your custom library.
57496 */
57497 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
57498 # define SQLITE_FILE_HEADER "SQLite format 3"
57499 #endif
57500 
57501 /*
57502 ** Page type flags. An ORed combination of these flags appear as the
57503 ** first byte of on-disk image of every BTree page.
57504 */
57505 #define PTF_INTKEY 0x01
57506 #define PTF_ZERODATA 0x02
57507 #define PTF_LEAFDATA 0x04
57508 #define PTF_LEAF 0x08
57509 
57510 /*
57511 ** As each page of the file is loaded into memory, an instance of the following
57512 ** structure is appended and initialized to zero. This structure stores
57513 ** information about the page that is decoded from the raw file page.
57514 **
57515 ** The pParent field points back to the parent page. This allows us to
57516 ** walk up the BTree from any leaf to the root. Care must be taken to
57517 ** unref() the parent page pointer when this page is no longer referenced.
57518 ** The pageDestructor() routine handles that chore.
57519 **
57520 ** Access to all fields of this structure is controlled by the mutex
57521 ** stored in MemPage.pBt->mutex.
57522 */
57523 struct MemPage {
57524  u8 isInit; /* True if previously initialized. MUST BE FIRST! */
57525  u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
57526  u8 intKey; /* True if table b-trees. False for index b-trees */
57527  u8 intKeyLeaf; /* True if the leaf of an intKey table */
57528  u8 leaf; /* True if a leaf page */
57529  u8 hdrOffset; /* 100 for page 1. 0 otherwise */
57530  u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
57531  u8 max1bytePayload; /* min(maxLocal,127) */
57532  u8 bBusy; /* Prevent endless loops on corrupt database files */
57533  u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
57534  u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
57535  u16 cellOffset; /* Index in aData of first cell pointer */
57536  u16 nFree; /* Number of free bytes on the page */
57537  u16 nCell; /* Number of cells on this page, local and ovfl */
57538  u16 maskPage; /* Mask for page offset */
57539  u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
57540  ** non-overflow cell */
57541  u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
57542  BtShared *pBt; /* Pointer to BtShared that this page is part of */
57543  u8 *aData; /* Pointer to disk image of the page data */
57544  u8 *aDataEnd; /* One byte past the end of usable data */
57545  u8 *aCellIdx; /* The cell index area */
57546  u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
57547  DbPage *pDbPage; /* Pager page handle */
57548  u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
57549  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
57550  Pgno pgno; /* Page number for this page */
57551 };
57552 
57553 /*
57554 ** The in-memory image of a disk page has the auxiliary information appended
57555 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
57556 ** that extra information.
57557 */
57558 #define EXTRA_SIZE sizeof(MemPage)
57559 
57560 /*
57561 ** A linked list of the following structures is stored at BtShared.pLock.
57562 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
57563 ** is opened on the table with root page BtShared.iTable. Locks are removed
57564 ** from this list when a transaction is committed or rolled back, or when
57565 ** a btree handle is closed.
57566 */
57567 struct BtLock {
57568  Btree *pBtree; /* Btree handle holding this lock */
57569  Pgno iTable; /* Root page of table */
57570  u8 eLock; /* READ_LOCK or WRITE_LOCK */
57571  BtLock *pNext; /* Next in BtShared.pLock list */
57572 };
57573 
57574 /* Candidate values for BtLock.eLock */
57575 #define READ_LOCK 1
57576 #define WRITE_LOCK 2
57577 
57578 /* A Btree handle
57579 **
57580 ** A database connection contains a pointer to an instance of
57581 ** this object for every database file that it has open. This structure
57582 ** is opaque to the database connection. The database connection cannot
57583 ** see the internals of this structure and only deals with pointers to
57584 ** this structure.
57585 **
57586 ** For some database files, the same underlying database cache might be
57587 ** shared between multiple connections. In that case, each connection
57588 ** has it own instance of this object. But each instance of this object
57589 ** points to the same BtShared object. The database cache and the
57590 ** schema associated with the database file are all contained within
57591 ** the BtShared object.
57592 **
57593 ** All fields in this structure are accessed under sqlite3.mutex.
57594 ** The pBt pointer itself may not be changed while there exists cursors
57595 ** in the referenced BtShared that point back to this Btree since those
57596 ** cursors have to go through this Btree to find their BtShared and
57597 ** they often do so without holding sqlite3.mutex.
57598 */
57599 struct Btree {
57600  sqlite3 *db; /* The database connection holding this btree */
57601  BtShared *pBt; /* Sharable content of this btree */
57602  u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
57603  u8 sharable; /* True if we can share pBt with another db */
57604  u8 locked; /* True if db currently has pBt locked */
57605  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
57606  int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
57607  int nBackup; /* Number of backup operations reading this btree */
57608  u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
57609  Btree *pNext; /* List of other sharable Btrees from the same db */
57610  Btree *pPrev; /* Back pointer of the same list */
57611 #ifndef SQLITE_OMIT_SHARED_CACHE
57612  BtLock lock; /* Object used to lock page 1 */
57613 #endif
57614 };
57615 
57616 /*
57617 ** Btree.inTrans may take one of the following values.
57618 **
57619 ** If the shared-data extension is enabled, there may be multiple users
57620 ** of the Btree structure. At most one of these may open a write transaction,
57621 ** but any number may have active read transactions.
57622 */
57623 #define TRANS_NONE 0
57624 #define TRANS_READ 1
57625 #define TRANS_WRITE 2
57626 
57627 /*
57628 ** An instance of this object represents a single database file.
57629 **
57630 ** A single database file can be in use at the same time by two
57631 ** or more database connections. When two or more connections are
57632 ** sharing the same database file, each connection has it own
57633 ** private Btree object for the file and each of those Btrees points
57634 ** to this one BtShared object. BtShared.nRef is the number of
57635 ** connections currently sharing this database file.
57636 **
57637 ** Fields in this structure are accessed under the BtShared.mutex
57638 ** mutex, except for nRef and pNext which are accessed under the
57639 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
57640 ** may not be modified once it is initially set as long as nRef>0.
57641 ** The pSchema field may be set once under BtShared.mutex and
57642 ** thereafter is unchanged as long as nRef>0.
57643 **
57644 ** isPending:
57645 **
57646 ** If a BtShared client fails to obtain a write-lock on a database
57647 ** table (because there exists one or more read-locks on the table),
57648 ** the shared-cache enters 'pending-lock' state and isPending is
57649 ** set to true.
57650 **
57651 ** The shared-cache leaves the 'pending lock' state when either of
57652 ** the following occur:
57653 **
57654 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
57655 ** 2) The number of locks held by other connections drops to zero.
57656 **
57657 ** while in the 'pending-lock' state, no connection may start a new
57658 ** transaction.
57659 **
57660 ** This feature is included to help prevent writer-starvation.
57661 */
57662 struct BtShared {
57663  Pager *pPager; /* The page cache */
57664  sqlite3 *db; /* Database connection currently using this Btree */
57665  BtCursor *pCursor; /* A list of all open cursors */
57666  MemPage *pPage1; /* First page of the database */
57667  u8 openFlags; /* Flags to sqlite3BtreeOpen() */
57668 #ifndef SQLITE_OMIT_AUTOVACUUM
57669  u8 autoVacuum; /* True if auto-vacuum is enabled */
57670  u8 incrVacuum; /* True if incr-vacuum is enabled */
57671  u8 bDoTruncate; /* True to truncate db on commit */
57672 #endif
57673  u8 inTransaction; /* Transaction state */
57674  u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
57675 #ifdef SQLITE_HAS_CODEC
57676  u8 optimalReserve; /* Desired amount of reserved space per page */
57677 #endif
57678  u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
57679  u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
57680  u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
57681  u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
57682  u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
57683  u32 pageSize; /* Total number of bytes on a page */
57684  u32 usableSize; /* Number of usable bytes on each page */
57685  int nTransaction; /* Number of open transactions (read + write) */
57686  u32 nPage; /* Number of pages in the database */
57687  void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
57688  void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
57689  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
57690  Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
57691 #ifndef SQLITE_OMIT_SHARED_CACHE
57692  int nRef; /* Number of references to this structure */
57693  BtShared *pNext; /* Next on a list of sharable BtShared structs */
57694  BtLock *pLock; /* List of locks held on this shared-btree struct */
57695  Btree *pWriter; /* Btree with currently open write transaction */
57696 #endif
57697  u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
57698 };
57699 
57700 /*
57701 ** Allowed values for BtShared.btsFlags
57702 */
57703 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
57704 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
57705 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
57706 #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
57707 #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
57708 #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
57709 #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
57710 
57711 /*
57712 ** An instance of the following structure is used to hold information
57713 ** about a cell. The parseCellPtr() function fills in this structure
57714 ** based on information extract from the raw disk page.
57715 */
57716 struct CellInfo {
57717  i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
57718  u8 *pPayload; /* Pointer to the start of payload */
57719  u32 nPayload; /* Bytes of payload */
57720  u16 nLocal; /* Amount of payload held locally, not on overflow */
57721  u16 nSize; /* Size of the cell content on the main b-tree page */
57722 };
57723 
57724 /*
57725 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
57726 ** this will be declared corrupt. This value is calculated based on a
57727 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
57728 ** root-node and 3 for all other internal nodes.
57729 **
57730 ** If a tree that appears to be taller than this is encountered, it is
57731 ** assumed that the database is corrupt.
57732 */
57733 #define BTCURSOR_MAX_DEPTH 20
57734 
57735 /*
57736 ** A cursor is a pointer to a particular entry within a particular
57737 ** b-tree within a database file.
57738 **
57739 ** The entry is identified by its MemPage and the index in
57740 ** MemPage.aCell[] of the entry.
57741 **
57742 ** A single database file can be shared by two more database connections,
57743 ** but cursors cannot be shared. Each cursor is associated with a
57744 ** particular database connection identified BtCursor.pBtree.db.
57745 **
57746 ** Fields in this structure are accessed under the BtShared.mutex
57747 ** found at self->pBt->mutex.
57748 **
57749 ** skipNext meaning:
57750 ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
57751 ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
57752 ** eState==FAULT: Cursor fault with skipNext as error code.
57753 */
57754 struct BtCursor {
57755  Btree *pBtree; /* The Btree to which this cursor belongs */
57756  BtShared *pBt; /* The BtShared this cursor points to */
57757  BtCursor *pNext; /* Forms a linked list of all cursors */
57758  Pgno *aOverflow; /* Cache of overflow page locations */
57759  CellInfo info; /* A parse of the cell we are pointing at */
57760  i64 nKey; /* Size of pKey, or last integer key */
57761  void *pKey; /* Saved key that was cursor last known position */
57762  Pgno pgnoRoot; /* The root page of this tree */
57763  int nOvflAlloc; /* Allocated size of aOverflow[] array */
57764  int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
57765  ** Error code if eState==CURSOR_FAULT */
57766  u8 curFlags; /* zero or more BTCF_* flags defined below */
57767  u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
57768  u8 eState; /* One of the CURSOR_XXX constants (see below) */
57769  u8 hints; /* As configured by CursorSetHints() */
57770  /* All fields above are zeroed when the cursor is allocated. See
57771  ** sqlite3BtreeCursorZero(). Fields that follow must be manually
57772  ** initialized. */
57773  i8 iPage; /* Index of current page in apPage */
57774  u8 curIntKey; /* Value of apPage[0]->intKey */
57775  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
57776  void *padding1; /* Make object size a multiple of 16 */
57777  u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
57778  MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
57779 };
57780 
57781 /*
57782 ** Legal values for BtCursor.curFlags
57783 */
57784 #define BTCF_WriteFlag 0x01 /* True if a write cursor */
57785 #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
57786 #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
57787 #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
57788 #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
57789 #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
57790 
57791 /*
57792 ** Potential values for BtCursor.eState.
57793 **
57794 ** CURSOR_INVALID:
57795 ** Cursor does not point to a valid entry. This can happen (for example)
57796 ** because the table is empty or because BtreeCursorFirst() has not been
57797 ** called.
57798 **
57799 ** CURSOR_VALID:
57800 ** Cursor points to a valid entry. getPayload() etc. may be called.
57801 **
57802 ** CURSOR_SKIPNEXT:
57803 ** Cursor is valid except that the Cursor.skipNext field is non-zero
57804 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
57805 ** operation should be a no-op.
57806 **
57807 ** CURSOR_REQUIRESEEK:
57808 ** The table that this cursor was opened on still exists, but has been
57809 ** modified since the cursor was last used. The cursor position is saved
57810 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
57811 ** this state, restoreCursorPosition() can be called to attempt to
57812 ** seek the cursor to the saved position.
57813 **
57814 ** CURSOR_FAULT:
57815 ** An unrecoverable error (an I/O error or a malloc failure) has occurred
57816 ** on a different connection that shares the BtShared cache with this
57817 ** cursor. The error has left the cache in an inconsistent state.
57818 ** Do nothing else with this cursor. Any attempt to use the cursor
57819 ** should return the error code stored in BtCursor.skipNext
57820 */
57821 #define CURSOR_INVALID 0
57822 #define CURSOR_VALID 1
57823 #define CURSOR_SKIPNEXT 2
57824 #define CURSOR_REQUIRESEEK 3
57825 #define CURSOR_FAULT 4
57826 
57827 /*
57828 ** The database page the PENDING_BYTE occupies. This page is never used.
57829 */
57830 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
57831 
57832 /*
57833 ** These macros define the location of the pointer-map entry for a
57834 ** database page. The first argument to each is the number of usable
57835 ** bytes on each page of the database (often 1024). The second is the
57836 ** page number to look up in the pointer map.
57837 **
57838 ** PTRMAP_PAGENO returns the database page number of the pointer-map
57839 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
57840 ** the offset of the requested map entry.
57841 **
57842 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
57843 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
57844 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
57845 ** this test.
57846 */
57847 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
57848 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
57849 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
57850 
57851 /*
57852 ** The pointer map is a lookup table that identifies the parent page for
57853 ** each child page in the database file. The parent page is the page that
57854 ** contains a pointer to the child. Every page in the database contains
57855 ** 0 or 1 parent pages. (In this context 'database page' refers
57856 ** to any page that is not part of the pointer map itself.) Each pointer map
57857 ** entry consists of a single byte 'type' and a 4 byte parent page number.
57858 ** The PTRMAP_XXX identifiers below are the valid types.
57859 **
57860 ** The purpose of the pointer map is to facility moving pages from one
57861 ** position in the file to another as part of autovacuum. When a page
57862 ** is moved, the pointer in its parent must be updated to point to the
57863 ** new location. The pointer map is used to locate the parent page quickly.
57864 **
57865 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
57866 ** used in this case.
57867 **
57868 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
57869 ** is not used in this case.
57870 **
57871 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
57872 ** overflow pages. The page number identifies the page that
57873 ** contains the cell with a pointer to this overflow page.
57874 **
57875 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
57876 ** overflow pages. The page-number identifies the previous
57877 ** page in the overflow page list.
57878 **
57879 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
57880 ** identifies the parent page in the btree.
57881 */
57882 #define PTRMAP_ROOTPAGE 1
57883 #define PTRMAP_FREEPAGE 2
57884 #define PTRMAP_OVERFLOW1 3
57885 #define PTRMAP_OVERFLOW2 4
57886 #define PTRMAP_BTREE 5
57887 
57888 /* A bunch of assert() statements to check the transaction state variables
57889 ** of handle p (type Btree*) are internally consistent.
57890 */
57891 #define btreeIntegrity(p) \
57892  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
57893  assert( p->pBt->inTransaction>=p->inTrans );
57894 
57895 
57896 /*
57897 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
57898 ** if the database supports auto-vacuum or not. Because it is used
57899 ** within an expression that is an argument to another macro
57900 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
57901 ** So, this macro is defined instead.
57902 */
57903 #ifndef SQLITE_OMIT_AUTOVACUUM
57904 #define ISAUTOVACUUM (pBt->autoVacuum)
57905 #else
57906 #define ISAUTOVACUUM 0
57907 #endif
57908 
57909 
57910 /*
57911 ** This structure is passed around through all the sanity checking routines
57912 ** in order to keep track of some global state information.
57913 **
57914 ** The aRef[] array is allocated so that there is 1 bit for each page in
57915 ** the database. As the integrity-check proceeds, for each page used in
57916 ** the database the corresponding bit is set. This allows integrity-check to
57917 ** detect pages that are used twice and orphaned pages (both of which
57918 ** indicate corruption).
57919 */
57920 typedef struct IntegrityCk IntegrityCk;
57921 struct IntegrityCk {
57922  BtShared *pBt; /* The tree being checked out */
57923  Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
57924  u8 *aPgRef; /* 1 bit per page in the db (see above) */
57925  Pgno nPage; /* Number of pages in the database */
57926  int mxErr; /* Stop accumulating errors when this reaches zero */
57927  int nErr; /* Number of messages written to zErrMsg so far */
57928  int mallocFailed; /* A memory allocation error has occurred */
57929  const char *zPfx; /* Error message prefix */
57930  int v1, v2; /* Values for up to two %d fields in zPfx */
57931  StrAccum errMsg; /* Accumulate the error message text here */
57932  u32 *heap; /* Min-heap used for analyzing cell coverage */
57933 };
57934 
57935 /*
57936 ** Routines to read or write a two- and four-byte big-endian integer values.
57937 */
57938 #define get2byte(x) ((x)[0]<<8 | (x)[1])
57939 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
57940 #define get4byte sqlite3Get4byte
57941 #define put4byte sqlite3Put4byte
57942 
57943 /*
57944 ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
57945 ** two-byte aligned address. get2bytea() is only used for accessing the
57946 ** cell addresses in a btree header.
57947 */
57948 #if SQLITE_BYTEORDER==4321
57949 # define get2byteAligned(x) (*(u16*)(x))
57950 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57951  && GCC_VERSION>=4008000
57952 # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
57953 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57954  && defined(_MSC_VER) && _MSC_VER>=1300
57955 # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
57956 #else
57957 # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
57958 #endif
57959 
57960 /************** End of btreeInt.h ********************************************/
57961 /************** Continuing where we left off in btmutex.c ********************/
57962 #ifndef SQLITE_OMIT_SHARED_CACHE
57963 #if SQLITE_THREADSAFE
57964 
57965 /*
57966 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
57967 ** set BtShared.db to the database handle associated with p and the
57968 ** p->locked boolean to true.
57969 */
57970 static void lockBtreeMutex(Btree *p){
57971  assert( p->locked==0 );
57972  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
57973  assert( sqlite3_mutex_held(p->db->mutex) );
57974 
57976  p->pBt->db = p->db;
57977  p->locked = 1;
57978 }
57979 
57980 /*
57981 ** Release the BtShared mutex associated with B-Tree handle p and
57982 ** clear the p->locked boolean.
57983 */
57985  BtShared *pBt = p->pBt;
57986  assert( p->locked==1 );
57987  assert( sqlite3_mutex_held(pBt->mutex) );
57988  assert( sqlite3_mutex_held(p->db->mutex) );
57989  assert( p->db==pBt->db );
57990 
57991  sqlite3_mutex_leave(pBt->mutex);
57992  p->locked = 0;
57993 }
57994 
57995 /* Forward reference */
57996 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
57997 
57998 /*
57999 ** Enter a mutex on the given BTree object.
58000 **
58001 ** If the object is not sharable, then no mutex is ever required
58002 ** and this routine is a no-op. The underlying mutex is non-recursive.
58003 ** But we keep a reference count in Btree.wantToLock so the behavior
58004 ** of this interface is recursive.
58005 **
58006 ** To avoid deadlocks, multiple Btrees are locked in the same order
58007 ** by all database connections. The p->pNext is a list of other
58008 ** Btrees belonging to the same database connection as the p Btree
58009 ** which need to be locked after p. If we cannot get a lock on
58010 ** p, then first unlock all of the others on p->pNext, then wait
58011 ** for the lock to become available on p, then relock all of the
58012 ** subsequent Btrees that desire a lock.
58013 */
58015  /* Some basic sanity checking on the Btree. The list of Btrees
58016  ** connected by pNext and pPrev should be in sorted order by
58017  ** Btree.pBt value. All elements of the list should belong to
58018  ** the same connection. Only shared Btrees are on the list. */
58019  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
58020  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
58021  assert( p->pNext==0 || p->pNext->db==p->db );
58022  assert( p->pPrev==0 || p->pPrev->db==p->db );
58023  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
58024 
58025  /* Check for locking consistency */
58026  assert( !p->locked || p->wantToLock>0 );
58027  assert( p->sharable || p->wantToLock==0 );
58028 
58029  /* We should already hold a lock on the database connection */
58030  assert( sqlite3_mutex_held(p->db->mutex) );
58031 
58032  /* Unless the database is sharable and unlocked, then BtShared.db
58033  ** should already be set correctly. */
58034  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
58035 
58036  if( !p->sharable ) return;
58037  p->wantToLock++;
58038  if( p->locked ) return;
58039  btreeLockCarefully(p);
58040 }
58041 
58042 /* This is a helper function for sqlite3BtreeLock(). By moving
58043 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
58044 ** into this routine, we avoid unnecessary stack pointer changes
58045 ** and thus help the sqlite3BtreeLock() routine to run much faster
58046 ** in the common case.
58047 */
58049  Btree *pLater;
58050 
58051  /* In most cases, we should be able to acquire the lock we
58052  ** want without having to go through the ascending lock
58053  ** procedure that follows. Just be sure not to block.
58054  */
58055  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
58056  p->pBt->db = p->db;
58057  p->locked = 1;
58058  return;
58059  }
58060 
58061  /* To avoid deadlock, first release all locks with a larger
58062  ** BtShared address. Then acquire our lock. Then reacquire
58063  ** the other BtShared locks that we used to hold in ascending
58064  ** order.
58065  */
58066  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
58067  assert( pLater->sharable );
58068  assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
58069  assert( !pLater->locked || pLater->wantToLock>0 );
58070  if( pLater->locked ){
58071  unlockBtreeMutex(pLater);
58072  }
58073  }
58074  lockBtreeMutex(p);
58075  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
58076  if( pLater->wantToLock ){
58077  lockBtreeMutex(pLater);
58078  }
58079  }
58080 }
58081 
58082 
58083 /*
58084 ** Exit the recursive mutex on a Btree.
58085 */
58087  assert( sqlite3_mutex_held(p->db->mutex) );
58088  if( p->sharable ){
58089  assert( p->wantToLock>0 );
58090  p->wantToLock--;
58091  if( p->wantToLock==0 ){
58092  unlockBtreeMutex(p);
58093  }
58094  }
58095 }
58096 
58097 #ifndef NDEBUG
58098 /*
58099 ** Return true if the BtShared mutex is held on the btree, or if the
58100 ** B-Tree is not marked as sharable.
58101 **
58102 ** This routine is used only from within assert() statements.
58103 */
58104 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
58105  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
58106  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
58107  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
58108  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
58109 
58110  return (p->sharable==0 || p->locked);
58111 }
58112 #endif
58113 
58114 
58115 /*
58116 ** Enter the mutex on every Btree associated with a database
58117 ** connection. This is needed (for example) prior to parsing
58118 ** a statement since we will be comparing table and column names
58119 ** against all schemas and we do not want those schemas being
58120 ** reset out from under us.
58121 **
58122 ** There is a corresponding leave-all procedures.
58123 **
58124 ** Enter the mutexes in accending order by BtShared pointer address
58125 ** to avoid the possibility of deadlock when two threads with
58126 ** two or more btrees in common both try to lock all their btrees
58127 ** at the same instant.
58128 */
58130  int i;
58131  Btree *p;
58132  assert( sqlite3_mutex_held(db->mutex) );
58133  for(i=0; i<db->nDb; i++){
58134  p = db->aDb[i].pBt;
58135  if( p ) sqlite3BtreeEnter(p);
58136  }
58137 }
58139  int i;
58140  Btree *p;
58141  assert( sqlite3_mutex_held(db->mutex) );
58142  for(i=0; i<db->nDb; i++){
58143  p = db->aDb[i].pBt;
58144  if( p ) sqlite3BtreeLeave(p);
58145  }
58146 }
58147 
58148 #ifndef NDEBUG
58149 /*
58150 ** Return true if the current thread holds the database connection
58151 ** mutex and all required BtShared mutexes.
58152 **
58153 ** This routine is used inside assert() statements only.
58154 */
58155 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
58156  int i;
58157  if( !sqlite3_mutex_held(db->mutex) ){
58158  return 0;
58159  }
58160  for(i=0; i<db->nDb; i++){
58161  Btree *p;
58162  p = db->aDb[i].pBt;
58163  if( p && p->sharable &&
58164  (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
58165  return 0;
58166  }
58167  }
58168  return 1;
58169 }
58170 #endif /* NDEBUG */
58171 
58172 #ifndef NDEBUG
58173 /*
58174 ** Return true if the correct mutexes are held for accessing the
58175 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
58176 ** access are:
58177 **
58178 ** (1) The mutex on db
58179 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
58180 **
58181 ** If pSchema is not NULL, then iDb is computed from pSchema and
58182 ** db using sqlite3SchemaToIndex().
58183 */
58184 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
58185  Btree *p;
58186  assert( db!=0 );
58187  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
58188  assert( iDb>=0 && iDb<db->nDb );
58189  if( !sqlite3_mutex_held(db->mutex) ) return 0;
58190  if( iDb==1 ) return 1;
58191  p = db->aDb[iDb].pBt;
58192  assert( p!=0 );
58193  return p->sharable==0 || p->locked==1;
58194 }
58195 #endif /* NDEBUG */
58196 
58197 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
58198 /*
58199 ** The following are special cases for mutex enter routines for use
58200 ** in single threaded applications that use shared cache. Except for
58201 ** these two routines, all mutex operations are no-ops in that case and
58202 ** are null #defines in btree.h.
58203 **
58204 ** If shared cache is disabled, then all btree mutex routines, including
58205 ** the ones below, are no-ops and are null #defines in btree.h.
58206 */
58207 
58209  p->pBt->db = p->db;
58210 }
58212  int i;
58213  for(i=0; i<db->nDb; i++){
58214  Btree *p = db->aDb[i].pBt;
58215  if( p ){
58216  p->pBt->db = p->db;
58217  }
58218  }
58219 }
58220 #endif /* if SQLITE_THREADSAFE */
58221 
58222 #ifndef SQLITE_OMIT_INCRBLOB
58223 /*
58224 ** Enter a mutex on a Btree given a cursor owned by that Btree.
58225 **
58226 ** These entry points are used by incremental I/O only. Enter() is required
58227 ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
58228 ** the build is threadsafe. Leave() is only required by threadsafe builds.
58229 */
58231  sqlite3BtreeEnter(pCur->pBtree);
58232 }
58233 # if SQLITE_THREADSAFE
58235  sqlite3BtreeLeave(pCur->pBtree);
58236 }
58237 # endif
58238 #endif /* ifndef SQLITE_OMIT_INCRBLOB */
58239 
58240 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
58241 
58242 /************** End of btmutex.c *********************************************/
58243 /************** Begin file btree.c *******************************************/
58244 /*
58245 ** 2004 April 6
58246 **
58247 ** The author disclaims copyright to this source code. In place of
58248 ** a legal notice, here is a blessing:
58249 **
58250 ** May you do good and not evil.
58251 ** May you find forgiveness for yourself and forgive others.
58252 ** May you share freely, never taking more than you give.
58253 **
58254 *************************************************************************
58255 ** This file implements an external (disk-based) database using BTrees.
58256 ** See the header comment on "btreeInt.h" for additional information.
58257 ** Including a description of file format and an overview of operation.
58258 */
58259 /* #include "btreeInt.h" */
58260 
58261 /*
58262 ** The header string that appears at the beginning of every
58263 ** SQLite database.
58264 */
58265 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
58266 
58267 /*
58268 ** Set this global variable to 1 to enable tracing using the TRACE
58269 ** macro.
58270 */
58271 #if 0
58272 int sqlite3BtreeTrace=1; /* True to enable tracing */
58273 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
58274 #else
58275 # define TRACE(X)
58276 #endif
58277 
58278 /*
58279 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
58280 ** But if the value is zero, make it 65536.
58281 **
58282 ** This routine is used to extract the "offset to cell content area" value
58283 ** from the header of a btree page. If the page size is 65536 and the page
58284 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
58285 ** This routine makes the necessary adjustment to 65536.
58286 */
58287 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
58288 
58289 /*
58290 ** Values passed as the 5th argument to allocateBtreePage()
58291 */
58292 #define BTALLOC_ANY 0 /* Allocate any page */
58293 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
58294 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
58295 
58296 /*
58297 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
58298 ** defined, or 0 if it is. For example:
58299 **
58300 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58301 */
58302 #ifndef SQLITE_OMIT_AUTOVACUUM
58303 #define IfNotOmitAV(expr) (expr)
58304 #else
58305 #define IfNotOmitAV(expr) 0
58306 #endif
58307 
58308 #ifndef SQLITE_OMIT_SHARED_CACHE
58309 /*
58310 ** A list of BtShared objects that are eligible for participation
58311 ** in shared cache. This variable has file scope during normal builds,
58312 ** but the test harness needs to access it so we make it global for
58313 ** test builds.
58314 **
58315 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
58316 */
58317 #ifdef SQLITE_TEST
58319 #else
58320 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58321 #endif
58322 #endif /* SQLITE_OMIT_SHARED_CACHE */
58323 
58324 #ifndef SQLITE_OMIT_SHARED_CACHE
58325 /*
58326 ** Enable or disable the shared pager and schema features.
58327 **
58328 ** This routine has no effect on existing database connections.
58329 ** The shared cache setting effects only future calls to
58330 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
58331 */
58333  sqlite3GlobalConfig.sharedCacheEnabled = enable;
58334  return SQLITE_OK;
58335 }
58336 #endif
58337 
58338 
58339 
58340 #ifdef SQLITE_OMIT_SHARED_CACHE
58341  /*
58342  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
58343  ** and clearAllSharedCacheTableLocks()
58344  ** manipulate entries in the BtShared.pLock linked list used to store
58345  ** shared-cache table level locks. If the library is compiled with the
58346  ** shared-cache feature disabled, then there is only ever one user
58347  ** of each BtShared structure and so this locking is not necessary.
58348  ** So define the lock related functions as no-ops.
58349  */
58350  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
58351  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
58352  #define clearAllSharedCacheTableLocks(a)
58353  #define downgradeAllSharedCacheTableLocks(a)
58354  #define hasSharedCacheTableLock(a,b,c,d) 1
58355  #define hasReadConflicts(a, b) 0
58356 #endif
58357 
58358 #ifndef SQLITE_OMIT_SHARED_CACHE
58359 
58360 #ifdef SQLITE_DEBUG
58361 /*
58362 **** This function is only used as part of an assert() statement. ***
58363 **
58364 ** Check to see if pBtree holds the required locks to read or write to the
58365 ** table with root page iRoot. Return 1 if it does and 0 if not.
58366 **
58367 ** For example, when writing to a table with root-page iRoot via
58368 ** Btree connection pBtree:
58369 **
58370 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
58371 **
58372 ** When writing to an index that resides in a sharable database, the
58373 ** caller should have first obtained a lock specifying the root page of
58374 ** the corresponding table. This makes things a bit more complicated,
58375 ** as this module treats each table as a separate structure. To determine
58376 ** the table corresponding to the index being written, this
58377 ** function has to search through the database schema.
58378 **
58379 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
58380 ** hold a write-lock on the schema table (root page 1). This is also
58381 ** acceptable.
58382 */
58383 static int hasSharedCacheTableLock(
58384  Btree *pBtree, /* Handle that must hold lock */
58385  Pgno iRoot, /* Root page of b-tree */
58386  int isIndex, /* True if iRoot is the root of an index b-tree */
58387  int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
58388 ){
58389  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
58390  Pgno iTab = 0;
58391  BtLock *pLock;
58392 
58393  /* If this database is not shareable, or if the client is reading
58394  ** and has the read-uncommitted flag set, then no lock is required.
58395  ** Return true immediately.
58396  */
58397  if( (pBtree->sharable==0)
58398  || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
58399  ){
58400  return 1;
58401  }
58402 
58403  /* If the client is reading or writing an index and the schema is
58404  ** not loaded, then it is too difficult to actually check to see if
58405  ** the correct locks are held. So do not bother - just return true.
58406  ** This case does not come up very often anyhow.
58407  */
58408  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
58409  return 1;
58410  }
58411 
58412  /* Figure out the root-page that the lock should be held on. For table
58413  ** b-trees, this is just the root page of the b-tree being read or
58414  ** written. For index b-trees, it is the root page of the associated
58415  ** table. */
58416  if( isIndex ){
58417  HashElem *p;
58418  for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
58419  Index *pIdx = (Index *)sqliteHashData(p);
58420  if( pIdx->tnum==(int)iRoot ){
58421  if( iTab ){
58422  /* Two or more indexes share the same root page. There must
58423  ** be imposter tables. So just return true. The assert is not
58424  ** useful in that case. */
58425  return 1;
58426  }
58427  iTab = pIdx->pTable->tnum;
58428  }
58429  }
58430  }else{
58431  iTab = iRoot;
58432  }
58433 
58434  /* Search for the required lock. Either a write-lock on root-page iTab, a
58435  ** write-lock on the schema table, or (if the client is reading) a
58436  ** read-lock on iTab will suffice. Return 1 if any of these are found. */
58437  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
58438  if( pLock->pBtree==pBtree
58439  && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
58440  && pLock->eLock>=eLockType
58441  ){
58442  return 1;
58443  }
58444  }
58445 
58446  /* Failed to find the required lock. */
58447  return 0;
58448 }
58449 #endif /* SQLITE_DEBUG */
58450 
58451 #ifdef SQLITE_DEBUG
58452 /*
58453 **** This function may be used as part of assert() statements only. ****
58454 **
58455 ** Return true if it would be illegal for pBtree to write into the
58456 ** table or index rooted at iRoot because other shared connections are
58457 ** simultaneously reading that same table or index.
58458 **
58459 ** It is illegal for pBtree to write if some other Btree object that
58460 ** shares the same BtShared object is currently reading or writing
58461 ** the iRoot table. Except, if the other Btree object has the
58462 ** read-uncommitted flag set, then it is OK for the other object to
58463 ** have a read cursor.
58464 **
58465 ** For example, before writing to any part of the table or index
58466 ** rooted at page iRoot, one should call:
58467 **
58468 ** assert( !hasReadConflicts(pBtree, iRoot) );
58469 */
58470 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
58471  BtCursor *p;
58472  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58473  if( p->pgnoRoot==iRoot
58474  && p->pBtree!=pBtree
58475  && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
58476  ){
58477  return 1;
58478  }
58479  }
58480  return 0;
58481 }
58482 #endif /* #ifdef SQLITE_DEBUG */
58483 
58484 /*
58485 ** Query to see if Btree handle p may obtain a lock of type eLock
58486 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
58487 ** SQLITE_OK if the lock may be obtained (by calling
58488 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
58489 */
58490 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
58491  BtShared *pBt = p->pBt;
58492  BtLock *pIter;
58493 
58494  assert( sqlite3BtreeHoldsMutex(p) );
58495  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58496  assert( p->db!=0 );
58497  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
58498 
58499  /* If requesting a write-lock, then the Btree must have an open write
58500  ** transaction on this file. And, obviously, for this to be so there
58501  ** must be an open write transaction on the file itself.
58502  */
58503  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
58504  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
58505 
58506  /* This routine is a no-op if the shared-cache is not enabled */
58507  if( !p->sharable ){
58508  return SQLITE_OK;
58509  }
58510 
58511  /* If some other connection is holding an exclusive lock, the
58512  ** requested lock may not be obtained.
58513  */
58514  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
58517  }
58518 
58519  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58520  /* The condition (pIter->eLock!=eLock) in the following if(...)
58521  ** statement is a simplification of:
58522  **
58523  ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
58524  **
58525  ** since we know that if eLock==WRITE_LOCK, then no other connection
58526  ** may hold a WRITE_LOCK on any table in this file (since there can
58527  ** only be a single writer).
58528  */
58529  assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
58530  assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
58531  if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
58532  sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
58533  if( eLock==WRITE_LOCK ){
58534  assert( p==pBt->pWriter );
58535  pBt->btsFlags |= BTS_PENDING;
58536  }
58538  }
58539  }
58540  return SQLITE_OK;
58541 }
58542 #endif /* !SQLITE_OMIT_SHARED_CACHE */
58543 
58544 #ifndef SQLITE_OMIT_SHARED_CACHE
58545 /*
58546 ** Add a lock on the table with root-page iTable to the shared-btree used
58547 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
58548 ** WRITE_LOCK.
58549 **
58550 ** This function assumes the following:
58551 **
58552 ** (a) The specified Btree object p is connected to a sharable
58553 ** database (one with the BtShared.sharable flag set), and
58554 **
58555 ** (b) No other Btree objects hold a lock that conflicts
58556 ** with the requested lock (i.e. querySharedCacheTableLock() has
58557 ** already been called and returned SQLITE_OK).
58558 **
58559 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
58560 ** is returned if a malloc attempt fails.
58561 */
58562 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
58563  BtShared *pBt = p->pBt;
58564  BtLock *pLock = 0;
58565  BtLock *pIter;
58566 
58567  assert( sqlite3BtreeHoldsMutex(p) );
58568  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58569  assert( p->db!=0 );
58570 
58571  /* A connection with the read-uncommitted flag set will never try to
58572  ** obtain a read-lock using this function. The only read-lock obtained
58573  ** by a connection in read-uncommitted mode is on the sqlite_master
58574  ** table, and that lock is obtained in BtreeBeginTrans(). */
58575  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
58576 
58577  /* This function should only be called on a sharable b-tree after it
58578  ** has been determined that no other b-tree holds a conflicting lock. */
58579  assert( p->sharable );
58580  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
58581 
58582  /* First search the list for an existing lock on this table. */
58583  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58584  if( pIter->iTable==iTable && pIter->pBtree==p ){
58585  pLock = pIter;
58586  break;
58587  }
58588  }
58589 
58590  /* If the above search did not find a BtLock struct associating Btree p
58591  ** with table iTable, allocate one and link it into the list.
58592  */
58593  if( !pLock ){
58594  pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
58595  if( !pLock ){
58596  return SQLITE_NOMEM_BKPT;
58597  }
58598  pLock->iTable = iTable;
58599  pLock->pBtree = p;
58600  pLock->pNext = pBt->pLock;
58601  pBt->pLock = pLock;
58602  }
58603 
58604  /* Set the BtLock.eLock variable to the maximum of the current lock
58605  ** and the requested lock. This means if a write-lock was already held
58606  ** and a read-lock requested, we don't incorrectly downgrade the lock.
58607  */
58608  assert( WRITE_LOCK>READ_LOCK );
58609  if( eLock>pLock->eLock ){
58610  pLock->eLock = eLock;
58611  }
58612 
58613  return SQLITE_OK;
58614 }
58615 #endif /* !SQLITE_OMIT_SHARED_CACHE */
58616 
58617 #ifndef SQLITE_OMIT_SHARED_CACHE
58618 /*
58619 ** Release all the table locks (locks obtained via calls to
58620 ** the setSharedCacheTableLock() procedure) held by Btree object p.
58621 **
58622 ** This function assumes that Btree p has an open read or write
58623 ** transaction. If it does not, then the BTS_PENDING flag
58624 ** may be incorrectly cleared.
58625 */
58627  BtShared *pBt = p->pBt;
58628  BtLock **ppIter = &pBt->pLock;
58629 
58630  assert( sqlite3BtreeHoldsMutex(p) );
58631  assert( p->sharable || 0==*ppIter );
58632  assert( p->inTrans>0 );
58633 
58634  while( *ppIter ){
58635  BtLock *pLock = *ppIter;
58636  assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
58637  assert( pLock->pBtree->inTrans>=pLock->eLock );
58638  if( pLock->pBtree==p ){
58639  *ppIter = pLock->pNext;
58640  assert( pLock->iTable!=1 || pLock==&p->lock );
58641  if( pLock->iTable!=1 ){
58642  sqlite3_free(pLock);
58643  }
58644  }else{
58645  ppIter = &pLock->pNext;
58646  }
58647  }
58648 
58649  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
58650  if( pBt->pWriter==p ){
58651  pBt->pWriter = 0;
58652  pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58653  }else if( pBt->nTransaction==2 ){
58654  /* This function is called when Btree p is concluding its
58655  ** transaction. If there currently exists a writer, and p is not
58656  ** that writer, then the number of locks held by connections other
58657  ** than the writer must be about to drop to zero. In this case
58658  ** set the BTS_PENDING flag to 0.
58659  **
58660  ** If there is not currently a writer, then BTS_PENDING must
58661  ** be zero already. So this next line is harmless in that case.
58662  */
58663  pBt->btsFlags &= ~BTS_PENDING;
58664  }
58665 }
58666 
58667 /*
58668 ** This function changes all write-locks held by Btree p into read-locks.
58669 */
58671  BtShared *pBt = p->pBt;
58672  if( pBt->pWriter==p ){
58673  BtLock *pLock;
58674  pBt->pWriter = 0;
58675  pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58676  for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
58677  assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
58678  pLock->eLock = READ_LOCK;
58679  }
58680  }
58681 }
58682 
58683 #endif /* SQLITE_OMIT_SHARED_CACHE */
58684 
58685 static void releasePage(MemPage *pPage); /* Forward reference */
58686 
58687 /*
58688 ***** This routine is used inside of assert() only ****
58689 **
58690 ** Verify that the cursor holds the mutex on its BtShared
58691 */
58692 #ifdef SQLITE_DEBUG
58693 static int cursorHoldsMutex(BtCursor *p){
58694  return sqlite3_mutex_held(p->pBt->mutex);
58695 }
58696 
58697 /* Verify that the cursor and the BtShared agree about what is the current
58698 ** database connetion. This is important in shared-cache mode. If the database
58699 ** connection pointers get out-of-sync, it is possible for routines like
58700 ** btreeInitPage() to reference an stale connection pointer that references a
58701 ** a connection that has already closed. This routine is used inside assert()
58702 ** statements only and for the purpose of double-checking that the btree code
58703 ** does keep the database connection pointers up-to-date.
58704 */
58705 static int cursorOwnsBtShared(BtCursor *p){
58706  assert( cursorHoldsMutex(p) );
58707  return (p->pBtree->db==p->pBt->db);
58708 }
58709 #endif
58710 
58711 /*
58712 ** Invalidate the overflow cache of the cursor passed as the first argument.
58713 ** on the shared btree structure pBt.
58714 */
58715 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
58716 
58717 /*
58718 ** Invalidate the overflow page-list cache for all cursors opened
58719 ** on the shared btree structure pBt.
58720 */
58722  BtCursor *p;
58723  assert( sqlite3_mutex_held(pBt->mutex) );
58724  for(p=pBt->pCursor; p; p=p->pNext){
58726  }
58727 }
58728 
58729 #ifndef SQLITE_OMIT_INCRBLOB
58730 /*
58731 ** This function is called before modifying the contents of a table
58732 ** to invalidate any incrblob cursors that are open on the
58733 ** row or one of the rows being modified.
58734 **
58735 ** If argument isClearTable is true, then the entire contents of the
58736 ** table is about to be deleted. In this case invalidate all incrblob
58737 ** cursors open on any row within the table with root-page pgnoRoot.
58738 **
58739 ** Otherwise, if argument isClearTable is false, then the row with
58740 ** rowid iRow is being replaced or deleted. In this case invalidate
58741 ** only those incrblob cursors open on that specific row.
58742 */
58744  Btree *pBtree, /* The database file to check */
58745  i64 iRow, /* The rowid that might be changing */
58746  int isClearTable /* True if all rows are being deleted */
58747 ){
58748  BtCursor *p;
58749  if( pBtree->hasIncrblobCur==0 ) return;
58750  assert( sqlite3BtreeHoldsMutex(pBtree) );
58751  pBtree->hasIncrblobCur = 0;
58752  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58753  if( (p->curFlags & BTCF_Incrblob)!=0 ){
58754  pBtree->hasIncrblobCur = 1;
58755  if( isClearTable || p->info.nKey==iRow ){
58756  p->eState = CURSOR_INVALID;
58757  }
58758  }
58759  }
58760 }
58761 
58762 #else
58763  /* Stub function when INCRBLOB is omitted */
58764  #define invalidateIncrblobCursors(x,y,z)
58765 #endif /* SQLITE_OMIT_INCRBLOB */
58766 
58767 /*
58768 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
58769 ** when a page that previously contained data becomes a free-list leaf
58770 ** page.
58771 **
58772 ** The BtShared.pHasContent bitvec exists to work around an obscure
58773 ** bug caused by the interaction of two useful IO optimizations surrounding
58774 ** free-list leaf pages:
58775 **
58776 ** 1) When all data is deleted from a page and the page becomes
58777 ** a free-list leaf page, the page is not written to the database
58778 ** (as free-list leaf pages contain no meaningful data). Sometimes
58779 ** such a page is not even journalled (as it will not be modified,
58780 ** why bother journalling it?).
58781 **
58782 ** 2) When a free-list leaf page is reused, its content is not read
58783 ** from the database or written to the journal file (why should it
58784 ** be, if it is not at all meaningful?).
58785 **
58786 ** By themselves, these optimizations work fine and provide a handy
58787 ** performance boost to bulk delete or insert operations. However, if
58788 ** a page is moved to the free-list and then reused within the same
58789 ** transaction, a problem comes up. If the page is not journalled when
58790 ** it is moved to the free-list and it is also not journalled when it
58791 ** is extracted from the free-list and reused, then the original data
58792 ** may be lost. In the event of a rollback, it may not be possible
58793 ** to restore the database to its original configuration.
58794 **
58795 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
58796 ** moved to become a free-list leaf page, the corresponding bit is
58797 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
58798 ** optimization 2 above is omitted if the corresponding bit is already
58799 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
58800 ** at the end of every transaction.
58801 */
58802 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
58803  int rc = SQLITE_OK;
58804  if( !pBt->pHasContent ){
58805  assert( pgno<=pBt->nPage );
58806  pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
58807  if( !pBt->pHasContent ){
58808  rc = SQLITE_NOMEM_BKPT;
58809  }
58810  }
58811  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
58812  rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
58813  }
58814  return rc;
58815 }
58816 
58817 /*
58818 ** Query the BtShared.pHasContent vector.
58819 **
58820 ** This function is called when a free-list leaf page is removed from the
58821 ** free-list for reuse. It returns false if it is safe to retrieve the
58822 ** page from the pager layer with the 'no-content' flag set. True otherwise.
58823 */
58824 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
58825  Bitvec *p = pBt->pHasContent;
58826  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
58827 }
58828 
58829 /*
58830 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
58831 ** invoked at the conclusion of each write-transaction.
58832 */
58833 static void btreeClearHasContent(BtShared *pBt){
58835  pBt->pHasContent = 0;
58836 }
58837 
58838 /*
58839 ** Release all of the apPage[] pages for a cursor.
58840 */
58842  int i;
58843  for(i=0; i<=pCur->iPage; i++){
58844  releasePage(pCur->apPage[i]);
58845  pCur->apPage[i] = 0;
58846  }
58847  pCur->iPage = -1;
58848 }
58849 
58850 /*
58851 ** The cursor passed as the only argument must point to a valid entry
58852 ** when this function is called (i.e. have eState==CURSOR_VALID). This
58853 ** function saves the current cursor key in variables pCur->nKey and
58854 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
58855 ** code otherwise.
58856 **
58857 ** If the cursor is open on an intkey table, then the integer key
58858 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
58859 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
58860 ** set to point to a malloced buffer pCur->nKey bytes in size containing
58861 ** the key.
58862 */
58863 static int saveCursorKey(BtCursor *pCur){
58864  int rc = SQLITE_OK;
58865  assert( CURSOR_VALID==pCur->eState );
58866  assert( 0==pCur->pKey );
58867  assert( cursorHoldsMutex(pCur) );
58868 
58869  if( pCur->curIntKey ){
58870  /* Only the rowid is required for a table btree */
58871  pCur->nKey = sqlite3BtreeIntegerKey(pCur);
58872  }else{
58873  /* For an index btree, save the complete key content */
58874  void *pKey;
58875  pCur->nKey = sqlite3BtreePayloadSize(pCur);
58876  pKey = sqlite3Malloc( pCur->nKey );
58877  if( pKey ){
58878  rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
58879  if( rc==SQLITE_OK ){
58880  pCur->pKey = pKey;
58881  }else{
58882  sqlite3_free(pKey);
58883  }
58884  }else{
58885  rc = SQLITE_NOMEM_BKPT;
58886  }
58887  }
58888  assert( !pCur->curIntKey || !pCur->pKey );
58889  return rc;
58890 }
58891 
58892 /*
58893 ** Save the current cursor position in the variables BtCursor.nKey
58894 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
58895 **
58896 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
58897 ** prior to calling this routine.
58898 */
58899 static int saveCursorPosition(BtCursor *pCur){
58900  int rc;
58901 
58902  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
58903  assert( 0==pCur->pKey );
58904  assert( cursorHoldsMutex(pCur) );
58905 
58906  if( pCur->eState==CURSOR_SKIPNEXT ){
58907  pCur->eState = CURSOR_VALID;
58908  }else{
58909  pCur->skipNext = 0;
58910  }
58911 
58912  rc = saveCursorKey(pCur);
58913  if( rc==SQLITE_OK ){
58915  pCur->eState = CURSOR_REQUIRESEEK;
58916  }
58917 
58919  return rc;
58920 }
58921 
58922 /* Forward reference */
58924 
58925 /*
58926 ** Save the positions of all cursors (except pExcept) that are open on
58927 ** the table with root-page iRoot. "Saving the cursor position" means that
58928 ** the location in the btree is remembered in such a way that it can be
58929 ** moved back to the same spot after the btree has been modified. This
58930 ** routine is called just before cursor pExcept is used to modify the
58931 ** table, for example in BtreeDelete() or BtreeInsert().
58932 **
58933 ** If there are two or more cursors on the same btree, then all such
58934 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
58935 ** routine enforces that rule. This routine only needs to be called in
58936 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
58937 **
58938 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
58939 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
58940 ** pointless call to this routine.
58941 **
58942 ** Implementation note: This routine merely checks to see if any cursors
58943 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
58944 ** event that cursors are in need to being saved.
58945 */
58946 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
58947  BtCursor *p;
58948  assert( sqlite3_mutex_held(pBt->mutex) );
58949  assert( pExcept==0 || pExcept->pBt==pBt );
58950  for(p=pBt->pCursor; p; p=p->pNext){
58951  if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
58952  }
58953  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
58954  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
58955  return SQLITE_OK;
58956 }
58957 
58958 /* This helper routine to saveAllCursors does the actual work of saving
58959 ** the cursors if and when a cursor is found that actually requires saving.
58960 ** The common case is that no cursors need to be saved, so this routine is
58961 ** broken out from its caller to avoid unnecessary stack pointer movement.
58962 */
58964  BtCursor *p, /* The first cursor that needs saving */
58965  Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
58966  BtCursor *pExcept /* Do not save this cursor */
58967 ){
58968  do{
58969  if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
58970  if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58971  int rc = saveCursorPosition(p);
58972  if( SQLITE_OK!=rc ){
58973  return rc;
58974  }
58975  }else{
58976  testcase( p->iPage>0 );
58978  }
58979  }
58980  p = p->pNext;
58981  }while( p );
58982  return SQLITE_OK;
58983 }
58984 
58985 /*
58986 ** Clear the current cursor position.
58987 */
58989  assert( cursorHoldsMutex(pCur) );
58990  sqlite3_free(pCur->pKey);
58991  pCur->pKey = 0;
58992  pCur->eState = CURSOR_INVALID;
58993 }
58994 
58995 /*
58996 ** In this version of BtreeMoveto, pKey is a packed index record
58997 ** such as is generated by the OP_MakeRecord opcode. Unpack the
58998 ** record and then call BtreeMovetoUnpacked() to do the work.
58999 */
59000 static int btreeMoveto(
59001  BtCursor *pCur, /* Cursor open on the btree to be searched */
59002  const void *pKey, /* Packed key if the btree is an index */
59003  i64 nKey, /* Integer key for tables. Size of pKey for indices */
59004  int bias, /* Bias search to the high end */
59005  int *pRes /* Write search results here */
59006 ){
59007  int rc; /* Status code */
59008  UnpackedRecord *pIdxKey; /* Unpacked index key */
59009  char aSpace[384]; /* Temp space for pIdxKey - to avoid a malloc */
59010  char *pFree = 0;
59011 
59012  if( pKey ){
59013  assert( nKey==(i64)(int)nKey );
59015  pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
59016  );
59017  if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
59018  sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
59019  if( pIdxKey->nField==0 ){
59020  sqlite3DbFree(pCur->pKeyInfo->db, pFree);
59021  return SQLITE_CORRUPT_BKPT;
59022  }
59023  }else{
59024  pIdxKey = 0;
59025  }
59026  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
59027  if( pFree ){
59028  sqlite3DbFree(pCur->pKeyInfo->db, pFree);
59029  }
59030  return rc;
59031 }
59032 
59033 /*
59034 ** Restore the cursor to the position it was in (or as close to as possible)
59035 ** when saveCursorPosition() was called. Note that this call deletes the
59036 ** saved position info stored by saveCursorPosition(), so there can be
59037 ** at most one effective restoreCursorPosition() call after each
59038 ** saveCursorPosition().
59039 */
59041  int rc;
59042  int skipNext;
59043  assert( cursorOwnsBtShared(pCur) );
59044  assert( pCur->eState>=CURSOR_REQUIRESEEK );
59045  if( pCur->eState==CURSOR_FAULT ){
59046  return pCur->skipNext;
59047  }
59048  pCur->eState = CURSOR_INVALID;
59049  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
59050  if( rc==SQLITE_OK ){
59051  sqlite3_free(pCur->pKey);
59052  pCur->pKey = 0;
59053  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
59054  pCur->skipNext |= skipNext;
59055  if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
59056  pCur->eState = CURSOR_SKIPNEXT;
59057  }
59058  }
59059  return rc;
59060 }
59061 
59062 #define restoreCursorPosition(p) \
59063  (p->eState>=CURSOR_REQUIRESEEK ? \
59064  btreeRestoreCursorPosition(p) : \
59065  SQLITE_OK)
59066 
59067 /*
59068 ** Determine whether or not a cursor has moved from the position where
59069 ** it was last placed, or has been invalidated for any other reason.
59070 ** Cursors can move when the row they are pointing at is deleted out
59071 ** from under them, for example. Cursor might also move if a btree
59072 ** is rebalanced.
59073 **
59074 ** Calling this routine with a NULL cursor pointer returns false.
59075 **
59076 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
59077 ** back to where it ought to be if this routine returns true.
59078 */
59080  return pCur->eState!=CURSOR_VALID;
59081 }
59082 
59083 /*
59084 ** This routine restores a cursor back to its original position after it
59085 ** has been moved by some outside activity (such as a btree rebalance or
59086 ** a row having been deleted out from under the cursor).
59087 **
59088 ** On success, the *pDifferentRow parameter is false if the cursor is left
59089 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
59090 ** was pointing to has been deleted, forcing the cursor to point to some
59091 ** nearby row.
59092 **
59093 ** This routine should only be called for a cursor that just returned
59094 ** TRUE from sqlite3BtreeCursorHasMoved().
59095 */
59096 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
59097  int rc;
59098 
59099  assert( pCur!=0 );
59100  assert( pCur->eState!=CURSOR_VALID );
59101  rc = restoreCursorPosition(pCur);
59102  if( rc ){
59103  *pDifferentRow = 1;
59104  return rc;
59105  }
59106  if( pCur->eState!=CURSOR_VALID ){
59107  *pDifferentRow = 1;
59108  }else{
59109  assert( pCur->skipNext==0 );
59110  *pDifferentRow = 0;
59111  }
59112  return SQLITE_OK;
59113 }
59114 
59115 #ifdef SQLITE_ENABLE_CURSOR_HINTS
59116 /*
59117 ** Provide hints to the cursor. The particular hint given (and the type
59118 ** and number of the varargs parameters) is determined by the eHintType
59119 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
59120 */
59121 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
59122  /* Used only by system that substitute their own storage engine */
59123 }
59124 #endif
59125 
59126 /*
59127 ** Provide flag hints to the cursor.
59128 */
59130  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
59131  pCur->hints = x;
59132 }
59133 
59134 
59135 #ifndef SQLITE_OMIT_AUTOVACUUM
59136 /*
59137 ** Given a page number of a regular database page, return the page
59138 ** number for the pointer-map page that contains the entry for the
59139 ** input page number.
59140 **
59141 ** Return 0 (not a valid page) for pgno==1 since there is
59142 ** no pointer map associated with page 1. The integrity_check logic
59143 ** requires that ptrmapPageno(*,1)!=1.
59144 */
59145 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
59146  int nPagesPerMapPage;
59147  Pgno iPtrMap, ret;
59148  assert( sqlite3_mutex_held(pBt->mutex) );
59149  if( pgno<2 ) return 0;
59150  nPagesPerMapPage = (pBt->usableSize/5)+1;
59151  iPtrMap = (pgno-2)/nPagesPerMapPage;
59152  ret = (iPtrMap*nPagesPerMapPage) + 2;
59153  if( ret==PENDING_BYTE_PAGE(pBt) ){
59154  ret++;
59155  }
59156  return ret;
59157 }
59158 
59159 /*
59160 ** Write an entry into the pointer map.
59161 **
59162 ** This routine updates the pointer map entry for page number 'key'
59163 ** so that it maps to type 'eType' and parent page number 'pgno'.
59164 **
59165 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
59166 ** a no-op. If an error occurs, the appropriate error code is written
59167 ** into *pRC.
59168 */
59169 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
59170  DbPage *pDbPage; /* The pointer map page */
59171  u8 *pPtrmap; /* The pointer map data */
59172  Pgno iPtrmap; /* The pointer map page number */
59173  int offset; /* Offset in pointer map page */
59174  int rc; /* Return code from subfunctions */
59175 
59176  if( *pRC ) return;
59177 
59178  assert( sqlite3_mutex_held(pBt->mutex) );
59179  /* The master-journal page number must never be used as a pointer map page */
59180  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
59181 
59182  assert( pBt->autoVacuum );
59183  if( key==0 ){
59184  *pRC = SQLITE_CORRUPT_BKPT;
59185  return;
59186  }
59187  iPtrmap = PTRMAP_PAGENO(pBt, key);
59188  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59189  if( rc!=SQLITE_OK ){
59190  *pRC = rc;
59191  return;
59192  }
59193  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59194  if( offset<0 ){
59195  *pRC = SQLITE_CORRUPT_BKPT;
59196  goto ptrmap_exit;
59197  }
59198  assert( offset <= (int)pBt->usableSize-5 );
59199  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59200 
59201  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
59202  TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
59203  *pRC= rc = sqlite3PagerWrite(pDbPage);
59204  if( rc==SQLITE_OK ){
59205  pPtrmap[offset] = eType;
59206  put4byte(&pPtrmap[offset+1], parent);
59207  }
59208  }
59209 
59210 ptrmap_exit:
59211  sqlite3PagerUnref(pDbPage);
59212 }
59213 
59214 /*
59215 ** Read an entry from the pointer map.
59216 **
59217 ** This routine retrieves the pointer map entry for page 'key', writing
59218 ** the type and parent page number to *pEType and *pPgno respectively.
59219 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
59220 */
59221 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
59222  DbPage *pDbPage; /* The pointer map page */
59223  int iPtrmap; /* Pointer map page index */
59224  u8 *pPtrmap; /* Pointer map page data */
59225  int offset; /* Offset of entry in pointer map */
59226  int rc;
59227 
59228  assert( sqlite3_mutex_held(pBt->mutex) );
59229 
59230  iPtrmap = PTRMAP_PAGENO(pBt, key);
59231  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59232  if( rc!=0 ){
59233  return rc;
59234  }
59235  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59236 
59237  offset = PTRMAP_PTROFFSET(iPtrmap, key);
59238  if( offset<0 ){
59239  sqlite3PagerUnref(pDbPage);
59240  return SQLITE_CORRUPT_BKPT;
59241  }
59242  assert( offset <= (int)pBt->usableSize-5 );
59243  assert( pEType!=0 );
59244  *pEType = pPtrmap[offset];
59245  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
59246 
59247  sqlite3PagerUnref(pDbPage);
59248  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
59249  return SQLITE_OK;
59250 }
59251 
59252 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
59253  #define ptrmapPut(w,x,y,z,rc)
59254  #define ptrmapGet(w,x,y,z) SQLITE_OK
59255  #define ptrmapPutOvflPtr(x, y, rc)
59256 #endif
59257 
59258 /*
59259 ** Given a btree page and a cell index (0 means the first cell on
59260 ** the page, 1 means the second cell, and so forth) return a pointer
59261 ** to the cell content.
59262 **
59263 ** findCellPastPtr() does the same except it skips past the initial
59264 ** 4-byte child pointer found on interior pages, if there is one.
59265 **
59266 ** This routine works only for pages that do not contain overflow cells.
59267 */
59268 #define findCell(P,I) \
59269  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59270 #define findCellPastPtr(P,I) \
59271  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59272 
59273 
59274 /*
59275 ** This is common tail processing for btreeParseCellPtr() and
59276 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
59277 ** on a single B-tree page. Make necessary adjustments to the CellInfo
59278 ** structure.
59279 */
59281  MemPage *pPage, /* Page containing the cell */
59282  u8 *pCell, /* Pointer to the cell text. */
59283  CellInfo *pInfo /* Fill in this structure */
59284 ){
59285  /* If the payload will not fit completely on the local page, we have
59286  ** to decide how much to store locally and how much to spill onto
59287  ** overflow pages. The strategy is to minimize the amount of unused
59288  ** space on overflow pages while keeping the amount of local storage
59289  ** in between minLocal and maxLocal.
59290  **
59291  ** Warning: changing the way overflow payload is distributed in any
59292  ** way will result in an incompatible file format.
59293  */
59294  int minLocal; /* Minimum amount of payload held locally */
59295  int maxLocal; /* Maximum amount of payload held locally */
59296  int surplus; /* Overflow payload available for local storage */
59297 
59298  minLocal = pPage->minLocal;
59299  maxLocal = pPage->maxLocal;
59300  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
59301  testcase( surplus==maxLocal );
59302  testcase( surplus==maxLocal+1 );
59303  if( surplus <= maxLocal ){
59304  pInfo->nLocal = (u16)surplus;
59305  }else{
59306  pInfo->nLocal = (u16)minLocal;
59307  }
59308  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
59309 }
59310 
59311 /*
59312 ** The following routines are implementations of the MemPage.xParseCell()
59313 ** method.
59314 **
59315 ** Parse a cell content block and fill in the CellInfo structure.
59316 **
59317 ** btreeParseCellPtr() => table btree leaf nodes
59318 ** btreeParseCellNoPayload() => table btree internal nodes
59319 ** btreeParseCellPtrIndex() => index btree nodes
59320 **
59321 ** There is also a wrapper function btreeParseCell() that works for
59322 ** all MemPage types and that references the cell by index rather than
59323 ** by pointer.
59324 */
59326  MemPage *pPage, /* Page containing the cell */
59327  u8 *pCell, /* Pointer to the cell text. */
59328  CellInfo *pInfo /* Fill in this structure */
59329 ){
59330  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59331  assert( pPage->leaf==0 );
59332  assert( pPage->childPtrSize==4 );
59333 #ifndef SQLITE_DEBUG
59334  UNUSED_PARAMETER(pPage);
59335 #endif
59336  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
59337  pInfo->nPayload = 0;
59338  pInfo->nLocal = 0;
59339  pInfo->pPayload = 0;
59340  return;
59341 }
59342 static void btreeParseCellPtr(
59343  MemPage *pPage, /* Page containing the cell */
59344  u8 *pCell, /* Pointer to the cell text. */
59345  CellInfo *pInfo /* Fill in this structure */
59346 ){
59347  u8 *pIter; /* For scanning through pCell */
59348  u32 nPayload; /* Number of bytes of cell payload */
59349  u64 iKey; /* Extracted Key value */
59350 
59351  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59352  assert( pPage->leaf==0 || pPage->leaf==1 );
59353  assert( pPage->intKeyLeaf );
59354  assert( pPage->childPtrSize==0 );
59355  pIter = pCell;
59356 
59357  /* The next block of code is equivalent to:
59358  **
59359  ** pIter += getVarint32(pIter, nPayload);
59360  **
59361  ** The code is inlined to avoid a function call.
59362  */
59363  nPayload = *pIter;
59364  if( nPayload>=0x80 ){
59365  u8 *pEnd = &pIter[8];
59366  nPayload &= 0x7f;
59367  do{
59368  nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59369  }while( (*pIter)>=0x80 && pIter<pEnd );
59370  }
59371  pIter++;
59372 
59373  /* The next block of code is equivalent to:
59374  **
59375  ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
59376  **
59377  ** The code is inlined to avoid a function call.
59378  */
59379  iKey = *pIter;
59380  if( iKey>=0x80 ){
59381  u8 *pEnd = &pIter[7];
59382  iKey &= 0x7f;
59383  while(1){
59384  iKey = (iKey<<7) | (*++pIter & 0x7f);
59385  if( (*pIter)<0x80 ) break;
59386  if( pIter>=pEnd ){
59387  iKey = (iKey<<8) | *++pIter;
59388  break;
59389  }
59390  }
59391  }
59392  pIter++;
59393 
59394  pInfo->nKey = *(i64*)&iKey;
59395  pInfo->nPayload = nPayload;
59396  pInfo->pPayload = pIter;
59397  testcase( nPayload==pPage->maxLocal );
59398  testcase( nPayload==pPage->maxLocal+1 );
59399  if( nPayload<=pPage->maxLocal ){
59400  /* This is the (easy) common case where the entire payload fits
59401  ** on the local page. No overflow is required.
59402  */
59403  pInfo->nSize = nPayload + (u16)(pIter - pCell);
59404  if( pInfo->nSize<4 ) pInfo->nSize = 4;
59405  pInfo->nLocal = (u16)nPayload;
59406  }else{
59407  btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59408  }
59409 }
59411  MemPage *pPage, /* Page containing the cell */
59412  u8 *pCell, /* Pointer to the cell text. */
59413  CellInfo *pInfo /* Fill in this structure */
59414 ){
59415  u8 *pIter; /* For scanning through pCell */
59416  u32 nPayload; /* Number of bytes of cell payload */
59417 
59418  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59419  assert( pPage->leaf==0 || pPage->leaf==1 );
59420  assert( pPage->intKeyLeaf==0 );
59421  pIter = pCell + pPage->childPtrSize;
59422  nPayload = *pIter;
59423  if( nPayload>=0x80 ){
59424  u8 *pEnd = &pIter[8];
59425  nPayload &= 0x7f;
59426  do{
59427  nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59428  }while( *(pIter)>=0x80 && pIter<pEnd );
59429  }
59430  pIter++;
59431  pInfo->nKey = nPayload;
59432  pInfo->nPayload = nPayload;
59433  pInfo->pPayload = pIter;
59434  testcase( nPayload==pPage->maxLocal );
59435  testcase( nPayload==pPage->maxLocal+1 );
59436  if( nPayload<=pPage->maxLocal ){
59437  /* This is the (easy) common case where the entire payload fits
59438  ** on the local page. No overflow is required.
59439  */
59440  pInfo->nSize = nPayload + (u16)(pIter - pCell);
59441  if( pInfo->nSize<4 ) pInfo->nSize = 4;
59442  pInfo->nLocal = (u16)nPayload;
59443  }else{
59444  btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59445  }
59446 }
59447 static void btreeParseCell(
59448  MemPage *pPage, /* Page containing the cell */
59449  int iCell, /* The cell index. First cell is 0 */
59450  CellInfo *pInfo /* Fill in this structure */
59451 ){
59452  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
59453 }
59454 
59455 /*
59456 ** The following routines are implementations of the MemPage.xCellSize
59457 ** method.
59458 **
59459 ** Compute the total number of bytes that a Cell needs in the cell
59460 ** data area of the btree-page. The return number includes the cell
59461 ** data header and the local payload, but not any overflow page or
59462 ** the space used by the cell pointer.
59463 **
59464 ** cellSizePtrNoPayload() => table internal nodes
59465 ** cellSizePtr() => all index nodes & table leaf nodes
59466 */
59467 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
59468  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
59469  u8 *pEnd; /* End mark for a varint */
59470  u32 nSize; /* Size value to return */
59471 
59472 #ifdef SQLITE_DEBUG
59473  /* The value returned by this function should always be the same as
59474  ** the (CellInfo.nSize) value found by doing a full parse of the
59475  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59476  ** this function verifies that this invariant is not violated. */
59477  CellInfo debuginfo;
59478  pPage->xParseCell(pPage, pCell, &debuginfo);
59479 #endif
59480 
59481  nSize = *pIter;
59482  if( nSize>=0x80 ){
59483  pEnd = &pIter[8];
59484  nSize &= 0x7f;
59485  do{
59486  nSize = (nSize<<7) | (*++pIter & 0x7f);
59487  }while( *(pIter)>=0x80 && pIter<pEnd );
59488  }
59489  pIter++;
59490  if( pPage->intKey ){
59491  /* pIter now points at the 64-bit integer key value, a variable length
59492  ** integer. The following block moves pIter to point at the first byte
59493  ** past the end of the key value. */
59494  pEnd = &pIter[9];
59495  while( (*pIter++)&0x80 && pIter<pEnd );
59496  }
59497  testcase( nSize==pPage->maxLocal );
59498  testcase( nSize==pPage->maxLocal+1 );
59499  if( nSize<=pPage->maxLocal ){
59500  nSize += (u32)(pIter - pCell);
59501  if( nSize<4 ) nSize = 4;
59502  }else{
59503  int minLocal = pPage->minLocal;
59504  nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
59505  testcase( nSize==pPage->maxLocal );
59506  testcase( nSize==pPage->maxLocal+1 );
59507  if( nSize>pPage->maxLocal ){
59508  nSize = minLocal;
59509  }
59510  nSize += 4 + (u16)(pIter - pCell);
59511  }
59512  assert( nSize==debuginfo.nSize || CORRUPT_DB );
59513  return (u16)nSize;
59514 }
59515 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
59516  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
59517  u8 *pEnd; /* End mark for a varint */
59518 
59519 #ifdef SQLITE_DEBUG
59520  /* The value returned by this function should always be the same as
59521  ** the (CellInfo.nSize) value found by doing a full parse of the
59522  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59523  ** this function verifies that this invariant is not violated. */
59524  CellInfo debuginfo;
59525  pPage->xParseCell(pPage, pCell, &debuginfo);
59526 #else
59527  UNUSED_PARAMETER(pPage);
59528 #endif
59529 
59530  assert( pPage->childPtrSize==4 );
59531  pEnd = pIter + 9;
59532  while( (*pIter++)&0x80 && pIter<pEnd );
59533  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
59534  return (u16)(pIter - pCell);
59535 }
59536 
59537 
59538 #ifdef SQLITE_DEBUG
59539 /* This variation on cellSizePtr() is used inside of assert() statements
59540 ** only. */
59541 static u16 cellSize(MemPage *pPage, int iCell){
59542  return pPage->xCellSize(pPage, findCell(pPage, iCell));
59543 }
59544 #endif
59545 
59546 #ifndef SQLITE_OMIT_AUTOVACUUM
59547 /*
59548 ** If the cell pCell, part of page pPage contains a pointer
59549 ** to an overflow page, insert an entry into the pointer-map
59550 ** for the overflow page.
59551 */
59552 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
59553  CellInfo info;
59554  if( *pRC ) return;
59555  assert( pCell!=0 );
59556  pPage->xParseCell(pPage, pCell, &info);
59557  if( info.nLocal<info.nPayload ){
59558  Pgno ovfl = get4byte(&pCell[info.nSize-4]);
59559  ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
59560  }
59561 }
59562 #endif
59563 
59564 
59565 /*
59566 ** Defragment the page given. All Cells are moved to the
59567 ** end of the page and all free space is collected into one
59568 ** big FreeBlk that occurs in between the header and cell
59569 ** pointer array and the cell content area.
59570 **
59571 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
59572 ** b-tree page so that there are no freeblocks or fragment bytes, all
59573 ** unused bytes are contained in the unallocated space region, and all
59574 ** cells are packed tightly at the end of the page.
59575 */
59576 static int defragmentPage(MemPage *pPage){
59577  int i; /* Loop counter */
59578  int pc; /* Address of the i-th cell */
59579  int hdr; /* Offset to the page header */
59580  int size; /* Size of a cell */
59581  int usableSize; /* Number of usable bytes on a page */
59582  int cellOffset; /* Offset to the cell pointer array */
59583  int cbrk; /* Offset to the cell content area */
59584  int nCell; /* Number of cells on the page */
59585  unsigned char *data; /* The page data */
59586  unsigned char *temp; /* Temp area for cell content */
59587  unsigned char *src; /* Source of content */
59588  int iCellFirst; /* First allowable cell index */
59589  int iCellLast; /* Last possible cell index */
59590 
59591 
59592  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59593  assert( pPage->pBt!=0 );
59594  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
59595  assert( pPage->nOverflow==0 );
59596  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59597  temp = 0;
59598  src = data = pPage->aData;
59599  hdr = pPage->hdrOffset;
59600  cellOffset = pPage->cellOffset;
59601  nCell = pPage->nCell;
59602  assert( nCell==get2byte(&data[hdr+3]) );
59603  usableSize = pPage->pBt->usableSize;
59604  cbrk = usableSize;
59605  iCellFirst = cellOffset + 2*nCell;
59606  iCellLast = usableSize - 4;
59607  for(i=0; i<nCell; i++){
59608  u8 *pAddr; /* The i-th cell pointer */
59609  pAddr = &data[cellOffset + i*2];
59610  pc = get2byte(pAddr);
59611  testcase( pc==iCellFirst );
59612  testcase( pc==iCellLast );
59613  /* These conditions have already been verified in btreeInitPage()
59614  ** if PRAGMA cell_size_check=ON.
59615  */
59616  if( pc<iCellFirst || pc>iCellLast ){
59617  return SQLITE_CORRUPT_BKPT;
59618  }
59619  assert( pc>=iCellFirst && pc<=iCellLast );
59620  size = pPage->xCellSize(pPage, &src[pc]);
59621  cbrk -= size;
59622  if( cbrk<iCellFirst || pc+size>usableSize ){
59623  return SQLITE_CORRUPT_BKPT;
59624  }
59625  assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
59626  testcase( cbrk+size==usableSize );
59627  testcase( pc+size==usableSize );
59628  put2byte(pAddr, cbrk);
59629  if( temp==0 ){
59630  int x;
59631  if( cbrk==pc ) continue;
59632  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
59633  x = get2byte(&data[hdr+5]);
59634  memcpy(&temp[x], &data[x], (cbrk+size) - x);
59635  src = temp;
59636  }
59637  memcpy(&data[cbrk], &src[pc], size);
59638  }
59639  assert( cbrk>=iCellFirst );
59640  put2byte(&data[hdr+5], cbrk);
59641  data[hdr+1] = 0;
59642  data[hdr+2] = 0;
59643  data[hdr+7] = 0;
59644  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
59645  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59646  if( cbrk-iCellFirst!=pPage->nFree ){
59647  return SQLITE_CORRUPT_BKPT;
59648  }
59649  return SQLITE_OK;
59650 }
59651 
59652 /*
59653 ** Search the free-list on page pPg for space to store a cell nByte bytes in
59654 ** size. If one can be found, return a pointer to the space and remove it
59655 ** from the free-list.
59656 **
59657 ** If no suitable space can be found on the free-list, return NULL.
59658 **
59659 ** This function may detect corruption within pPg. If corruption is
59660 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
59661 **
59662 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
59663 ** will be ignored if adding the extra space to the fragmentation count
59664 ** causes the fragmentation count to exceed 60.
59665 */
59666 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
59667  const int hdr = pPg->hdrOffset;
59668  u8 * const aData = pPg->aData;
59669  int iAddr = hdr + 1;
59670  int pc = get2byte(&aData[iAddr]);
59671  int x;
59672  int usableSize = pPg->pBt->usableSize;
59673 
59674  assert( pc>0 );
59675  do{
59676  int size; /* Size of the free slot */
59677  /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
59678  ** increasing offset. */
59679  if( pc>usableSize-4 || pc<iAddr+4 ){
59680  *pRc = SQLITE_CORRUPT_BKPT;
59681  return 0;
59682  }
59683  /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
59684  ** freeblock form a big-endian integer which is the size of the freeblock
59685  ** in bytes, including the 4-byte header. */
59686  size = get2byte(&aData[pc+2]);
59687  if( (x = size - nByte)>=0 ){
59688  testcase( x==4 );
59689  testcase( x==3 );
59690  if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
59691  *pRc = SQLITE_CORRUPT_BKPT;
59692  return 0;
59693  }else if( x<4 ){
59694  /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
59695  ** number of bytes in fragments may not exceed 60. */
59696  if( aData[hdr+7]>57 ) return 0;
59697 
59698  /* Remove the slot from the free-list. Update the number of
59699  ** fragmented bytes within the page. */
59700  memcpy(&aData[iAddr], &aData[pc], 2);
59701  aData[hdr+7] += (u8)x;
59702  }else{
59703  /* The slot remains on the free-list. Reduce its size to account
59704  ** for the portion used by the new allocation. */
59705  put2byte(&aData[pc+2], x);
59706  }
59707  return &aData[pc + x];
59708  }
59709  iAddr = pc;
59710  pc = get2byte(&aData[pc]);
59711  }while( pc );
59712 
59713  return 0;
59714 }
59715 
59716 /*
59717 ** Allocate nByte bytes of space from within the B-Tree page passed
59718 ** as the first argument. Write into *pIdx the index into pPage->aData[]
59719 ** of the first byte of allocated space. Return either SQLITE_OK or
59720 ** an error code (usually SQLITE_CORRUPT).
59721 **
59722 ** The caller guarantees that there is sufficient space to make the
59723 ** allocation. This routine might need to defragment in order to bring
59724 ** all the space together, however. This routine will avoid using
59725 ** the first two bytes past the cell pointer area since presumably this
59726 ** allocation is being made in order to insert a new cell, so we will
59727 ** also end up needing a new cell pointer.
59728 */
59729 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
59730  const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
59731  u8 * const data = pPage->aData; /* Local cache of pPage->aData */
59732  int top; /* First byte of cell content area */
59733  int rc = SQLITE_OK; /* Integer return code */
59734  int gap; /* First byte of gap between cell pointers and cell content */
59735 
59736  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59737  assert( pPage->pBt );
59738  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59739  assert( nByte>=0 ); /* Minimum cell size is 4 */
59740  assert( pPage->nFree>=nByte );
59741  assert( pPage->nOverflow==0 );
59742  assert( nByte < (int)(pPage->pBt->usableSize-8) );
59743 
59744  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
59745  gap = pPage->cellOffset + 2*pPage->nCell;
59746  assert( gap<=65536 );
59747  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
59748  ** and the reserved space is zero (the usual value for reserved space)
59749  ** then the cell content offset of an empty page wants to be 65536.
59750  ** However, that integer is too large to be stored in a 2-byte unsigned
59751  ** integer, so a value of 0 is used in its place. */
59752  top = get2byte(&data[hdr+5]);
59753  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
59754  if( gap>top ){
59755  if( top==0 && pPage->pBt->usableSize==65536 ){
59756  top = 65536;
59757  }else{
59758  return SQLITE_CORRUPT_BKPT;
59759  }
59760  }
59761 
59762  /* If there is enough space between gap and top for one more cell pointer
59763  ** array entry offset, and if the freelist is not empty, then search the
59764  ** freelist looking for a free slot big enough to satisfy the request.
59765  */
59766  testcase( gap+2==top );
59767  testcase( gap+1==top );
59768  testcase( gap==top );
59769  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
59770  u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
59771  if( pSpace ){
59772  assert( pSpace>=data && (pSpace - data)<65536 );
59773  *pIdx = (int)(pSpace - data);
59774  return SQLITE_OK;
59775  }else if( rc ){
59776  return rc;
59777  }
59778  }
59779 
59780  /* The request could not be fulfilled using a freelist slot. Check
59781  ** to see if defragmentation is necessary.
59782  */
59783  testcase( gap+2+nByte==top );
59784  if( gap+2+nByte>top ){
59785  assert( pPage->nCell>0 || CORRUPT_DB );
59786  rc = defragmentPage(pPage);
59787  if( rc ) return rc;
59788  top = get2byteNotZero(&data[hdr+5]);
59789  assert( gap+nByte<=top );
59790  }
59791 
59792 
59793  /* Allocate memory from the gap in between the cell pointer array
59794  ** and the cell content area. The btreeInitPage() call has already
59795  ** validated the freelist. Given that the freelist is valid, there
59796  ** is no way that the allocation can extend off the end of the page.
59797  ** The assert() below verifies the previous sentence.
59798  */
59799  top -= nByte;
59800  put2byte(&data[hdr+5], top);
59801  assert( top+nByte <= (int)pPage->pBt->usableSize );
59802  *pIdx = top;
59803  return SQLITE_OK;
59804 }
59805 
59806 /*
59807 ** Return a section of the pPage->aData to the freelist.
59808 ** The first byte of the new free block is pPage->aData[iStart]
59809 ** and the size of the block is iSize bytes.
59810 **
59811 ** Adjacent freeblocks are coalesced.
59812 **
59813 ** Note that even though the freeblock list was checked by btreeInitPage(),
59814 ** that routine will not detect overlap between cells or freeblocks. Nor
59815 ** does it detect cells or freeblocks that encrouch into the reserved bytes
59816 ** at the end of the page. So do additional corruption checks inside this
59817 ** routine and return SQLITE_CORRUPT if any problems are found.
59818 */
59819 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
59820  u16 iPtr; /* Address of ptr to next freeblock */
59821  u16 iFreeBlk; /* Address of the next freeblock */
59822  u8 hdr; /* Page header size. 0 or 100 */
59823  u8 nFrag = 0; /* Reduction in fragmentation */
59824  u16 iOrigSize = iSize; /* Original value of iSize */
59825  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
59826  u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
59827  unsigned char *data = pPage->aData; /* Page content */
59828 
59829  assert( pPage->pBt!=0 );
59830  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59831  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
59832  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
59833  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59834  assert( iSize>=4 ); /* Minimum cell size is 4 */
59835  assert( iStart<=iLast );
59836 
59837  /* Overwrite deleted information with zeros when the secure_delete
59838  ** option is enabled */
59839  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
59840  memset(&data[iStart], 0, iSize);
59841  }
59842 
59843  /* The list of freeblocks must be in ascending order. Find the
59844  ** spot on the list where iStart should be inserted.
59845  */
59846  hdr = pPage->hdrOffset;
59847  iPtr = hdr + 1;
59848  if( data[iPtr+1]==0 && data[iPtr]==0 ){
59849  iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
59850  }else{
59851  while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
59852  if( iFreeBlk<iPtr+4 ){
59853  if( iFreeBlk==0 ) break;
59854  return SQLITE_CORRUPT_BKPT;
59855  }
59856  iPtr = iFreeBlk;
59857  }
59858  if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
59859  assert( iFreeBlk>iPtr || iFreeBlk==0 );
59860 
59861  /* At this point:
59862  ** iFreeBlk: First freeblock after iStart, or zero if none
59863  ** iPtr: The address of a pointer to iFreeBlk
59864  **
59865  ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
59866  */
59867  if( iFreeBlk && iEnd+3>=iFreeBlk ){
59868  nFrag = iFreeBlk - iEnd;
59869  if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
59870  iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
59871  if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
59872  iSize = iEnd - iStart;
59873  iFreeBlk = get2byte(&data[iFreeBlk]);
59874  }
59875 
59876  /* If iPtr is another freeblock (that is, if iPtr is not the freelist
59877  ** pointer in the page header) then check to see if iStart should be
59878  ** coalesced onto the end of iPtr.
59879  */
59880  if( iPtr>hdr+1 ){
59881  int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
59882  if( iPtrEnd+3>=iStart ){
59883  if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
59884  nFrag += iStart - iPtrEnd;
59885  iSize = iEnd - iPtr;
59886  iStart = iPtr;
59887  }
59888  }
59889  if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
59890  data[hdr+7] -= nFrag;
59891  }
59892  if( iStart==get2byte(&data[hdr+5]) ){
59893  /* The new freeblock is at the beginning of the cell content area,
59894  ** so just extend the cell content area rather than create another
59895  ** freelist entry */
59896  if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
59897  put2byte(&data[hdr+1], iFreeBlk);
59898  put2byte(&data[hdr+5], iEnd);
59899  }else{
59900  /* Insert the new freeblock into the freelist */
59901  put2byte(&data[iPtr], iStart);
59902  put2byte(&data[iStart], iFreeBlk);
59903  put2byte(&data[iStart+2], iSize);
59904  }
59905  pPage->nFree += iOrigSize;
59906  return SQLITE_OK;
59907 }
59908 
59909 /*
59910 ** Decode the flags byte (the first byte of the header) for a page
59911 ** and initialize fields of the MemPage structure accordingly.
59912 **
59913 ** Only the following combinations are supported. Anything different
59914 ** indicates a corrupt database files:
59915 **
59916 ** PTF_ZERODATA
59917 ** PTF_ZERODATA | PTF_LEAF
59918 ** PTF_LEAFDATA | PTF_INTKEY
59919 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
59920 */
59921 static int decodeFlags(MemPage *pPage, int flagByte){
59922  BtShared *pBt; /* A copy of pPage->pBt */
59923 
59924  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
59925  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59926  pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
59927  flagByte &= ~PTF_LEAF;
59928  pPage->childPtrSize = 4-4*pPage->leaf;
59929  pPage->xCellSize = cellSizePtr;
59930  pBt = pPage->pBt;
59931  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
59932  /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59933  ** interior table b-tree page. */
59934  assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
59935  /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59936  ** leaf table b-tree page. */
59937  assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
59938  pPage->intKey = 1;
59939  if( pPage->leaf ){
59940  pPage->intKeyLeaf = 1;
59941  pPage->xParseCell = btreeParseCellPtr;
59942  }else{
59943  pPage->intKeyLeaf = 0;
59946  }
59947  pPage->maxLocal = pBt->maxLeaf;
59948  pPage->minLocal = pBt->minLeaf;
59949  }else if( flagByte==PTF_ZERODATA ){
59950  /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59951  ** interior index b-tree page. */
59952  assert( (PTF_ZERODATA)==2 );
59953  /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59954  ** leaf index b-tree page. */
59955  assert( (PTF_ZERODATA|PTF_LEAF)==10 );
59956  pPage->intKey = 0;
59957  pPage->intKeyLeaf = 0;
59959  pPage->maxLocal = pBt->maxLocal;
59960  pPage->minLocal = pBt->minLocal;
59961  }else{
59962  /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
59963  ** an error. */
59964  return SQLITE_CORRUPT_BKPT;
59965  }
59966  pPage->max1bytePayload = pBt->max1bytePayload;
59967  return SQLITE_OK;
59968 }
59969 
59970 /*
59971 ** Initialize the auxiliary information for a disk block.
59972 **
59973 ** Return SQLITE_OK on success. If we see that the page does
59974 ** not contain a well-formed database page, then return
59975 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
59976 ** guarantee that the page is well-formed. It only shows that
59977 ** we failed to detect any corruption.
59978 */
59979 static int btreeInitPage(MemPage *pPage){
59980 
59981  assert( pPage->pBt!=0 );
59982  assert( pPage->pBt->db!=0 );
59983  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59984  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
59985  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
59986  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
59987 
59988  if( !pPage->isInit ){
59989  u16 pc; /* Address of a freeblock within pPage->aData[] */
59990  u8 hdr; /* Offset to beginning of page header */
59991  u8 *data; /* Equal to pPage->aData */
59992  BtShared *pBt; /* The main btree structure */
59993  int usableSize; /* Amount of usable space on each page */
59994  u16 cellOffset; /* Offset from start of page to first cell pointer */
59995  int nFree; /* Number of unused bytes on the page */
59996  int top; /* First byte of the cell content area */
59997  int iCellFirst; /* First allowable cell or freeblock offset */
59998  int iCellLast; /* Last possible cell or freeblock offset */
59999 
60000  pBt = pPage->pBt;
60001 
60002  hdr = pPage->hdrOffset;
60003  data = pPage->aData;
60004  /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
60005  ** the b-tree page type. */
60006  if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
60007  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60008  pPage->maskPage = (u16)(pBt->pageSize - 1);
60009  pPage->nOverflow = 0;
60010  usableSize = pBt->usableSize;
60011  pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
60012  pPage->aDataEnd = &data[usableSize];
60013  pPage->aCellIdx = &data[cellOffset];
60014  pPage->aDataOfst = &data[pPage->childPtrSize];
60015  /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
60016  ** the start of the cell content area. A zero value for this integer is
60017  ** interpreted as 65536. */
60018  top = get2byteNotZero(&data[hdr+5]);
60019  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
60020  ** number of cells on the page. */
60021  pPage->nCell = get2byte(&data[hdr+3]);
60022  if( pPage->nCell>MX_CELL(pBt) ){
60023  /* To many cells for a single page. The page must be corrupt */
60024  return SQLITE_CORRUPT_BKPT;
60025  }
60026  testcase( pPage->nCell==MX_CELL(pBt) );
60027  /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
60028  ** possible for a root page of a table that contains no rows) then the
60029  ** offset to the cell content area will equal the page size minus the
60030  ** bytes of reserved space. */
60031  assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
60032 
60033  /* A malformed database page might cause us to read past the end
60034  ** of page when parsing a cell.
60035  **
60036  ** The following block of code checks early to see if a cell extends
60037  ** past the end of a page boundary and causes SQLITE_CORRUPT to be
60038  ** returned if it does.
60039  */
60040  iCellFirst = cellOffset + 2*pPage->nCell;
60041  iCellLast = usableSize - 4;
60042  if( pBt->db->flags & SQLITE_CellSizeCk ){
60043  int i; /* Index into the cell pointer array */
60044  int sz; /* Size of a cell */
60045 
60046  if( !pPage->leaf ) iCellLast--;
60047  for(i=0; i<pPage->nCell; i++){
60048  pc = get2byteAligned(&data[cellOffset+i*2]);
60049  testcase( pc==iCellFirst );
60050  testcase( pc==iCellLast );
60051  if( pc<iCellFirst || pc>iCellLast ){
60052  return SQLITE_CORRUPT_BKPT;
60053  }
60054  sz = pPage->xCellSize(pPage, &data[pc]);
60055  testcase( pc+sz==usableSize );
60056  if( pc+sz>usableSize ){
60057  return SQLITE_CORRUPT_BKPT;
60058  }
60059  }
60060  if( !pPage->leaf ) iCellLast++;
60061  }
60062 
60063  /* Compute the total free space on the page
60064  ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
60065  ** start of the first freeblock on the page, or is zero if there are no
60066  ** freeblocks. */
60067  pc = get2byte(&data[hdr+1]);
60068  nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
60069  while( pc>0 ){
60070  u16 next, size;
60071  if( pc<iCellFirst || pc>iCellLast ){
60072  /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
60073  ** always be at least one cell before the first freeblock.
60074  **
60075  ** Or, the freeblock is off the end of the page
60076  */
60077  return SQLITE_CORRUPT_BKPT;
60078  }
60079  next = get2byte(&data[pc]);
60080  size = get2byte(&data[pc+2]);
60081  if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
60082  /* Free blocks must be in ascending order. And the last byte of
60083  ** the free-block must lie on the database page. */
60084  return SQLITE_CORRUPT_BKPT;
60085  }
60086  nFree = nFree + size;
60087  pc = next;
60088  }
60089 
60090  /* At this point, nFree contains the sum of the offset to the start
60091  ** of the cell-content area plus the number of free bytes within
60092  ** the cell-content area. If this is greater than the usable-size
60093  ** of the page, then the page must be corrupted. This check also
60094  ** serves to verify that the offset to the start of the cell-content
60095  ** area, according to the page header, lies within the page.
60096  */
60097  if( nFree>usableSize ){
60098  return SQLITE_CORRUPT_BKPT;
60099  }
60100  pPage->nFree = (u16)(nFree - iCellFirst);
60101  pPage->isInit = 1;
60102  }
60103  return SQLITE_OK;
60104 }
60105 
60106 /*
60107 ** Set up a raw page so that it looks like a database page holding
60108 ** no entries.
60109 */
60110 static void zeroPage(MemPage *pPage, int flags){
60111  unsigned char *data = pPage->aData;
60112  BtShared *pBt = pPage->pBt;
60113  u8 hdr = pPage->hdrOffset;
60114  u16 first;
60115 
60116  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
60117  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60118  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
60119  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60120  assert( sqlite3_mutex_held(pBt->mutex) );
60121  if( pBt->btsFlags & BTS_SECURE_DELETE ){
60122  memset(&data[hdr], 0, pBt->usableSize - hdr);
60123  }
60124  data[hdr] = (char)flags;
60125  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
60126  memset(&data[hdr+1], 0, 4);
60127  data[hdr+7] = 0;
60128  put2byte(&data[hdr+5], pBt->usableSize);
60129  pPage->nFree = (u16)(pBt->usableSize - first);
60130  decodeFlags(pPage, flags);
60131  pPage->cellOffset = first;
60132  pPage->aDataEnd = &data[pBt->usableSize];
60133  pPage->aCellIdx = &data[first];
60134  pPage->aDataOfst = &data[pPage->childPtrSize];
60135  pPage->nOverflow = 0;
60136  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60137  pPage->maskPage = (u16)(pBt->pageSize - 1);
60138  pPage->nCell = 0;
60139  pPage->isInit = 1;
60140 }
60141 
60142 
60143 /*
60144 ** Convert a DbPage obtained from the pager into a MemPage used by
60145 ** the btree layer.
60146 */
60147 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
60148  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60149  if( pgno!=pPage->pgno ){
60150  pPage->aData = sqlite3PagerGetData(pDbPage);
60151  pPage->pDbPage = pDbPage;
60152  pPage->pBt = pBt;
60153  pPage->pgno = pgno;
60154  pPage->hdrOffset = pgno==1 ? 100 : 0;
60155  }
60156  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
60157  return pPage;
60158 }
60159 
60160 /*
60161 ** Get a page from the pager. Initialize the MemPage.pBt and
60162 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
60163 **
60164 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
60165 ** about the content of the page at this time. So do not go to the disk
60166 ** to fetch the content. Just fill in the content with zeros for now.
60167 ** If in the future we call sqlite3PagerWrite() on this page, that
60168 ** means we have started to be concerned about content and the disk
60169 ** read should occur at that point.
60170 */
60171 static int btreeGetPage(
60172  BtShared *pBt, /* The btree */
60173  Pgno pgno, /* Number of the page to fetch */
60174  MemPage **ppPage, /* Return the page in this parameter */
60175  int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60176 ){
60177  int rc;
60178  DbPage *pDbPage;
60179 
60180  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
60181  assert( sqlite3_mutex_held(pBt->mutex) );
60182  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
60183  if( rc ) return rc;
60184  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
60185  return SQLITE_OK;
60186 }
60187 
60188 /*
60189 ** Retrieve a page from the pager cache. If the requested page is not
60190 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
60191 ** MemPage.aData elements if needed.
60192 */
60193 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
60194  DbPage *pDbPage;
60195  assert( sqlite3_mutex_held(pBt->mutex) );
60196  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
60197  if( pDbPage ){
60198  return btreePageFromDbPage(pDbPage, pgno, pBt);
60199  }
60200  return 0;
60201 }
60202 
60203 /*
60204 ** Return the size of the database file in pages. If there is any kind of
60205 ** error, return ((unsigned int)-1).
60206 */
60207 static Pgno btreePagecount(BtShared *pBt){
60208  return pBt->nPage;
60209 }
60211  assert( sqlite3BtreeHoldsMutex(p) );
60212  assert( ((p->pBt->nPage)&0x8000000)==0 );
60213  return btreePagecount(p->pBt);
60214 }
60215 
60216 /*
60217 ** Get a page from the pager and initialize it.
60218 **
60219 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
60220 ** call. Do additional sanity checking on the page in this case.
60221 ** And if the fetch fails, this routine must decrement pCur->iPage.
60222 **
60223 ** The page is fetched as read-write unless pCur is not NULL and is
60224 ** a read-only cursor.
60225 **
60226 ** If an error occurs, then *ppPage is undefined. It
60227 ** may remain unchanged, or it may be set to an invalid value.
60228 */
60229 static int getAndInitPage(
60230  BtShared *pBt, /* The database file */
60231  Pgno pgno, /* Number of the page to get */
60232  MemPage **ppPage, /* Write the page pointer here */
60233  BtCursor *pCur, /* Cursor to receive the page, or NULL */
60234  int bReadOnly /* True for a read-only page */
60235 ){
60236  int rc;
60237  DbPage *pDbPage;
60238  assert( sqlite3_mutex_held(pBt->mutex) );
60239  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
60240  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
60241  assert( pCur==0 || pCur->iPage>0 );
60242 
60243  if( pgno>btreePagecount(pBt) ){
60244  rc = SQLITE_CORRUPT_BKPT;
60245  goto getAndInitPage_error;
60246  }
60247  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
60248  if( rc ){
60249  goto getAndInitPage_error;
60250  }
60251  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60252  if( (*ppPage)->isInit==0 ){
60253  btreePageFromDbPage(pDbPage, pgno, pBt);
60254  rc = btreeInitPage(*ppPage);
60255  if( rc!=SQLITE_OK ){
60256  releasePage(*ppPage);
60257  goto getAndInitPage_error;
60258  }
60259  }
60260  assert( (*ppPage)->pgno==pgno );
60261  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
60262 
60263  /* If obtaining a child page for a cursor, we must verify that the page is
60264  ** compatible with the root page. */
60265  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
60266  rc = SQLITE_CORRUPT_BKPT;
60267  releasePage(*ppPage);
60268  goto getAndInitPage_error;
60269  }
60270  return SQLITE_OK;
60271 
60272 getAndInitPage_error:
60273  if( pCur ) pCur->iPage--;
60274  testcase( pgno==0 );
60275  assert( pgno!=0 || rc==SQLITE_CORRUPT );
60276  return rc;
60277 }
60278 
60279 /*
60280 ** Release a MemPage. This should be called once for each prior
60281 ** call to btreeGetPage.
60282 */
60283 static void releasePageNotNull(MemPage *pPage){
60284  assert( pPage->aData );
60285  assert( pPage->pBt );
60286  assert( pPage->pDbPage!=0 );
60287  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60288  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
60289  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60291 }
60292 static void releasePage(MemPage *pPage){
60293  if( pPage ) releasePageNotNull(pPage);
60294 }
60295 
60296 /*
60297 ** Get an unused page.
60298 **
60299 ** This works just like btreeGetPage() with the addition:
60300 **
60301 ** * If the page is already in use for some other purpose, immediately
60302 ** release it and return an SQLITE_CURRUPT error.
60303 ** * Make sure the isInit flag is clear
60304 */
60306  BtShared *pBt, /* The btree */
60307  Pgno pgno, /* Number of the page to fetch */
60308  MemPage **ppPage, /* Return the page in this parameter */
60309  int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60310 ){
60311  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
60312  if( rc==SQLITE_OK ){
60313  if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
60314  releasePage(*ppPage);
60315  *ppPage = 0;
60316  return SQLITE_CORRUPT_BKPT;
60317  }
60318  (*ppPage)->isInit = 0;
60319  }else{
60320  *ppPage = 0;
60321  }
60322  return rc;
60323 }
60324 
60325 
60326 /*
60327 ** During a rollback, when the pager reloads information into the cache
60328 ** so that the cache is restored to its original state at the start of
60329 ** the transaction, for each page restored this routine is called.
60330 **
60331 ** This routine needs to reset the extra data section at the end of the
60332 ** page to agree with the restored data.
60333 */
60334 static void pageReinit(DbPage *pData){
60335  MemPage *pPage;
60336  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
60337  assert( sqlite3PagerPageRefcount(pData)>0 );
60338  if( pPage->isInit ){
60339  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60340  pPage->isInit = 0;
60341  if( sqlite3PagerPageRefcount(pData)>1 ){
60342  /* pPage might not be a btree page; it might be an overflow page
60343  ** or ptrmap page or a free page. In those cases, the following
60344  ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
60345  ** But no harm is done by this. And it is very important that
60346  ** btreeInitPage() be called on every btree page so we make
60347  ** the call for every page that comes in for re-initing. */
60348  btreeInitPage(pPage);
60349  }
60350  }
60351 }
60352 
60353 /*
60354 ** Invoke the busy handler for a btree.
60355 */
60356 static int btreeInvokeBusyHandler(void *pArg){
60357  BtShared *pBt = (BtShared*)pArg;
60358  assert( pBt->db );
60359  assert( sqlite3_mutex_held(pBt->db->mutex) );
60360  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
60361 }
60362 
60363 /*
60364 ** Open a database file.
60365 **
60366 ** zFilename is the name of the database file. If zFilename is NULL
60367 ** then an ephemeral database is created. The ephemeral database might
60368 ** be exclusively in memory, or it might use a disk-based memory cache.
60369 ** Either way, the ephemeral database will be automatically deleted
60370 ** when sqlite3BtreeClose() is called.
60371 **
60372 ** If zFilename is ":memory:" then an in-memory database is created
60373 ** that is automatically destroyed when it is closed.
60374 **
60375 ** The "flags" parameter is a bitmask that might contain bits like
60376 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
60377 **
60378 ** If the database is already opened in the same database connection
60379 ** and we are in shared cache mode, then the open will fail with an
60380 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
60381 ** objects in the same database connection since doing so will lead
60382 ** to problems with locking.
60383 */
60385  sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
60386  const char *zFilename, /* Name of the file containing the BTree database */
60387  sqlite3 *db, /* Associated database handle */
60388  Btree **ppBtree, /* Pointer to new Btree object written here */
60389  int flags, /* Options */
60390  int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
60391 ){
60392  BtShared *pBt = 0; /* Shared part of btree structure */
60393  Btree *p; /* Handle to return */
60394  sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
60395  int rc = SQLITE_OK; /* Result code from this function */
60396  u8 nReserve; /* Byte of unused space on each page */
60397  unsigned char zDbHeader[100]; /* Database header content */
60398 
60399  /* True if opening an ephemeral, temporary database */
60400  const int isTempDb = zFilename==0 || zFilename[0]==0;
60401 
60402  /* Set the variable isMemdb to true for an in-memory database, or
60403  ** false for a file-based database.
60404  */
60405 #ifdef SQLITE_OMIT_MEMORYDB
60406  const int isMemdb = 0;
60407 #else
60408  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
60409  || (isTempDb && sqlite3TempInMemory(db))
60410  || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
60411 #endif
60412 
60413  assert( db!=0 );
60414  assert( pVfs!=0 );
60415  assert( sqlite3_mutex_held(db->mutex) );
60416  assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
60417 
60418  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
60419  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
60420 
60421  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
60422  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
60423 
60424  if( isMemdb ){
60425  flags |= BTREE_MEMORY;
60426  }
60427  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
60428  vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
60429  }
60430  p = sqlite3MallocZero(sizeof(Btree));
60431  if( !p ){
60432  return SQLITE_NOMEM_BKPT;
60433  }
60434  p->inTrans = TRANS_NONE;
60435  p->db = db;
60436 #ifndef SQLITE_OMIT_SHARED_CACHE
60437  p->lock.pBtree = p;
60438  p->lock.iTable = 1;
60439 #endif
60440 
60441 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60442  /*
60443  ** If this Btree is a candidate for shared cache, try to find an
60444  ** existing BtShared object that we can share with
60445  */
60446  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
60447  if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
60448  int nFilename = sqlite3Strlen30(zFilename)+1;
60449  int nFullPathname = pVfs->mxPathname+1;
60450  char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
60451  MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60452 
60453  p->sharable = 1;
60454  if( !zFullPathname ){
60455  sqlite3_free(p);
60456  return SQLITE_NOMEM_BKPT;
60457  }
60458  if( isMemdb ){
60459  memcpy(zFullPathname, zFilename, nFilename);
60460  }else{
60461  rc = sqlite3OsFullPathname(pVfs, zFilename,
60462  nFullPathname, zFullPathname);
60463  if( rc ){
60464  sqlite3_free(zFullPathname);
60465  sqlite3_free(p);
60466  return rc;
60467  }
60468  }
60469 #if SQLITE_THREADSAFE
60471  sqlite3_mutex_enter(mutexOpen);
60473  sqlite3_mutex_enter(mutexShared);
60474 #endif
60475  for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
60476  assert( pBt->nRef>0 );
60477  if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
60478  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
60479  int iDb;
60480  for(iDb=db->nDb-1; iDb>=0; iDb--){
60481  Btree *pExisting = db->aDb[iDb].pBt;
60482  if( pExisting && pExisting->pBt==pBt ){
60483  sqlite3_mutex_leave(mutexShared);
60484  sqlite3_mutex_leave(mutexOpen);
60485  sqlite3_free(zFullPathname);
60486  sqlite3_free(p);
60487  return SQLITE_CONSTRAINT;
60488  }
60489  }
60490  p->pBt = pBt;
60491  pBt->nRef++;
60492  break;
60493  }
60494  }
60495  sqlite3_mutex_leave(mutexShared);
60496  sqlite3_free(zFullPathname);
60497  }
60498 #ifdef SQLITE_DEBUG
60499  else{
60500  /* In debug mode, we mark all persistent databases as sharable
60501  ** even when they are not. This exercises the locking code and
60502  ** gives more opportunity for asserts(sqlite3_mutex_held())
60503  ** statements to find locking problems.
60504  */
60505  p->sharable = 1;
60506  }
60507 #endif
60508  }
60509 #endif
60510  if( pBt==0 ){
60511  /*
60512  ** The following asserts make sure that structures used by the btree are
60513  ** the right size. This is to guard against size changes that result
60514  ** when compiling on a different architecture.
60515  */
60516  assert( sizeof(i64)==8 );
60517  assert( sizeof(u64)==8 );
60518  assert( sizeof(u32)==4 );
60519  assert( sizeof(u16)==2 );
60520  assert( sizeof(Pgno)==4 );
60521 
60522  pBt = sqlite3MallocZero( sizeof(*pBt) );
60523  if( pBt==0 ){
60524  rc = SQLITE_NOMEM_BKPT;
60525  goto btree_open_out;
60526  }
60527  rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
60528  EXTRA_SIZE, flags, vfsFlags, pageReinit);
60529  if( rc==SQLITE_OK ){
60531  rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
60532  }
60533  if( rc!=SQLITE_OK ){
60534  goto btree_open_out;
60535  }
60536  pBt->openFlags = (u8)flags;
60537  pBt->db = db;
60539  p->pBt = pBt;
60540 
60541  pBt->pCursor = 0;
60542  pBt->pPage1 = 0;
60544 #ifdef SQLITE_SECURE_DELETE
60545  pBt->btsFlags |= BTS_SECURE_DELETE;
60546 #endif
60547  /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
60548  ** determined by the 2-byte integer located at an offset of 16 bytes from
60549  ** the beginning of the database file. */
60550  pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
60551  if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
60552  || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
60553  pBt->pageSize = 0;
60554 #ifndef SQLITE_OMIT_AUTOVACUUM
60555  /* If the magic name ":memory:" will create an in-memory database, then
60556  ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
60557  ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
60558  ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
60559  ** regular file-name. In this case the auto-vacuum applies as per normal.
60560  */
60561  if( zFilename && !isMemdb ){
60562  pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
60563  pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
60564  }
60565 #endif
60566  nReserve = 0;
60567  }else{
60568  /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
60569  ** determined by the one-byte unsigned integer found at an offset of 20
60570  ** into the database file header. */
60571  nReserve = zDbHeader[20];
60572  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60573 #ifndef SQLITE_OMIT_AUTOVACUUM
60574  pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
60575  pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
60576 #endif
60577  }
60578  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60579  if( rc ) goto btree_open_out;
60580  pBt->usableSize = pBt->pageSize - nReserve;
60581  assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
60582 
60583 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60584  /* Add the new BtShared object to the linked list sharable BtShareds.
60585  */
60586  pBt->nRef = 1;
60587  if( p->sharable ){
60588  MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60590  if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
60592  if( pBt->mutex==0 ){
60593  rc = SQLITE_NOMEM_BKPT;
60594  goto btree_open_out;
60595  }
60596  }
60597  sqlite3_mutex_enter(mutexShared);
60598  pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
60599  GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
60600  sqlite3_mutex_leave(mutexShared);
60601  }
60602 #endif
60603  }
60604 
60605 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60606  /* If the new Btree uses a sharable pBtShared, then link the new
60607  ** Btree into the list of all sharable Btrees for the same connection.
60608  ** The list is kept in ascending order by pBt address.
60609  */
60610  if( p->sharable ){
60611  int i;
60612  Btree *pSib;
60613  for(i=0; i<db->nDb; i++){
60614  if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
60615  while( pSib->pPrev ){ pSib = pSib->pPrev; }
60616  if( (uptr)p->pBt<(uptr)pSib->pBt ){
60617  p->pNext = pSib;
60618  p->pPrev = 0;
60619  pSib->pPrev = p;
60620  }else{
60621  while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
60622  pSib = pSib->pNext;
60623  }
60624  p->pNext = pSib->pNext;
60625  p->pPrev = pSib;
60626  if( p->pNext ){
60627  p->pNext->pPrev = p;
60628  }
60629  pSib->pNext = p;
60630  }
60631  break;
60632  }
60633  }
60634  }
60635 #endif
60636  *ppBtree = p;
60637 
60638 btree_open_out:
60639  if( rc!=SQLITE_OK ){
60640  if( pBt && pBt->pPager ){
60641  sqlite3PagerClose(pBt->pPager);
60642  }
60643  sqlite3_free(pBt);
60644  sqlite3_free(p);
60645  *ppBtree = 0;
60646  }else{
60647  /* If the B-Tree was successfully opened, set the pager-cache size to the
60648  ** default value. Except, when opening on an existing shared pager-cache,
60649  ** do not change the pager-cache size.
60650  */
60651  if( sqlite3BtreeSchema(p, 0, 0)==0 ){
60653  }
60654  }
60655  if( mutexOpen ){
60656  assert( sqlite3_mutex_held(mutexOpen) );
60657  sqlite3_mutex_leave(mutexOpen);
60658  }
60659  assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
60660  return rc;
60661 }
60662 
60663 /*
60664 ** Decrement the BtShared.nRef counter. When it reaches zero,
60665 ** remove the BtShared structure from the sharing list. Return
60666 ** true if the BtShared.nRef counter reaches zero and return
60667 ** false if it is still positive.
60668 */
60670 #ifndef SQLITE_OMIT_SHARED_CACHE
60671  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
60672  BtShared *pList;
60673  int removed = 0;
60674 
60675  assert( sqlite3_mutex_notheld(pBt->mutex) );
60677  sqlite3_mutex_enter(pMaster);
60678  pBt->nRef--;
60679  if( pBt->nRef<=0 ){
60680  if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
60681  GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
60682  }else{
60683  pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
60684  while( ALWAYS(pList) && pList->pNext!=pBt ){
60685  pList=pList->pNext;
60686  }
60687  if( ALWAYS(pList) ){
60688  pList->pNext = pBt->pNext;
60689  }
60690  }
60691  if( SQLITE_THREADSAFE ){
60692  sqlite3_mutex_free(pBt->mutex);
60693  }
60694  removed = 1;
60695  }
60696  sqlite3_mutex_leave(pMaster);
60697  return removed;
60698 #else
60699  return 1;
60700 #endif
60701 }
60702 
60703 /*
60704 ** Make sure pBt->pTmpSpace points to an allocation of
60705 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
60706 ** pointer.
60707 */
60708 static void allocateTempSpace(BtShared *pBt){
60709  if( !pBt->pTmpSpace ){
60710  pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
60711 
60712  /* One of the uses of pBt->pTmpSpace is to format cells before
60713  ** inserting them into a leaf page (function fillInCell()). If
60714  ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
60715  ** by the various routines that manipulate binary cells. Which
60716  ** can mean that fillInCell() only initializes the first 2 or 3
60717  ** bytes of pTmpSpace, but that the first 4 bytes are copied from
60718  ** it into a database page. This is not actually a problem, but it
60719  ** does cause a valgrind error when the 1 or 2 bytes of unitialized
60720  ** data is passed to system call write(). So to avoid this error,
60721  ** zero the first 4 bytes of temp space here.
60722  **
60723  ** Also: Provide four bytes of initialized space before the
60724  ** beginning of pTmpSpace as an area available to prepend the
60725  ** left-child pointer to the beginning of a cell.
60726  */
60727  if( pBt->pTmpSpace ){
60728  memset(pBt->pTmpSpace, 0, 8);
60729  pBt->pTmpSpace += 4;
60730  }
60731  }
60732 }
60733 
60734 /*
60735 ** Free the pBt->pTmpSpace allocation
60736 */
60737 static void freeTempSpace(BtShared *pBt){
60738  if( pBt->pTmpSpace ){
60739  pBt->pTmpSpace -= 4;
60740  sqlite3PageFree(pBt->pTmpSpace);
60741  pBt->pTmpSpace = 0;
60742  }
60743 }
60744 
60745 /*
60746 ** Close an open database and invalidate all cursors.
60747 */
60749  BtShared *pBt = p->pBt;
60750  BtCursor *pCur;
60751 
60752  /* Close all cursors opened via this handle. */
60753  assert( sqlite3_mutex_held(p->db->mutex) );
60754  sqlite3BtreeEnter(p);
60755  pCur = pBt->pCursor;
60756  while( pCur ){
60757  BtCursor *pTmp = pCur;
60758  pCur = pCur->pNext;
60759  if( pTmp->pBtree==p ){
60761  }
60762  }
60763 
60764  /* Rollback any active transaction and free the handle structure.
60765  ** The call to sqlite3BtreeRollback() drops any table-locks held by
60766  ** this handle.
60767  */
60769  sqlite3BtreeLeave(p);
60770 
60771  /* If there are still other outstanding references to the shared-btree
60772  ** structure, return now. The remainder of this procedure cleans
60773  ** up the shared-btree.
60774  */
60775  assert( p->wantToLock==0 && p->locked==0 );
60776  if( !p->sharable || removeFromSharingList(pBt) ){
60777  /* The pBt is no longer on the sharing list, so we can access
60778  ** it without having to hold the mutex.
60779  **
60780  ** Clean out and delete the BtShared object.
60781  */
60782  assert( !pBt->pCursor );
60783  sqlite3PagerClose(pBt->pPager);
60784  if( pBt->xFreeSchema && pBt->pSchema ){
60785  pBt->xFreeSchema(pBt->pSchema);
60786  }
60787  sqlite3DbFree(0, pBt->pSchema);
60788  freeTempSpace(pBt);
60789  sqlite3_free(pBt);
60790  }
60791 
60792 #ifndef SQLITE_OMIT_SHARED_CACHE
60793  assert( p->wantToLock==0 );
60794  assert( p->locked==0 );
60795  if( p->pPrev ) p->pPrev->pNext = p->pNext;
60796  if( p->pNext ) p->pNext->pPrev = p->pPrev;
60797 #endif
60798 
60799  sqlite3_free(p);
60800  return SQLITE_OK;
60801 }
60802 
60803 /*
60804 ** Change the "soft" limit on the number of pages in the cache.
60805 ** Unused and unmodified pages will be recycled when the number of
60806 ** pages in the cache exceeds this soft limit. But the size of the
60807 ** cache is allowed to grow larger than this limit if it contains
60808 ** dirty pages or pages still in active use.
60809 */
60811  BtShared *pBt = p->pBt;
60812  assert( sqlite3_mutex_held(p->db->mutex) );
60813  sqlite3BtreeEnter(p);
60814  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
60815  sqlite3BtreeLeave(p);
60816  return SQLITE_OK;
60817 }
60818 
60819 /*
60820 ** Change the "spill" limit on the number of pages in the cache.
60821 ** If the number of pages exceeds this limit during a write transaction,
60822 ** the pager might attempt to "spill" pages to the journal early in
60823 ** order to free up memory.
60824 **
60825 ** The value returned is the current spill size. If zero is passed
60826 ** as an argument, no changes are made to the spill size setting, so
60827 ** using mxPage of 0 is a way to query the current spill size.
60828 */
60830  BtShared *pBt = p->pBt;
60831  int res;
60832  assert( sqlite3_mutex_held(p->db->mutex) );
60833  sqlite3BtreeEnter(p);
60834  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
60835  sqlite3BtreeLeave(p);
60836  return res;
60837 }
60838 
60839 #if SQLITE_MAX_MMAP_SIZE>0
60840 /*
60841 ** Change the limit on the amount of the database file that may be
60842 ** memory mapped.
60843 */
60844 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
60845  BtShared *pBt = p->pBt;
60846  assert( sqlite3_mutex_held(p->db->mutex) );
60847  sqlite3BtreeEnter(p);
60848  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
60849  sqlite3BtreeLeave(p);
60850  return SQLITE_OK;
60851 }
60852 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
60853 
60854 /*
60855 ** Change the way data is synced to disk in order to increase or decrease
60856 ** how well the database resists damage due to OS crashes and power
60857 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
60858 ** there is a high probability of damage) Level 2 is the default. There
60859 ** is a very low but non-zero probability of damage. Level 3 reduces the
60860 ** probability of damage to near zero but with a write performance reduction.
60861 */
60862 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
60864  Btree *p, /* The btree to set the safety level on */
60865  unsigned pgFlags /* Various PAGER_* flags */
60866 ){
60867  BtShared *pBt = p->pBt;
60868  assert( sqlite3_mutex_held(p->db->mutex) );
60869  sqlite3BtreeEnter(p);
60870  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
60871  sqlite3BtreeLeave(p);
60872  return SQLITE_OK;
60873 }
60874 #endif
60875 
60876 /*
60877 ** Change the default pages size and the number of reserved bytes per page.
60878 ** Or, if the page size has already been fixed, return SQLITE_READONLY
60879 ** without changing anything.
60880 **
60881 ** The page size must be a power of 2 between 512 and 65536. If the page
60882 ** size supplied does not meet this constraint then the page size is not
60883 ** changed.
60884 **
60885 ** Page sizes are constrained to be a power of two so that the region
60886 ** of the database file used for locking (beginning at PENDING_BYTE,
60887 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
60888 ** at the beginning of a page.
60889 **
60890 ** If parameter nReserve is less than zero, then the number of reserved
60891 ** bytes per page is left unchanged.
60892 **
60893 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
60894 ** and autovacuum mode can no longer be changed.
60895 */
60896 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
60897  int rc = SQLITE_OK;
60898  BtShared *pBt = p->pBt;
60899  assert( nReserve>=-1 && nReserve<=255 );
60900  sqlite3BtreeEnter(p);
60901 #if SQLITE_HAS_CODEC
60902  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
60903 #endif
60904  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
60905  sqlite3BtreeLeave(p);
60906  return SQLITE_READONLY;
60907  }
60908  if( nReserve<0 ){
60909  nReserve = pBt->pageSize - pBt->usableSize;
60910  }
60911  assert( nReserve>=0 && nReserve<=255 );
60912  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
60913  ((pageSize-1)&pageSize)==0 ){
60914  assert( (pageSize & 7)==0 );
60915  assert( !pBt->pCursor );
60916  pBt->pageSize = (u32)pageSize;
60917  freeTempSpace(pBt);
60918  }
60919  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60920  pBt->usableSize = pBt->pageSize - (u16)nReserve;
60921  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60922  sqlite3BtreeLeave(p);
60923  return rc;
60924 }
60925 
60926 /*
60927 ** Return the currently defined page size
60928 */
60930  return p->pBt->pageSize;
60931 }
60932 
60933 /*
60934 ** This function is similar to sqlite3BtreeGetReserve(), except that it
60935 ** may only be called if it is guaranteed that the b-tree mutex is already
60936 ** held.
60937 **
60938 ** This is useful in one special case in the backup API code where it is
60939 ** known that the shared b-tree mutex is held, but the mutex on the
60940 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
60941 ** were to be called, it might collide with some other operation on the
60942 ** database handle that owns *p, causing undefined behavior.
60943 */
60945  int n;
60946  assert( sqlite3_mutex_held(p->pBt->mutex) );
60947  n = p->pBt->pageSize - p->pBt->usableSize;
60948  return n;
60949 }
60950 
60951 /*
60952 ** Return the number of bytes of space at the end of every page that
60953 ** are intentually left unused. This is the "reserved" space that is
60954 ** sometimes used by extensions.
60955 **
60956 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
60957 ** greater of the current reserved space and the maximum requested
60958 ** reserve space.
60959 */
60961  int n;
60962  sqlite3BtreeEnter(p);
60964 #ifdef SQLITE_HAS_CODEC
60965  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
60966 #endif
60967  sqlite3BtreeLeave(p);
60968  return n;
60969 }
60970 
60971 
60972 /*
60973 ** Set the maximum page count for a database if mxPage is positive.
60974 ** No changes are made if mxPage is 0 or negative.
60975 ** Regardless of the value of mxPage, return the maximum page count.
60976 */
60978  int n;
60979  sqlite3BtreeEnter(p);
60980  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
60981  sqlite3BtreeLeave(p);
60982  return n;
60983 }
60984 
60985 /*
60986 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
60987 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
60988 ** setting after the change.
60989 */
60991  int b;
60992  if( p==0 ) return 0;
60993  sqlite3BtreeEnter(p);
60994  if( newFlag>=0 ){
60995  p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
60996  if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
60997  }
60998  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
60999  sqlite3BtreeLeave(p);
61000  return b;
61001 }
61002 
61003 /*
61004 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
61005 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
61006 ** is disabled. The default value for the auto-vacuum property is
61007 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
61008 */
61010 #ifdef SQLITE_OMIT_AUTOVACUUM
61011  return SQLITE_READONLY;
61012 #else
61013  BtShared *pBt = p->pBt;
61014  int rc = SQLITE_OK;
61015  u8 av = (u8)autoVacuum;
61016 
61017  sqlite3BtreeEnter(p);
61018  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
61019  rc = SQLITE_READONLY;
61020  }else{
61021  pBt->autoVacuum = av ?1:0;
61022  pBt->incrVacuum = av==2 ?1:0;
61023  }
61024  sqlite3BtreeLeave(p);
61025  return rc;
61026 #endif
61027 }
61028 
61029 /*
61030 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
61031 ** enabled 1 is returned. Otherwise 0.
61032 */
61034 #ifdef SQLITE_OMIT_AUTOVACUUM
61035  return BTREE_AUTOVACUUM_NONE;
61036 #else
61037  int rc;
61038  sqlite3BtreeEnter(p);
61039  rc = (
61043  );
61044  sqlite3BtreeLeave(p);
61045  return rc;
61046 #endif
61047 }
61048 
61049 
61050 /*
61051 ** Get a reference to pPage1 of the database file. This will
61052 ** also acquire a readlock on that file.
61053 **
61054 ** SQLITE_OK is returned on success. If the file is not a
61055 ** well-formed database file, then SQLITE_CORRUPT is returned.
61056 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
61057 ** is returned if we run out of memory.
61058 */
61059 static int lockBtree(BtShared *pBt){
61060  int rc; /* Result code from subfunctions */
61061  MemPage *pPage1; /* Page 1 of the database file */
61062  int nPage; /* Number of pages in the database */
61063  int nPageFile = 0; /* Number of pages in the database file */
61064  int nPageHeader; /* Number of pages in the database according to hdr */
61065 
61066  assert( sqlite3_mutex_held(pBt->mutex) );
61067  assert( pBt->pPage1==0 );
61068  rc = sqlite3PagerSharedLock(pBt->pPager);
61069  if( rc!=SQLITE_OK ) return rc;
61070  rc = btreeGetPage(pBt, 1, &pPage1, 0);
61071  if( rc!=SQLITE_OK ) return rc;
61072 
61073  /* Do some checking to help insure the file we opened really is
61074  ** a valid database file.
61075  */
61076  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
61077  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
61078  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
61079  nPage = nPageFile;
61080  }
61081  if( nPage>0 ){
61082  u32 pageSize;
61083  u32 usableSize;
61084  u8 *page1 = pPage1->aData;
61085  rc = SQLITE_NOTADB;
61086  /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
61087  ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
61088  ** 61 74 20 33 00. */
61089  if( memcmp(page1, zMagicHeader, 16)!=0 ){
61090  goto page1_init_failed;
61091  }
61092 
61093 #ifdef SQLITE_OMIT_WAL
61094  if( page1[18]>1 ){
61095  pBt->btsFlags |= BTS_READ_ONLY;
61096  }
61097  if( page1[19]>1 ){
61098  goto page1_init_failed;
61099  }
61100 #else
61101  if( page1[18]>2 ){
61102  pBt->btsFlags |= BTS_READ_ONLY;
61103  }
61104  if( page1[19]>2 ){
61105  goto page1_init_failed;
61106  }
61107 
61108  /* If the write version is set to 2, this database should be accessed
61109  ** in WAL mode. If the log is not already open, open it now. Then
61110  ** return SQLITE_OK and return without populating BtShared.pPage1.
61111  ** The caller detects this and calls this function again. This is
61112  ** required as the version of page 1 currently in the page1 buffer
61113  ** may not be the latest version - there may be a newer one in the log
61114  ** file.
61115  */
61116  if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
61117  int isOpen = 0;
61118  rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
61119  if( rc!=SQLITE_OK ){
61120  goto page1_init_failed;
61121  }else{
61122 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
61123  sqlite3 *db;
61124  Db *pDb;
61125  if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
61126  while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
61127  if( pDb->bSyncSet==0
61129  ){
61132  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
61133  }
61134  }
61135 #endif
61136  if( isOpen==0 ){
61137  releasePage(pPage1);
61138  return SQLITE_OK;
61139  }
61140  }
61141  rc = SQLITE_NOTADB;
61142  }
61143 #endif
61144 
61145  /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
61146  ** fractions and the leaf payload fraction values must be 64, 32, and 32.
61147  **
61148  ** The original design allowed these amounts to vary, but as of
61149  ** version 3.6.0, we require them to be fixed.
61150  */
61151  if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
61152  goto page1_init_failed;
61153  }
61154  /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61155  ** determined by the 2-byte integer located at an offset of 16 bytes from
61156  ** the beginning of the database file. */
61157  pageSize = (page1[16]<<8) | (page1[17]<<16);
61158  /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
61159  ** between 512 and 65536 inclusive. */
61160  if( ((pageSize-1)&pageSize)!=0
61161  || pageSize>SQLITE_MAX_PAGE_SIZE
61162  || pageSize<=256
61163  ){
61164  goto page1_init_failed;
61165  }
61166  assert( (pageSize & 7)==0 );
61167  /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
61168  ** integer at offset 20 is the number of bytes of space at the end of
61169  ** each page to reserve for extensions.
61170  **
61171  ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61172  ** determined by the one-byte unsigned integer found at an offset of 20
61173  ** into the database file header. */
61174  usableSize = pageSize - page1[20];
61175  if( (u32)pageSize!=pBt->pageSize ){
61176  /* After reading the first page of the database assuming a page size
61177  ** of BtShared.pageSize, we have discovered that the page-size is
61178  ** actually pageSize. Unlock the database, leave pBt->pPage1 at
61179  ** zero and return SQLITE_OK. The caller will call this function
61180  ** again with the correct page-size.
61181  */
61182  releasePage(pPage1);
61183  pBt->usableSize = usableSize;
61184  pBt->pageSize = pageSize;
61185  freeTempSpace(pBt);
61186  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
61187  pageSize-usableSize);
61188  return rc;
61189  }
61190  if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
61191  rc = SQLITE_CORRUPT_BKPT;
61192  goto page1_init_failed;
61193  }
61194  /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
61195  ** be less than 480. In other words, if the page size is 512, then the
61196  ** reserved space size cannot exceed 32. */
61197  if( usableSize<480 ){
61198  goto page1_init_failed;
61199  }
61200  pBt->pageSize = pageSize;
61201  pBt->usableSize = usableSize;
61202 #ifndef SQLITE_OMIT_AUTOVACUUM
61203  pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
61204  pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
61205 #endif
61206  }
61207 
61208  /* maxLocal is the maximum amount of payload to store locally for
61209  ** a cell. Make sure it is small enough so that at least minFanout
61210  ** cells can will fit on one page. We assume a 10-byte page header.
61211  ** Besides the payload, the cell must store:
61212  ** 2-byte pointer to the cell
61213  ** 4-byte child pointer
61214  ** 9-byte nKey value
61215  ** 4-byte nData value
61216  ** 4-byte overflow page pointer
61217  ** So a cell consists of a 2-byte pointer, a header which is as much as
61218  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
61219  ** page pointer.
61220  */
61221  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
61222  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
61223  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
61224  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
61225  if( pBt->maxLocal>127 ){
61226  pBt->max1bytePayload = 127;
61227  }else{
61228  pBt->max1bytePayload = (u8)pBt->maxLocal;
61229  }
61230  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
61231  pBt->pPage1 = pPage1;
61232  pBt->nPage = nPage;
61233  return SQLITE_OK;
61234 
61235 page1_init_failed:
61236  releasePage(pPage1);
61237  pBt->pPage1 = 0;
61238  return rc;
61239 }
61240 
61241 #ifndef NDEBUG
61242 /*
61243 ** Return the number of cursors open on pBt. This is for use
61244 ** in assert() expressions, so it is only compiled if NDEBUG is not
61245 ** defined.
61246 **
61247 ** Only write cursors are counted if wrOnly is true. If wrOnly is
61248 ** false then all cursors are counted.
61249 **
61250 ** For the purposes of this routine, a cursor is any cursor that
61251 ** is capable of reading or writing to the database. Cursors that
61252 ** have been tripped into the CURSOR_FAULT state are not counted.
61253 */
61254 static int countValidCursors(BtShared *pBt, int wrOnly){
61255  BtCursor *pCur;
61256  int r = 0;
61257  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
61258  if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
61259  && pCur->eState!=CURSOR_FAULT ) r++;
61260  }
61261  return r;
61262 }
61263 #endif
61264 
61265 /*
61266 ** If there are no outstanding cursors and we are not in the middle
61267 ** of a transaction but there is a read lock on the database, then
61268 ** this routine unrefs the first page of the database file which
61269 ** has the effect of releasing the read lock.
61270 **
61271 ** If there is a transaction in progress, this routine is a no-op.
61272 */
61273 static void unlockBtreeIfUnused(BtShared *pBt){
61274  assert( sqlite3_mutex_held(pBt->mutex) );
61275  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
61276  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
61277  MemPage *pPage1 = pBt->pPage1;
61278  assert( pPage1->aData );
61279  assert( sqlite3PagerRefcount(pBt->pPager)==1 );
61280  pBt->pPage1 = 0;
61281  releasePageNotNull(pPage1);
61282  }
61283 }
61284 
61285 /*
61286 ** If pBt points to an empty file then convert that empty file
61287 ** into a new empty database by initializing the first page of
61288 ** the database.
61289 */
61290 static int newDatabase(BtShared *pBt){
61291  MemPage *pP1;
61292  unsigned char *data;
61293  int rc;
61294 
61295  assert( sqlite3_mutex_held(pBt->mutex) );
61296  if( pBt->nPage>0 ){
61297  return SQLITE_OK;
61298  }
61299  pP1 = pBt->pPage1;
61300  assert( pP1!=0 );
61301  data = pP1->aData;
61302  rc = sqlite3PagerWrite(pP1->pDbPage);
61303  if( rc ) return rc;
61304  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
61305  assert( sizeof(zMagicHeader)==16 );
61306  data[16] = (u8)((pBt->pageSize>>8)&0xff);
61307  data[17] = (u8)((pBt->pageSize>>16)&0xff);
61308  data[18] = 1;
61309  data[19] = 1;
61310  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
61311  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
61312  data[21] = 64;
61313  data[22] = 32;
61314  data[23] = 32;
61315  memset(&data[24], 0, 100-24);
61317  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61318 #ifndef SQLITE_OMIT_AUTOVACUUM
61319  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
61320  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
61321  put4byte(&data[36 + 4*4], pBt->autoVacuum);
61322  put4byte(&data[36 + 7*4], pBt->incrVacuum);
61323 #endif
61324  pBt->nPage = 1;
61325  data[31] = 1;
61326  return SQLITE_OK;
61327 }
61328 
61329 /*
61330 ** Initialize the first page of the database file (creating a database
61331 ** consisting of a single page and no schema objects). Return SQLITE_OK
61332 ** if successful, or an SQLite error code otherwise.
61333 */
61335  int rc;
61336  sqlite3BtreeEnter(p);
61337  p->pBt->nPage = 0;
61338  rc = newDatabase(p->pBt);
61339  sqlite3BtreeLeave(p);
61340  return rc;
61341 }
61342 
61343 /*
61344 ** Attempt to start a new transaction. A write-transaction
61345 ** is started if the second argument is nonzero, otherwise a read-
61346 ** transaction. If the second argument is 2 or more and exclusive
61347 ** transaction is started, meaning that no other process is allowed
61348 ** to access the database. A preexisting transaction may not be
61349 ** upgraded to exclusive by calling this routine a second time - the
61350 ** exclusivity flag only works for a new transaction.
61351 **
61352 ** A write-transaction must be started before attempting any
61353 ** changes to the database. None of the following routines
61354 ** will work unless a transaction is started first:
61355 **
61356 ** sqlite3BtreeCreateTable()
61357 ** sqlite3BtreeCreateIndex()
61358 ** sqlite3BtreeClearTable()
61359 ** sqlite3BtreeDropTable()
61360 ** sqlite3BtreeInsert()
61361 ** sqlite3BtreeDelete()
61362 ** sqlite3BtreeUpdateMeta()
61363 **
61364 ** If an initial attempt to acquire the lock fails because of lock contention
61365 ** and the database was previously unlocked, then invoke the busy handler
61366 ** if there is one. But if there was previously a read-lock, do not
61367 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
61368 ** returned when there is already a read-lock in order to avoid a deadlock.
61369 **
61370 ** Suppose there are two processes A and B. A has a read lock and B has
61371 ** a reserved lock. B tries to promote to exclusive but is blocked because
61372 ** of A's read lock. A tries to promote to reserved but is blocked by B.
61373 ** One or the other of the two processes must give way or there can be
61374 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
61375 ** when A already has a read lock, we encourage A to give up and let B
61376 ** proceed.
61377 */
61379  BtShared *pBt = p->pBt;
61380  int rc = SQLITE_OK;
61381 
61382  sqlite3BtreeEnter(p);
61383  btreeIntegrity(p);
61384 
61385  /* If the btree is already in a write-transaction, or it
61386  ** is already in a read-transaction and a read-transaction
61387  ** is requested, this is a no-op.
61388  */
61389  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
61390  goto trans_begun;
61391  }
61392  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
61393 
61394  /* Write transactions are not possible on a read-only database */
61395  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
61396  rc = SQLITE_READONLY;
61397  goto trans_begun;
61398  }
61399 
61400 #ifndef SQLITE_OMIT_SHARED_CACHE
61401  {
61402  sqlite3 *pBlock = 0;
61403  /* If another database handle has already opened a write transaction
61404  ** on this shared-btree structure and a second write transaction is
61405  ** requested, return SQLITE_LOCKED.
61406  */
61407  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
61408  || (pBt->btsFlags & BTS_PENDING)!=0
61409  ){
61410  pBlock = pBt->pWriter->db;
61411  }else if( wrflag>1 ){
61412  BtLock *pIter;
61413  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
61414  if( pIter->pBtree!=p ){
61415  pBlock = pIter->pBtree->db;
61416  break;
61417  }
61418  }
61419  }
61420  if( pBlock ){
61421  sqlite3ConnectionBlocked(p->db, pBlock);
61423  goto trans_begun;
61424  }
61425  }
61426 #endif
61427 
61428  /* Any read-only or read-write transaction implies a read-lock on
61429  ** page 1. So if some other shared-cache client already has a write-lock
61430  ** on page 1, the transaction cannot be opened. */
61432  if( SQLITE_OK!=rc ) goto trans_begun;
61433 
61434  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
61435  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
61436  do {
61437  /* Call lockBtree() until either pBt->pPage1 is populated or
61438  ** lockBtree() returns something other than SQLITE_OK. lockBtree()
61439  ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
61440  ** reading page 1 it discovers that the page-size of the database
61441  ** file is not pBt->pageSize. In this case lockBtree() will update
61442  ** pBt->pageSize to the page-size of the file on disk.
61443  */
61444  while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
61445 
61446  if( rc==SQLITE_OK && wrflag ){
61447  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
61448  rc = SQLITE_READONLY;
61449  }else{
61450  rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
61451  if( rc==SQLITE_OK ){
61452  rc = newDatabase(pBt);
61453  }
61454  }
61455  }
61456 
61457  if( rc!=SQLITE_OK ){
61458  unlockBtreeIfUnused(pBt);
61459  }
61460  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
61461  btreeInvokeBusyHandler(pBt) );
61462 
61463  if( rc==SQLITE_OK ){
61464  if( p->inTrans==TRANS_NONE ){
61465  pBt->nTransaction++;
61466 #ifndef SQLITE_OMIT_SHARED_CACHE
61467  if( p->sharable ){
61468  assert( p->lock.pBtree==p && p->lock.iTable==1 );
61469  p->lock.eLock = READ_LOCK;
61470  p->lock.pNext = pBt->pLock;
61471  pBt->pLock = &p->lock;
61472  }
61473 #endif
61474  }
61475  p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
61476  if( p->inTrans>pBt->inTransaction ){
61477  pBt->inTransaction = p->inTrans;
61478  }
61479  if( wrflag ){
61480  MemPage *pPage1 = pBt->pPage1;
61481 #ifndef SQLITE_OMIT_SHARED_CACHE
61482  assert( !pBt->pWriter );
61483  pBt->pWriter = p;
61484  pBt->btsFlags &= ~BTS_EXCLUSIVE;
61485  if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
61486 #endif
61487 
61488  /* If the db-size header field is incorrect (as it may be if an old
61489  ** client has been writing the database file), update it now. Doing
61490  ** this sooner rather than later means the database size can safely
61491  ** re-read the database size from page 1 if a savepoint or transaction
61492  ** rollback occurs within the transaction.
61493  */
61494  if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
61495  rc = sqlite3PagerWrite(pPage1->pDbPage);
61496  if( rc==SQLITE_OK ){
61497  put4byte(&pPage1->aData[28], pBt->nPage);
61498  }
61499  }
61500  }
61501  }
61502 
61503 
61504 trans_begun:
61505  if( rc==SQLITE_OK && wrflag ){
61506  /* This call makes sure that the pager has the correct number of
61507  ** open savepoints. If the second parameter is greater than 0 and
61508  ** the sub-journal is not already open, then it will be opened here.
61509  */
61511  }
61512 
61513  btreeIntegrity(p);
61514  sqlite3BtreeLeave(p);
61515  return rc;
61516 }
61517 
61518 #ifndef SQLITE_OMIT_AUTOVACUUM
61519 
61520 /*
61521 ** Set the pointer-map entries for all children of page pPage. Also, if
61522 ** pPage contains cells that point to overflow pages, set the pointer
61523 ** map entries for the overflow pages as well.
61524 */
61525 static int setChildPtrmaps(MemPage *pPage){
61526  int i; /* Counter variable */
61527  int nCell; /* Number of cells in page pPage */
61528  int rc; /* Return code */
61529  BtShared *pBt = pPage->pBt;
61530  u8 isInitOrig = pPage->isInit;
61531  Pgno pgno = pPage->pgno;
61532 
61533  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61534  rc = btreeInitPage(pPage);
61535  if( rc!=SQLITE_OK ){
61536  goto set_child_ptrmaps_out;
61537  }
61538  nCell = pPage->nCell;
61539 
61540  for(i=0; i<nCell; i++){
61541  u8 *pCell = findCell(pPage, i);
61542 
61543  ptrmapPutOvflPtr(pPage, pCell, &rc);
61544 
61545  if( !pPage->leaf ){
61546  Pgno childPgno = get4byte(pCell);
61547  ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61548  }
61549  }
61550 
61551  if( !pPage->leaf ){
61552  Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61553  ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61554  }
61555 
61556 set_child_ptrmaps_out:
61557  pPage->isInit = isInitOrig;
61558  return rc;
61559 }
61560 
61561 /*
61562 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
61563 ** that it points to iTo. Parameter eType describes the type of pointer to
61564 ** be modified, as follows:
61565 **
61566 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
61567 ** page of pPage.
61568 **
61569 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
61570 ** page pointed to by one of the cells on pPage.
61571 **
61572 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
61573 ** overflow page in the list.
61574 */
61575 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
61576  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61577  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61578  if( eType==PTRMAP_OVERFLOW2 ){
61579  /* The pointer is always the first 4 bytes of the page in this case. */
61580  if( get4byte(pPage->aData)!=iFrom ){
61581  return SQLITE_CORRUPT_BKPT;
61582  }
61583  put4byte(pPage->aData, iTo);
61584  }else{
61585  u8 isInitOrig = pPage->isInit;
61586  int i;
61587  int nCell;
61588  int rc;
61589 
61590  rc = btreeInitPage(pPage);
61591  if( rc ) return rc;
61592  nCell = pPage->nCell;
61593 
61594  for(i=0; i<nCell; i++){
61595  u8 *pCell = findCell(pPage, i);
61596  if( eType==PTRMAP_OVERFLOW1 ){
61597  CellInfo info;
61598  pPage->xParseCell(pPage, pCell, &info);
61599  if( info.nLocal<info.nPayload
61600  && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
61601  && iFrom==get4byte(pCell+info.nSize-4)
61602  ){
61603  put4byte(pCell+info.nSize-4, iTo);
61604  break;
61605  }
61606  }else{
61607  if( get4byte(pCell)==iFrom ){
61608  put4byte(pCell, iTo);
61609  break;
61610  }
61611  }
61612  }
61613 
61614  if( i==nCell ){
61615  if( eType!=PTRMAP_BTREE ||
61616  get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
61617  return SQLITE_CORRUPT_BKPT;
61618  }
61619  put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
61620  }
61621 
61622  pPage->isInit = isInitOrig;
61623  }
61624  return SQLITE_OK;
61625 }
61626 
61627 
61628 /*
61629 ** Move the open database page pDbPage to location iFreePage in the
61630 ** database. The pDbPage reference remains valid.
61631 **
61632 ** The isCommit flag indicates that there is no need to remember that
61633 ** the journal needs to be sync()ed before database page pDbPage->pgno
61634 ** can be written to. The caller has already promised not to write to that
61635 ** page.
61636 */
61637 static int relocatePage(
61638  BtShared *pBt, /* Btree */
61639  MemPage *pDbPage, /* Open page to move */
61640  u8 eType, /* Pointer map 'type' entry for pDbPage */
61641  Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
61642  Pgno iFreePage, /* The location to move pDbPage to */
61643  int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
61644 ){
61645  MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
61646  Pgno iDbPage = pDbPage->pgno;
61647  Pager *pPager = pBt->pPager;
61648  int rc;
61649 
61650  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
61651  eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
61652  assert( sqlite3_mutex_held(pBt->mutex) );
61653  assert( pDbPage->pBt==pBt );
61654 
61655  /* Move page iDbPage from its current location to page number iFreePage */
61656  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
61657  iDbPage, iFreePage, iPtrPage, eType));
61658  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
61659  if( rc!=SQLITE_OK ){
61660  return rc;
61661  }
61662  pDbPage->pgno = iFreePage;
61663 
61664  /* If pDbPage was a btree-page, then it may have child pages and/or cells
61665  ** that point to overflow pages. The pointer map entries for all these
61666  ** pages need to be changed.
61667  **
61668  ** If pDbPage is an overflow page, then the first 4 bytes may store a
61669  ** pointer to a subsequent overflow page. If this is the case, then
61670  ** the pointer map needs to be updated for the subsequent overflow page.
61671  */
61672  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
61673  rc = setChildPtrmaps(pDbPage);
61674  if( rc!=SQLITE_OK ){
61675  return rc;
61676  }
61677  }else{
61678  Pgno nextOvfl = get4byte(pDbPage->aData);
61679  if( nextOvfl!=0 ){
61680  ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
61681  if( rc!=SQLITE_OK ){
61682  return rc;
61683  }
61684  }
61685  }
61686 
61687  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
61688  ** that it points at iFreePage. Also fix the pointer map entry for
61689  ** iPtrPage.
61690  */
61691  if( eType!=PTRMAP_ROOTPAGE ){
61692  rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
61693  if( rc!=SQLITE_OK ){
61694  return rc;
61695  }
61696  rc = sqlite3PagerWrite(pPtrPage->pDbPage);
61697  if( rc!=SQLITE_OK ){
61698  releasePage(pPtrPage);
61699  return rc;
61700  }
61701  rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
61702  releasePage(pPtrPage);
61703  if( rc==SQLITE_OK ){
61704  ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
61705  }
61706  }
61707  return rc;
61708 }
61709 
61710 /* Forward declaration required by incrVacuumStep(). */
61711 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
61712 
61713 /*
61714 ** Perform a single step of an incremental-vacuum. If successful, return
61715 ** SQLITE_OK. If there is no work to do (and therefore no point in
61716 ** calling this function again), return SQLITE_DONE. Or, if an error
61717 ** occurs, return some other error code.
61718 **
61719 ** More specifically, this function attempts to re-organize the database so
61720 ** that the last page of the file currently in use is no longer in use.
61721 **
61722 ** Parameter nFin is the number of pages that this database would contain
61723 ** were this function called until it returns SQLITE_DONE.
61724 **
61725 ** If the bCommit parameter is non-zero, this function assumes that the
61726 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
61727 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
61728 ** operation, or false for an incremental vacuum.
61729 */
61730 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
61731  Pgno nFreeList; /* Number of pages still on the free-list */
61732  int rc;
61733 
61734  assert( sqlite3_mutex_held(pBt->mutex) );
61735  assert( iLastPg>nFin );
61736 
61737  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
61738  u8 eType;
61739  Pgno iPtrPage;
61740 
61741  nFreeList = get4byte(&pBt->pPage1->aData[36]);
61742  if( nFreeList==0 ){
61743  return SQLITE_DONE;
61744  }
61745 
61746  rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
61747  if( rc!=SQLITE_OK ){
61748  return rc;
61749  }
61750  if( eType==PTRMAP_ROOTPAGE ){
61751  return SQLITE_CORRUPT_BKPT;
61752  }
61753 
61754  if( eType==PTRMAP_FREEPAGE ){
61755  if( bCommit==0 ){
61756  /* Remove the page from the files free-list. This is not required
61757  ** if bCommit is non-zero. In that case, the free-list will be
61758  ** truncated to zero after this function returns, so it doesn't
61759  ** matter if it still contains some garbage entries.
61760  */
61761  Pgno iFreePg;
61762  MemPage *pFreePg;
61763  rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
61764  if( rc!=SQLITE_OK ){
61765  return rc;
61766  }
61767  assert( iFreePg==iLastPg );
61768  releasePage(pFreePg);
61769  }
61770  } else {
61771  Pgno iFreePg; /* Index of free page to move pLastPg to */
61772  MemPage *pLastPg;
61773  u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
61774  Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
61775 
61776  rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
61777  if( rc!=SQLITE_OK ){
61778  return rc;
61779  }
61780 
61781  /* If bCommit is zero, this loop runs exactly once and page pLastPg
61782  ** is swapped with the first free page pulled off the free list.
61783  **
61784  ** On the other hand, if bCommit is greater than zero, then keep
61785  ** looping until a free-page located within the first nFin pages
61786  ** of the file is found.
61787  */
61788  if( bCommit==0 ){
61789  eMode = BTALLOC_LE;
61790  iNear = nFin;
61791  }
61792  do {
61793  MemPage *pFreePg;
61794  rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
61795  if( rc!=SQLITE_OK ){
61796  releasePage(pLastPg);
61797  return rc;
61798  }
61799  releasePage(pFreePg);
61800  }while( bCommit && iFreePg>nFin );
61801  assert( iFreePg<iLastPg );
61802 
61803  rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
61804  releasePage(pLastPg);
61805  if( rc!=SQLITE_OK ){
61806  return rc;
61807  }
61808  }
61809  }
61810 
61811  if( bCommit==0 ){
61812  do {
61813  iLastPg--;
61814  }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
61815  pBt->bDoTruncate = 1;
61816  pBt->nPage = iLastPg;
61817  }
61818  return SQLITE_OK;
61819 }
61820 
61821 /*
61822 ** The database opened by the first argument is an auto-vacuum database
61823 ** nOrig pages in size containing nFree free pages. Return the expected
61824 ** size of the database in pages following an auto-vacuum operation.
61825 */
61826 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
61827  int nEntry; /* Number of entries on one ptrmap page */
61828  Pgno nPtrmap; /* Number of PtrMap pages to be freed */
61829  Pgno nFin; /* Return value */
61830 
61831  nEntry = pBt->usableSize/5;
61832  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
61833  nFin = nOrig - nFree - nPtrmap;
61834  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
61835  nFin--;
61836  }
61837  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
61838  nFin--;
61839  }
61840 
61841  return nFin;
61842 }
61843 
61844 /*
61845 ** A write-transaction must be opened before calling this function.
61846 ** It performs a single unit of work towards an incremental vacuum.
61847 **
61848 ** If the incremental vacuum is finished after this function has run,
61849 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
61850 ** SQLITE_OK is returned. Otherwise an SQLite error code.
61851 */
61853  int rc;
61854  BtShared *pBt = p->pBt;
61855 
61856  sqlite3BtreeEnter(p);
61857  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
61858  if( !pBt->autoVacuum ){
61859  rc = SQLITE_DONE;
61860  }else{
61861  Pgno nOrig = btreePagecount(pBt);
61862  Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
61863  Pgno nFin = finalDbSize(pBt, nOrig, nFree);
61864 
61865  if( nOrig<nFin ){
61866  rc = SQLITE_CORRUPT_BKPT;
61867  }else if( nFree>0 ){
61868  rc = saveAllCursors(pBt, 0, 0);
61869  if( rc==SQLITE_OK ){
61871  rc = incrVacuumStep(pBt, nFin, nOrig, 0);
61872  }
61873  if( rc==SQLITE_OK ){
61874  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61875  put4byte(&pBt->pPage1->aData[28], pBt->nPage);
61876  }
61877  }else{
61878  rc = SQLITE_DONE;
61879  }
61880  }
61881  sqlite3BtreeLeave(p);
61882  return rc;
61883 }
61884 
61885 /*
61886 ** This routine is called prior to sqlite3PagerCommit when a transaction
61887 ** is committed for an auto-vacuum database.
61888 **
61889 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
61890 ** the database file should be truncated to during the commit process.
61891 ** i.e. the database has been reorganized so that only the first *pnTrunc
61892 ** pages are in use.
61893 */
61894 static int autoVacuumCommit(BtShared *pBt){
61895  int rc = SQLITE_OK;
61896  Pager *pPager = pBt->pPager;
61897  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
61898 
61899  assert( sqlite3_mutex_held(pBt->mutex) );
61901  assert(pBt->autoVacuum);
61902  if( !pBt->incrVacuum ){
61903  Pgno nFin; /* Number of pages in database after autovacuuming */
61904  Pgno nFree; /* Number of pages on the freelist initially */
61905  Pgno iFree; /* The next page to be freed */
61906  Pgno nOrig; /* Database size before freeing */
61907 
61908  nOrig = btreePagecount(pBt);
61909  if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
61910  /* It is not possible to create a database for which the final page
61911  ** is either a pointer-map page or the pending-byte page. If one
61912  ** is encountered, this indicates corruption.
61913  */
61914  return SQLITE_CORRUPT_BKPT;
61915  }
61916 
61917  nFree = get4byte(&pBt->pPage1->aData[36]);
61918  nFin = finalDbSize(pBt, nOrig, nFree);
61919  if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
61920  if( nFin<nOrig ){
61921  rc = saveAllCursors(pBt, 0, 0);
61922  }
61923  for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
61924  rc = incrVacuumStep(pBt, nFin, iFree, 1);
61925  }
61926  if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
61927  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61928  put4byte(&pBt->pPage1->aData[32], 0);
61929  put4byte(&pBt->pPage1->aData[36], 0);
61930  put4byte(&pBt->pPage1->aData[28], nFin);
61931  pBt->bDoTruncate = 1;
61932  pBt->nPage = nFin;
61933  }
61934  if( rc!=SQLITE_OK ){
61935  sqlite3PagerRollback(pPager);
61936  }
61937  }
61938 
61939  assert( nRef>=sqlite3PagerRefcount(pPager) );
61940  return rc;
61941 }
61942 
61943 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
61944 # define setChildPtrmaps(x) SQLITE_OK
61945 #endif
61946 
61947 /*
61948 ** This routine does the first phase of a two-phase commit. This routine
61949 ** causes a rollback journal to be created (if it does not already exist)
61950 ** and populated with enough information so that if a power loss occurs
61951 ** the database can be restored to its original state by playing back
61952 ** the journal. Then the contents of the journal are flushed out to
61953 ** the disk. After the journal is safely on oxide, the changes to the
61954 ** database are written into the database file and flushed to oxide.
61955 ** At the end of this call, the rollback journal still exists on the
61956 ** disk and we are still holding all locks, so the transaction has not
61957 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
61958 ** commit process.
61959 **
61960 ** This call is a no-op if no write-transaction is currently active on pBt.
61961 **
61962 ** Otherwise, sync the database file for the btree pBt. zMaster points to
61963 ** the name of a master journal file that should be written into the
61964 ** individual journal file, or is NULL, indicating no master journal file
61965 ** (single database transaction).
61966 **
61967 ** When this is called, the master journal should already have been
61968 ** created, populated with this journal pointer and synced to disk.
61969 **
61970 ** Once this is routine has returned, the only thing required to commit
61971 ** the write-transaction for this database file is to delete the journal.
61972 */
61973 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
61974  int rc = SQLITE_OK;
61975  if( p->inTrans==TRANS_WRITE ){
61976  BtShared *pBt = p->pBt;
61977  sqlite3BtreeEnter(p);
61978 #ifndef SQLITE_OMIT_AUTOVACUUM
61979  if( pBt->autoVacuum ){
61980  rc = autoVacuumCommit(pBt);
61981  if( rc!=SQLITE_OK ){
61982  sqlite3BtreeLeave(p);
61983  return rc;
61984  }
61985  }
61986  if( pBt->bDoTruncate ){
61988  }
61989 #endif
61990  rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
61991  sqlite3BtreeLeave(p);
61992  }
61993  return rc;
61994 }
61995 
61996 /*
61997 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
61998 ** at the conclusion of a transaction.
61999 */
62000 static void btreeEndTransaction(Btree *p){
62001  BtShared *pBt = p->pBt;
62002  sqlite3 *db = p->db;
62003  assert( sqlite3BtreeHoldsMutex(p) );
62004 
62005 #ifndef SQLITE_OMIT_AUTOVACUUM
62006  pBt->bDoTruncate = 0;
62007 #endif
62008  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
62009  /* If there are other active statements that belong to this database
62010  ** handle, downgrade to a read-only transaction. The other statements
62011  ** may still be reading from the database. */
62013  p->inTrans = TRANS_READ;
62014  }else{
62015  /* If the handle had any kind of transaction open, decrement the
62016  ** transaction count of the shared btree. If the transaction count
62017  ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
62018  ** call below will unlock the pager. */
62019  if( p->inTrans!=TRANS_NONE ){
62021  pBt->nTransaction--;
62022  if( 0==pBt->nTransaction ){
62023  pBt->inTransaction = TRANS_NONE;
62024  }
62025  }
62026 
62027  /* Set the current transaction state to TRANS_NONE and unlock the
62028  ** pager if this call closed the only read or write transaction. */
62029  p->inTrans = TRANS_NONE;
62030  unlockBtreeIfUnused(pBt);
62031  }
62032 
62033  btreeIntegrity(p);
62034 }
62035 
62036 /*
62037 ** Commit the transaction currently in progress.
62038 **
62039 ** This routine implements the second phase of a 2-phase commit. The
62040 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
62041 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
62042 ** routine did all the work of writing information out to disk and flushing the
62043 ** contents so that they are written onto the disk platter. All this
62044 ** routine has to do is delete or truncate or zero the header in the
62045 ** the rollback journal (which causes the transaction to commit) and
62046 ** drop locks.
62047 **
62048 ** Normally, if an error occurs while the pager layer is attempting to
62049 ** finalize the underlying journal file, this function returns an error and
62050 ** the upper layer will attempt a rollback. However, if the second argument
62051 ** is non-zero then this b-tree transaction is part of a multi-file
62052 ** transaction. In this case, the transaction has already been committed
62053 ** (by deleting a master journal file) and the caller will ignore this
62054 ** functions return code. So, even if an error occurs in the pager layer,
62055 ** reset the b-tree objects internal state to indicate that the write
62056 ** transaction has been closed. This is quite safe, as the pager will have
62057 ** transitioned to the error state.
62058 **
62059 ** This will release the write lock on the database file. If there
62060 ** are no active cursors, it also releases the read lock.
62061 */
62063 
62064  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
62065  sqlite3BtreeEnter(p);
62066  btreeIntegrity(p);
62067 
62068  /* If the handle has a write-transaction open, commit the shared-btrees
62069  ** transaction and set the shared state to TRANS_READ.
62070  */
62071  if( p->inTrans==TRANS_WRITE ){
62072  int rc;
62073  BtShared *pBt = p->pBt;
62074  assert( pBt->inTransaction==TRANS_WRITE );
62075  assert( pBt->nTransaction>0 );
62077  if( rc!=SQLITE_OK && bCleanup==0 ){
62078  sqlite3BtreeLeave(p);
62079  return rc;
62080  }
62081  p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
62082  pBt->inTransaction = TRANS_READ;
62083  btreeClearHasContent(pBt);
62084  }
62085 
62087  sqlite3BtreeLeave(p);
62088  return SQLITE_OK;
62089 }
62090 
62091 /*
62092 ** Do both phases of a commit.
62093 */
62095  int rc;
62096  sqlite3BtreeEnter(p);
62097  rc = sqlite3BtreeCommitPhaseOne(p, 0);
62098  if( rc==SQLITE_OK ){
62099  rc = sqlite3BtreeCommitPhaseTwo(p, 0);
62100  }
62101  sqlite3BtreeLeave(p);
62102  return rc;
62103 }
62104 
62105 /*
62106 ** This routine sets the state to CURSOR_FAULT and the error
62107 ** code to errCode for every cursor on any BtShared that pBtree
62108 ** references. Or if the writeOnly flag is set to 1, then only
62109 ** trip write cursors and leave read cursors unchanged.
62110 **
62111 ** Every cursor is a candidate to be tripped, including cursors
62112 ** that belong to other database connections that happen to be
62113 ** sharing the cache with pBtree.
62114 **
62115 ** This routine gets called when a rollback occurs. If the writeOnly
62116 ** flag is true, then only write-cursors need be tripped - read-only
62117 ** cursors save their current positions so that they may continue
62118 ** following the rollback. Or, if writeOnly is false, all cursors are
62119 ** tripped. In general, writeOnly is false if the transaction being
62120 ** rolled back modified the database schema. In this case b-tree root
62121 ** pages may be moved or deleted from the database altogether, making
62122 ** it unsafe for read cursors to continue.
62123 **
62124 ** If the writeOnly flag is true and an error is encountered while
62125 ** saving the current position of a read-only cursor, all cursors,
62126 ** including all read-cursors are tripped.
62127 **
62128 ** SQLITE_OK is returned if successful, or if an error occurs while
62129 ** saving a cursor position, an SQLite error code.
62130 */
62131 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
62132  BtCursor *p;
62133  int rc = SQLITE_OK;
62134 
62135  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
62136  if( pBtree ){
62137  sqlite3BtreeEnter(pBtree);
62138  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
62139  int i;
62140  if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
62141  if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
62142  rc = saveCursorPosition(p);
62143  if( rc!=SQLITE_OK ){
62144  (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
62145  break;
62146  }
62147  }
62148  }else{
62150  p->eState = CURSOR_FAULT;
62151  p->skipNext = errCode;
62152  }
62153  for(i=0; i<=p->iPage; i++){
62154  releasePage(p->apPage[i]);
62155  p->apPage[i] = 0;
62156  }
62157  }
62158  sqlite3BtreeLeave(pBtree);
62159  }
62160  return rc;
62161 }
62162 
62163 /*
62164 ** Rollback the transaction in progress.
62165 **
62166 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
62167 ** Only write cursors are tripped if writeOnly is true but all cursors are
62168 ** tripped if writeOnly is false. Any attempt to use
62169 ** a tripped cursor will result in an error.
62170 **
62171 ** This will release the write lock on the database file. If there
62172 ** are no active cursors, it also releases the read lock.
62173 */
62174 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
62175  int rc;
62176  BtShared *pBt = p->pBt;
62177  MemPage *pPage1;
62178 
62179  assert( writeOnly==1 || writeOnly==0 );
62180  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
62181  sqlite3BtreeEnter(p);
62182  if( tripCode==SQLITE_OK ){
62183  rc = tripCode = saveAllCursors(pBt, 0, 0);
62184  if( rc ) writeOnly = 0;
62185  }else{
62186  rc = SQLITE_OK;
62187  }
62188  if( tripCode ){
62189  int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
62190  assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
62191  if( rc2!=SQLITE_OK ) rc = rc2;
62192  }
62193  btreeIntegrity(p);
62194 
62195  if( p->inTrans==TRANS_WRITE ){
62196  int rc2;
62197 
62198  assert( TRANS_WRITE==pBt->inTransaction );
62199  rc2 = sqlite3PagerRollback(pBt->pPager);
62200  if( rc2!=SQLITE_OK ){
62201  rc = rc2;
62202  }
62203 
62204  /* The rollback may have destroyed the pPage1->aData value. So
62205  ** call btreeGetPage() on page 1 again to make
62206  ** sure pPage1->aData is set correctly. */
62207  if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
62208  int nPage = get4byte(28+(u8*)pPage1->aData);
62209  testcase( nPage==0 );
62210  if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
62211  testcase( pBt->nPage!=nPage );
62212  pBt->nPage = nPage;
62213  releasePage(pPage1);
62214  }
62215  assert( countValidCursors(pBt, 1)==0 );
62216  pBt->inTransaction = TRANS_READ;
62217  btreeClearHasContent(pBt);
62218  }
62219 
62221  sqlite3BtreeLeave(p);
62222  return rc;
62223 }
62224 
62225 /*
62226 ** Start a statement subtransaction. The subtransaction can be rolled
62227 ** back independently of the main transaction. You must start a transaction
62228 ** before starting a subtransaction. The subtransaction is ended automatically
62229 ** if the main transaction commits or rolls back.
62230 **
62231 ** Statement subtransactions are used around individual SQL statements
62232 ** that are contained within a BEGIN...COMMIT block. If a constraint
62233 ** error occurs within the statement, the effect of that one statement
62234 ** can be rolled back without having to rollback the entire transaction.
62235 **
62236 ** A statement sub-transaction is implemented as an anonymous savepoint. The
62237 ** value passed as the second parameter is the total number of savepoints,
62238 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
62239 ** are no active savepoints and no other statement-transactions open,
62240 ** iStatement is 1. This anonymous savepoint can be released or rolled back
62241 ** using the sqlite3BtreeSavepoint() function.
62242 */
62244  int rc;
62245  BtShared *pBt = p->pBt;
62246  sqlite3BtreeEnter(p);
62247  assert( p->inTrans==TRANS_WRITE );
62248  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62249  assert( iStatement>0 );
62250  assert( iStatement>p->db->nSavepoint );
62251  assert( pBt->inTransaction==TRANS_WRITE );
62252  /* At the pager level, a statement transaction is a savepoint with
62253  ** an index greater than all savepoints created explicitly using
62254  ** SQL statements. It is illegal to open, release or rollback any
62255  ** such savepoints while the statement transaction savepoint is active.
62256  */
62257  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
62258  sqlite3BtreeLeave(p);
62259  return rc;
62260 }
62261 
62262 /*
62263 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
62264 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
62265 ** savepoint identified by parameter iSavepoint, depending on the value
62266 ** of op.
62267 **
62268 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
62269 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
62270 ** contents of the entire transaction are rolled back. This is different
62271 ** from a normal transaction rollback, as no locks are released and the
62272 ** transaction remains open.
62273 */
62274 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
62275  int rc = SQLITE_OK;
62276  if( p && p->inTrans==TRANS_WRITE ){
62277  BtShared *pBt = p->pBt;
62278  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
62279  assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
62280  sqlite3BtreeEnter(p);
62281  rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
62282  if( rc==SQLITE_OK ){
62283  if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
62284  pBt->nPage = 0;
62285  }
62286  rc = newDatabase(pBt);
62287  pBt->nPage = get4byte(28 + pBt->pPage1->aData);
62288 
62289  /* The database size was written into the offset 28 of the header
62290  ** when the transaction started, so we know that the value at offset
62291  ** 28 is nonzero. */
62292  assert( pBt->nPage>0 );
62293  }
62294  sqlite3BtreeLeave(p);
62295  }
62296  return rc;
62297 }
62298 
62299 /*
62300 ** Create a new cursor for the BTree whose root is on the page
62301 ** iTable. If a read-only cursor is requested, it is assumed that
62302 ** the caller already has at least a read-only transaction open
62303 ** on the database already. If a write-cursor is requested, then
62304 ** the caller is assumed to have an open write transaction.
62305 **
62306 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
62307 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
62308 ** can be used for reading or for writing if other conditions for writing
62309 ** are also met. These are the conditions that must be met in order
62310 ** for writing to be allowed:
62311 **
62312 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
62313 **
62314 ** 2: Other database connections that share the same pager cache
62315 ** but which are not in the READ_UNCOMMITTED state may not have
62316 ** cursors open with wrFlag==0 on the same table. Otherwise
62317 ** the changes made by this write cursor would be visible to
62318 ** the read cursors in the other database connection.
62319 **
62320 ** 3: The database must be writable (not on read-only media)
62321 **
62322 ** 4: There must be an active transaction.
62323 **
62324 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
62325 ** is set. If FORDELETE is set, that is a hint to the implementation that
62326 ** this cursor will only be used to seek to and delete entries of an index
62327 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
62328 ** this implementation. But in a hypothetical alternative storage engine
62329 ** in which index entries are automatically deleted when corresponding table
62330 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
62331 ** operations on this cursor can be no-ops and all READ operations can
62332 ** return a null row (2-bytes: 0x01 0x00).
62333 **
62334 ** No checking is done to make sure that page iTable really is the
62335 ** root page of a b-tree. If it is not, then the cursor acquired
62336 ** will not work correctly.
62337 **
62338 ** It is assumed that the sqlite3BtreeCursorZero() has been called
62339 ** on pCur to initialize the memory space prior to invoking this routine.
62340 */
62341 static int btreeCursor(
62342  Btree *p, /* The btree */
62343  int iTable, /* Root page of table to open */
62344  int wrFlag, /* 1 to write. 0 read-only */
62345  struct KeyInfo *pKeyInfo, /* First arg to comparison function */
62346  BtCursor *pCur /* Space for new cursor */
62347 ){
62348  BtShared *pBt = p->pBt; /* Shared b-tree handle */
62349  BtCursor *pX; /* Looping over other all cursors */
62350 
62351  assert( sqlite3BtreeHoldsMutex(p) );
62352  assert( wrFlag==0
62353  || wrFlag==BTREE_WRCSR
62354  || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
62355  );
62356 
62357  /* The following assert statements verify that if this is a sharable
62358  ** b-tree database, the connection is holding the required table locks,
62359  ** and that no other connection has any open cursor that conflicts with
62360  ** this lock. */
62361  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
62362  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
62363 
62364  /* Assert that the caller has opened the required transaction. */
62365  assert( p->inTrans>TRANS_NONE );
62366  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
62367  assert( pBt->pPage1 && pBt->pPage1->aData );
62368  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
62369 
62370  if( wrFlag ){
62371  allocateTempSpace(pBt);
62372  if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
62373  }
62374  if( iTable==1 && btreePagecount(pBt)==0 ){
62375  assert( wrFlag==0 );
62376  iTable = 0;
62377  }
62378 
62379  /* Now that no other errors can occur, finish filling in the BtCursor
62380  ** variables and link the cursor into the BtShared list. */
62381  pCur->pgnoRoot = (Pgno)iTable;
62382  pCur->iPage = -1;
62383  pCur->pKeyInfo = pKeyInfo;
62384  pCur->pBtree = p;
62385  pCur->pBt = pBt;
62386  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
62387  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
62388  /* If there are two or more cursors on the same btree, then all such
62389  ** cursors *must* have the BTCF_Multiple flag set. */
62390  for(pX=pBt->pCursor; pX; pX=pX->pNext){
62391  if( pX->pgnoRoot==(Pgno)iTable ){
62392  pX->curFlags |= BTCF_Multiple;
62393  pCur->curFlags |= BTCF_Multiple;
62394  }
62395  }
62396  pCur->pNext = pBt->pCursor;
62397  pBt->pCursor = pCur;
62398  pCur->eState = CURSOR_INVALID;
62399  return SQLITE_OK;
62400 }
62402  Btree *p, /* The btree */
62403  int iTable, /* Root page of table to open */
62404  int wrFlag, /* 1 to write. 0 read-only */
62405  struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
62406  BtCursor *pCur /* Write new cursor here */
62407 ){
62408  int rc;
62409  if( iTable<1 ){
62410  rc = SQLITE_CORRUPT_BKPT;
62411  }else{
62412  sqlite3BtreeEnter(p);
62413  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
62414  sqlite3BtreeLeave(p);
62415  }
62416  return rc;
62417 }
62418 
62419 /*
62420 ** Return the size of a BtCursor object in bytes.
62421 **
62422 ** This interfaces is needed so that users of cursors can preallocate
62423 ** sufficient storage to hold a cursor. The BtCursor object is opaque
62424 ** to users so they cannot do the sizeof() themselves - they must call
62425 ** this routine.
62426 */
62428  return ROUND8(sizeof(BtCursor));
62429 }
62430 
62431 /*
62432 ** Initialize memory that will be converted into a BtCursor object.
62433 **
62434 ** The simple approach here would be to memset() the entire object
62435 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
62436 ** do not need to be zeroed and they are large, so we can save a lot
62437 ** of run-time by skipping the initialization of those elements.
62438 */
62440  memset(p, 0, offsetof(BtCursor, iPage));
62441 }
62442 
62443 /*
62444 ** Close a cursor. The read lock on the database file is released
62445 ** when the last cursor is closed.
62446 */
62448  Btree *pBtree = pCur->pBtree;
62449  if( pBtree ){
62450  int i;
62451  BtShared *pBt = pCur->pBt;
62452  sqlite3BtreeEnter(pBtree);
62454  assert( pBt->pCursor!=0 );
62455  if( pBt->pCursor==pCur ){
62456  pBt->pCursor = pCur->pNext;
62457  }else{
62458  BtCursor *pPrev = pBt->pCursor;
62459  do{
62460  if( pPrev->pNext==pCur ){
62461  pPrev->pNext = pCur->pNext;
62462  break;
62463  }
62464  pPrev = pPrev->pNext;
62465  }while( ALWAYS(pPrev) );
62466  }
62467  for(i=0; i<=pCur->iPage; i++){
62468  releasePage(pCur->apPage[i]);
62469  }
62470  unlockBtreeIfUnused(pBt);
62471  sqlite3_free(pCur->aOverflow);
62472  /* sqlite3_free(pCur); */
62473  sqlite3BtreeLeave(pBtree);
62474  }
62475  return SQLITE_OK;
62476 }
62477 
62478 /*
62479 ** Make sure the BtCursor* given in the argument has a valid
62480 ** BtCursor.info structure. If it is not already valid, call
62481 ** btreeParseCell() to fill it in.
62482 **
62483 ** BtCursor.info is a cache of the information in the current cell.
62484 ** Using this cache reduces the number of calls to btreeParseCell().
62485 */
62486 #ifndef NDEBUG
62487  static void assertCellInfo(BtCursor *pCur){
62488  CellInfo info;
62489  int iPage = pCur->iPage;
62490  memset(&info, 0, sizeof(info));
62491  btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
62492  assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
62493  }
62494 #else
62495  #define assertCellInfo(x)
62496 #endif
62498  if( pCur->info.nSize==0 ){
62499  int iPage = pCur->iPage;
62500  pCur->curFlags |= BTCF_ValidNKey;
62501  btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
62502  }else{
62503  assertCellInfo(pCur);
62504  }
62505 }
62506 
62507 #ifndef NDEBUG /* The next routine used only within assert() statements */
62508 /*
62509 ** Return true if the given BtCursor is valid. A valid cursor is one
62510 ** that is currently pointing to a row in a (non-empty) table.
62511 ** This is a verification routine is used only within assert() statements.
62512 */
62513 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
62514  return pCur && pCur->eState==CURSOR_VALID;
62515 }
62516 #endif /* NDEBUG */
62517 
62518 /*
62519 ** Return the value of the integer key or "rowid" for a table btree.
62520 ** This routine is only valid for a cursor that is pointing into a
62521 ** ordinary table btree. If the cursor points to an index btree or
62522 ** is invalid, the result of this routine is undefined.
62523 */
62525  assert( cursorHoldsMutex(pCur) );
62526  assert( pCur->eState==CURSOR_VALID );
62527  assert( pCur->curIntKey );
62528  getCellInfo(pCur);
62529  return pCur->info.nKey;
62530 }
62531 
62532 /*
62533 ** Return the number of bytes of payload for the entry that pCur is
62534 ** currently pointing to. For table btrees, this will be the amount
62535 ** of data. For index btrees, this will be the size of the key.
62536 **
62537 ** The caller must guarantee that the cursor is pointing to a non-NULL
62538 ** valid entry. In other words, the calling procedure must guarantee
62539 ** that the cursor has Cursor.eState==CURSOR_VALID.
62540 */
62542  assert( cursorHoldsMutex(pCur) );
62543  assert( pCur->eState==CURSOR_VALID );
62544  getCellInfo(pCur);
62545  return pCur->info.nPayload;
62546 }
62547 
62548 /*
62549 ** Given the page number of an overflow page in the database (parameter
62550 ** ovfl), this function finds the page number of the next page in the
62551 ** linked list of overflow pages. If possible, it uses the auto-vacuum
62552 ** pointer-map data instead of reading the content of page ovfl to do so.
62553 **
62554 ** If an error occurs an SQLite error code is returned. Otherwise:
62555 **
62556 ** The page number of the next overflow page in the linked list is
62557 ** written to *pPgnoNext. If page ovfl is the last page in its linked
62558 ** list, *pPgnoNext is set to zero.
62559 **
62560 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
62561 ** to page number pOvfl was obtained, then *ppPage is set to point to that
62562 ** reference. It is the responsibility of the caller to call releasePage()
62563 ** on *ppPage to free the reference. In no reference was obtained (because
62564 ** the pointer-map was used to obtain the value for *pPgnoNext), then
62565 ** *ppPage is set to zero.
62566 */
62567 static int getOverflowPage(
62568  BtShared *pBt, /* The database file */
62569  Pgno ovfl, /* Current overflow page number */
62570  MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
62571  Pgno *pPgnoNext /* OUT: Next overflow page number */
62572 ){
62573  Pgno next = 0;
62574  MemPage *pPage = 0;
62575  int rc = SQLITE_OK;
62576 
62577  assert( sqlite3_mutex_held(pBt->mutex) );
62578  assert(pPgnoNext);
62579 
62580 #ifndef SQLITE_OMIT_AUTOVACUUM
62581  /* Try to find the next page in the overflow list using the
62582  ** autovacuum pointer-map pages. Guess that the next page in
62583  ** the overflow list is page number (ovfl+1). If that guess turns
62584  ** out to be wrong, fall back to loading the data of page
62585  ** number ovfl to determine the next page number.
62586  */
62587  if( pBt->autoVacuum ){
62588  Pgno pgno;
62589  Pgno iGuess = ovfl+1;
62590  u8 eType;
62591 
62592  while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
62593  iGuess++;
62594  }
62595 
62596  if( iGuess<=btreePagecount(pBt) ){
62597  rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
62598  if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
62599  next = iGuess;
62600  rc = SQLITE_DONE;
62601  }
62602  }
62603  }
62604 #endif
62605 
62606  assert( next==0 || rc==SQLITE_DONE );
62607  if( rc==SQLITE_OK ){
62608  rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
62609  assert( rc==SQLITE_OK || pPage==0 );
62610  if( rc==SQLITE_OK ){
62611  next = get4byte(pPage->aData);
62612  }
62613  }
62614 
62615  *pPgnoNext = next;
62616  if( ppPage ){
62617  *ppPage = pPage;
62618  }else{
62619  releasePage(pPage);
62620  }
62621  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
62622 }
62623 
62624 /*
62625 ** Copy data from a buffer to a page, or from a page to a buffer.
62626 **
62627 ** pPayload is a pointer to data stored on database page pDbPage.
62628 ** If argument eOp is false, then nByte bytes of data are copied
62629 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
62630 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
62631 ** of data are copied from the buffer pBuf to pPayload.
62632 **
62633 ** SQLITE_OK is returned on success, otherwise an error code.
62634 */
62635 static int copyPayload(
62636  void *pPayload, /* Pointer to page data */
62637  void *pBuf, /* Pointer to buffer */
62638  int nByte, /* Number of bytes to copy */
62639  int eOp, /* 0 -> copy from page, 1 -> copy to page */
62640  DbPage *pDbPage /* Page containing pPayload */
62641 ){
62642  if( eOp ){
62643  /* Copy data from buffer to page (a write operation) */
62644  int rc = sqlite3PagerWrite(pDbPage);
62645  if( rc!=SQLITE_OK ){
62646  return rc;
62647  }
62648  memcpy(pPayload, pBuf, nByte);
62649  }else{
62650  /* Copy data from page to buffer (a read operation) */
62651  memcpy(pBuf, pPayload, nByte);
62652  }
62653  return SQLITE_OK;
62654 }
62655 
62656 /*
62657 ** This function is used to read or overwrite payload information
62658 ** for the entry that the pCur cursor is pointing to. The eOp
62659 ** argument is interpreted as follows:
62660 **
62661 ** 0: The operation is a read. Populate the overflow cache.
62662 ** 1: The operation is a write. Populate the overflow cache.
62663 ** 2: The operation is a read. Do not populate the overflow cache.
62664 **
62665 ** A total of "amt" bytes are read or written beginning at "offset".
62666 ** Data is read to or from the buffer pBuf.
62667 **
62668 ** The content being read or written might appear on the main page
62669 ** or be scattered out on multiple overflow pages.
62670 **
62671 ** If the current cursor entry uses one or more overflow pages and the
62672 ** eOp argument is not 2, this function may allocate space for and lazily
62673 ** populates the overflow page-list cache array (BtCursor.aOverflow).
62674 ** Subsequent calls use this cache to make seeking to the supplied offset
62675 ** more efficient.
62676 **
62677 ** Once an overflow page-list cache has been allocated, it may be
62678 ** invalidated if some other cursor writes to the same table, or if
62679 ** the cursor is moved to a different row. Additionally, in auto-vacuum
62680 ** mode, the following events may invalidate an overflow page-list cache.
62681 **
62682 ** * An incremental vacuum,
62683 ** * A commit in auto_vacuum="full" mode,
62684 ** * Creating a table (may require moving an overflow page).
62685 */
62686 static int accessPayload(
62687  BtCursor *pCur, /* Cursor pointing to entry to read from */
62688  u32 offset, /* Begin reading this far into payload */
62689  u32 amt, /* Read this many bytes */
62690  unsigned char *pBuf, /* Write the bytes into this buffer */
62691  int eOp /* zero to read. non-zero to write. */
62692 ){
62693  unsigned char *aPayload;
62694  int rc = SQLITE_OK;
62695  int iIdx = 0;
62696  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
62697  BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
62698 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62699  unsigned char * const pBufStart = pBuf;
62700  int bEnd; /* True if reading to end of data */
62701 #endif
62702 
62703  assert( pPage );
62704  assert( pCur->eState==CURSOR_VALID );
62705  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
62706  assert( cursorHoldsMutex(pCur) );
62707  assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
62708 
62709  getCellInfo(pCur);
62710  aPayload = pCur->info.pPayload;
62711 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62712  bEnd = offset+amt==pCur->info.nPayload;
62713 #endif
62714  assert( offset+amt <= pCur->info.nPayload );
62715 
62716  assert( aPayload > pPage->aData );
62717  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
62718  /* Trying to read or write past the end of the data is an error. The
62719  ** conditional above is really:
62720  ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
62721  ** but is recast into its current form to avoid integer overflow problems
62722  */
62723  return SQLITE_CORRUPT_BKPT;
62724  }
62725 
62726  /* Check if data must be read/written to/from the btree page itself. */
62727  if( offset<pCur->info.nLocal ){
62728  int a = amt;
62729  if( a+offset>pCur->info.nLocal ){
62730  a = pCur->info.nLocal - offset;
62731  }
62732  rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
62733  offset = 0;
62734  pBuf += a;
62735  amt -= a;
62736  }else{
62737  offset -= pCur->info.nLocal;
62738  }
62739 
62740 
62741  if( rc==SQLITE_OK && amt>0 ){
62742  const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
62743  Pgno nextPage;
62744 
62745  nextPage = get4byte(&aPayload[pCur->info.nLocal]);
62746 
62747  /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
62748  ** Except, do not allocate aOverflow[] for eOp==2.
62749  **
62750  ** The aOverflow[] array is sized at one entry for each overflow page
62751  ** in the overflow chain. The page number of the first overflow page is
62752  ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
62753  ** means "not yet known" (the cache is lazily populated).
62754  */
62755  if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
62756  int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
62757  if( nOvfl>pCur->nOvflAlloc ){
62758  Pgno *aNew = (Pgno*)sqlite3Realloc(
62759  pCur->aOverflow, nOvfl*2*sizeof(Pgno)
62760  );
62761  if( aNew==0 ){
62762  rc = SQLITE_NOMEM_BKPT;
62763  }else{
62764  pCur->nOvflAlloc = nOvfl*2;
62765  pCur->aOverflow = aNew;
62766  }
62767  }
62768  if( rc==SQLITE_OK ){
62769  memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
62770  pCur->curFlags |= BTCF_ValidOvfl;
62771  }
62772  }
62773 
62774  /* If the overflow page-list cache has been allocated and the
62775  ** entry for the first required overflow page is valid, skip
62776  ** directly to it.
62777  */
62778  if( (pCur->curFlags & BTCF_ValidOvfl)!=0
62779  && pCur->aOverflow[offset/ovflSize]
62780  ){
62781  iIdx = (offset/ovflSize);
62782  nextPage = pCur->aOverflow[iIdx];
62783  offset = (offset%ovflSize);
62784  }
62785 
62786  for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
62787 
62788  /* If required, populate the overflow page-list cache. */
62789  if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
62790  assert( pCur->aOverflow[iIdx]==0
62791  || pCur->aOverflow[iIdx]==nextPage
62792  || CORRUPT_DB );
62793  pCur->aOverflow[iIdx] = nextPage;
62794  }
62795 
62796  if( offset>=ovflSize ){
62797  /* The only reason to read this page is to obtain the page
62798  ** number for the next page in the overflow chain. The page
62799  ** data is not required. So first try to lookup the overflow
62800  ** page-list cache, if any, then fall back to the getOverflowPage()
62801  ** function.
62802  **
62803  ** Note that the aOverflow[] array must be allocated because eOp!=2
62804  ** here. If eOp==2, then offset==0 and this branch is never taken.
62805  */
62806  assert( eOp!=2 );
62807  assert( pCur->curFlags & BTCF_ValidOvfl );
62808  assert( pCur->pBtree->db==pBt->db );
62809  if( pCur->aOverflow[iIdx+1] ){
62810  nextPage = pCur->aOverflow[iIdx+1];
62811  }else{
62812  rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
62813  }
62814  offset -= ovflSize;
62815  }else{
62816  /* Need to read this page properly. It contains some of the
62817  ** range of data that is being read (eOp==0) or written (eOp!=0).
62818  */
62819 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62820  sqlite3_file *fd;
62821 #endif
62822  int a = amt;
62823  if( a + offset > ovflSize ){
62824  a = ovflSize - offset;
62825  }
62826 
62827 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62828  /* If all the following are true:
62829  **
62830  ** 1) this is a read operation, and
62831  ** 2) data is required from the start of this overflow page, and
62832  ** 3) the database is file-backed, and
62833  ** 4) there is no open write-transaction, and
62834  ** 5) the database is not a WAL database,
62835  ** 6) all data from the page is being read.
62836  ** 7) at least 4 bytes have already been read into the output buffer
62837  **
62838  ** then data can be read directly from the database file into the
62839  ** output buffer, bypassing the page-cache altogether. This speeds
62840  ** up loading large records that span many overflow pages.
62841  */
62842  if( (eOp&0x01)==0 /* (1) */
62843  && offset==0 /* (2) */
62844  && (bEnd || a==ovflSize) /* (6) */
62845  && pBt->inTransaction==TRANS_READ /* (4) */
62846  && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
62847  && 0==sqlite3PagerUseWal(pBt->pPager) /* (5) */
62848  && &pBuf[-4]>=pBufStart /* (7) */
62849  ){
62850  u8 aSave[4];
62851  u8 *aWrite = &pBuf[-4];
62852  assert( aWrite>=pBufStart ); /* hence (7) */
62853  memcpy(aSave, aWrite, 4);
62854  rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
62855  nextPage = get4byte(aWrite);
62856  memcpy(aWrite, aSave, 4);
62857  }else
62858 #endif
62859 
62860  {
62861  DbPage *pDbPage;
62862  rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
62863  ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
62864  );
62865  if( rc==SQLITE_OK ){
62866  aPayload = sqlite3PagerGetData(pDbPage);
62867  nextPage = get4byte(aPayload);
62868  rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
62869  sqlite3PagerUnref(pDbPage);
62870  offset = 0;
62871  }
62872  }
62873  amt -= a;
62874  pBuf += a;
62875  }
62876  }
62877  }
62878 
62879  if( rc==SQLITE_OK && amt>0 ){
62880  return SQLITE_CORRUPT_BKPT;
62881  }
62882  return rc;
62883 }
62884 
62885 /*
62886 ** Read part of the key associated with cursor pCur. Exactly
62887 ** "amt" bytes will be transferred into pBuf[]. The transfer
62888 ** begins at "offset".
62889 **
62890 ** The caller must ensure that pCur is pointing to a valid row
62891 ** in the table.
62892 **
62893 ** Return SQLITE_OK on success or an error code if anything goes
62894 ** wrong. An error is returned if "offset+amt" is larger than
62895 ** the available payload.
62896 */
62897 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62898  assert( cursorHoldsMutex(pCur) );
62899  assert( pCur->eState==CURSOR_VALID );
62900  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62901  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62902  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
62903 }
62904 
62905 /*
62906 ** Read part of the data associated with cursor pCur. Exactly
62907 ** "amt" bytes will be transfered into pBuf[]. The transfer
62908 ** begins at "offset".
62909 **
62910 ** Return SQLITE_OK on success or an error code if anything goes
62911 ** wrong. An error is returned if "offset+amt" is larger than
62912 ** the available payload.
62913 */
62914 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62915  int rc;
62916 
62917 #ifndef SQLITE_OMIT_INCRBLOB
62918  if ( pCur->eState==CURSOR_INVALID ){
62919  return SQLITE_ABORT;
62920  }
62921 #endif
62922 
62923  assert( cursorOwnsBtShared(pCur) );
62924  rc = restoreCursorPosition(pCur);
62925  if( rc==SQLITE_OK ){
62926  assert( pCur->eState==CURSOR_VALID );
62927  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62928  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62929  rc = accessPayload(pCur, offset, amt, pBuf, 0);
62930  }
62931  return rc;
62932 }
62933 
62934 /*
62935 ** Return a pointer to payload information from the entry that the
62936 ** pCur cursor is pointing to. The pointer is to the beginning of
62937 ** the key if index btrees (pPage->intKey==0) and is the data for
62938 ** table btrees (pPage->intKey==1). The number of bytes of available
62939 ** key/data is written into *pAmt. If *pAmt==0, then the value
62940 ** returned will not be a valid pointer.
62941 **
62942 ** This routine is an optimization. It is common for the entire key
62943 ** and data to fit on the local page and for there to be no overflow
62944 ** pages. When that is so, this routine can be used to access the
62945 ** key and data without making a copy. If the key and/or data spills
62946 ** onto overflow pages, then accessPayload() must be used to reassemble
62947 ** the key/data and copy it into a preallocated buffer.
62948 **
62949 ** The pointer returned by this routine looks directly into the cached
62950 ** page of the database. The data might change or move the next time
62951 ** any btree routine is called.
62952 */
62953 static const void *fetchPayload(
62954  BtCursor *pCur, /* Cursor pointing to entry to read from */
62955  u32 *pAmt /* Write the number of available bytes here */
62956 ){
62957  u32 amt;
62958  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
62959  assert( pCur->eState==CURSOR_VALID );
62960  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62961  assert( cursorOwnsBtShared(pCur) );
62962  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62963  assert( pCur->info.nSize>0 );
62964  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
62965  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
62966  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
62967  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
62968  *pAmt = amt;
62969  return (void*)pCur->info.pPayload;
62970 }
62971 
62972 
62973 /*
62974 ** For the entry that cursor pCur is point to, return as
62975 ** many bytes of the key or data as are available on the local
62976 ** b-tree page. Write the number of available bytes into *pAmt.
62977 **
62978 ** The pointer returned is ephemeral. The key/data may move
62979 ** or be destroyed on the next call to any Btree routine,
62980 ** including calls from other threads against the same cache.
62981 ** Hence, a mutex on the BtShared should be held prior to calling
62982 ** this routine.
62983 **
62984 ** These routines is used to get quick access to key and data
62985 ** in the common case where no overflow pages are used.
62986 */
62987 SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
62988  return fetchPayload(pCur, pAmt);
62989 }
62990 
62991 
62992 /*
62993 ** Move the cursor down to a new child page. The newPgno argument is the
62994 ** page number of the child page to move to.
62995 **
62996 ** This function returns SQLITE_CORRUPT if the page-header flags field of
62997 ** the new child page does not match the flags field of the parent (i.e.
62998 ** if an intkey page appears to be the parent of a non-intkey page, or
62999 ** vice-versa).
63000 */
63001 static int moveToChild(BtCursor *pCur, u32 newPgno){
63002  BtShared *pBt = pCur->pBt;
63003 
63004  assert( cursorOwnsBtShared(pCur) );
63005  assert( pCur->eState==CURSOR_VALID );
63006  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
63007  assert( pCur->iPage>=0 );
63008  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
63009  return SQLITE_CORRUPT_BKPT;
63010  }
63011  pCur->info.nSize = 0;
63013  pCur->iPage++;
63014  pCur->aiIdx[pCur->iPage] = 0;
63015  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
63016  pCur, pCur->curPagerFlags);
63017 }
63018 
63019 #if SQLITE_DEBUG
63020 /*
63021 ** Page pParent is an internal (non-leaf) tree page. This function
63022 ** asserts that page number iChild is the left-child if the iIdx'th
63023 ** cell in page pParent. Or, if iIdx is equal to the total number of
63024 ** cells in pParent, that page number iChild is the right-child of
63025 ** the page.
63026 */
63027 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
63028  if( CORRUPT_DB ) return; /* The conditions tested below might not be true
63029  ** in a corrupt database */
63030  assert( iIdx<=pParent->nCell );
63031  if( iIdx==pParent->nCell ){
63032  assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
63033  }else{
63034  assert( get4byte(findCell(pParent, iIdx))==iChild );
63035  }
63036 }
63037 #else
63038 # define assertParentIndex(x,y,z)
63039 #endif
63040 
63041 /*
63042 ** Move the cursor up to the parent page.
63043 **
63044 ** pCur->idx is set to the cell index that contains the pointer
63045 ** to the page we are coming from. If we are coming from the
63046 ** right-most child page then pCur->idx is set to one more than
63047 ** the largest cell index.
63048 */
63049 static void moveToParent(BtCursor *pCur){
63050  assert( cursorOwnsBtShared(pCur) );
63051  assert( pCur->eState==CURSOR_VALID );
63052  assert( pCur->iPage>0 );
63053  assert( pCur->apPage[pCur->iPage] );
63055  pCur->apPage[pCur->iPage-1],
63056  pCur->aiIdx[pCur->iPage-1],
63057  pCur->apPage[pCur->iPage]->pgno
63058  );
63059  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
63060  pCur->info.nSize = 0;
63062  releasePageNotNull(pCur->apPage[pCur->iPage--]);
63063 }
63064 
63065 /*
63066 ** Move the cursor to point to the root page of its b-tree structure.
63067 **
63068 ** If the table has a virtual root page, then the cursor is moved to point
63069 ** to the virtual root page instead of the actual root page. A table has a
63070 ** virtual root page when the actual root page contains no cells and a
63071 ** single child page. This can only happen with the table rooted at page 1.
63072 **
63073 ** If the b-tree structure is empty, the cursor state is set to
63074 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
63075 ** cell located on the root (or virtual root) page and the cursor state
63076 ** is set to CURSOR_VALID.
63077 **
63078 ** If this function returns successfully, it may be assumed that the
63079 ** page-header flags indicate that the [virtual] root-page is the expected
63080 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
63081 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
63082 ** indicating a table b-tree, or if the caller did specify a KeyInfo
63083 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
63084 ** b-tree).
63085 */
63086 static int moveToRoot(BtCursor *pCur){
63087  MemPage *pRoot;
63088  int rc = SQLITE_OK;
63089 
63090  assert( cursorOwnsBtShared(pCur) );
63091  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
63092  assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
63093  assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
63094  if( pCur->eState>=CURSOR_REQUIRESEEK ){
63095  if( pCur->eState==CURSOR_FAULT ){
63096  assert( pCur->skipNext!=SQLITE_OK );
63097  return pCur->skipNext;
63098  }
63100  }
63101 
63102  if( pCur->iPage>=0 ){
63103  while( pCur->iPage ){
63104  assert( pCur->apPage[pCur->iPage]!=0 );
63105  releasePageNotNull(pCur->apPage[pCur->iPage--]);
63106  }
63107  }else if( pCur->pgnoRoot==0 ){
63108  pCur->eState = CURSOR_INVALID;
63109  return SQLITE_OK;
63110  }else{
63111  assert( pCur->iPage==(-1) );
63112  rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
63113  0, pCur->curPagerFlags);
63114  if( rc!=SQLITE_OK ){
63115  pCur->eState = CURSOR_INVALID;
63116  return rc;
63117  }
63118  pCur->iPage = 0;
63119  pCur->curIntKey = pCur->apPage[0]->intKey;
63120  }
63121  pRoot = pCur->apPage[0];
63122  assert( pRoot->pgno==pCur->pgnoRoot );
63123 
63124  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
63125  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
63126  ** NULL, the caller expects a table b-tree. If this is not the case,
63127  ** return an SQLITE_CORRUPT error.
63128  **
63129  ** Earlier versions of SQLite assumed that this test could not fail
63130  ** if the root page was already loaded when this function was called (i.e.
63131  ** if pCur->iPage>=0). But this is not so if the database is corrupted
63132  ** in such a way that page pRoot is linked into a second b-tree table
63133  ** (or the freelist). */
63134  assert( pRoot->intKey==1 || pRoot->intKey==0 );
63135  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
63136  return SQLITE_CORRUPT_BKPT;
63137  }
63138 
63139  pCur->aiIdx[0] = 0;
63140  pCur->info.nSize = 0;
63142 
63143  if( pRoot->nCell>0 ){
63144  pCur->eState = CURSOR_VALID;
63145  }else if( !pRoot->leaf ){
63146  Pgno subpage;
63147  if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
63148  subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
63149  pCur->eState = CURSOR_VALID;
63150  rc = moveToChild(pCur, subpage);
63151  }else{
63152  pCur->eState = CURSOR_INVALID;
63153  }
63154  return rc;
63155 }
63156 
63157 /*
63158 ** Move the cursor down to the left-most leaf entry beneath the
63159 ** entry to which it is currently pointing.
63160 **
63161 ** The left-most leaf is the one with the smallest key - the first
63162 ** in ascending order.
63163 */
63164 static int moveToLeftmost(BtCursor *pCur){
63165  Pgno pgno;
63166  int rc = SQLITE_OK;
63167  MemPage *pPage;
63168 
63169  assert( cursorOwnsBtShared(pCur) );
63170  assert( pCur->eState==CURSOR_VALID );
63171  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63172  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
63173  pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
63174  rc = moveToChild(pCur, pgno);
63175  }
63176  return rc;
63177 }
63178 
63179 /*
63180 ** Move the cursor down to the right-most leaf entry beneath the
63181 ** page to which it is currently pointing. Notice the difference
63182 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
63183 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
63184 ** finds the right-most entry beneath the *page*.
63185 **
63186 ** The right-most entry is the one with the largest key - the last
63187 ** key in ascending order.
63188 */
63189 static int moveToRightmost(BtCursor *pCur){
63190  Pgno pgno;
63191  int rc = SQLITE_OK;
63192  MemPage *pPage = 0;
63193 
63194  assert( cursorOwnsBtShared(pCur) );
63195  assert( pCur->eState==CURSOR_VALID );
63196  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63197  pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63198  pCur->aiIdx[pCur->iPage] = pPage->nCell;
63199  rc = moveToChild(pCur, pgno);
63200  if( rc ) return rc;
63201  }
63202  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
63203  assert( pCur->info.nSize==0 );
63204  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
63205  return SQLITE_OK;
63206 }
63207 
63208 /* Move the cursor to the first entry in the table. Return SQLITE_OK
63209 ** on success. Set *pRes to 0 if the cursor actually points to something
63210 ** or set *pRes to 1 if the table is empty.
63211 */
63213  int rc;
63214 
63215  assert( cursorOwnsBtShared(pCur) );
63216  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63217  rc = moveToRoot(pCur);
63218  if( rc==SQLITE_OK ){
63219  if( pCur->eState==CURSOR_INVALID ){
63220  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63221  *pRes = 1;
63222  }else{
63223  assert( pCur->apPage[pCur->iPage]->nCell>0 );
63224  *pRes = 0;
63225  rc = moveToLeftmost(pCur);
63226  }
63227  }
63228  return rc;
63229 }
63230 
63231 /* Move the cursor to the last entry in the table. Return SQLITE_OK
63232 ** on success. Set *pRes to 0 if the cursor actually points to something
63233 ** or set *pRes to 1 if the table is empty.
63234 */
63236  int rc;
63237 
63238  assert( cursorOwnsBtShared(pCur) );
63239  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63240 
63241  /* If the cursor already points to the last entry, this is a no-op. */
63242  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
63243 #ifdef SQLITE_DEBUG
63244  /* This block serves to assert() that the cursor really does point
63245  ** to the last entry in the b-tree. */
63246  int ii;
63247  for(ii=0; ii<pCur->iPage; ii++){
63248  assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
63249  }
63250  assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
63251  assert( pCur->apPage[pCur->iPage]->leaf );
63252 #endif
63253  return SQLITE_OK;
63254  }
63255 
63256  rc = moveToRoot(pCur);
63257  if( rc==SQLITE_OK ){
63258  if( CURSOR_INVALID==pCur->eState ){
63259  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63260  *pRes = 1;
63261  }else{
63262  assert( pCur->eState==CURSOR_VALID );
63263  *pRes = 0;
63264  rc = moveToRightmost(pCur);
63265  if( rc==SQLITE_OK ){
63266  pCur->curFlags |= BTCF_AtLast;
63267  }else{
63268  pCur->curFlags &= ~BTCF_AtLast;
63269  }
63270 
63271  }
63272  }
63273  return rc;
63274 }
63275 
63276 /* Move the cursor so that it points to an entry near the key
63277 ** specified by pIdxKey or intKey. Return a success code.
63278 **
63279 ** For INTKEY tables, the intKey parameter is used. pIdxKey
63280 ** must be NULL. For index tables, pIdxKey is used and intKey
63281 ** is ignored.
63282 **
63283 ** If an exact match is not found, then the cursor is always
63284 ** left pointing at a leaf page which would hold the entry if it
63285 ** were present. The cursor might point to an entry that comes
63286 ** before or after the key.
63287 **
63288 ** An integer is written into *pRes which is the result of
63289 ** comparing the key with the entry to which the cursor is
63290 ** pointing. The meaning of the integer written into
63291 ** *pRes is as follows:
63292 **
63293 ** *pRes<0 The cursor is left pointing at an entry that
63294 ** is smaller than intKey/pIdxKey or if the table is empty
63295 ** and the cursor is therefore left point to nothing.
63296 **
63297 ** *pRes==0 The cursor is left pointing at an entry that
63298 ** exactly matches intKey/pIdxKey.
63299 **
63300 ** *pRes>0 The cursor is left pointing at an entry that
63301 ** is larger than intKey/pIdxKey.
63302 **
63303 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
63304 ** exists an entry in the table that exactly matches pIdxKey.
63305 */
63307  BtCursor *pCur, /* The cursor to be moved */
63308  UnpackedRecord *pIdxKey, /* Unpacked index key */
63309  i64 intKey, /* The table key */
63310  int biasRight, /* If true, bias the search to the high end */
63311  int *pRes /* Write search results here */
63312 ){
63313  int rc;
63314  RecordCompare xRecordCompare;
63315 
63316  assert( cursorOwnsBtShared(pCur) );
63317  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63318  assert( pRes );
63319  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
63320  assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
63321 
63322  /* If the cursor is already positioned at the point we are trying
63323  ** to move to, then just return without doing any work */
63324  if( pIdxKey==0
63325  && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
63326  ){
63327  if( pCur->info.nKey==intKey ){
63328  *pRes = 0;
63329  return SQLITE_OK;
63330  }
63331  if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
63332  *pRes = -1;
63333  return SQLITE_OK;
63334  }
63335  }
63336 
63337  if( pIdxKey ){
63338  xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
63339  pIdxKey->errCode = 0;
63340  assert( pIdxKey->default_rc==1
63341  || pIdxKey->default_rc==0
63342  || pIdxKey->default_rc==-1
63343  );
63344  }else{
63345  xRecordCompare = 0; /* All keys are integers */
63346  }
63347 
63348  rc = moveToRoot(pCur);
63349  if( rc ){
63350  return rc;
63351  }
63352  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
63353  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
63354  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
63355  if( pCur->eState==CURSOR_INVALID ){
63356  *pRes = -1;
63357  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63358  return SQLITE_OK;
63359  }
63360  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
63361  assert( pCur->curIntKey || pIdxKey );
63362  for(;;){
63363  int lwr, upr, idx, c;
63364  Pgno chldPg;
63365  MemPage *pPage = pCur->apPage[pCur->iPage];
63366  u8 *pCell; /* Pointer to current cell in pPage */
63367 
63368  /* pPage->nCell must be greater than zero. If this is the root-page
63369  ** the cursor would have been INVALID above and this for(;;) loop
63370  ** not run. If this is not the root-page, then the moveToChild() routine
63371  ** would have already detected db corruption. Similarly, pPage must
63372  ** be the right kind (index or table) of b-tree page. Otherwise
63373  ** a moveToChild() or moveToRoot() call would have detected corruption. */
63374  assert( pPage->nCell>0 );
63375  assert( pPage->intKey==(pIdxKey==0) );
63376  lwr = 0;
63377  upr = pPage->nCell-1;
63378  assert( biasRight==0 || biasRight==1 );
63379  idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
63380  pCur->aiIdx[pCur->iPage] = (u16)idx;
63381  if( xRecordCompare==0 ){
63382  for(;;){
63383  i64 nCellKey;
63384  pCell = findCellPastPtr(pPage, idx);
63385  if( pPage->intKeyLeaf ){
63386  while( 0x80 <= *(pCell++) ){
63387  if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
63388  }
63389  }
63390  getVarint(pCell, (u64*)&nCellKey);
63391  if( nCellKey<intKey ){
63392  lwr = idx+1;
63393  if( lwr>upr ){ c = -1; break; }
63394  }else if( nCellKey>intKey ){
63395  upr = idx-1;
63396  if( lwr>upr ){ c = +1; break; }
63397  }else{
63398  assert( nCellKey==intKey );
63399  pCur->curFlags |= BTCF_ValidNKey;
63400  pCur->info.nKey = nCellKey;
63401  pCur->aiIdx[pCur->iPage] = (u16)idx;
63402  if( !pPage->leaf ){
63403  lwr = idx;
63404  goto moveto_next_layer;
63405  }else{
63406  *pRes = 0;
63407  rc = SQLITE_OK;
63408  goto moveto_finish;
63409  }
63410  }
63411  assert( lwr+upr>=0 );
63412  idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
63413  }
63414  }else{
63415  for(;;){
63416  int nCell; /* Size of the pCell cell in bytes */
63417  pCell = findCellPastPtr(pPage, idx);
63418 
63419  /* The maximum supported page-size is 65536 bytes. This means that
63420  ** the maximum number of record bytes stored on an index B-Tree
63421  ** page is less than 16384 bytes and may be stored as a 2-byte
63422  ** varint. This information is used to attempt to avoid parsing
63423  ** the entire cell by checking for the cases where the record is
63424  ** stored entirely within the b-tree page by inspecting the first
63425  ** 2 bytes of the cell.
63426  */
63427  nCell = pCell[0];
63428  if( nCell<=pPage->max1bytePayload ){
63429  /* This branch runs if the record-size field of the cell is a
63430  ** single byte varint and the record fits entirely on the main
63431  ** b-tree page. */
63432  testcase( pCell+nCell+1==pPage->aDataEnd );
63433  c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
63434  }else if( !(pCell[1] & 0x80)
63435  && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
63436  ){
63437  /* The record-size field is a 2 byte varint and the record
63438  ** fits entirely on the main b-tree page. */
63439  testcase( pCell+nCell+2==pPage->aDataEnd );
63440  c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
63441  }else{
63442  /* The record flows over onto one or more overflow pages. In
63443  ** this case the whole cell needs to be parsed, a buffer allocated
63444  ** and accessPayload() used to retrieve the record into the
63445  ** buffer before VdbeRecordCompare() can be called.
63446  **
63447  ** If the record is corrupt, the xRecordCompare routine may read
63448  ** up to two varints past the end of the buffer. An extra 18
63449  ** bytes of padding is allocated at the end of the buffer in
63450  ** case this happens. */
63451  void *pCellKey;
63452  u8 * const pCellBody = pCell - pPage->childPtrSize;
63453  pPage->xParseCell(pPage, pCellBody, &pCur->info);
63454  nCell = (int)pCur->info.nKey;
63455  testcase( nCell<0 ); /* True if key size is 2^32 or more */
63456  testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
63457  testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
63458  testcase( nCell==2 ); /* Minimum legal index key size */
63459  if( nCell<2 ){
63460  rc = SQLITE_CORRUPT_BKPT;
63461  goto moveto_finish;
63462  }
63463  pCellKey = sqlite3Malloc( nCell+18 );
63464  if( pCellKey==0 ){
63465  rc = SQLITE_NOMEM_BKPT;
63466  goto moveto_finish;
63467  }
63468  pCur->aiIdx[pCur->iPage] = (u16)idx;
63469  rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
63470  if( rc ){
63471  sqlite3_free(pCellKey);
63472  goto moveto_finish;
63473  }
63474  c = xRecordCompare(nCell, pCellKey, pIdxKey);
63475  sqlite3_free(pCellKey);
63476  }
63477  assert(
63478  (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
63479  && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
63480  );
63481  if( c<0 ){
63482  lwr = idx+1;
63483  }else if( c>0 ){
63484  upr = idx-1;
63485  }else{
63486  assert( c==0 );
63487  *pRes = 0;
63488  rc = SQLITE_OK;
63489  pCur->aiIdx[pCur->iPage] = (u16)idx;
63490  if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
63491  goto moveto_finish;
63492  }
63493  if( lwr>upr ) break;
63494  assert( lwr+upr>=0 );
63495  idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
63496  }
63497  }
63498  assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
63499  assert( pPage->isInit );
63500  if( pPage->leaf ){
63501  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
63502  pCur->aiIdx[pCur->iPage] = (u16)idx;
63503  *pRes = c;
63504  rc = SQLITE_OK;
63505  goto moveto_finish;
63506  }
63507 moveto_next_layer:
63508  if( lwr>=pPage->nCell ){
63509  chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63510  }else{
63511  chldPg = get4byte(findCell(pPage, lwr));
63512  }
63513  pCur->aiIdx[pCur->iPage] = (u16)lwr;
63514  rc = moveToChild(pCur, chldPg);
63515  if( rc ) break;
63516  }
63517 moveto_finish:
63518  pCur->info.nSize = 0;
63520  return rc;
63521 }
63522 
63523 
63524 /*
63525 ** Return TRUE if the cursor is not pointing at an entry of the table.
63526 **
63527 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
63528 ** past the last entry in the table or sqlite3BtreePrev() moves past
63529 ** the first entry. TRUE is also returned if the table is empty.
63530 */
63532  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
63533  ** have been deleted? This API will need to change to return an error code
63534  ** as well as the boolean result value.
63535  */
63536  return (CURSOR_VALID!=pCur->eState);
63537 }
63538 
63539 /*
63540 ** Advance the cursor to the next entry in the database. If
63541 ** successful then set *pRes=0. If the cursor
63542 ** was already pointing to the last entry in the database before
63543 ** this routine was called, then set *pRes=1.
63544 **
63545 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
63546 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
63547 ** to the next cell on the current page. The (slower) btreeNext() helper
63548 ** routine is called when it is necessary to move to a different page or
63549 ** to restore the cursor.
63550 **
63551 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
63552 ** will be 1 if the cursor being stepped corresponds to an SQL index and
63553 ** if this routine could have been skipped if that SQL index had been
63554 ** a unique index. Otherwise the caller will have set *pRes to zero.
63555 ** Zero is the common case. The btree implementation is free to use the
63556 ** initial *pRes value as a hint to improve performance, but the current
63557 ** SQLite btree implementation does not. (Note that the comdb2 btree
63558 ** implementation does use this hint, however.)
63559 */
63560 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
63561  int rc;
63562  int idx;
63563  MemPage *pPage;
63564 
63565  assert( cursorOwnsBtShared(pCur) );
63566  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63567  assert( *pRes==0 );
63568  if( pCur->eState!=CURSOR_VALID ){
63569  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
63570  rc = restoreCursorPosition(pCur);
63571  if( rc!=SQLITE_OK ){
63572  return rc;
63573  }
63574  if( CURSOR_INVALID==pCur->eState ){
63575  *pRes = 1;
63576  return SQLITE_OK;
63577  }
63578  if( pCur->skipNext ){
63579  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63580  pCur->eState = CURSOR_VALID;
63581  if( pCur->skipNext>0 ){
63582  pCur->skipNext = 0;
63583  return SQLITE_OK;
63584  }
63585  pCur->skipNext = 0;
63586  }
63587  }
63588 
63589  pPage = pCur->apPage[pCur->iPage];
63590  idx = ++pCur->aiIdx[pCur->iPage];
63591  assert( pPage->isInit );
63592 
63593  /* If the database file is corrupt, it is possible for the value of idx
63594  ** to be invalid here. This can only occur if a second cursor modifies
63595  ** the page while cursor pCur is holding a reference to it. Which can
63596  ** only happen if the database is corrupt in such a way as to link the
63597  ** page into more than one b-tree structure. */
63598  testcase( idx>pPage->nCell );
63599 
63600  if( idx>=pPage->nCell ){
63601  if( !pPage->leaf ){
63602  rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63603  if( rc ) return rc;
63604  return moveToLeftmost(pCur);
63605  }
63606  do{
63607  if( pCur->iPage==0 ){
63608  *pRes = 1;
63609  pCur->eState = CURSOR_INVALID;
63610  return SQLITE_OK;
63611  }
63612  moveToParent(pCur);
63613  pPage = pCur->apPage[pCur->iPage];
63614  }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
63615  if( pPage->intKey ){
63616  return sqlite3BtreeNext(pCur, pRes);
63617  }else{
63618  return SQLITE_OK;
63619  }
63620  }
63621  if( pPage->leaf ){
63622  return SQLITE_OK;
63623  }else{
63624  return moveToLeftmost(pCur);
63625  }
63626 }
63628  MemPage *pPage;
63629  assert( cursorOwnsBtShared(pCur) );
63630  assert( pRes!=0 );
63631  assert( *pRes==0 || *pRes==1 );
63632  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63633  pCur->info.nSize = 0;
63635  *pRes = 0;
63636  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
63637  pPage = pCur->apPage[pCur->iPage];
63638  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
63639  pCur->aiIdx[pCur->iPage]--;
63640  return btreeNext(pCur, pRes);
63641  }
63642  if( pPage->leaf ){
63643  return SQLITE_OK;
63644  }else{
63645  return moveToLeftmost(pCur);
63646  }
63647 }
63648 
63649 /*
63650 ** Step the cursor to the back to the previous entry in the database. If
63651 ** successful then set *pRes=0. If the cursor
63652 ** was already pointing to the first entry in the database before
63653 ** this routine was called, then set *pRes=1.
63654 **
63655 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
63656 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
63657 ** to the previous cell on the current page. The (slower) btreePrevious()
63658 ** helper routine is called when it is necessary to move to a different page
63659 ** or to restore the cursor.
63660 **
63661 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
63662 ** will be 1 if the cursor being stepped corresponds to an SQL index and
63663 ** if this routine could have been skipped if that SQL index had been
63664 ** a unique index. Otherwise the caller will have set *pRes to zero.
63665 ** Zero is the common case. The btree implementation is free to use the
63666 ** initial *pRes value as a hint to improve performance, but the current
63667 ** SQLite btree implementation does not. (Note that the comdb2 btree
63668 ** implementation does use this hint, however.)
63669 */
63670 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
63671  int rc;
63672  MemPage *pPage;
63673 
63674  assert( cursorOwnsBtShared(pCur) );
63675  assert( pRes!=0 );
63676  assert( *pRes==0 );
63677  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63678  assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
63679  assert( pCur->info.nSize==0 );
63680  if( pCur->eState!=CURSOR_VALID ){
63681  rc = restoreCursorPosition(pCur);
63682  if( rc!=SQLITE_OK ){
63683  return rc;
63684  }
63685  if( CURSOR_INVALID==pCur->eState ){
63686  *pRes = 1;
63687  return SQLITE_OK;
63688  }
63689  if( pCur->skipNext ){
63690  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63691  pCur->eState = CURSOR_VALID;
63692  if( pCur->skipNext<0 ){
63693  pCur->skipNext = 0;
63694  return SQLITE_OK;
63695  }
63696  pCur->skipNext = 0;
63697  }
63698  }
63699 
63700  pPage = pCur->apPage[pCur->iPage];
63701  assert( pPage->isInit );
63702  if( !pPage->leaf ){
63703  int idx = pCur->aiIdx[pCur->iPage];
63704  rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
63705  if( rc ) return rc;
63706  rc = moveToRightmost(pCur);
63707  }else{
63708  while( pCur->aiIdx[pCur->iPage]==0 ){
63709  if( pCur->iPage==0 ){
63710  pCur->eState = CURSOR_INVALID;
63711  *pRes = 1;
63712  return SQLITE_OK;
63713  }
63714  moveToParent(pCur);
63715  }
63716  assert( pCur->info.nSize==0 );
63717  assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
63718 
63719  pCur->aiIdx[pCur->iPage]--;
63720  pPage = pCur->apPage[pCur->iPage];
63721  if( pPage->intKey && !pPage->leaf ){
63722  rc = sqlite3BtreePrevious(pCur, pRes);
63723  }else{
63724  rc = SQLITE_OK;
63725  }
63726  }
63727  return rc;
63728 }
63730  assert( cursorOwnsBtShared(pCur) );
63731  assert( pRes!=0 );
63732  assert( *pRes==0 || *pRes==1 );
63733  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63734  *pRes = 0;
63736  pCur->info.nSize = 0;
63737  if( pCur->eState!=CURSOR_VALID
63738  || pCur->aiIdx[pCur->iPage]==0
63739  || pCur->apPage[pCur->iPage]->leaf==0
63740  ){
63741  return btreePrevious(pCur, pRes);
63742  }
63743  pCur->aiIdx[pCur->iPage]--;
63744  return SQLITE_OK;
63745 }
63746 
63747 /*
63748 ** Allocate a new page from the database file.
63749 **
63750 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
63751 ** has already been called on the new page.) The new page has also
63752 ** been referenced and the calling routine is responsible for calling
63753 ** sqlite3PagerUnref() on the new page when it is done.
63754 **
63755 ** SQLITE_OK is returned on success. Any other return value indicates
63756 ** an error. *ppPage is set to NULL in the event of an error.
63757 **
63758 ** If the "nearby" parameter is not 0, then an effort is made to
63759 ** locate a page close to the page number "nearby". This can be used in an
63760 ** attempt to keep related pages close to each other in the database file,
63761 ** which in turn can make database access faster.
63762 **
63763 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
63764 ** anywhere on the free-list, then it is guaranteed to be returned. If
63765 ** eMode is BTALLOC_LT then the page returned will be less than or equal
63766 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
63767 ** are no restrictions on which page is returned.
63768 */
63770  BtShared *pBt, /* The btree */
63771  MemPage **ppPage, /* Store pointer to the allocated page here */
63772  Pgno *pPgno, /* Store the page number here */
63773  Pgno nearby, /* Search for a page near this one */
63774  u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
63775 ){
63776  MemPage *pPage1;
63777  int rc;
63778  u32 n; /* Number of pages on the freelist */
63779  u32 k; /* Number of leaves on the trunk of the freelist */
63780  MemPage *pTrunk = 0;
63781  MemPage *pPrevTrunk = 0;
63782  Pgno mxPage; /* Total size of the database file */
63783 
63784  assert( sqlite3_mutex_held(pBt->mutex) );
63785  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
63786  pPage1 = pBt->pPage1;
63787  mxPage = btreePagecount(pBt);
63788  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
63789  ** stores stores the total number of pages on the freelist. */
63790  n = get4byte(&pPage1->aData[36]);
63791  testcase( n==mxPage-1 );
63792  if( n>=mxPage ){
63793  return SQLITE_CORRUPT_BKPT;
63794  }
63795  if( n>0 ){
63796  /* There are pages on the freelist. Reuse one of those pages. */
63797  Pgno iTrunk;
63798  u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
63799  u32 nSearch = 0; /* Count of the number of search attempts */
63800 
63801  /* If eMode==BTALLOC_EXACT and a query of the pointer-map
63802  ** shows that the page 'nearby' is somewhere on the free-list, then
63803  ** the entire-list will be searched for that page.
63804  */
63805 #ifndef SQLITE_OMIT_AUTOVACUUM
63806  if( eMode==BTALLOC_EXACT ){
63807  if( nearby<=mxPage ){
63808  u8 eType;
63809  assert( nearby>0 );
63810  assert( pBt->autoVacuum );
63811  rc = ptrmapGet(pBt, nearby, &eType, 0);
63812  if( rc ) return rc;
63813  if( eType==PTRMAP_FREEPAGE ){
63814  searchList = 1;
63815  }
63816  }
63817  }else if( eMode==BTALLOC_LE ){
63818  searchList = 1;
63819  }
63820 #endif
63821 
63822  /* Decrement the free-list count by 1. Set iTrunk to the index of the
63823  ** first free-list trunk page. iPrevTrunk is initially 1.
63824  */
63825  rc = sqlite3PagerWrite(pPage1->pDbPage);
63826  if( rc ) return rc;
63827  put4byte(&pPage1->aData[36], n-1);
63828 
63829  /* The code within this loop is run only once if the 'searchList' variable
63830  ** is not true. Otherwise, it runs once for each trunk-page on the
63831  ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
63832  ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
63833  */
63834  do {
63835  pPrevTrunk = pTrunk;
63836  if( pPrevTrunk ){
63837  /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
63838  ** is the page number of the next freelist trunk page in the list or
63839  ** zero if this is the last freelist trunk page. */
63840  iTrunk = get4byte(&pPrevTrunk->aData[0]);
63841  }else{
63842  /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
63843  ** stores the page number of the first page of the freelist, or zero if
63844  ** the freelist is empty. */
63845  iTrunk = get4byte(&pPage1->aData[32]);
63846  }
63847  testcase( iTrunk==mxPage );
63848  if( iTrunk>mxPage || nSearch++ > n ){
63849  rc = SQLITE_CORRUPT_BKPT;
63850  }else{
63851  rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
63852  }
63853  if( rc ){
63854  pTrunk = 0;
63855  goto end_allocate_page;
63856  }
63857  assert( pTrunk!=0 );
63858  assert( pTrunk->aData!=0 );
63859  /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
63860  ** is the number of leaf page pointers to follow. */
63861  k = get4byte(&pTrunk->aData[4]);
63862  if( k==0 && !searchList ){
63863  /* The trunk has no leaves and the list is not being searched.
63864  ** So extract the trunk page itself and use it as the newly
63865  ** allocated page */
63866  assert( pPrevTrunk==0 );
63867  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63868  if( rc ){
63869  goto end_allocate_page;
63870  }
63871  *pPgno = iTrunk;
63872  memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63873  *ppPage = pTrunk;
63874  pTrunk = 0;
63875  TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63876  }else if( k>(u32)(pBt->usableSize/4 - 2) ){
63877  /* Value of k is out of range. Database corruption */
63878  rc = SQLITE_CORRUPT_BKPT;
63879  goto end_allocate_page;
63880 #ifndef SQLITE_OMIT_AUTOVACUUM
63881  }else if( searchList
63882  && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
63883  ){
63884  /* The list is being searched and this trunk page is the page
63885  ** to allocate, regardless of whether it has leaves.
63886  */
63887  *pPgno = iTrunk;
63888  *ppPage = pTrunk;
63889  searchList = 0;
63890  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63891  if( rc ){
63892  goto end_allocate_page;
63893  }
63894  if( k==0 ){
63895  if( !pPrevTrunk ){
63896  memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63897  }else{
63898  rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63899  if( rc!=SQLITE_OK ){
63900  goto end_allocate_page;
63901  }
63902  memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
63903  }
63904  }else{
63905  /* The trunk page is required by the caller but it contains
63906  ** pointers to free-list leaves. The first leaf becomes a trunk
63907  ** page in this case.
63908  */
63909  MemPage *pNewTrunk;
63910  Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
63911  if( iNewTrunk>mxPage ){
63912  rc = SQLITE_CORRUPT_BKPT;
63913  goto end_allocate_page;
63914  }
63915  testcase( iNewTrunk==mxPage );
63916  rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
63917  if( rc!=SQLITE_OK ){
63918  goto end_allocate_page;
63919  }
63920  rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
63921  if( rc!=SQLITE_OK ){
63922  releasePage(pNewTrunk);
63923  goto end_allocate_page;
63924  }
63925  memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
63926  put4byte(&pNewTrunk->aData[4], k-1);
63927  memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
63928  releasePage(pNewTrunk);
63929  if( !pPrevTrunk ){
63930  assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
63931  put4byte(&pPage1->aData[32], iNewTrunk);
63932  }else{
63933  rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63934  if( rc ){
63935  goto end_allocate_page;
63936  }
63937  put4byte(&pPrevTrunk->aData[0], iNewTrunk);
63938  }
63939  }
63940  pTrunk = 0;
63941  TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63942 #endif
63943  }else if( k>0 ){
63944  /* Extract a leaf from the trunk */
63945  u32 closest;
63946  Pgno iPage;
63947  unsigned char *aData = pTrunk->aData;
63948  if( nearby>0 ){
63949  u32 i;
63950  closest = 0;
63951  if( eMode==BTALLOC_LE ){
63952  for(i=0; i<k; i++){
63953  iPage = get4byte(&aData[8+i*4]);
63954  if( iPage<=nearby ){
63955  closest = i;
63956  break;
63957  }
63958  }
63959  }else{
63960  int dist;
63961  dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
63962  for(i=1; i<k; i++){
63963  int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
63964  if( d2<dist ){
63965  closest = i;
63966  dist = d2;
63967  }
63968  }
63969  }
63970  }else{
63971  closest = 0;
63972  }
63973 
63974  iPage = get4byte(&aData[8+closest*4]);
63975  testcase( iPage==mxPage );
63976  if( iPage>mxPage ){
63977  rc = SQLITE_CORRUPT_BKPT;
63978  goto end_allocate_page;
63979  }
63980  testcase( iPage==mxPage );
63981  if( !searchList
63982  || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
63983  ){
63984  int noContent;
63985  *pPgno = iPage;
63986  TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
63987  ": %d more free pages\n",
63988  *pPgno, closest+1, k, pTrunk->pgno, n-1));
63989  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63990  if( rc ) goto end_allocate_page;
63991  if( closest<k-1 ){
63992  memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
63993  }
63994  put4byte(&aData[4], k-1);
63995  noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
63996  rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
63997  if( rc==SQLITE_OK ){
63998  rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63999  if( rc!=SQLITE_OK ){
64000  releasePage(*ppPage);
64001  *ppPage = 0;
64002  }
64003  }
64004  searchList = 0;
64005  }
64006  }
64007  releasePage(pPrevTrunk);
64008  pPrevTrunk = 0;
64009  }while( searchList );
64010  }else{
64011  /* There are no pages on the freelist, so append a new page to the
64012  ** database image.
64013  **
64014  ** Normally, new pages allocated by this block can be requested from the
64015  ** pager layer with the 'no-content' flag set. This prevents the pager
64016  ** from trying to read the pages content from disk. However, if the
64017  ** current transaction has already run one or more incremental-vacuum
64018  ** steps, then the page we are about to allocate may contain content
64019  ** that is required in the event of a rollback. In this case, do
64020  ** not set the no-content flag. This causes the pager to load and journal
64021  ** the current page content before overwriting it.
64022  **
64023  ** Note that the pager will not actually attempt to load or journal
64024  ** content for any page that really does lie past the end of the database
64025  ** file on disk. So the effects of disabling the no-content optimization
64026  ** here are confined to those pages that lie between the end of the
64027  ** database image and the end of the database file.
64028  */
64029  int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
64030 
64031  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
64032  if( rc ) return rc;
64033  pBt->nPage++;
64034  if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
64035 
64036 #ifndef SQLITE_OMIT_AUTOVACUUM
64037  if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
64038  /* If *pPgno refers to a pointer-map page, allocate two new pages
64039  ** at the end of the file instead of one. The first allocated page
64040  ** becomes a new pointer-map page, the second is used by the caller.
64041  */
64042  MemPage *pPg = 0;
64043  TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
64044  assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
64045  rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
64046  if( rc==SQLITE_OK ){
64047  rc = sqlite3PagerWrite(pPg->pDbPage);
64048  releasePage(pPg);
64049  }
64050  if( rc ) return rc;
64051  pBt->nPage++;
64052  if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
64053  }
64054 #endif
64055  put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
64056  *pPgno = pBt->nPage;
64057 
64058  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
64059  rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
64060  if( rc ) return rc;
64061  rc = sqlite3PagerWrite((*ppPage)->pDbPage);
64062  if( rc!=SQLITE_OK ){
64063  releasePage(*ppPage);
64064  *ppPage = 0;
64065  }
64066  TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
64067  }
64068 
64069  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
64070 
64071 end_allocate_page:
64072  releasePage(pTrunk);
64073  releasePage(pPrevTrunk);
64074  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
64075  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
64076  return rc;
64077 }
64078 
64079 /*
64080 ** This function is used to add page iPage to the database file free-list.
64081 ** It is assumed that the page is not already a part of the free-list.
64082 **
64083 ** The value passed as the second argument to this function is optional.
64084 ** If the caller happens to have a pointer to the MemPage object
64085 ** corresponding to page iPage handy, it may pass it as the second value.
64086 ** Otherwise, it may pass NULL.
64087 **
64088 ** If a pointer to a MemPage object is passed as the second argument,
64089 ** its reference count is not altered by this function.
64090 */
64091 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
64092  MemPage *pTrunk = 0; /* Free-list trunk page */
64093  Pgno iTrunk = 0; /* Page number of free-list trunk page */
64094  MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
64095  MemPage *pPage; /* Page being freed. May be NULL. */
64096  int rc; /* Return Code */
64097  int nFree; /* Initial number of pages on free-list */
64098 
64099  assert( sqlite3_mutex_held(pBt->mutex) );
64100  assert( CORRUPT_DB || iPage>1 );
64101  assert( !pMemPage || pMemPage->pgno==iPage );
64102 
64103  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
64104  if( pMemPage ){
64105  pPage = pMemPage;
64106  sqlite3PagerRef(pPage->pDbPage);
64107  }else{
64108  pPage = btreePageLookup(pBt, iPage);
64109  }
64110 
64111  /* Increment the free page count on pPage1 */
64112  rc = sqlite3PagerWrite(pPage1->pDbPage);
64113  if( rc ) goto freepage_out;
64114  nFree = get4byte(&pPage1->aData[36]);
64115  put4byte(&pPage1->aData[36], nFree+1);
64116 
64117  if( pBt->btsFlags & BTS_SECURE_DELETE ){
64118  /* If the secure_delete option is enabled, then
64119  ** always fully overwrite deleted information with zeros.
64120  */
64121  if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
64122  || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
64123  ){
64124  goto freepage_out;
64125  }
64126  memset(pPage->aData, 0, pPage->pBt->pageSize);
64127  }
64128 
64129  /* If the database supports auto-vacuum, write an entry in the pointer-map
64130  ** to indicate that the page is free.
64131  */
64132  if( ISAUTOVACUUM ){
64133  ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
64134  if( rc ) goto freepage_out;
64135  }
64136 
64137  /* Now manipulate the actual database free-list structure. There are two
64138  ** possibilities. If the free-list is currently empty, or if the first
64139  ** trunk page in the free-list is full, then this page will become a
64140  ** new free-list trunk page. Otherwise, it will become a leaf of the
64141  ** first trunk page in the current free-list. This block tests if it
64142  ** is possible to add the page as a new free-list leaf.
64143  */
64144  if( nFree!=0 ){
64145  u32 nLeaf; /* Initial number of leaf cells on trunk page */
64146 
64147  iTrunk = get4byte(&pPage1->aData[32]);
64148  rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
64149  if( rc!=SQLITE_OK ){
64150  goto freepage_out;
64151  }
64152 
64153  nLeaf = get4byte(&pTrunk->aData[4]);
64154  assert( pBt->usableSize>32 );
64155  if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
64156  rc = SQLITE_CORRUPT_BKPT;
64157  goto freepage_out;
64158  }
64159  if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
64160  /* In this case there is room on the trunk page to insert the page
64161  ** being freed as a new leaf.
64162  **
64163  ** Note that the trunk page is not really full until it contains
64164  ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
64165  ** coded. But due to a coding error in versions of SQLite prior to
64166  ** 3.6.0, databases with freelist trunk pages holding more than
64167  ** usableSize/4 - 8 entries will be reported as corrupt. In order
64168  ** to maintain backwards compatibility with older versions of SQLite,
64169  ** we will continue to restrict the number of entries to usableSize/4 - 8
64170  ** for now. At some point in the future (once everyone has upgraded
64171  ** to 3.6.0 or later) we should consider fixing the conditional above
64172  ** to read "usableSize/4-2" instead of "usableSize/4-8".
64173  **
64174  ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
64175  ** avoid using the last six entries in the freelist trunk page array in
64176  ** order that database files created by newer versions of SQLite can be
64177  ** read by older versions of SQLite.
64178  */
64179  rc = sqlite3PagerWrite(pTrunk->pDbPage);
64180  if( rc==SQLITE_OK ){
64181  put4byte(&pTrunk->aData[4], nLeaf+1);
64182  put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
64183  if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
64185  }
64186  rc = btreeSetHasContent(pBt, iPage);
64187  }
64188  TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
64189  goto freepage_out;
64190  }
64191  }
64192 
64193  /* If control flows to this point, then it was not possible to add the
64194  ** the page being freed as a leaf page of the first trunk in the free-list.
64195  ** Possibly because the free-list is empty, or possibly because the
64196  ** first trunk in the free-list is full. Either way, the page being freed
64197  ** will become the new first trunk page in the free-list.
64198  */
64199  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
64200  goto freepage_out;
64201  }
64202  rc = sqlite3PagerWrite(pPage->pDbPage);
64203  if( rc!=SQLITE_OK ){
64204  goto freepage_out;
64205  }
64206  put4byte(pPage->aData, iTrunk);
64207  put4byte(&pPage->aData[4], 0);
64208  put4byte(&pPage1->aData[32], iPage);
64209  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
64210 
64211 freepage_out:
64212  if( pPage ){
64213  pPage->isInit = 0;
64214  }
64215  releasePage(pPage);
64216  releasePage(pTrunk);
64217  return rc;
64218 }
64219 static void freePage(MemPage *pPage, int *pRC){
64220  if( (*pRC)==SQLITE_OK ){
64221  *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
64222  }
64223 }
64224 
64225 /*
64226 ** Free any overflow pages associated with the given Cell. Write the
64227 ** local Cell size (the number of bytes on the original page, omitting
64228 ** overflow) into *pnSize.
64229 */
64230 static int clearCell(
64231  MemPage *pPage, /* The page that contains the Cell */
64232  unsigned char *pCell, /* First byte of the Cell */
64233  u16 *pnSize /* Write the size of the Cell here */
64234 ){
64235  BtShared *pBt = pPage->pBt;
64236  CellInfo info;
64237  Pgno ovflPgno;
64238  int rc;
64239  int nOvfl;
64240  u32 ovflPageSize;
64241 
64242  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64243  pPage->xParseCell(pPage, pCell, &info);
64244  *pnSize = info.nSize;
64245  if( info.nLocal==info.nPayload ){
64246  return SQLITE_OK; /* No overflow pages. Return without doing anything */
64247  }
64248  if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
64249  return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
64250  }
64251  ovflPgno = get4byte(pCell + info.nSize - 4);
64252  assert( pBt->usableSize > 4 );
64253  ovflPageSize = pBt->usableSize - 4;
64254  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
64255  assert( nOvfl>0 ||
64256  (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
64257  );
64258  while( nOvfl-- ){
64259  Pgno iNext = 0;
64260  MemPage *pOvfl = 0;
64261  if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
64262  /* 0 is not a legal page number and page 1 cannot be an
64263  ** overflow page. Therefore if ovflPgno<2 or past the end of the
64264  ** file the database must be corrupt. */
64265  return SQLITE_CORRUPT_BKPT;
64266  }
64267  if( nOvfl ){
64268  rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
64269  if( rc ) return rc;
64270  }
64271 
64272  if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
64273  && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
64274  ){
64275  /* There is no reason any cursor should have an outstanding reference
64276  ** to an overflow page belonging to a cell that is being deleted/updated.
64277  ** So if there exists more than one reference to this page, then it
64278  ** must not really be an overflow page and the database must be corrupt.
64279  ** It is helpful to detect this before calling freePage2(), as
64280  ** freePage2() may zero the page contents if secure-delete mode is
64281  ** enabled. If this 'overflow' page happens to be a page that the
64282  ** caller is iterating through or using in some other way, this
64283  ** can be problematic.
64284  */
64285  rc = SQLITE_CORRUPT_BKPT;
64286  }else{
64287  rc = freePage2(pBt, pOvfl, ovflPgno);
64288  }
64289 
64290  if( pOvfl ){
64291  sqlite3PagerUnref(pOvfl->pDbPage);
64292  }
64293  if( rc ) return rc;
64294  ovflPgno = iNext;
64295  }
64296  return SQLITE_OK;
64297 }
64298 
64299 /*
64300 ** Create the byte sequence used to represent a cell on page pPage
64301 ** and write that byte sequence into pCell[]. Overflow pages are
64302 ** allocated and filled in as necessary. The calling procedure
64303 ** is responsible for making sure sufficient space has been allocated
64304 ** for pCell[].
64305 **
64306 ** Note that pCell does not necessary need to point to the pPage->aData
64307 ** area. pCell might point to some temporary storage. The cell will
64308 ** be constructed in this temporary area then copied into pPage->aData
64309 ** later.
64310 */
64311 static int fillInCell(
64312  MemPage *pPage, /* The page that contains the cell */
64313  unsigned char *pCell, /* Complete text of the cell */
64314  const BtreePayload *pX, /* Payload with which to construct the cell */
64315  int *pnSize /* Write cell size here */
64316 ){
64317  int nPayload;
64318  const u8 *pSrc;
64319  int nSrc, n, rc;
64320  int spaceLeft;
64321  MemPage *pOvfl = 0;
64322  MemPage *pToRelease = 0;
64323  unsigned char *pPrior;
64324  unsigned char *pPayload;
64325  BtShared *pBt = pPage->pBt;
64326  Pgno pgnoOvfl = 0;
64327  int nHeader;
64328 
64329  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64330 
64331  /* pPage is not necessarily writeable since pCell might be auxiliary
64332  ** buffer space that is separate from the pPage buffer area */
64333  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
64334  || sqlite3PagerIswriteable(pPage->pDbPage) );
64335 
64336  /* Fill in the header. */
64337  nHeader = pPage->childPtrSize;
64338  if( pPage->intKey ){
64339  nPayload = pX->nData + pX->nZero;
64340  pSrc = pX->pData;
64341  nSrc = pX->nData;
64342  assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
64343  nHeader += putVarint32(&pCell[nHeader], nPayload);
64344  nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
64345  }else{
64346  assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
64347  nSrc = nPayload = (int)pX->nKey;
64348  pSrc = pX->pKey;
64349  nHeader += putVarint32(&pCell[nHeader], nPayload);
64350  }
64351 
64352  /* Fill in the payload */
64353  if( nPayload<=pPage->maxLocal ){
64354  n = nHeader + nPayload;
64355  testcase( n==3 );
64356  testcase( n==4 );
64357  if( n<4 ) n = 4;
64358  *pnSize = n;
64359  spaceLeft = nPayload;
64360  pPrior = pCell;
64361  }else{
64362  int mn = pPage->minLocal;
64363  n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
64364  testcase( n==pPage->maxLocal );
64365  testcase( n==pPage->maxLocal+1 );
64366  if( n > pPage->maxLocal ) n = mn;
64367  spaceLeft = n;
64368  *pnSize = n + nHeader + 4;
64369  pPrior = &pCell[nHeader+n];
64370  }
64371  pPayload = &pCell[nHeader];
64372 
64373  /* At this point variables should be set as follows:
64374  **
64375  ** nPayload Total payload size in bytes
64376  ** pPayload Begin writing payload here
64377  ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
64378  ** that means content must spill into overflow pages.
64379  ** *pnSize Size of the local cell (not counting overflow pages)
64380  ** pPrior Where to write the pgno of the first overflow page
64381  **
64382  ** Use a call to btreeParseCellPtr() to verify that the values above
64383  ** were computed correctly.
64384  */
64385 #if SQLITE_DEBUG
64386  {
64387  CellInfo info;
64388  pPage->xParseCell(pPage, pCell, &info);
64389  assert( nHeader==(int)(info.pPayload - pCell) );
64390  assert( info.nKey==pX->nKey );
64391  assert( *pnSize == info.nSize );
64392  assert( spaceLeft == info.nLocal );
64393  }
64394 #endif
64395 
64396  /* Write the payload into the local Cell and any extra into overflow pages */
64397  while( nPayload>0 ){
64398  if( spaceLeft==0 ){
64399 #ifndef SQLITE_OMIT_AUTOVACUUM
64400  Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
64401  if( pBt->autoVacuum ){
64402  do{
64403  pgnoOvfl++;
64404  } while(
64405  PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
64406  );
64407  }
64408 #endif
64409  rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
64410 #ifndef SQLITE_OMIT_AUTOVACUUM
64411  /* If the database supports auto-vacuum, and the second or subsequent
64412  ** overflow page is being allocated, add an entry to the pointer-map
64413  ** for that page now.
64414  **
64415  ** If this is the first overflow page, then write a partial entry
64416  ** to the pointer-map. If we write nothing to this pointer-map slot,
64417  ** then the optimistic overflow chain processing in clearCell()
64418  ** may misinterpret the uninitialized values and delete the
64419  ** wrong pages from the database.
64420  */
64421  if( pBt->autoVacuum && rc==SQLITE_OK ){
64422  u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
64423  ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
64424  if( rc ){
64425  releasePage(pOvfl);
64426  }
64427  }
64428 #endif
64429  if( rc ){
64430  releasePage(pToRelease);
64431  return rc;
64432  }
64433 
64434  /* If pToRelease is not zero than pPrior points into the data area
64435  ** of pToRelease. Make sure pToRelease is still writeable. */
64436  assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64437 
64438  /* If pPrior is part of the data area of pPage, then make sure pPage
64439  ** is still writeable */
64440  assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
64441  || sqlite3PagerIswriteable(pPage->pDbPage) );
64442 
64443  put4byte(pPrior, pgnoOvfl);
64444  releasePage(pToRelease);
64445  pToRelease = pOvfl;
64446  pPrior = pOvfl->aData;
64447  put4byte(pPrior, 0);
64448  pPayload = &pOvfl->aData[4];
64449  spaceLeft = pBt->usableSize - 4;
64450  }
64451  n = nPayload;
64452  if( n>spaceLeft ) n = spaceLeft;
64453 
64454  /* If pToRelease is not zero than pPayload points into the data area
64455  ** of pToRelease. Make sure pToRelease is still writeable. */
64456  assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64457 
64458  /* If pPayload is part of the data area of pPage, then make sure pPage
64459  ** is still writeable */
64460  assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
64461  || sqlite3PagerIswriteable(pPage->pDbPage) );
64462 
64463  if( nSrc>0 ){
64464  if( n>nSrc ) n = nSrc;
64465  assert( pSrc );
64466  memcpy(pPayload, pSrc, n);
64467  }else{
64468  memset(pPayload, 0, n);
64469  }
64470  nPayload -= n;
64471  pPayload += n;
64472  pSrc += n;
64473  nSrc -= n;
64474  spaceLeft -= n;
64475  }
64476  releasePage(pToRelease);
64477  return SQLITE_OK;
64478 }
64479 
64480 /*
64481 ** Remove the i-th cell from pPage. This routine effects pPage only.
64482 ** The cell content is not freed or deallocated. It is assumed that
64483 ** the cell content has been copied someplace else. This routine just
64484 ** removes the reference to the cell from pPage.
64485 **
64486 ** "sz" must be the number of bytes in the cell.
64487 */
64488 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
64489  u32 pc; /* Offset to cell content of cell being deleted */
64490  u8 *data; /* pPage->aData */
64491  u8 *ptr; /* Used to move bytes around within data[] */
64492  int rc; /* The return code */
64493  int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
64494 
64495  if( *pRC ) return;
64496 
64497  assert( idx>=0 && idx<pPage->nCell );
64498  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
64499  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64500  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64501  data = pPage->aData;
64502  ptr = &pPage->aCellIdx[2*idx];
64503  pc = get2byte(ptr);
64504  hdr = pPage->hdrOffset;
64505  testcase( pc==get2byte(&data[hdr+5]) );
64506  testcase( pc+sz==pPage->pBt->usableSize );
64507  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
64508  *pRC = SQLITE_CORRUPT_BKPT;
64509  return;
64510  }
64511  rc = freeSpace(pPage, pc, sz);
64512  if( rc ){
64513  *pRC = rc;
64514  return;
64515  }
64516  pPage->nCell--;
64517  if( pPage->nCell==0 ){
64518  memset(&data[hdr+1], 0, 4);
64519  data[hdr+7] = 0;
64520  put2byte(&data[hdr+5], pPage->pBt->usableSize);
64521  pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
64522  - pPage->childPtrSize - 8;
64523  }else{
64524  memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
64525  put2byte(&data[hdr+3], pPage->nCell);
64526  pPage->nFree += 2;
64527  }
64528 }
64529 
64530 /*
64531 ** Insert a new cell on pPage at cell index "i". pCell points to the
64532 ** content of the cell.
64533 **
64534 ** If the cell content will fit on the page, then put it there. If it
64535 ** will not fit, then make a copy of the cell content into pTemp if
64536 ** pTemp is not null. Regardless of pTemp, allocate a new entry
64537 ** in pPage->apOvfl[] and make it point to the cell content (either
64538 ** in pTemp or the original pCell) and also record its index.
64539 ** Allocating a new entry in pPage->aCell[] implies that
64540 ** pPage->nOverflow is incremented.
64541 **
64542 ** *pRC must be SQLITE_OK when this routine is called.
64543 */
64544 static void insertCell(
64545  MemPage *pPage, /* Page into which we are copying */
64546  int i, /* New cell becomes the i-th cell of the page */
64547  u8 *pCell, /* Content of the new cell */
64548  int sz, /* Bytes of content in pCell */
64549  u8 *pTemp, /* Temp storage space for pCell, if needed */
64550  Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
64551  int *pRC /* Read and write return code from here */
64552 ){
64553  int idx = 0; /* Where to write new cell content in data[] */
64554  int j; /* Loop counter */
64555  u8 *data; /* The content of the whole page */
64556  u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
64557 
64558  assert( *pRC==SQLITE_OK );
64559  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
64560  assert( MX_CELL(pPage->pBt)<=10921 );
64561  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
64562  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
64563  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
64564  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64565  /* The cell should normally be sized correctly. However, when moving a
64566  ** malformed cell from a leaf page to an interior page, if the cell size
64567  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
64568  ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
64569  ** the term after the || in the following assert(). */
64570  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
64571  if( pPage->nOverflow || sz+2>pPage->nFree ){
64572  if( pTemp ){
64573  memcpy(pTemp, pCell, sz);
64574  pCell = pTemp;
64575  }
64576  if( iChild ){
64577  put4byte(pCell, iChild);
64578  }
64579  j = pPage->nOverflow++;
64580  assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
64581  pPage->apOvfl[j] = pCell;
64582  pPage->aiOvfl[j] = (u16)i;
64583 
64584  /* When multiple overflows occur, they are always sequential and in
64585  ** sorted order. This invariants arise because multiple overflows can
64586  ** only occur when inserting divider cells into the parent page during
64587  ** balancing, and the dividers are adjacent and sorted.
64588  */
64589  assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
64590  assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
64591  }else{
64592  int rc = sqlite3PagerWrite(pPage->pDbPage);
64593  if( rc!=SQLITE_OK ){
64594  *pRC = rc;
64595  return;
64596  }
64597  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64598  data = pPage->aData;
64599  assert( &data[pPage->cellOffset]==pPage->aCellIdx );
64600  rc = allocateSpace(pPage, sz, &idx);
64601  if( rc ){ *pRC = rc; return; }
64602  /* The allocateSpace() routine guarantees the following properties
64603  ** if it returns successfully */
64604  assert( idx >= 0 );
64605  assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
64606  assert( idx+sz <= (int)pPage->pBt->usableSize );
64607  pPage->nFree -= (u16)(2 + sz);
64608  memcpy(&data[idx], pCell, sz);
64609  if( iChild ){
64610  put4byte(&data[idx], iChild);
64611  }
64612  pIns = pPage->aCellIdx + i*2;
64613  memmove(pIns+2, pIns, 2*(pPage->nCell - i));
64614  put2byte(pIns, idx);
64615  pPage->nCell++;
64616  /* increment the cell count */
64617  if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
64618  assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
64619 #ifndef SQLITE_OMIT_AUTOVACUUM
64620  if( pPage->pBt->autoVacuum ){
64621  /* The cell may contain a pointer to an overflow page. If so, write
64622  ** the entry for the overflow page into the pointer map.
64623  */
64624  ptrmapPutOvflPtr(pPage, pCell, pRC);
64625  }
64626 #endif
64627  }
64628 }
64629 
64630 /*
64631 ** A CellArray object contains a cache of pointers and sizes for a
64632 ** consecutive sequence of cells that might be held on multiple pages.
64633 */
64634 typedef struct CellArray CellArray;
64635 struct CellArray {
64636  int nCell; /* Number of cells in apCell[] */
64637  MemPage *pRef; /* Reference page */
64638  u8 **apCell; /* All cells begin balanced */
64639  u16 *szCell; /* Local size of all cells in apCell[] */
64640 };
64641 
64642 /*
64643 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
64644 ** computed.
64645 */
64646 static void populateCellCache(CellArray *p, int idx, int N){
64647  assert( idx>=0 && idx+N<=p->nCell );
64648  while( N>0 ){
64649  assert( p->apCell[idx]!=0 );
64650  if( p->szCell[idx]==0 ){
64651  p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
64652  }else{
64653  assert( CORRUPT_DB ||
64654  p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
64655  }
64656  idx++;
64657  N--;
64658  }
64659 }
64660 
64661 /*
64662 ** Return the size of the Nth element of the cell array
64663 */
64665  assert( N>=0 && N<p->nCell );
64666  assert( p->szCell[N]==0 );
64667  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
64668  return p->szCell[N];
64669 }
64670 static u16 cachedCellSize(CellArray *p, int N){
64671  assert( N>=0 && N<p->nCell );
64672  if( p->szCell[N] ) return p->szCell[N];
64673  return computeCellSize(p, N);
64674 }
64675 
64676 /*
64677 ** Array apCell[] contains pointers to nCell b-tree page cells. The
64678 ** szCell[] array contains the size in bytes of each cell. This function
64679 ** replaces the current contents of page pPg with the contents of the cell
64680 ** array.
64681 **
64682 ** Some of the cells in apCell[] may currently be stored in pPg. This
64683 ** function works around problems caused by this by making a copy of any
64684 ** such cells before overwriting the page data.
64685 **
64686 ** The MemPage.nFree field is invalidated by this function. It is the
64687 ** responsibility of the caller to set it correctly.
64688 */
64689 static int rebuildPage(
64690  MemPage *pPg, /* Edit this page */
64691  int nCell, /* Final number of cells on page */
64692  u8 **apCell, /* Array of cells */
64693  u16 *szCell /* Array of cell sizes */
64694 ){
64695  const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
64696  u8 * const aData = pPg->aData; /* Pointer to data for pPg */
64697  const int usableSize = pPg->pBt->usableSize;
64698  u8 * const pEnd = &aData[usableSize];
64699  int i;
64700  u8 *pCellptr = pPg->aCellIdx;
64701  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64702  u8 *pData;
64703 
64704  i = get2byte(&aData[hdr+5]);
64705  memcpy(&pTmp[i], &aData[i], usableSize - i);
64706 
64707  pData = pEnd;
64708  for(i=0; i<nCell; i++){
64709  u8 *pCell = apCell[i];
64710  if( SQLITE_WITHIN(pCell,aData,pEnd) ){
64711  pCell = &pTmp[pCell - aData];
64712  }
64713  pData -= szCell[i];
64714  put2byte(pCellptr, (pData - aData));
64715  pCellptr += 2;
64716  if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
64717  memcpy(pData, pCell, szCell[i]);
64718  assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
64719  testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
64720  }
64721 
64722  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
64723  pPg->nCell = nCell;
64724  pPg->nOverflow = 0;
64725 
64726  put2byte(&aData[hdr+1], 0);
64727  put2byte(&aData[hdr+3], pPg->nCell);
64728  put2byte(&aData[hdr+5], pData - aData);
64729  aData[hdr+7] = 0x00;
64730  return SQLITE_OK;
64731 }
64732 
64733 /*
64734 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64735 ** contains the size in bytes of each such cell. This function attempts to
64736 ** add the cells stored in the array to page pPg. If it cannot (because
64737 ** the page needs to be defragmented before the cells will fit), non-zero
64738 ** is returned. Otherwise, if the cells are added successfully, zero is
64739 ** returned.
64740 **
64741 ** Argument pCellptr points to the first entry in the cell-pointer array
64742 ** (part of page pPg) to populate. After cell apCell[0] is written to the
64743 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
64744 ** cell in the array. It is the responsibility of the caller to ensure
64745 ** that it is safe to overwrite this part of the cell-pointer array.
64746 **
64747 ** When this function is called, *ppData points to the start of the
64748 ** content area on page pPg. If the size of the content area is extended,
64749 ** *ppData is updated to point to the new start of the content area
64750 ** before returning.
64751 **
64752 ** Finally, argument pBegin points to the byte immediately following the
64753 ** end of the space required by this page for the cell-pointer area (for
64754 ** all cells - not just those inserted by the current call). If the content
64755 ** area must be extended to before this point in order to accomodate all
64756 ** cells in apCell[], then the cells do not fit and non-zero is returned.
64757 */
64758 static int pageInsertArray(
64759  MemPage *pPg, /* Page to add cells to */
64760  u8 *pBegin, /* End of cell-pointer array */
64761  u8 **ppData, /* IN/OUT: Page content -area pointer */
64762  u8 *pCellptr, /* Pointer to cell-pointer area */
64763  int iFirst, /* Index of first cell to add */
64764  int nCell, /* Number of cells to add to pPg */
64765  CellArray *pCArray /* Array of cells */
64766 ){
64767  int i;
64768  u8 *aData = pPg->aData;
64769  u8 *pData = *ppData;
64770  int iEnd = iFirst + nCell;
64771  assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
64772  for(i=iFirst; i<iEnd; i++){
64773  int sz, rc;
64774  u8 *pSlot;
64775  sz = cachedCellSize(pCArray, i);
64776  if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64777  if( (pData - pBegin)<sz ) return 1;
64778  pData -= sz;
64779  pSlot = pData;
64780  }
64781  /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
64782  ** database. But they might for a corrupt database. Hence use memmove()
64783  ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
64784  assert( (pSlot+sz)<=pCArray->apCell[i]
64785  || pSlot>=(pCArray->apCell[i]+sz)
64786  || CORRUPT_DB );
64787  memmove(pSlot, pCArray->apCell[i], sz);
64788  put2byte(pCellptr, (pSlot - aData));
64789  pCellptr += 2;
64790  }
64791  *ppData = pData;
64792  return 0;
64793 }
64794 
64795 /*
64796 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64797 ** contains the size in bytes of each such cell. This function adds the
64798 ** space associated with each cell in the array that is currently stored
64799 ** within the body of pPg to the pPg free-list. The cell-pointers and other
64800 ** fields of the page are not updated.
64801 **
64802 ** This function returns the total number of cells added to the free-list.
64803 */
64804 static int pageFreeArray(
64805  MemPage *pPg, /* Page to edit */
64806  int iFirst, /* First cell to delete */
64807  int nCell, /* Cells to delete */
64808  CellArray *pCArray /* Array of cells */
64809 ){
64810  u8 * const aData = pPg->aData;
64811  u8 * const pEnd = &aData[pPg->pBt->usableSize];
64812  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
64813  int nRet = 0;
64814  int i;
64815  int iEnd = iFirst + nCell;
64816  u8 *pFree = 0;
64817  int szFree = 0;
64818 
64819  for(i=iFirst; i<iEnd; i++){
64820  u8 *pCell = pCArray->apCell[i];
64821  if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
64822  int sz;
64823  /* No need to use cachedCellSize() here. The sizes of all cells that
64824  ** are to be freed have already been computing while deciding which
64825  ** cells need freeing */
64826  sz = pCArray->szCell[i]; assert( sz>0 );
64827  if( pFree!=(pCell + sz) ){
64828  if( pFree ){
64829  assert( pFree>aData && (pFree - aData)<65536 );
64830  freeSpace(pPg, (u16)(pFree - aData), szFree);
64831  }
64832  pFree = pCell;
64833  szFree = sz;
64834  if( pFree+sz>pEnd ) return 0;
64835  }else{
64836  pFree = pCell;
64837  szFree += sz;
64838  }
64839  nRet++;
64840  }
64841  }
64842  if( pFree ){
64843  assert( pFree>aData && (pFree - aData)<65536 );
64844  freeSpace(pPg, (u16)(pFree - aData), szFree);
64845  }
64846  return nRet;
64847 }
64848 
64849 /*
64850 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
64851 ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
64852 ** with apCell[iOld]. After balancing, this page should hold nNew cells
64853 ** starting at apCell[iNew].
64854 **
64855 ** This routine makes the necessary adjustments to pPg so that it contains
64856 ** the correct cells after being balanced.
64857 **
64858 ** The pPg->nFree field is invalid when this function returns. It is the
64859 ** responsibility of the caller to set it correctly.
64860 */
64861 static int editPage(
64862  MemPage *pPg, /* Edit this page */
64863  int iOld, /* Index of first cell currently on page */
64864  int iNew, /* Index of new first cell on page */
64865  int nNew, /* Final number of cells on page */
64866  CellArray *pCArray /* Array of cells and sizes */
64867 ){
64868  u8 * const aData = pPg->aData;
64869  const int hdr = pPg->hdrOffset;
64870  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
64871  int nCell = pPg->nCell; /* Cells stored on pPg */
64872  u8 *pData;
64873  u8 *pCellptr;
64874  int i;
64875  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
64876  int iNewEnd = iNew + nNew;
64877 
64878 #ifdef SQLITE_DEBUG
64879  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64880  memcpy(pTmp, aData, pPg->pBt->usableSize);
64881 #endif
64882 
64883  /* Remove cells from the start and end of the page */
64884  if( iOld<iNew ){
64885  int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
64886  memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
64887  nCell -= nShift;
64888  }
64889  if( iNewEnd < iOldEnd ){
64890  nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
64891  }
64892 
64893  pData = &aData[get2byteNotZero(&aData[hdr+5])];
64894  if( pData<pBegin ) goto editpage_fail;
64895 
64896  /* Add cells to the start of the page */
64897  if( iNew<iOld ){
64898  int nAdd = MIN(nNew,iOld-iNew);
64899  assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
64900  pCellptr = pPg->aCellIdx;
64901  memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
64902  if( pageInsertArray(
64903  pPg, pBegin, &pData, pCellptr,
64904  iNew, nAdd, pCArray
64905  ) ) goto editpage_fail;
64906  nCell += nAdd;
64907  }
64908 
64909  /* Add any overflow cells */
64910  for(i=0; i<pPg->nOverflow; i++){
64911  int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
64912  if( iCell>=0 && iCell<nNew ){
64913  pCellptr = &pPg->aCellIdx[iCell * 2];
64914  memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
64915  nCell++;
64916  if( pageInsertArray(
64917  pPg, pBegin, &pData, pCellptr,
64918  iCell+iNew, 1, pCArray
64919  ) ) goto editpage_fail;
64920  }
64921  }
64922 
64923  /* Append cells to the end of the page */
64924  pCellptr = &pPg->aCellIdx[nCell*2];
64925  if( pageInsertArray(
64926  pPg, pBegin, &pData, pCellptr,
64927  iNew+nCell, nNew-nCell, pCArray
64928  ) ) goto editpage_fail;
64929 
64930  pPg->nCell = nNew;
64931  pPg->nOverflow = 0;
64932 
64933  put2byte(&aData[hdr+3], pPg->nCell);
64934  put2byte(&aData[hdr+5], pData - aData);
64935 
64936 #ifdef SQLITE_DEBUG
64937  for(i=0; i<nNew && !CORRUPT_DB; i++){
64938  u8 *pCell = pCArray->apCell[i+iNew];
64939  int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
64940  if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
64941  pCell = &pTmp[pCell - aData];
64942  }
64943  assert( 0==memcmp(pCell, &aData[iOff],
64944  pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
64945  }
64946 #endif
64947 
64948  return SQLITE_OK;
64949  editpage_fail:
64950  /* Unable to edit this page. Rebuild it from scratch instead. */
64951  populateCellCache(pCArray, iNew, nNew);
64952  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
64953 }
64954 
64955 /*
64956 ** The following parameters determine how many adjacent pages get involved
64957 ** in a balancing operation. NN is the number of neighbors on either side
64958 ** of the page that participate in the balancing operation. NB is the
64959 ** total number of pages that participate, including the target page and
64960 ** NN neighbors on either side.
64961 **
64962 ** The minimum value of NN is 1 (of course). Increasing NN above 1
64963 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
64964 ** in exchange for a larger degradation in INSERT and UPDATE performance.
64965 ** The value of NN appears to give the best results overall.
64966 */
64967 #define NN 1 /* Number of neighbors on either side of pPage */
64968 #define NB (NN*2+1) /* Total pages involved in the balance */
64969 
64970 
64971 #ifndef SQLITE_OMIT_QUICKBALANCE
64972 /*
64973 ** This version of balance() handles the common special case where
64974 ** a new entry is being inserted on the extreme right-end of the
64975 ** tree, in other words, when the new entry will become the largest
64976 ** entry in the tree.
64977 **
64978 ** Instead of trying to balance the 3 right-most leaf pages, just add
64979 ** a new page to the right-hand side and put the one new entry in
64980 ** that page. This leaves the right side of the tree somewhat
64981 ** unbalanced. But odds are that we will be inserting new entries
64982 ** at the end soon afterwards so the nearly empty page will quickly
64983 ** fill up. On average.
64984 **
64985 ** pPage is the leaf page which is the right-most page in the tree.
64986 ** pParent is its parent. pPage must have a single overflow entry
64987 ** which is also the right-most entry on the page.
64988 **
64989 ** The pSpace buffer is used to store a temporary copy of the divider
64990 ** cell that will be inserted into pParent. Such a cell consists of a 4
64991 ** byte page number followed by a variable length integer. In other
64992 ** words, at most 13 bytes. Hence the pSpace buffer must be at
64993 ** least 13 bytes in size.
64994 */
64995 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
64996  BtShared *const pBt = pPage->pBt; /* B-Tree Database */
64997  MemPage *pNew; /* Newly allocated page */
64998  int rc; /* Return Code */
64999  Pgno pgnoNew; /* Page number of pNew */
65000 
65001  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
65002  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65003  assert( pPage->nOverflow==1 );
65004 
65005  /* This error condition is now caught prior to reaching this function */
65006  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
65007 
65008  /* Allocate a new page. This page will become the right-sibling of
65009  ** pPage. Make the parent page writable, so that the new divider cell
65010  ** may be inserted. If both these operations are successful, proceed.
65011  */
65012  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
65013 
65014  if( rc==SQLITE_OK ){
65015 
65016  u8 *pOut = &pSpace[4];
65017  u8 *pCell = pPage->apOvfl[0];
65018  u16 szCell = pPage->xCellSize(pPage, pCell);
65019  u8 *pStop;
65020 
65021  assert( sqlite3PagerIswriteable(pNew->pDbPage) );
65022  assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
65024  rc = rebuildPage(pNew, 1, &pCell, &szCell);
65025  if( NEVER(rc) ) return rc;
65026  pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
65027 
65028  /* If this is an auto-vacuum database, update the pointer map
65029  ** with entries for the new page, and any pointer from the
65030  ** cell on the page to an overflow page. If either of these
65031  ** operations fails, the return code is set, but the contents
65032  ** of the parent page are still manipulated by thh code below.
65033  ** That is Ok, at this point the parent page is guaranteed to
65034  ** be marked as dirty. Returning an error code will cause a
65035  ** rollback, undoing any changes made to the parent page.
65036  */
65037  if( ISAUTOVACUUM ){
65038  ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
65039  if( szCell>pNew->minLocal ){
65040  ptrmapPutOvflPtr(pNew, pCell, &rc);
65041  }
65042  }
65043 
65044  /* Create a divider cell to insert into pParent. The divider cell
65045  ** consists of a 4-byte page number (the page number of pPage) and
65046  ** a variable length key value (which must be the same value as the
65047  ** largest key on pPage).
65048  **
65049  ** To find the largest key value on pPage, first find the right-most
65050  ** cell on pPage. The first two fields of this cell are the
65051  ** record-length (a variable length integer at most 32-bits in size)
65052  ** and the key value (a variable length integer, may have any value).
65053  ** The first of the while(...) loops below skips over the record-length
65054  ** field. The second while(...) loop copies the key value from the
65055  ** cell on pPage into the pSpace buffer.
65056  */
65057  pCell = findCell(pPage, pPage->nCell-1);
65058  pStop = &pCell[9];
65059  while( (*(pCell++)&0x80) && pCell<pStop );
65060  pStop = &pCell[9];
65061  while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
65062 
65063  /* Insert the new divider cell into pParent. */
65064  if( rc==SQLITE_OK ){
65065  insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
65066  0, pPage->pgno, &rc);
65067  }
65068 
65069  /* Set the right-child pointer of pParent to point to the new page. */
65070  put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
65071 
65072  /* Release the reference to the new page. */
65073  releasePage(pNew);
65074  }
65075 
65076  return rc;
65077 }
65078 #endif /* SQLITE_OMIT_QUICKBALANCE */
65079 
65080 #if 0
65081 /*
65082 ** This function does not contribute anything to the operation of SQLite.
65083 ** it is sometimes activated temporarily while debugging code responsible
65084 ** for setting pointer-map entries.
65085 */
65086 static int ptrmapCheckPages(MemPage **apPage, int nPage){
65087  int i, j;
65088  for(i=0; i<nPage; i++){
65089  Pgno n;
65090  u8 e;
65091  MemPage *pPage = apPage[i];
65092  BtShared *pBt = pPage->pBt;
65093  assert( pPage->isInit );
65094 
65095  for(j=0; j<pPage->nCell; j++){
65096  CellInfo info;
65097  u8 *z;
65098 
65099  z = findCell(pPage, j);
65100  pPage->xParseCell(pPage, z, &info);
65101  if( info.nLocal<info.nPayload ){
65102  Pgno ovfl = get4byte(&z[info.nSize-4]);
65103  ptrmapGet(pBt, ovfl, &e, &n);
65104  assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
65105  }
65106  if( !pPage->leaf ){
65107  Pgno child = get4byte(z);
65108  ptrmapGet(pBt, child, &e, &n);
65109  assert( n==pPage->pgno && e==PTRMAP_BTREE );
65110  }
65111  }
65112  if( !pPage->leaf ){
65113  Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
65114  ptrmapGet(pBt, child, &e, &n);
65115  assert( n==pPage->pgno && e==PTRMAP_BTREE );
65116  }
65117  }
65118  return 1;
65119 }
65120 #endif
65121 
65122 /*
65123 ** This function is used to copy the contents of the b-tree node stored
65124 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
65125 ** the pointer-map entries for each child page are updated so that the
65126 ** parent page stored in the pointer map is page pTo. If pFrom contained
65127 ** any cells with overflow page pointers, then the corresponding pointer
65128 ** map entries are also updated so that the parent page is page pTo.
65129 **
65130 ** If pFrom is currently carrying any overflow cells (entries in the
65131 ** MemPage.apOvfl[] array), they are not copied to pTo.
65132 **
65133 ** Before returning, page pTo is reinitialized using btreeInitPage().
65134 **
65135 ** The performance of this function is not critical. It is only used by
65136 ** the balance_shallower() and balance_deeper() procedures, neither of
65137 ** which are called often under normal circumstances.
65138 */
65139 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
65140  if( (*pRC)==SQLITE_OK ){
65141  BtShared * const pBt = pFrom->pBt;
65142  u8 * const aFrom = pFrom->aData;
65143  u8 * const aTo = pTo->aData;
65144  int const iFromHdr = pFrom->hdrOffset;
65145  int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
65146  int rc;
65147  int iData;
65148 
65149 
65150  assert( pFrom->isInit );
65151  assert( pFrom->nFree>=iToHdr );
65152  assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
65153 
65154  /* Copy the b-tree node content from page pFrom to page pTo. */
65155  iData = get2byte(&aFrom[iFromHdr+5]);
65156  memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
65157  memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
65158 
65159  /* Reinitialize page pTo so that the contents of the MemPage structure
65160  ** match the new data. The initialization of pTo can actually fail under
65161  ** fairly obscure circumstances, even though it is a copy of initialized
65162  ** page pFrom.
65163  */
65164  pTo->isInit = 0;
65165  rc = btreeInitPage(pTo);
65166  if( rc!=SQLITE_OK ){
65167  *pRC = rc;
65168  return;
65169  }
65170 
65171  /* If this is an auto-vacuum database, update the pointer-map entries
65172  ** for any b-tree or overflow pages that pTo now contains the pointers to.
65173  */
65174  if( ISAUTOVACUUM ){
65175  *pRC = setChildPtrmaps(pTo);
65176  }
65177  }
65178 }
65179 
65180 /*
65181 ** This routine redistributes cells on the iParentIdx'th child of pParent
65182 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
65183 ** same amount of free space. Usually a single sibling on either side of the
65184 ** page are used in the balancing, though both siblings might come from one
65185 ** side if the page is the first or last child of its parent. If the page
65186 ** has fewer than 2 siblings (something which can only happen if the page
65187 ** is a root page or a child of a root page) then all available siblings
65188 ** participate in the balancing.
65189 **
65190 ** The number of siblings of the page might be increased or decreased by
65191 ** one or two in an effort to keep pages nearly full but not over full.
65192 **
65193 ** Note that when this routine is called, some of the cells on the page
65194 ** might not actually be stored in MemPage.aData[]. This can happen
65195 ** if the page is overfull. This routine ensures that all cells allocated
65196 ** to the page and its siblings fit into MemPage.aData[] before returning.
65197 **
65198 ** In the course of balancing the page and its siblings, cells may be
65199 ** inserted into or removed from the parent page (pParent). Doing so
65200 ** may cause the parent page to become overfull or underfull. If this
65201 ** happens, it is the responsibility of the caller to invoke the correct
65202 ** balancing routine to fix this problem (see the balance() routine).
65203 **
65204 ** If this routine fails for any reason, it might leave the database
65205 ** in a corrupted state. So if this routine fails, the database should
65206 ** be rolled back.
65207 **
65208 ** The third argument to this function, aOvflSpace, is a pointer to a
65209 ** buffer big enough to hold one page. If while inserting cells into the parent
65210 ** page (pParent) the parent page becomes overfull, this buffer is
65211 ** used to store the parent's overflow cells. Because this function inserts
65212 ** a maximum of four divider cells into the parent page, and the maximum
65213 ** size of a cell stored within an internal node is always less than 1/4
65214 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
65215 ** enough for all overflow cells.
65216 **
65217 ** If aOvflSpace is set to a null pointer, this function returns
65218 ** SQLITE_NOMEM.
65219 */
65220 static int balance_nonroot(
65221  MemPage *pParent, /* Parent page of siblings being balanced */
65222  int iParentIdx, /* Index of "the page" in pParent */
65223  u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
65224  int isRoot, /* True if pParent is a root-page */
65225  int bBulk /* True if this call is part of a bulk load */
65226 ){
65227  BtShared *pBt; /* The whole database */
65228  int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
65229  int nNew = 0; /* Number of pages in apNew[] */
65230  int nOld; /* Number of pages in apOld[] */
65231  int i, j, k; /* Loop counters */
65232  int nxDiv; /* Next divider slot in pParent->aCell[] */
65233  int rc = SQLITE_OK; /* The return code */
65234  u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
65235  int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
65236  int usableSpace; /* Bytes in pPage beyond the header */
65237  int pageFlags; /* Value of pPage->aData[0] */
65238  int iSpace1 = 0; /* First unused byte of aSpace1[] */
65239  int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
65240  int szScratch; /* Size of scratch memory requested */
65241  MemPage *apOld[NB]; /* pPage and up to two siblings */
65242  MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
65243  u8 *pRight; /* Location in parent of right-sibling pointer */
65244  u8 *apDiv[NB-1]; /* Divider cells in pParent */
65245  int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
65246  int cntOld[NB+2]; /* Old index in b.apCell[] */
65247  int szNew[NB+2]; /* Combined size of cells placed on i-th page */
65248  u8 *aSpace1; /* Space for copies of dividers cells */
65249  Pgno pgno; /* Temp var to store a page number in */
65250  u8 abDone[NB+2]; /* True after i'th new page is populated */
65251  Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
65252  Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
65253  u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
65254  CellArray b; /* Parsed information on cells being balanced */
65255 
65256  memset(abDone, 0, sizeof(abDone));
65257  b.nCell = 0;
65258  b.apCell = 0;
65259  pBt = pParent->pBt;
65260  assert( sqlite3_mutex_held(pBt->mutex) );
65261  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65262 
65263 #if 0
65264  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
65265 #endif
65266 
65267  /* At this point pParent may have at most one overflow cell. And if
65268  ** this overflow cell is present, it must be the cell with
65269  ** index iParentIdx. This scenario comes about when this function
65270  ** is called (indirectly) from sqlite3BtreeDelete().
65271  */
65272  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
65273  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
65274 
65275  if( !aOvflSpace ){
65276  return SQLITE_NOMEM_BKPT;
65277  }
65278 
65279  /* Find the sibling pages to balance. Also locate the cells in pParent
65280  ** that divide the siblings. An attempt is made to find NN siblings on
65281  ** either side of pPage. More siblings are taken from one side, however,
65282  ** if there are fewer than NN siblings on the other side. If pParent
65283  ** has NB or fewer children then all children of pParent are taken.
65284  **
65285  ** This loop also drops the divider cells from the parent page. This
65286  ** way, the remainder of the function does not have to deal with any
65287  ** overflow cells in the parent page, since if any existed they will
65288  ** have already been removed.
65289  */
65290  i = pParent->nOverflow + pParent->nCell;
65291  if( i<2 ){
65292  nxDiv = 0;
65293  }else{
65294  assert( bBulk==0 || bBulk==1 );
65295  if( iParentIdx==0 ){
65296  nxDiv = 0;
65297  }else if( iParentIdx==i ){
65298  nxDiv = i-2+bBulk;
65299  }else{
65300  nxDiv = iParentIdx-1;
65301  }
65302  i = 2-bBulk;
65303  }
65304  nOld = i+1;
65305  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
65306  pRight = &pParent->aData[pParent->hdrOffset+8];
65307  }else{
65308  pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
65309  }
65310  pgno = get4byte(pRight);
65311  while( 1 ){
65312  rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
65313  if( rc ){
65314  memset(apOld, 0, (i+1)*sizeof(MemPage*));
65315  goto balance_cleanup;
65316  }
65317  nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
65318  if( (i--)==0 ) break;
65319 
65320  if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
65321  apDiv[i] = pParent->apOvfl[0];
65322  pgno = get4byte(apDiv[i]);
65323  szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65324  pParent->nOverflow = 0;
65325  }else{
65326  apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
65327  pgno = get4byte(apDiv[i]);
65328  szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65329 
65330  /* Drop the cell from the parent page. apDiv[i] still points to
65331  ** the cell within the parent, even though it has been dropped.
65332  ** This is safe because dropping a cell only overwrites the first
65333  ** four bytes of it, and this function does not need the first
65334  ** four bytes of the divider cell. So the pointer is safe to use
65335  ** later on.
65336  **
65337  ** But not if we are in secure-delete mode. In secure-delete mode,
65338  ** the dropCell() routine will overwrite the entire cell with zeroes.
65339  ** In this case, temporarily copy the cell into the aOvflSpace[]
65340  ** buffer. It will be copied out again as soon as the aSpace[] buffer
65341  ** is allocated. */
65342  if( pBt->btsFlags & BTS_SECURE_DELETE ){
65343  int iOff;
65344 
65345  iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
65346  if( (iOff+szNew[i])>(int)pBt->usableSize ){
65347  rc = SQLITE_CORRUPT_BKPT;
65348  memset(apOld, 0, (i+1)*sizeof(MemPage*));
65349  goto balance_cleanup;
65350  }else{
65351  memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
65352  apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
65353  }
65354  }
65355  dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
65356  }
65357  }
65358 
65359  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
65360  ** alignment */
65361  nMaxCells = (nMaxCells + 3)&~3;
65362 
65363  /*
65364  ** Allocate space for memory structures
65365  */
65366  szScratch =
65367  nMaxCells*sizeof(u8*) /* b.apCell */
65368  + nMaxCells*sizeof(u16) /* b.szCell */
65369  + pBt->pageSize; /* aSpace1 */
65370 
65371  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
65372  ** that is more than 6 times the database page size. */
65373  assert( szScratch<=6*(int)pBt->pageSize );
65374  b.apCell = sqlite3ScratchMalloc( szScratch );
65375  if( b.apCell==0 ){
65376  rc = SQLITE_NOMEM_BKPT;
65377  goto balance_cleanup;
65378  }
65379  b.szCell = (u16*)&b.apCell[nMaxCells];
65380  aSpace1 = (u8*)&b.szCell[nMaxCells];
65381  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
65382 
65383  /*
65384  ** Load pointers to all cells on sibling pages and the divider cells
65385  ** into the local b.apCell[] array. Make copies of the divider cells
65386  ** into space obtained from aSpace1[]. The divider cells have already
65387  ** been removed from pParent.
65388  **
65389  ** If the siblings are on leaf pages, then the child pointers of the
65390  ** divider cells are stripped from the cells before they are copied
65391  ** into aSpace1[]. In this way, all cells in b.apCell[] are without
65392  ** child pointers. If siblings are not leaves, then all cell in
65393  ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
65394  ** are alike.
65395  **
65396  ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
65397  ** leafData: 1 if pPage holds key+data and pParent holds only keys.
65398  */
65399  b.pRef = apOld[0];
65400  leafCorrection = b.pRef->leaf*4;
65401  leafData = b.pRef->intKeyLeaf;
65402  for(i=0; i<nOld; i++){
65403  MemPage *pOld = apOld[i];
65404  int limit = pOld->nCell;
65405  u8 *aData = pOld->aData;
65406  u16 maskPage = pOld->maskPage;
65407  u8 *piCell = aData + pOld->cellOffset;
65408  u8 *piEnd;
65409 
65410  /* Verify that all sibling pages are of the same "type" (table-leaf,
65411  ** table-interior, index-leaf, or index-interior).
65412  */
65413  if( pOld->aData[0]!=apOld[0]->aData[0] ){
65414  rc = SQLITE_CORRUPT_BKPT;
65415  goto balance_cleanup;
65416  }
65417 
65418  /* Load b.apCell[] with pointers to all cells in pOld. If pOld
65419  ** constains overflow cells, include them in the b.apCell[] array
65420  ** in the correct spot.
65421  **
65422  ** Note that when there are multiple overflow cells, it is always the
65423  ** case that they are sequential and adjacent. This invariant arises
65424  ** because multiple overflows can only occurs when inserting divider
65425  ** cells into a parent on a prior balance, and divider cells are always
65426  ** adjacent and are inserted in order. There is an assert() tagged
65427  ** with "NOTE 1" in the overflow cell insertion loop to prove this
65428  ** invariant.
65429  **
65430  ** This must be done in advance. Once the balance starts, the cell
65431  ** offset section of the btree page will be overwritten and we will no
65432  ** long be able to find the cells if a pointer to each cell is not saved
65433  ** first.
65434  */
65435  memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
65436  if( pOld->nOverflow>0 ){
65437  limit = pOld->aiOvfl[0];
65438  for(j=0; j<limit; j++){
65439  b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65440  piCell += 2;
65441  b.nCell++;
65442  }
65443  for(k=0; k<pOld->nOverflow; k++){
65444  assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
65445  b.apCell[b.nCell] = pOld->apOvfl[k];
65446  b.nCell++;
65447  }
65448  }
65449  piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
65450  while( piCell<piEnd ){
65451  assert( b.nCell<nMaxCells );
65452  b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65453  piCell += 2;
65454  b.nCell++;
65455  }
65456 
65457  cntOld[i] = b.nCell;
65458  if( i<nOld-1 && !leafData){
65459  u16 sz = (u16)szNew[i];
65460  u8 *pTemp;
65461  assert( b.nCell<nMaxCells );
65462  b.szCell[b.nCell] = sz;
65463  pTemp = &aSpace1[iSpace1];
65464  iSpace1 += sz;
65465  assert( sz<=pBt->maxLocal+23 );
65466  assert( iSpace1 <= (int)pBt->pageSize );
65467  memcpy(pTemp, apDiv[i], sz);
65468  b.apCell[b.nCell] = pTemp+leafCorrection;
65469  assert( leafCorrection==0 || leafCorrection==4 );
65470  b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
65471  if( !pOld->leaf ){
65472  assert( leafCorrection==0 );
65473  assert( pOld->hdrOffset==0 );
65474  /* The right pointer of the child page pOld becomes the left
65475  ** pointer of the divider cell */
65476  memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
65477  }else{
65478  assert( leafCorrection==4 );
65479  while( b.szCell[b.nCell]<4 ){
65480  /* Do not allow any cells smaller than 4 bytes. If a smaller cell
65481  ** does exist, pad it with 0x00 bytes. */
65482  assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
65483  assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
65484  aSpace1[iSpace1++] = 0x00;
65485  b.szCell[b.nCell]++;
65486  }
65487  }
65488  b.nCell++;
65489  }
65490  }
65491 
65492  /*
65493  ** Figure out the number of pages needed to hold all b.nCell cells.
65494  ** Store this number in "k". Also compute szNew[] which is the total
65495  ** size of all cells on the i-th page and cntNew[] which is the index
65496  ** in b.apCell[] of the cell that divides page i from page i+1.
65497  ** cntNew[k] should equal b.nCell.
65498  **
65499  ** Values computed by this block:
65500  **
65501  ** k: The total number of sibling pages
65502  ** szNew[i]: Spaced used on the i-th sibling page.
65503  ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
65504  ** the right of the i-th sibling page.
65505  ** usableSpace: Number of bytes of space available on each sibling.
65506  **
65507  */
65508  usableSpace = pBt->usableSize - 12 + leafCorrection;
65509  for(i=0; i<nOld; i++){
65510  MemPage *p = apOld[i];
65511  szNew[i] = usableSpace - p->nFree;
65512  if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65513  for(j=0; j<p->nOverflow; j++){
65514  szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
65515  }
65516  cntNew[i] = cntOld[i];
65517  }
65518  k = nOld;
65519  for(i=0; i<k; i++){
65520  int sz;
65521  while( szNew[i]>usableSpace ){
65522  if( i+1>=k ){
65523  k = i+2;
65524  if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65525  szNew[k-1] = 0;
65526  cntNew[k-1] = b.nCell;
65527  }
65528  sz = 2 + cachedCellSize(&b, cntNew[i]-1);
65529  szNew[i] -= sz;
65530  if( !leafData ){
65531  if( cntNew[i]<b.nCell ){
65532  sz = 2 + cachedCellSize(&b, cntNew[i]);
65533  }else{
65534  sz = 0;
65535  }
65536  }
65537  szNew[i+1] += sz;
65538  cntNew[i]--;
65539  }
65540  while( cntNew[i]<b.nCell ){
65541  sz = 2 + cachedCellSize(&b, cntNew[i]);
65542  if( szNew[i]+sz>usableSpace ) break;
65543  szNew[i] += sz;
65544  cntNew[i]++;
65545  if( !leafData ){
65546  if( cntNew[i]<b.nCell ){
65547  sz = 2 + cachedCellSize(&b, cntNew[i]);
65548  }else{
65549  sz = 0;
65550  }
65551  }
65552  szNew[i+1] -= sz;
65553  }
65554  if( cntNew[i]>=b.nCell ){
65555  k = i+1;
65556  }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
65557  rc = SQLITE_CORRUPT_BKPT;
65558  goto balance_cleanup;
65559  }
65560  }
65561 
65562  /*
65563  ** The packing computed by the previous block is biased toward the siblings
65564  ** on the left side (siblings with smaller keys). The left siblings are
65565  ** always nearly full, while the right-most sibling might be nearly empty.
65566  ** The next block of code attempts to adjust the packing of siblings to
65567  ** get a better balance.
65568  **
65569  ** This adjustment is more than an optimization. The packing above might
65570  ** be so out of balance as to be illegal. For example, the right-most
65571  ** sibling might be completely empty. This adjustment is not optional.
65572  */
65573  for(i=k-1; i>0; i--){
65574  int szRight = szNew[i]; /* Size of sibling on the right */
65575  int szLeft = szNew[i-1]; /* Size of sibling on the left */
65576  int r; /* Index of right-most cell in left sibling */
65577  int d; /* Index of first cell to the left of right sibling */
65578 
65579  r = cntNew[i-1] - 1;
65580  d = r + 1 - leafData;
65581  (void)cachedCellSize(&b, d);
65582  do{
65583  assert( d<nMaxCells );
65584  assert( r<nMaxCells );
65585  (void)cachedCellSize(&b, r);
65586  if( szRight!=0
65587  && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
65588  break;
65589  }
65590  szRight += b.szCell[d] + 2;
65591  szLeft -= b.szCell[r] + 2;
65592  cntNew[i-1] = r;
65593  r--;
65594  d--;
65595  }while( r>=0 );
65596  szNew[i] = szRight;
65597  szNew[i-1] = szLeft;
65598  if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
65599  rc = SQLITE_CORRUPT_BKPT;
65600  goto balance_cleanup;
65601  }
65602  }
65603 
65604  /* Sanity check: For a non-corrupt database file one of the follwing
65605  ** must be true:
65606  ** (1) We found one or more cells (cntNew[0])>0), or
65607  ** (2) pPage is a virtual root page. A virtual root page is when
65608  ** the real root page is page 1 and we are the only child of
65609  ** that page.
65610  */
65611  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
65612  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
65613  apOld[0]->pgno, apOld[0]->nCell,
65614  nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
65615  nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
65616  ));
65617 
65618  /*
65619  ** Allocate k new pages. Reuse old pages where possible.
65620  */
65621  pageFlags = apOld[0]->aData[0];
65622  for(i=0; i<k; i++){
65623  MemPage *pNew;
65624  if( i<nOld ){
65625  pNew = apNew[i] = apOld[i];
65626  apOld[i] = 0;
65627  rc = sqlite3PagerWrite(pNew->pDbPage);
65628  nNew++;
65629  if( rc ) goto balance_cleanup;
65630  }else{
65631  assert( i>0 );
65632  rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
65633  if( rc ) goto balance_cleanup;
65634  zeroPage(pNew, pageFlags);
65635  apNew[i] = pNew;
65636  nNew++;
65637  cntOld[i] = b.nCell;
65638 
65639  /* Set the pointer-map entry for the new sibling page. */
65640  if( ISAUTOVACUUM ){
65641  ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
65642  if( rc!=SQLITE_OK ){
65643  goto balance_cleanup;
65644  }
65645  }
65646  }
65647  }
65648 
65649  /*
65650  ** Reassign page numbers so that the new pages are in ascending order.
65651  ** This helps to keep entries in the disk file in order so that a scan
65652  ** of the table is closer to a linear scan through the file. That in turn
65653  ** helps the operating system to deliver pages from the disk more rapidly.
65654  **
65655  ** An O(n^2) insertion sort algorithm is used, but since n is never more
65656  ** than (NB+2) (a small constant), that should not be a problem.
65657  **
65658  ** When NB==3, this one optimization makes the database about 25% faster
65659  ** for large insertions and deletions.
65660  */
65661  for(i=0; i<nNew; i++){
65662  aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
65663  aPgFlags[i] = apNew[i]->pDbPage->flags;
65664  for(j=0; j<i; j++){
65665  if( aPgno[j]==aPgno[i] ){
65666  /* This branch is taken if the set of sibling pages somehow contains
65667  ** duplicate entries. This can happen if the database is corrupt.
65668  ** It would be simpler to detect this as part of the loop below, but
65669  ** we do the detection here in order to avoid populating the pager
65670  ** cache with two separate objects associated with the same
65671  ** page number. */
65672  assert( CORRUPT_DB );
65673  rc = SQLITE_CORRUPT_BKPT;
65674  goto balance_cleanup;
65675  }
65676  }
65677  }
65678  for(i=0; i<nNew; i++){
65679  int iBest = 0; /* aPgno[] index of page number to use */
65680  for(j=1; j<nNew; j++){
65681  if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
65682  }
65683  pgno = aPgOrder[iBest];
65684  aPgOrder[iBest] = 0xffffffff;
65685  if( iBest!=i ){
65686  if( iBest>i ){
65687  sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
65688  }
65689  sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
65690  apNew[i]->pgno = pgno;
65691  }
65692  }
65693 
65694  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
65695  "%d(%d nc=%d) %d(%d nc=%d)\n",
65696  apNew[0]->pgno, szNew[0], cntNew[0],
65697  nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
65698  nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
65699  nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
65700  nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
65701  nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
65702  nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
65703  nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
65704  nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
65705  ));
65706 
65707  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65708  put4byte(pRight, apNew[nNew-1]->pgno);
65709 
65710  /* If the sibling pages are not leaves, ensure that the right-child pointer
65711  ** of the right-most new sibling page is set to the value that was
65712  ** originally in the same field of the right-most old sibling page. */
65713  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
65714  MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
65715  memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
65716  }
65717 
65718  /* Make any required updates to pointer map entries associated with
65719  ** cells stored on sibling pages following the balance operation. Pointer
65720  ** map entries associated with divider cells are set by the insertCell()
65721  ** routine. The associated pointer map entries are:
65722  **
65723  ** a) if the cell contains a reference to an overflow chain, the
65724  ** entry associated with the first page in the overflow chain, and
65725  **
65726  ** b) if the sibling pages are not leaves, the child page associated
65727  ** with the cell.
65728  **
65729  ** If the sibling pages are not leaves, then the pointer map entry
65730  ** associated with the right-child of each sibling may also need to be
65731  ** updated. This happens below, after the sibling pages have been
65732  ** populated, not here.
65733  */
65734  if( ISAUTOVACUUM ){
65735  MemPage *pNew = apNew[0];
65736  u8 *aOld = pNew->aData;
65737  int cntOldNext = pNew->nCell + pNew->nOverflow;
65738  int usableSize = pBt->usableSize;
65739  int iNew = 0;
65740  int iOld = 0;
65741 
65742  for(i=0; i<b.nCell; i++){
65743  u8 *pCell = b.apCell[i];
65744  if( i==cntOldNext ){
65745  MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
65746  cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
65747  aOld = pOld->aData;
65748  }
65749  if( i==cntNew[iNew] ){
65750  pNew = apNew[++iNew];
65751  if( !leafData ) continue;
65752  }
65753 
65754  /* Cell pCell is destined for new sibling page pNew. Originally, it
65755  ** was either part of sibling page iOld (possibly an overflow cell),
65756  ** or else the divider cell to the left of sibling page iOld. So,
65757  ** if sibling page iOld had the same page number as pNew, and if
65758  ** pCell really was a part of sibling page iOld (not a divider or
65759  ** overflow cell), we can skip updating the pointer map entries. */
65760  if( iOld>=nNew
65761  || pNew->pgno!=aPgno[iOld]
65762  || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
65763  ){
65764  if( !leafCorrection ){
65765  ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
65766  }
65767  if( cachedCellSize(&b,i)>pNew->minLocal ){
65768  ptrmapPutOvflPtr(pNew, pCell, &rc);
65769  }
65770  if( rc ) goto balance_cleanup;
65771  }
65772  }
65773  }
65774 
65775  /* Insert new divider cells into pParent. */
65776  for(i=0; i<nNew-1; i++){
65777  u8 *pCell;
65778  u8 *pTemp;
65779  int sz;
65780  MemPage *pNew = apNew[i];
65781  j = cntNew[i];
65782 
65783  assert( j<nMaxCells );
65784  assert( b.apCell[j]!=0 );
65785  pCell = b.apCell[j];
65786  sz = b.szCell[j] + leafCorrection;
65787  pTemp = &aOvflSpace[iOvflSpace];
65788  if( !pNew->leaf ){
65789  memcpy(&pNew->aData[8], pCell, 4);
65790  }else if( leafData ){
65791  /* If the tree is a leaf-data tree, and the siblings are leaves,
65792  ** then there is no divider cell in b.apCell[]. Instead, the divider
65793  ** cell consists of the integer key for the right-most cell of
65794  ** the sibling-page assembled above only.
65795  */
65796  CellInfo info;
65797  j--;
65798  pNew->xParseCell(pNew, b.apCell[j], &info);
65799  pCell = pTemp;
65800  sz = 4 + putVarint(&pCell[4], info.nKey);
65801  pTemp = 0;
65802  }else{
65803  pCell -= 4;
65804  /* Obscure case for non-leaf-data trees: If the cell at pCell was
65805  ** previously stored on a leaf node, and its reported size was 4
65806  ** bytes, then it may actually be smaller than this
65807  ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
65808  ** any cell). But it is important to pass the correct size to
65809  ** insertCell(), so reparse the cell now.
65810  **
65811  ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
65812  ** and WITHOUT ROWID tables with exactly one column which is the
65813  ** primary key.
65814  */
65815  if( b.szCell[j]==4 ){
65816  assert(leafCorrection==4);
65817  sz = pParent->xCellSize(pParent, pCell);
65818  }
65819  }
65820  iOvflSpace += sz;
65821  assert( sz<=pBt->maxLocal+23 );
65822  assert( iOvflSpace <= (int)pBt->pageSize );
65823  insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
65824  if( rc!=SQLITE_OK ) goto balance_cleanup;
65825  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65826  }
65827 
65828  /* Now update the actual sibling pages. The order in which they are updated
65829  ** is important, as this code needs to avoid disrupting any page from which
65830  ** cells may still to be read. In practice, this means:
65831  **
65832  ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
65833  ** then it is not safe to update page apNew[iPg] until after
65834  ** the left-hand sibling apNew[iPg-1] has been updated.
65835  **
65836  ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
65837  ** then it is not safe to update page apNew[iPg] until after
65838  ** the right-hand sibling apNew[iPg+1] has been updated.
65839  **
65840  ** If neither of the above apply, the page is safe to update.
65841  **
65842  ** The iPg value in the following loop starts at nNew-1 goes down
65843  ** to 0, then back up to nNew-1 again, thus making two passes over
65844  ** the pages. On the initial downward pass, only condition (1) above
65845  ** needs to be tested because (2) will always be true from the previous
65846  ** step. On the upward pass, both conditions are always true, so the
65847  ** upwards pass simply processes pages that were missed on the downward
65848  ** pass.
65849  */
65850  for(i=1-nNew; i<nNew; i++){
65851  int iPg = i<0 ? -i : i;
65852  assert( iPg>=0 && iPg<nNew );
65853  if( abDone[iPg] ) continue; /* Skip pages already processed */
65854  if( i>=0 /* On the upwards pass, or... */
65855  || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
65856  ){
65857  int iNew;
65858  int iOld;
65859  int nNewCell;
65860 
65861  /* Verify condition (1): If cells are moving left, update iPg
65862  ** only after iPg-1 has already been updated. */
65863  assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
65864 
65865  /* Verify condition (2): If cells are moving right, update iPg
65866  ** only after iPg+1 has already been updated. */
65867  assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
65868 
65869  if( iPg==0 ){
65870  iNew = iOld = 0;
65871  nNewCell = cntNew[0];
65872  }else{
65873  iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
65874  iNew = cntNew[iPg-1] + !leafData;
65875  nNewCell = cntNew[iPg] - iNew;
65876  }
65877 
65878  rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
65879  if( rc ) goto balance_cleanup;
65880  abDone[iPg]++;
65881  apNew[iPg]->nFree = usableSpace-szNew[iPg];
65882  assert( apNew[iPg]->nOverflow==0 );
65883  assert( apNew[iPg]->nCell==nNewCell );
65884  }
65885  }
65886 
65887  /* All pages have been processed exactly once */
65888  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
65889 
65890  assert( nOld>0 );
65891  assert( nNew>0 );
65892 
65893  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
65894  /* The root page of the b-tree now contains no cells. The only sibling
65895  ** page is the right-child of the parent. Copy the contents of the
65896  ** child page into the parent, decreasing the overall height of the
65897  ** b-tree structure by one. This is described as the "balance-shallower"
65898  ** sub-algorithm in some documentation.
65899  **
65900  ** If this is an auto-vacuum database, the call to copyNodeContent()
65901  ** sets all pointer-map entries corresponding to database image pages
65902  ** for which the pointer is stored within the content being copied.
65903  **
65904  ** It is critical that the child page be defragmented before being
65905  ** copied into the parent, because if the parent is page 1 then it will
65906  ** by smaller than the child due to the database header, and so all the
65907  ** free space needs to be up front.
65908  */
65909  assert( nNew==1 || CORRUPT_DB );
65910  rc = defragmentPage(apNew[0]);
65911  testcase( rc!=SQLITE_OK );
65912  assert( apNew[0]->nFree ==
65913  (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
65914  || rc!=SQLITE_OK
65915  );
65916  copyNodeContent(apNew[0], pParent, &rc);
65917  freePage(apNew[0], &rc);
65918  }else if( ISAUTOVACUUM && !leafCorrection ){
65919  /* Fix the pointer map entries associated with the right-child of each
65920  ** sibling page. All other pointer map entries have already been taken
65921  ** care of. */
65922  for(i=0; i<nNew; i++){
65923  u32 key = get4byte(&apNew[i]->aData[8]);
65924  ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
65925  }
65926  }
65927 
65928  assert( pParent->isInit );
65929  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
65930  nOld, nNew, b.nCell));
65931 
65932  /* Free any old pages that were not reused as new pages.
65933  */
65934  for(i=nNew; i<nOld; i++){
65935  freePage(apOld[i], &rc);
65936  }
65937 
65938 #if 0
65939  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
65940  /* The ptrmapCheckPages() contains assert() statements that verify that
65941  ** all pointer map pages are set correctly. This is helpful while
65942  ** debugging. This is usually disabled because a corrupt database may
65943  ** cause an assert() statement to fail. */
65944  ptrmapCheckPages(apNew, nNew);
65945  ptrmapCheckPages(&pParent, 1);
65946  }
65947 #endif
65948 
65949  /*
65950  ** Cleanup before returning.
65951  */
65952 balance_cleanup:
65954  for(i=0; i<nOld; i++){
65955  releasePage(apOld[i]);
65956  }
65957  for(i=0; i<nNew; i++){
65958  releasePage(apNew[i]);
65959  }
65960 
65961  return rc;
65962 }
65963 
65964 
65965 /*
65966 ** This function is called when the root page of a b-tree structure is
65967 ** overfull (has one or more overflow pages).
65968 **
65969 ** A new child page is allocated and the contents of the current root
65970 ** page, including overflow cells, are copied into the child. The root
65971 ** page is then overwritten to make it an empty page with the right-child
65972 ** pointer pointing to the new page.
65973 **
65974 ** Before returning, all pointer-map entries corresponding to pages
65975 ** that the new child-page now contains pointers to are updated. The
65976 ** entry corresponding to the new right-child pointer of the root
65977 ** page is also updated.
65978 **
65979 ** If successful, *ppChild is set to contain a reference to the child
65980 ** page and SQLITE_OK is returned. In this case the caller is required
65981 ** to call releasePage() on *ppChild exactly once. If an error occurs,
65982 ** an error code is returned and *ppChild is set to 0.
65983 */
65984 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
65985  int rc; /* Return value from subprocedures */
65986  MemPage *pChild = 0; /* Pointer to a new child page */
65987  Pgno pgnoChild = 0; /* Page number of the new child page */
65988  BtShared *pBt = pRoot->pBt; /* The BTree */
65989 
65990  assert( pRoot->nOverflow>0 );
65991  assert( sqlite3_mutex_held(pBt->mutex) );
65992 
65993  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
65994  ** page that will become the new right-child of pPage. Copy the contents
65995  ** of the node stored on pRoot into the new child page.
65996  */
65997  rc = sqlite3PagerWrite(pRoot->pDbPage);
65998  if( rc==SQLITE_OK ){
65999  rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
66000  copyNodeContent(pRoot, pChild, &rc);
66001  if( ISAUTOVACUUM ){
66002  ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
66003  }
66004  }
66005  if( rc ){
66006  *ppChild = 0;
66007  releasePage(pChild);
66008  return rc;
66009  }
66010  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
66011  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66012  assert( pChild->nCell==pRoot->nCell );
66013 
66014  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
66015 
66016  /* Copy the overflow cells from pRoot to pChild */
66017  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
66018  pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
66019  memcpy(pChild->apOvfl, pRoot->apOvfl,
66020  pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
66021  pChild->nOverflow = pRoot->nOverflow;
66022 
66023  /* Zero the contents of pRoot. Then install pChild as the right-child. */
66024  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
66025  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
66026 
66027  *ppChild = pChild;
66028  return SQLITE_OK;
66029 }
66030 
66031 /*
66032 ** The page that pCur currently points to has just been modified in
66033 ** some way. This function figures out if this modification means the
66034 ** tree needs to be balanced, and if so calls the appropriate balancing
66035 ** routine. Balancing routines are:
66036 **
66037 ** balance_quick()
66038 ** balance_deeper()
66039 ** balance_nonroot()
66040 */
66041 static int balance(BtCursor *pCur){
66042  int rc = SQLITE_OK;
66043  const int nMin = pCur->pBt->usableSize * 2 / 3;
66044  u8 aBalanceQuickSpace[13];
66045  u8 *pFree = 0;
66046 
66047  VVA_ONLY( int balance_quick_called = 0 );
66048  VVA_ONLY( int balance_deeper_called = 0 );
66049 
66050  do {
66051  int iPage = pCur->iPage;
66052  MemPage *pPage = pCur->apPage[iPage];
66053 
66054  if( iPage==0 ){
66055  if( pPage->nOverflow ){
66056  /* The root page of the b-tree is overfull. In this case call the
66057  ** balance_deeper() function to create a new child for the root-page
66058  ** and copy the current contents of the root-page to it. The
66059  ** next iteration of the do-loop will balance the child page.
66060  */
66061  assert( balance_deeper_called==0 );
66062  VVA_ONLY( balance_deeper_called++ );
66063  rc = balance_deeper(pPage, &pCur->apPage[1]);
66064  if( rc==SQLITE_OK ){
66065  pCur->iPage = 1;
66066  pCur->aiIdx[0] = 0;
66067  pCur->aiIdx[1] = 0;
66068  assert( pCur->apPage[1]->nOverflow );
66069  }
66070  }else{
66071  break;
66072  }
66073  }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
66074  break;
66075  }else{
66076  MemPage * const pParent = pCur->apPage[iPage-1];
66077  int const iIdx = pCur->aiIdx[iPage-1];
66078 
66079  rc = sqlite3PagerWrite(pParent->pDbPage);
66080  if( rc==SQLITE_OK ){
66081 #ifndef SQLITE_OMIT_QUICKBALANCE
66082  if( pPage->intKeyLeaf
66083  && pPage->nOverflow==1
66084  && pPage->aiOvfl[0]==pPage->nCell
66085  && pParent->pgno!=1
66086  && pParent->nCell==iIdx
66087  ){
66088  /* Call balance_quick() to create a new sibling of pPage on which
66089  ** to store the overflow cell. balance_quick() inserts a new cell
66090  ** into pParent, which may cause pParent overflow. If this
66091  ** happens, the next iteration of the do-loop will balance pParent
66092  ** use either balance_nonroot() or balance_deeper(). Until this
66093  ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
66094  ** buffer.
66095  **
66096  ** The purpose of the following assert() is to check that only a
66097  ** single call to balance_quick() is made for each call to this
66098  ** function. If this were not verified, a subtle bug involving reuse
66099  ** of the aBalanceQuickSpace[] might sneak in.
66100  */
66101  assert( balance_quick_called==0 );
66102  VVA_ONLY( balance_quick_called++ );
66103  rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
66104  }else
66105 #endif
66106  {
66107  /* In this case, call balance_nonroot() to redistribute cells
66108  ** between pPage and up to 2 of its sibling pages. This involves
66109  ** modifying the contents of pParent, which may cause pParent to
66110  ** become overfull or underfull. The next iteration of the do-loop
66111  ** will balance the parent page to correct this.
66112  **
66113  ** If the parent page becomes overfull, the overflow cell or cells
66114  ** are stored in the pSpace buffer allocated immediately below.
66115  ** A subsequent iteration of the do-loop will deal with this by
66116  ** calling balance_nonroot() (balance_deeper() may be called first,
66117  ** but it doesn't deal with overflow cells - just moves them to a
66118  ** different page). Once this subsequent call to balance_nonroot()
66119  ** has completed, it is safe to release the pSpace buffer used by
66120  ** the previous call, as the overflow cell data will have been
66121  ** copied either into the body of a database page or into the new
66122  ** pSpace buffer passed to the latter call to balance_nonroot().
66123  */
66124  u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
66125  rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
66126  pCur->hints&BTREE_BULKLOAD);
66127  if( pFree ){
66128  /* If pFree is not NULL, it points to the pSpace buffer used
66129  ** by a previous call to balance_nonroot(). Its contents are
66130  ** now stored either on real database pages or within the
66131  ** new pSpace buffer, so it may be safely freed here. */
66132  sqlite3PageFree(pFree);
66133  }
66134 
66135  /* The pSpace buffer will be freed after the next call to
66136  ** balance_nonroot(), or just before this function returns, whichever
66137  ** comes first. */
66138  pFree = pSpace;
66139  }
66140  }
66141 
66142  pPage->nOverflow = 0;
66143 
66144  /* The next iteration of the do-loop balances the parent page. */
66145  releasePage(pPage);
66146  pCur->iPage--;
66147  assert( pCur->iPage>=0 );
66148  }
66149  }while( rc==SQLITE_OK );
66150 
66151  if( pFree ){
66152  sqlite3PageFree(pFree);
66153  }
66154  return rc;
66155 }
66156 
66157 
66158 /*
66159 ** Insert a new record into the BTree. The content of the new record
66160 ** is described by the pX object. The pCur cursor is used only to
66161 ** define what table the record should be inserted into, and is left
66162 ** pointing at a random location.
66163 **
66164 ** For a table btree (used for rowid tables), only the pX.nKey value of
66165 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
66166 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
66167 ** hold the content of the row.
66168 **
66169 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
66170 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
66171 ** pX.pData,nData,nZero fields must be zero.
66172 **
66173 ** If the seekResult parameter is non-zero, then a successful call to
66174 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
66175 ** been performed. seekResult is the search result returned (a negative
66176 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
66177 ** a positive value if pCur points at an entry that is larger than
66178 ** (pKey, nKey)).
66179 **
66180 ** If the seekResult parameter is non-zero, then the caller guarantees that
66181 ** cursor pCur is pointing at the existing copy of a row that is to be
66182 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
66183 ** point to any entry or to no entry at all and so this function has to seek
66184 ** the cursor before the new key can be inserted.
66185 */
66187  BtCursor *pCur, /* Insert data into the table of this cursor */
66188  const BtreePayload *pX, /* Content of the row to be inserted */
66189  int appendBias, /* True if this is likely an append */
66190  int seekResult /* Result of prior MovetoUnpacked() call */
66191 ){
66192  int rc;
66193  int loc = seekResult; /* -1: before desired location +1: after */
66194  int szNew = 0;
66195  int idx;
66196  MemPage *pPage;
66197  Btree *p = pCur->pBtree;
66198  BtShared *pBt = p->pBt;
66199  unsigned char *oldCell;
66200  unsigned char *newCell = 0;
66201 
66202  if( pCur->eState==CURSOR_FAULT ){
66203  assert( pCur->skipNext!=SQLITE_OK );
66204  return pCur->skipNext;
66205  }
66206 
66207  assert( cursorOwnsBtShared(pCur) );
66208  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
66209  && pBt->inTransaction==TRANS_WRITE
66210  && (pBt->btsFlags & BTS_READ_ONLY)==0 );
66211  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66212 
66213  /* Assert that the caller has been consistent. If this cursor was opened
66214  ** expecting an index b-tree, then the caller should be inserting blob
66215  ** keys with no associated data. If the cursor was opened expecting an
66216  ** intkey table, the caller should be inserting integer keys with a
66217  ** blob of associated data. */
66218  assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
66219 
66220  /* Save the positions of any other cursors open on this table.
66221  **
66222  ** In some cases, the call to btreeMoveto() below is a no-op. For
66223  ** example, when inserting data into a table with auto-generated integer
66224  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
66225  ** integer key to use. It then calls this function to actually insert the
66226  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
66227  ** that the cursor is already where it needs to be and returns without
66228  ** doing any work. To avoid thwarting these optimizations, it is important
66229  ** not to clear the cursor here.
66230  */
66231  if( pCur->curFlags & BTCF_Multiple ){
66232  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66233  if( rc ) return rc;
66234  }
66235 
66236  if( pCur->pKeyInfo==0 ){
66237  assert( pX->pKey==0 );
66238  /* If this is an insert into a table b-tree, invalidate any incrblob
66239  ** cursors open on the row being replaced */
66240  invalidateIncrblobCursors(p, pX->nKey, 0);
66241 
66242  /* If the cursor is currently on the last row and we are appending a
66243  ** new row onto the end, set the "loc" to avoid an unnecessary
66244  ** btreeMoveto() call */
66245  if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0
66246  && pCur->info.nKey==pX->nKey-1 ){
66247  loc = -1;
66248  }else if( loc==0 ){
66249  rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, appendBias, &loc);
66250  if( rc ) return rc;
66251  }
66252  }else if( loc==0 ){
66253  rc = btreeMoveto(pCur, pX->pKey, pX->nKey, appendBias, &loc);
66254  if( rc ) return rc;
66255  }
66256  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
66257 
66258  pPage = pCur->apPage[pCur->iPage];
66259  assert( pPage->intKey || pX->nKey>=0 );
66260  assert( pPage->leaf || !pPage->intKey );
66261 
66262  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
66263  pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
66264  loc==0 ? "overwrite" : "new entry"));
66265  assert( pPage->isInit );
66266  newCell = pBt->pTmpSpace;
66267  assert( newCell!=0 );
66268  rc = fillInCell(pPage, newCell, pX, &szNew);
66269  if( rc ) goto end_insert;
66270  assert( szNew==pPage->xCellSize(pPage, newCell) );
66271  assert( szNew <= MX_CELL_SIZE(pBt) );
66272  idx = pCur->aiIdx[pCur->iPage];
66273  if( loc==0 ){
66274  u16 szOld;
66275  assert( idx<pPage->nCell );
66276  rc = sqlite3PagerWrite(pPage->pDbPage);
66277  if( rc ){
66278  goto end_insert;
66279  }
66280  oldCell = findCell(pPage, idx);
66281  if( !pPage->leaf ){
66282  memcpy(newCell, oldCell, 4);
66283  }
66284  rc = clearCell(pPage, oldCell, &szOld);
66285  dropCell(pPage, idx, szOld, &rc);
66286  if( rc ) goto end_insert;
66287  }else if( loc<0 && pPage->nCell>0 ){
66288  assert( pPage->leaf );
66289  idx = ++pCur->aiIdx[pCur->iPage];
66290  }else{
66291  assert( pPage->leaf );
66292  }
66293  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
66294  assert( pPage->nOverflow==0 || rc==SQLITE_OK );
66295  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
66296 
66297  /* If no error has occurred and pPage has an overflow cell, call balance()
66298  ** to redistribute the cells within the tree. Since balance() may move
66299  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
66300  ** variables.
66301  **
66302  ** Previous versions of SQLite called moveToRoot() to move the cursor
66303  ** back to the root page as balance() used to invalidate the contents
66304  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
66305  ** set the cursor state to "invalid". This makes common insert operations
66306  ** slightly faster.
66307  **
66308  ** There is a subtle but important optimization here too. When inserting
66309  ** multiple records into an intkey b-tree using a single cursor (as can
66310  ** happen while processing an "INSERT INTO ... SELECT" statement), it
66311  ** is advantageous to leave the cursor pointing to the last entry in
66312  ** the b-tree if possible. If the cursor is left pointing to the last
66313  ** entry in the table, and the next row inserted has an integer key
66314  ** larger than the largest existing key, it is possible to insert the
66315  ** row without seeking the cursor. This can be a big performance boost.
66316  */
66317  pCur->info.nSize = 0;
66318  if( pPage->nOverflow ){
66319  assert( rc==SQLITE_OK );
66320  pCur->curFlags &= ~(BTCF_ValidNKey);
66321  rc = balance(pCur);
66322 
66323  /* Must make sure nOverflow is reset to zero even if the balance()
66324  ** fails. Internal data structure corruption will result otherwise.
66325  ** Also, set the cursor state to invalid. This stops saveCursorPosition()
66326  ** from trying to save the current position of the cursor. */
66327  pCur->apPage[pCur->iPage]->nOverflow = 0;
66328  pCur->eState = CURSOR_INVALID;
66329  }
66330  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
66331 
66332 end_insert:
66333  return rc;
66334 }
66335 
66336 /*
66337 ** Delete the entry that the cursor is pointing to.
66338 **
66339 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
66340 ** the cursor is left pointing at an arbitrary location after the delete.
66341 ** But if that bit is set, then the cursor is left in a state such that
66342 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
66343 ** as it would have been on if the call to BtreeDelete() had been omitted.
66344 **
66345 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
66346 ** associated with a single table entry and its indexes. Only one of those
66347 ** deletes is considered the "primary" delete. The primary delete occurs
66348 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
66349 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
66350 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
66351 ** but which might be used by alternative storage engines.
66352 */
66354  Btree *p = pCur->pBtree;
66355  BtShared *pBt = p->pBt;
66356  int rc; /* Return code */
66357  MemPage *pPage; /* Page to delete cell from */
66358  unsigned char *pCell; /* Pointer to cell to delete */
66359  int iCellIdx; /* Index of cell to delete */
66360  int iCellDepth; /* Depth of node containing pCell */
66361  u16 szCell; /* Size of the cell being deleted */
66362  int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
66363  u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
66364 
66365  assert( cursorOwnsBtShared(pCur) );
66366  assert( pBt->inTransaction==TRANS_WRITE );
66367  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66368  assert( pCur->curFlags & BTCF_WriteFlag );
66369  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66370  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
66371  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
66372  assert( pCur->eState==CURSOR_VALID );
66373  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
66374 
66375  iCellDepth = pCur->iPage;
66376  iCellIdx = pCur->aiIdx[iCellDepth];
66377  pPage = pCur->apPage[iCellDepth];
66378  pCell = findCell(pPage, iCellIdx);
66379 
66380  /* If the bPreserve flag is set to true, then the cursor position must
66381  ** be preserved following this delete operation. If the current delete
66382  ** will cause a b-tree rebalance, then this is done by saving the cursor
66383  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
66384  ** returning.
66385  **
66386  ** Or, if the current delete will not cause a rebalance, then the cursor
66387  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
66388  ** before or after the deleted entry. In this case set bSkipnext to true. */
66389  if( bPreserve ){
66390  if( !pPage->leaf
66391  || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
66392  ){
66393  /* A b-tree rebalance will be required after deleting this entry.
66394  ** Save the cursor key. */
66395  rc = saveCursorKey(pCur);
66396  if( rc ) return rc;
66397  }else{
66398  bSkipnext = 1;
66399  }
66400  }
66401 
66402  /* If the page containing the entry to delete is not a leaf page, move
66403  ** the cursor to the largest entry in the tree that is smaller than
66404  ** the entry being deleted. This cell will replace the cell being deleted
66405  ** from the internal node. The 'previous' entry is used for this instead
66406  ** of the 'next' entry, as the previous entry is always a part of the
66407  ** sub-tree headed by the child page of the cell being deleted. This makes
66408  ** balancing the tree following the delete operation easier. */
66409  if( !pPage->leaf ){
66410  int notUsed = 0;
66411  rc = sqlite3BtreePrevious(pCur, &notUsed);
66412  if( rc ) return rc;
66413  }
66414 
66415  /* Save the positions of any other cursors open on this table before
66416  ** making any modifications. */
66417  if( pCur->curFlags & BTCF_Multiple ){
66418  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66419  if( rc ) return rc;
66420  }
66421 
66422  /* If this is a delete operation to remove a row from a table b-tree,
66423  ** invalidate any incrblob cursors open on the row being deleted. */
66424  if( pCur->pKeyInfo==0 ){
66425  invalidateIncrblobCursors(p, pCur->info.nKey, 0);
66426  }
66427 
66428  /* Make the page containing the entry to be deleted writable. Then free any
66429  ** overflow pages associated with the entry and finally remove the cell
66430  ** itself from within the page. */
66431  rc = sqlite3PagerWrite(pPage->pDbPage);
66432  if( rc ) return rc;
66433  rc = clearCell(pPage, pCell, &szCell);
66434  dropCell(pPage, iCellIdx, szCell, &rc);
66435  if( rc ) return rc;
66436 
66437  /* If the cell deleted was not located on a leaf page, then the cursor
66438  ** is currently pointing to the largest entry in the sub-tree headed
66439  ** by the child-page of the cell that was just deleted from an internal
66440  ** node. The cell from the leaf node needs to be moved to the internal
66441  ** node to replace the deleted cell. */
66442  if( !pPage->leaf ){
66443  MemPage *pLeaf = pCur->apPage[pCur->iPage];
66444  int nCell;
66445  Pgno n = pCur->apPage[iCellDepth+1]->pgno;
66446  unsigned char *pTmp;
66447 
66448  pCell = findCell(pLeaf, pLeaf->nCell-1);
66449  if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
66450  nCell = pLeaf->xCellSize(pLeaf, pCell);
66451  assert( MX_CELL_SIZE(pBt) >= nCell );
66452  pTmp = pBt->pTmpSpace;
66453  assert( pTmp!=0 );
66454  rc = sqlite3PagerWrite(pLeaf->pDbPage);
66455  if( rc==SQLITE_OK ){
66456  insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
66457  }
66458  dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
66459  if( rc ) return rc;
66460  }
66461 
66462  /* Balance the tree. If the entry deleted was located on a leaf page,
66463  ** then the cursor still points to that page. In this case the first
66464  ** call to balance() repairs the tree, and the if(...) condition is
66465  ** never true.
66466  **
66467  ** Otherwise, if the entry deleted was on an internal node page, then
66468  ** pCur is pointing to the leaf page from which a cell was removed to
66469  ** replace the cell deleted from the internal node. This is slightly
66470  ** tricky as the leaf node may be underfull, and the internal node may
66471  ** be either under or overfull. In this case run the balancing algorithm
66472  ** on the leaf node first. If the balance proceeds far enough up the
66473  ** tree that we can be sure that any problem in the internal node has
66474  ** been corrected, so be it. Otherwise, after balancing the leaf node,
66475  ** walk the cursor up the tree to the internal node and balance it as
66476  ** well. */
66477  rc = balance(pCur);
66478  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
66479  while( pCur->iPage>iCellDepth ){
66480  releasePage(pCur->apPage[pCur->iPage--]);
66481  }
66482  rc = balance(pCur);
66483  }
66484 
66485  if( rc==SQLITE_OK ){
66486  if( bSkipnext ){
66487  assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
66488  assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
66489  assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
66490  pCur->eState = CURSOR_SKIPNEXT;
66491  if( iCellIdx>=pPage->nCell ){
66492  pCur->skipNext = -1;
66493  pCur->aiIdx[iCellDepth] = pPage->nCell-1;
66494  }else{
66495  pCur->skipNext = 1;
66496  }
66497  }else{
66498  rc = moveToRoot(pCur);
66499  if( bPreserve ){
66500  pCur->eState = CURSOR_REQUIRESEEK;
66501  }
66502  }
66503  }
66504  return rc;
66505 }
66506 
66507 /*
66508 ** Create a new BTree table. Write into *piTable the page
66509 ** number for the root page of the new table.
66510 **
66511 ** The type of type is determined by the flags parameter. Only the
66512 ** following values of flags are currently in use. Other values for
66513 ** flags might not work:
66514 **
66515 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
66516 ** BTREE_ZERODATA Used for SQL indices
66517 */
66518 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
66519  BtShared *pBt = p->pBt;
66520  MemPage *pRoot;
66521  Pgno pgnoRoot;
66522  int rc;
66523  int ptfFlags; /* Page-type flage for the root page of new table */
66524 
66525  assert( sqlite3BtreeHoldsMutex(p) );
66526  assert( pBt->inTransaction==TRANS_WRITE );
66527  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66528 
66529 #ifdef SQLITE_OMIT_AUTOVACUUM
66530  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66531  if( rc ){
66532  return rc;
66533  }
66534 #else
66535  if( pBt->autoVacuum ){
66536  Pgno pgnoMove; /* Move a page here to make room for the root-page */
66537  MemPage *pPageMove; /* The page to move to. */
66538 
66539  /* Creating a new table may probably require moving an existing database
66540  ** to make room for the new tables root page. In case this page turns
66541  ** out to be an overflow page, delete all overflow page-map caches
66542  ** held by open cursors.
66543  */
66545 
66546  /* Read the value of meta[3] from the database to determine where the
66547  ** root page of the new table should go. meta[3] is the largest root-page
66548  ** created so far, so the new root-page is (meta[3]+1).
66549  */
66551  pgnoRoot++;
66552 
66553  /* The new root-page may not be allocated on a pointer-map page, or the
66554  ** PENDING_BYTE page.
66555  */
66556  while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
66557  pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
66558  pgnoRoot++;
66559  }
66560  assert( pgnoRoot>=3 || CORRUPT_DB );
66561  testcase( pgnoRoot<3 );
66562 
66563  /* Allocate a page. The page that currently resides at pgnoRoot will
66564  ** be moved to the allocated page (unless the allocated page happens
66565  ** to reside at pgnoRoot).
66566  */
66567  rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
66568  if( rc!=SQLITE_OK ){
66569  return rc;
66570  }
66571 
66572  if( pgnoMove!=pgnoRoot ){
66573  /* pgnoRoot is the page that will be used for the root-page of
66574  ** the new table (assuming an error did not occur). But we were
66575  ** allocated pgnoMove. If required (i.e. if it was not allocated
66576  ** by extending the file), the current page at position pgnoMove
66577  ** is already journaled.
66578  */
66579  u8 eType = 0;
66580  Pgno iPtrPage = 0;
66581 
66582  /* Save the positions of any open cursors. This is required in
66583  ** case they are holding a reference to an xFetch reference
66584  ** corresponding to page pgnoRoot. */
66585  rc = saveAllCursors(pBt, 0, 0);
66586  releasePage(pPageMove);
66587  if( rc!=SQLITE_OK ){
66588  return rc;
66589  }
66590 
66591  /* Move the page currently at pgnoRoot to pgnoMove. */
66592  rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66593  if( rc!=SQLITE_OK ){
66594  return rc;
66595  }
66596  rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
66597  if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
66598  rc = SQLITE_CORRUPT_BKPT;
66599  }
66600  if( rc!=SQLITE_OK ){
66601  releasePage(pRoot);
66602  return rc;
66603  }
66604  assert( eType!=PTRMAP_ROOTPAGE );
66605  assert( eType!=PTRMAP_FREEPAGE );
66606  rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
66607  releasePage(pRoot);
66608 
66609  /* Obtain the page at pgnoRoot */
66610  if( rc!=SQLITE_OK ){
66611  return rc;
66612  }
66613  rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66614  if( rc!=SQLITE_OK ){
66615  return rc;
66616  }
66617  rc = sqlite3PagerWrite(pRoot->pDbPage);
66618  if( rc!=SQLITE_OK ){
66619  releasePage(pRoot);
66620  return rc;
66621  }
66622  }else{
66623  pRoot = pPageMove;
66624  }
66625 
66626  /* Update the pointer-map and meta-data with the new root-page number. */
66627  ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
66628  if( rc ){
66629  releasePage(pRoot);
66630  return rc;
66631  }
66632 
66633  /* When the new root page was allocated, page 1 was made writable in
66634  ** order either to increase the database filesize, or to decrement the
66635  ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
66636  */
66637  assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
66638  rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
66639  if( NEVER(rc) ){
66640  releasePage(pRoot);
66641  return rc;
66642  }
66643 
66644  }else{
66645  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66646  if( rc ) return rc;
66647  }
66648 #endif
66649  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66650  if( createTabFlags & BTREE_INTKEY ){
66651  ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
66652  }else{
66653  ptfFlags = PTF_ZERODATA | PTF_LEAF;
66654  }
66655  zeroPage(pRoot, ptfFlags);
66656  sqlite3PagerUnref(pRoot->pDbPage);
66657  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
66658  *piTable = (int)pgnoRoot;
66659  return SQLITE_OK;
66660 }
66661 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
66662  int rc;
66663  sqlite3BtreeEnter(p);
66664  rc = btreeCreateTable(p, piTable, flags);
66665  sqlite3BtreeLeave(p);
66666  return rc;
66667 }
66668 
66669 /*
66670 ** Erase the given database page and all its children. Return
66671 ** the page to the freelist.
66672 */
66674  BtShared *pBt, /* The BTree that contains the table */
66675  Pgno pgno, /* Page number to clear */
66676  int freePageFlag, /* Deallocate page if true */
66677  int *pnChange /* Add number of Cells freed to this counter */
66678 ){
66679  MemPage *pPage;
66680  int rc;
66681  unsigned char *pCell;
66682  int i;
66683  int hdr;
66684  u16 szCell;
66685 
66686  assert( sqlite3_mutex_held(pBt->mutex) );
66687  if( pgno>btreePagecount(pBt) ){
66688  return SQLITE_CORRUPT_BKPT;
66689  }
66690  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
66691  if( rc ) return rc;
66692  if( pPage->bBusy ){
66693  rc = SQLITE_CORRUPT_BKPT;
66694  goto cleardatabasepage_out;
66695  }
66696  pPage->bBusy = 1;
66697  hdr = pPage->hdrOffset;
66698  for(i=0; i<pPage->nCell; i++){
66699  pCell = findCell(pPage, i);
66700  if( !pPage->leaf ){
66701  rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
66702  if( rc ) goto cleardatabasepage_out;
66703  }
66704  rc = clearCell(pPage, pCell, &szCell);
66705  if( rc ) goto cleardatabasepage_out;
66706  }
66707  if( !pPage->leaf ){
66708  rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
66709  if( rc ) goto cleardatabasepage_out;
66710  }else if( pnChange ){
66711  assert( pPage->intKey || CORRUPT_DB );
66712  testcase( !pPage->intKey );
66713  *pnChange += pPage->nCell;
66714  }
66715  if( freePageFlag ){
66716  freePage(pPage, &rc);
66717  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
66718  zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
66719  }
66720 
66721 cleardatabasepage_out:
66722  pPage->bBusy = 0;
66723  releasePage(pPage);
66724  return rc;
66725 }
66726 
66727 /*
66728 ** Delete all information from a single table in the database. iTable is
66729 ** the page number of the root of the table. After this routine returns,
66730 ** the root page is empty, but still exists.
66731 **
66732 ** This routine will fail with SQLITE_LOCKED if there are any open
66733 ** read cursors on the table. Open write cursors are moved to the
66734 ** root of the table.
66735 **
66736 ** If pnChange is not NULL, then table iTable must be an intkey table. The
66737 ** integer value pointed to by pnChange is incremented by the number of
66738 ** entries in the table.
66739 */
66740 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
66741  int rc;
66742  BtShared *pBt = p->pBt;
66743  sqlite3BtreeEnter(p);
66744  assert( p->inTrans==TRANS_WRITE );
66745 
66746  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
66747 
66748  if( SQLITE_OK==rc ){
66749  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
66750  ** is the root of a table b-tree - if it is not, the following call is
66751  ** a no-op). */
66752  invalidateIncrblobCursors(p, 0, 1);
66753  rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
66754  }
66755  sqlite3BtreeLeave(p);
66756  return rc;
66757 }
66758 
66759 /*
66760 ** Delete all information from the single table that pCur is open on.
66761 **
66762 ** This routine only work for pCur on an ephemeral table.
66763 */
66765  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
66766 }
66767 
66768 /*
66769 ** Erase all information in a table and add the root of the table to
66770 ** the freelist. Except, the root of the principle table (the one on
66771 ** page 1) is never added to the freelist.
66772 **
66773 ** This routine will fail with SQLITE_LOCKED if there are any open
66774 ** cursors on the table.
66775 **
66776 ** If AUTOVACUUM is enabled and the page at iTable is not the last
66777 ** root page in the database file, then the last root page
66778 ** in the database file is moved into the slot formerly occupied by
66779 ** iTable and that last slot formerly occupied by the last root page
66780 ** is added to the freelist instead of iTable. In this say, all
66781 ** root pages are kept at the beginning of the database file, which
66782 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
66783 ** page number that used to be the last root page in the file before
66784 ** the move. If no page gets moved, *piMoved is set to 0.
66785 ** The last root page is recorded in meta[3] and the value of
66786 ** meta[3] is updated by this procedure.
66787 */
66788 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
66789  int rc;
66790  MemPage *pPage = 0;
66791  BtShared *pBt = p->pBt;
66792 
66793  assert( sqlite3BtreeHoldsMutex(p) );
66794  assert( p->inTrans==TRANS_WRITE );
66795 
66796  /* It is illegal to drop a table if any cursors are open on the
66797  ** database. This is because in auto-vacuum mode the backend may
66798  ** need to move another root-page to fill a gap left by the deleted
66799  ** root page. If an open cursor was using this page a problem would
66800  ** occur.
66801  **
66802  ** This error is caught long before control reaches this point.
66803  */
66804  if( NEVER(pBt->pCursor) ){
66807  }
66808 
66809  /*
66810  ** It is illegal to drop the sqlite_master table on page 1. But again,
66811  ** this error is caught long before reaching this point.
66812  */
66813  if( NEVER(iTable<2) ){
66814  return SQLITE_CORRUPT_BKPT;
66815  }
66816 
66817  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
66818  if( rc ) return rc;
66819  rc = sqlite3BtreeClearTable(p, iTable, 0);
66820  if( rc ){
66821  releasePage(pPage);
66822  return rc;
66823  }
66824 
66825  *piMoved = 0;
66826 
66827 #ifdef SQLITE_OMIT_AUTOVACUUM
66828  freePage(pPage, &rc);
66829  releasePage(pPage);
66830 #else
66831  if( pBt->autoVacuum ){
66832  Pgno maxRootPgno;
66833  sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
66834 
66835  if( iTable==maxRootPgno ){
66836  /* If the table being dropped is the table with the largest root-page
66837  ** number in the database, put the root page on the free list.
66838  */
66839  freePage(pPage, &rc);
66840  releasePage(pPage);
66841  if( rc!=SQLITE_OK ){
66842  return rc;
66843  }
66844  }else{
66845  /* The table being dropped does not have the largest root-page
66846  ** number in the database. So move the page that does into the
66847  ** gap left by the deleted root-page.
66848  */
66849  MemPage *pMove;
66850  releasePage(pPage);
66851  rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66852  if( rc!=SQLITE_OK ){
66853  return rc;
66854  }
66855  rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
66856  releasePage(pMove);
66857  if( rc!=SQLITE_OK ){
66858  return rc;
66859  }
66860  pMove = 0;
66861  rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66862  freePage(pMove, &rc);
66863  releasePage(pMove);
66864  if( rc!=SQLITE_OK ){
66865  return rc;
66866  }
66867  *piMoved = maxRootPgno;
66868  }
66869 
66870  /* Set the new 'max-root-page' value in the database header. This
66871  ** is the old value less one, less one more if that happens to
66872  ** be a root-page number, less one again if that is the
66873  ** PENDING_BYTE_PAGE.
66874  */
66875  maxRootPgno--;
66876  while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
66877  || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
66878  maxRootPgno--;
66879  }
66880  assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
66881 
66882  rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
66883  }else{
66884  freePage(pPage, &rc);
66885  releasePage(pPage);
66886  }
66887 #endif
66888  return rc;
66889 }
66890 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
66891  int rc;
66892  sqlite3BtreeEnter(p);
66893  rc = btreeDropTable(p, iTable, piMoved);
66894  sqlite3BtreeLeave(p);
66895  return rc;
66896 }
66897 
66898 
66899 /*
66900 ** This function may only be called if the b-tree connection already
66901 ** has a read or write transaction open on the database.
66902 **
66903 ** Read the meta-information out of a database file. Meta[0]
66904 ** is the number of free pages currently in the database. Meta[1]
66905 ** through meta[15] are available for use by higher layers. Meta[0]
66906 ** is read-only, the others are read/write.
66907 **
66908 ** The schema layer numbers meta values differently. At the schema
66909 ** layer (and the SetCookie and ReadCookie opcodes) the number of
66910 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
66911 **
66912 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
66913 ** of reading the value out of the header, it instead loads the "DataVersion"
66914 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
66915 ** database file. It is a number computed by the pager. But its access
66916 ** pattern is the same as header meta values, and so it is convenient to
66917 ** read it from this routine.
66918 */
66919 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
66920  BtShared *pBt = p->pBt;
66921 
66922  sqlite3BtreeEnter(p);
66923  assert( p->inTrans>TRANS_NONE );
66925  assert( pBt->pPage1 );
66926  assert( idx>=0 && idx<=15 );
66927 
66928  if( idx==BTREE_DATA_VERSION ){
66929  *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
66930  }else{
66931  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
66932  }
66933 
66934  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
66935  ** database, mark the database as read-only. */
66936 #ifdef SQLITE_OMIT_AUTOVACUUM
66937  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
66938  pBt->btsFlags |= BTS_READ_ONLY;
66939  }
66940 #endif
66941 
66942  sqlite3BtreeLeave(p);
66943 }
66944 
66945 /*
66946 ** Write meta-information back into the database. Meta[0] is
66947 ** read-only and may not be written.
66948 */
66949 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
66950  BtShared *pBt = p->pBt;
66951  unsigned char *pP1;
66952  int rc;
66953  assert( idx>=1 && idx<=15 );
66954  sqlite3BtreeEnter(p);
66955  assert( p->inTrans==TRANS_WRITE );
66956  assert( pBt->pPage1!=0 );
66957  pP1 = pBt->pPage1->aData;
66958  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
66959  if( rc==SQLITE_OK ){
66960  put4byte(&pP1[36 + idx*4], iMeta);
66961 #ifndef SQLITE_OMIT_AUTOVACUUM
66962  if( idx==BTREE_INCR_VACUUM ){
66963  assert( pBt->autoVacuum || iMeta==0 );
66964  assert( iMeta==0 || iMeta==1 );
66965  pBt->incrVacuum = (u8)iMeta;
66966  }
66967 #endif
66968  }
66969  sqlite3BtreeLeave(p);
66970  return rc;
66971 }
66972 
66973 #ifndef SQLITE_OMIT_BTREECOUNT
66974 /*
66975 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
66976 ** number of entries in the b-tree and write the result to *pnEntry.
66977 **
66978 ** SQLITE_OK is returned if the operation is successfully executed.
66979 ** Otherwise, if an error is encountered (i.e. an IO error or database
66980 ** corruption) an SQLite error code is returned.
66981 */
66982 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
66983  i64 nEntry = 0; /* Value to return in *pnEntry */
66984  int rc; /* Return code */
66985 
66986  if( pCur->pgnoRoot==0 ){
66987  *pnEntry = 0;
66988  return SQLITE_OK;
66989  }
66990  rc = moveToRoot(pCur);
66991 
66992  /* Unless an error occurs, the following loop runs one iteration for each
66993  ** page in the B-Tree structure (not including overflow pages).
66994  */
66995  while( rc==SQLITE_OK ){
66996  int iIdx; /* Index of child node in parent */
66997  MemPage *pPage; /* Current page of the b-tree */
66998 
66999  /* If this is a leaf page or the tree is not an int-key tree, then
67000  ** this page contains countable entries. Increment the entry counter
67001  ** accordingly.
67002  */
67003  pPage = pCur->apPage[pCur->iPage];
67004  if( pPage->leaf || !pPage->intKey ){
67005  nEntry += pPage->nCell;
67006  }
67007 
67008  /* pPage is a leaf node. This loop navigates the cursor so that it
67009  ** points to the first interior cell that it points to the parent of
67010  ** the next page in the tree that has not yet been visited. The
67011  ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
67012  ** of the page, or to the number of cells in the page if the next page
67013  ** to visit is the right-child of its parent.
67014  **
67015  ** If all pages in the tree have been visited, return SQLITE_OK to the
67016  ** caller.
67017  */
67018  if( pPage->leaf ){
67019  do {
67020  if( pCur->iPage==0 ){
67021  /* All pages of the b-tree have been visited. Return successfully. */
67022  *pnEntry = nEntry;
67023  return moveToRoot(pCur);
67024  }
67025  moveToParent(pCur);
67026  }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
67027 
67028  pCur->aiIdx[pCur->iPage]++;
67029  pPage = pCur->apPage[pCur->iPage];
67030  }
67031 
67032  /* Descend to the child node of the cell that the cursor currently
67033  ** points at. This is the right-child if (iIdx==pPage->nCell).
67034  */
67035  iIdx = pCur->aiIdx[pCur->iPage];
67036  if( iIdx==pPage->nCell ){
67037  rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
67038  }else{
67039  rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
67040  }
67041  }
67042 
67043  /* An error has occurred. Return an error code. */
67044  return rc;
67045 }
67046 #endif
67047 
67048 /*
67049 ** Return the pager associated with a BTree. This routine is used for
67050 ** testing and debugging only.
67051 */
67053  return p->pBt->pPager;
67054 }
67055 
67056 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67057 /*
67058 ** Append a message to the error message string.
67059 */
67060 static void checkAppendMsg(
67061  IntegrityCk *pCheck,
67062  const char *zFormat,
67063  ...
67064 ){
67065  va_list ap;
67066  if( !pCheck->mxErr ) return;
67067  pCheck->mxErr--;
67068  pCheck->nErr++;
67069  va_start(ap, zFormat);
67070  if( pCheck->errMsg.nChar ){
67071  sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
67072  }
67073  if( pCheck->zPfx ){
67074  sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
67075  }
67076  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
67077  va_end(ap);
67078  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
67079  pCheck->mallocFailed = 1;
67080  }
67081 }
67082 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67083 
67084 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67085 
67086 /*
67087 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
67088 ** corresponds to page iPg is already set.
67089 */
67090 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
67091  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
67092  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
67093 }
67094 
67095 /*
67096 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
67097 */
67098 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
67099  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
67100  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
67101 }
67102 
67103 
67104 /*
67105 ** Add 1 to the reference count for page iPage. If this is the second
67106 ** reference to the page, add an error message to pCheck->zErrMsg.
67107 ** Return 1 if there are 2 or more references to the page and 0 if
67108 ** if this is the first reference to the page.
67109 **
67110 ** Also check that the page number is in bounds.
67111 */
67112 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
67113  if( iPage==0 ) return 1;
67114  if( iPage>pCheck->nPage ){
67115  checkAppendMsg(pCheck, "invalid page number %d", iPage);
67116  return 1;
67117  }
67118  if( getPageReferenced(pCheck, iPage) ){
67119  checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
67120  return 1;
67121  }
67122  setPageReferenced(pCheck, iPage);
67123  return 0;
67124 }
67125 
67126 #ifndef SQLITE_OMIT_AUTOVACUUM
67127 /*
67128 ** Check that the entry in the pointer-map for page iChild maps to
67129 ** page iParent, pointer type ptrType. If not, append an error message
67130 ** to pCheck.
67131 */
67132 static void checkPtrmap(
67133  IntegrityCk *pCheck, /* Integrity check context */
67134  Pgno iChild, /* Child page number */
67135  u8 eType, /* Expected pointer map type */
67136  Pgno iParent /* Expected pointer map parent page number */
67137 ){
67138  int rc;
67139  u8 ePtrmapType;
67140  Pgno iPtrmapParent;
67141 
67142  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
67143  if( rc!=SQLITE_OK ){
67144  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
67145  checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
67146  return;
67147  }
67148 
67149  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
67150  checkAppendMsg(pCheck,
67151  "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
67152  iChild, eType, iParent, ePtrmapType, iPtrmapParent);
67153  }
67154 }
67155 #endif
67156 
67157 /*
67158 ** Check the integrity of the freelist or of an overflow page list.
67159 ** Verify that the number of pages on the list is N.
67160 */
67161 static void checkList(
67162  IntegrityCk *pCheck, /* Integrity checking context */
67163  int isFreeList, /* True for a freelist. False for overflow page list */
67164  int iPage, /* Page number for first page in the list */
67165  int N /* Expected number of pages in the list */
67166 ){
67167  int i;
67168  int expected = N;
67169  int iFirst = iPage;
67170  while( N-- > 0 && pCheck->mxErr ){
67171  DbPage *pOvflPage;
67172  unsigned char *pOvflData;
67173  if( iPage<1 ){
67174  checkAppendMsg(pCheck,
67175  "%d of %d pages missing from overflow list starting at %d",
67176  N+1, expected, iFirst);
67177  break;
67178  }
67179  if( checkRef(pCheck, iPage) ) break;
67180  if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
67181  checkAppendMsg(pCheck, "failed to get page %d", iPage);
67182  break;
67183  }
67184  pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
67185  if( isFreeList ){
67186  int n = get4byte(&pOvflData[4]);
67187 #ifndef SQLITE_OMIT_AUTOVACUUM
67188  if( pCheck->pBt->autoVacuum ){
67189  checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
67190  }
67191 #endif
67192  if( n>(int)pCheck->pBt->usableSize/4-2 ){
67193  checkAppendMsg(pCheck,
67194  "freelist leaf count too big on page %d", iPage);
67195  N--;
67196  }else{
67197  for(i=0; i<n; i++){
67198  Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
67199 #ifndef SQLITE_OMIT_AUTOVACUUM
67200  if( pCheck->pBt->autoVacuum ){
67201  checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
67202  }
67203 #endif
67204  checkRef(pCheck, iFreePage);
67205  }
67206  N -= n;
67207  }
67208  }
67209 #ifndef SQLITE_OMIT_AUTOVACUUM
67210  else{
67211  /* If this database supports auto-vacuum and iPage is not the last
67212  ** page in this overflow list, check that the pointer-map entry for
67213  ** the following page matches iPage.
67214  */
67215  if( pCheck->pBt->autoVacuum && N>0 ){
67216  i = get4byte(pOvflData);
67217  checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
67218  }
67219  }
67220 #endif
67221  iPage = get4byte(pOvflData);
67222  sqlite3PagerUnref(pOvflPage);
67223 
67224  if( isFreeList && N<(iPage!=0) ){
67225  checkAppendMsg(pCheck, "free-page count in header is too small");
67226  }
67227  }
67228 }
67229 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67230 
67231 /*
67232 ** An implementation of a min-heap.
67233 **
67234 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
67235 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
67236 ** and aHeap[N*2+1].
67237 **
67238 ** The heap property is this: Every node is less than or equal to both
67239 ** of its daughter nodes. A consequence of the heap property is that the
67240 ** root node aHeap[1] is always the minimum value currently in the heap.
67241 **
67242 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
67243 ** the heap, preserving the heap property. The btreeHeapPull() routine
67244 ** removes the root element from the heap (the minimum value in the heap)
67245 ** and then moves other nodes around as necessary to preserve the heap
67246 ** property.
67247 **
67248 ** This heap is used for cell overlap and coverage testing. Each u32
67249 ** entry represents the span of a cell or freeblock on a btree page.
67250 ** The upper 16 bits are the index of the first byte of a range and the
67251 ** lower 16 bits are the index of the last byte of that range.
67252 */
67253 static void btreeHeapInsert(u32 *aHeap, u32 x){
67254  u32 j, i = ++aHeap[0];
67255  aHeap[i] = x;
67256  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
67257  x = aHeap[j];
67258  aHeap[j] = aHeap[i];
67259  aHeap[i] = x;
67260  i = j;
67261  }
67262 }
67263 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
67264  u32 j, i, x;
67265  if( (x = aHeap[0])==0 ) return 0;
67266  *pOut = aHeap[1];
67267  aHeap[1] = aHeap[x];
67268  aHeap[x] = 0xffffffff;
67269  aHeap[0]--;
67270  i = 1;
67271  while( (j = i*2)<=aHeap[0] ){
67272  if( aHeap[j]>aHeap[j+1] ) j++;
67273  if( aHeap[i]<aHeap[j] ) break;
67274  x = aHeap[i];
67275  aHeap[i] = aHeap[j];
67276  aHeap[j] = x;
67277  i = j;
67278  }
67279  return 1;
67280 }
67281 
67282 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67283 /*
67284 ** Do various sanity checks on a single page of a tree. Return
67285 ** the tree depth. Root pages return 0. Parents of root pages
67286 ** return 1, and so forth.
67287 **
67288 ** These checks are done:
67289 **
67290 ** 1. Make sure that cells and freeblocks do not overlap
67291 ** but combine to completely cover the page.
67292 ** 2. Make sure integer cell keys are in order.
67293 ** 3. Check the integrity of overflow pages.
67294 ** 4. Recursively call checkTreePage on all children.
67295 ** 5. Verify that the depth of all children is the same.
67296 */
67297 static int checkTreePage(
67298  IntegrityCk *pCheck, /* Context for the sanity check */
67299  int iPage, /* Page number of the page to check */
67300  i64 *piMinKey, /* Write minimum integer primary key here */
67301  i64 maxKey /* Error if integer primary key greater than this */
67302 ){
67303  MemPage *pPage = 0; /* The page being analyzed */
67304  int i; /* Loop counter */
67305  int rc; /* Result code from subroutine call */
67306  int depth = -1, d2; /* Depth of a subtree */
67307  int pgno; /* Page number */
67308  int nFrag; /* Number of fragmented bytes on the page */
67309  int hdr; /* Offset to the page header */
67310  int cellStart; /* Offset to the start of the cell pointer array */
67311  int nCell; /* Number of cells */
67312  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
67313  int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
67314  ** False if IPK must be strictly less than maxKey */
67315  u8 *data; /* Page content */
67316  u8 *pCell; /* Cell content */
67317  u8 *pCellIdx; /* Next element of the cell pointer array */
67318  BtShared *pBt; /* The BtShared object that owns pPage */
67319  u32 pc; /* Address of a cell */
67320  u32 usableSize; /* Usable size of the page */
67321  u32 contentOffset; /* Offset to the start of the cell content area */
67322  u32 *heap = 0; /* Min-heap used for checking cell coverage */
67323  u32 x, prev = 0; /* Next and previous entry on the min-heap */
67324  const char *saved_zPfx = pCheck->zPfx;
67325  int saved_v1 = pCheck->v1;
67326  int saved_v2 = pCheck->v2;
67327  u8 savedIsInit = 0;
67328 
67329  /* Check that the page exists
67330  */
67331  pBt = pCheck->pBt;
67332  usableSize = pBt->usableSize;
67333  if( iPage==0 ) return 0;
67334  if( checkRef(pCheck, iPage) ) return 0;
67335  pCheck->zPfx = "Page %d: ";
67336  pCheck->v1 = iPage;
67337  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
67338  checkAppendMsg(pCheck,
67339  "unable to get the page. error code=%d", rc);
67340  goto end_of_check;
67341  }
67342 
67343  /* Clear MemPage.isInit to make sure the corruption detection code in
67344  ** btreeInitPage() is executed. */
67345  savedIsInit = pPage->isInit;
67346  pPage->isInit = 0;
67347  if( (rc = btreeInitPage(pPage))!=0 ){
67348  assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
67349  checkAppendMsg(pCheck,
67350  "btreeInitPage() returns error code %d", rc);
67351  goto end_of_check;
67352  }
67353  data = pPage->aData;
67354  hdr = pPage->hdrOffset;
67355 
67356  /* Set up for cell analysis */
67357  pCheck->zPfx = "On tree page %d cell %d: ";
67358  contentOffset = get2byteNotZero(&data[hdr+5]);
67359  assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
67360 
67361  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
67362  ** number of cells on the page. */
67363  nCell = get2byte(&data[hdr+3]);
67364  assert( pPage->nCell==nCell );
67365 
67366  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
67367  ** immediately follows the b-tree page header. */
67368  cellStart = hdr + 12 - 4*pPage->leaf;
67369  assert( pPage->aCellIdx==&data[cellStart] );
67370  pCellIdx = &data[cellStart + 2*(nCell-1)];
67371 
67372  if( !pPage->leaf ){
67373  /* Analyze the right-child page of internal pages */
67374  pgno = get4byte(&data[hdr+8]);
67375 #ifndef SQLITE_OMIT_AUTOVACUUM
67376  if( pBt->autoVacuum ){
67377  pCheck->zPfx = "On page %d at right child: ";
67378  checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67379  }
67380 #endif
67381  depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67382  keyCanBeEqual = 0;
67383  }else{
67384  /* For leaf pages, the coverage check will occur in the same loop
67385  ** as the other cell checks, so initialize the heap. */
67386  heap = pCheck->heap;
67387  heap[0] = 0;
67388  }
67389 
67390  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
67391  ** integer offsets to the cell contents. */
67392  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
67393  CellInfo info;
67394 
67395  /* Check cell size */
67396  pCheck->v2 = i;
67397  assert( pCellIdx==&data[cellStart + i*2] );
67398  pc = get2byteAligned(pCellIdx);
67399  pCellIdx -= 2;
67400  if( pc<contentOffset || pc>usableSize-4 ){
67401  checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
67402  pc, contentOffset, usableSize-4);
67403  doCoverageCheck = 0;
67404  continue;
67405  }
67406  pCell = &data[pc];
67407  pPage->xParseCell(pPage, pCell, &info);
67408  if( pc+info.nSize>usableSize ){
67409  checkAppendMsg(pCheck, "Extends off end of page");
67410  doCoverageCheck = 0;
67411  continue;
67412  }
67413 
67414  /* Check for integer primary key out of range */
67415  if( pPage->intKey ){
67416  if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
67417  checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
67418  }
67419  maxKey = info.nKey;
67420  }
67421 
67422  /* Check the content overflow list */
67423  if( info.nPayload>info.nLocal ){
67424  int nPage; /* Number of pages on the overflow chain */
67425  Pgno pgnoOvfl; /* First page of the overflow chain */
67426  assert( pc + info.nSize - 4 <= usableSize );
67427  nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
67428  pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
67429 #ifndef SQLITE_OMIT_AUTOVACUUM
67430  if( pBt->autoVacuum ){
67431  checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
67432  }
67433 #endif
67434  checkList(pCheck, 0, pgnoOvfl, nPage);
67435  }
67436 
67437  if( !pPage->leaf ){
67438  /* Check sanity of left child page for internal pages */
67439  pgno = get4byte(pCell);
67440 #ifndef SQLITE_OMIT_AUTOVACUUM
67441  if( pBt->autoVacuum ){
67442  checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67443  }
67444 #endif
67445  d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67446  keyCanBeEqual = 0;
67447  if( d2!=depth ){
67448  checkAppendMsg(pCheck, "Child page depth differs");
67449  depth = d2;
67450  }
67451  }else{
67452  /* Populate the coverage-checking heap for leaf pages */
67453  btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
67454  }
67455  }
67456  *piMinKey = maxKey;
67457 
67458  /* Check for complete coverage of the page
67459  */
67460  pCheck->zPfx = 0;
67461  if( doCoverageCheck && pCheck->mxErr>0 ){
67462  /* For leaf pages, the min-heap has already been initialized and the
67463  ** cells have already been inserted. But for internal pages, that has
67464  ** not yet been done, so do it now */
67465  if( !pPage->leaf ){
67466  heap = pCheck->heap;
67467  heap[0] = 0;
67468  for(i=nCell-1; i>=0; i--){
67469  u32 size;
67470  pc = get2byteAligned(&data[cellStart+i*2]);
67471  size = pPage->xCellSize(pPage, &data[pc]);
67472  btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
67473  }
67474  }
67475  /* Add the freeblocks to the min-heap
67476  **
67477  ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
67478  ** is the offset of the first freeblock, or zero if there are no
67479  ** freeblocks on the page.
67480  */
67481  i = get2byte(&data[hdr+1]);
67482  while( i>0 ){
67483  int size, j;
67484  assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
67485  size = get2byte(&data[i+2]);
67486  assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
67487  btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
67488  /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
67489  ** big-endian integer which is the offset in the b-tree page of the next
67490  ** freeblock in the chain, or zero if the freeblock is the last on the
67491  ** chain. */
67492  j = get2byte(&data[i]);
67493  /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
67494  ** increasing offset. */
67495  assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
67496  assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
67497  i = j;
67498  }
67499  /* Analyze the min-heap looking for overlap between cells and/or
67500  ** freeblocks, and counting the number of untracked bytes in nFrag.
67501  **
67502  ** Each min-heap entry is of the form: (start_address<<16)|end_address.
67503  ** There is an implied first entry the covers the page header, the cell
67504  ** pointer index, and the gap between the cell pointer index and the start
67505  ** of cell content.
67506  **
67507  ** The loop below pulls entries from the min-heap in order and compares
67508  ** the start_address against the previous end_address. If there is an
67509  ** overlap, that means bytes are used multiple times. If there is a gap,
67510  ** that gap is added to the fragmentation count.
67511  */
67512  nFrag = 0;
67513  prev = contentOffset - 1; /* Implied first min-heap entry */
67514  while( btreeHeapPull(heap,&x) ){
67515  if( (prev&0xffff)>=(x>>16) ){
67516  checkAppendMsg(pCheck,
67517  "Multiple uses for byte %u of page %d", x>>16, iPage);
67518  break;
67519  }else{
67520  nFrag += (x>>16) - (prev&0xffff) - 1;
67521  prev = x;
67522  }
67523  }
67524  nFrag += usableSize - (prev&0xffff) - 1;
67525  /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
67526  ** is stored in the fifth field of the b-tree page header.
67527  ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
67528  ** number of fragmented free bytes within the cell content area.
67529  */
67530  if( heap[0]==0 && nFrag!=data[hdr+7] ){
67531  checkAppendMsg(pCheck,
67532  "Fragmentation of %d bytes reported as %d on page %d",
67533  nFrag, data[hdr+7], iPage);
67534  }
67535  }
67536 
67537 end_of_check:
67538  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
67539  releasePage(pPage);
67540  pCheck->zPfx = saved_zPfx;
67541  pCheck->v1 = saved_v1;
67542  pCheck->v2 = saved_v2;
67543  return depth+1;
67544 }
67545 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67546 
67547 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67548 /*
67549 ** This routine does a complete check of the given BTree file. aRoot[] is
67550 ** an array of pages numbers were each page number is the root page of
67551 ** a table. nRoot is the number of entries in aRoot.
67552 **
67553 ** A read-only or read-write transaction must be opened before calling
67554 ** this function.
67555 **
67556 ** Write the number of error seen in *pnErr. Except for some memory
67557 ** allocation errors, an error message held in memory obtained from
67558 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
67559 ** returned. If a memory allocation error occurs, NULL is returned.
67560 */
67562  Btree *p, /* The btree to be checked */
67563  int *aRoot, /* An array of root pages numbers for individual trees */
67564  int nRoot, /* Number of entries in aRoot[] */
67565  int mxErr, /* Stop reporting errors after this many */
67566  int *pnErr /* Write number of errors seen to this variable */
67567 ){
67568  Pgno i;
67569  IntegrityCk sCheck;
67570  BtShared *pBt = p->pBt;
67571  int savedDbFlags = pBt->db->flags;
67572  char zErr[100];
67573  VVA_ONLY( int nRef );
67574 
67575  sqlite3BtreeEnter(p);
67576  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
67577  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
67578  assert( nRef>=0 );
67579  sCheck.pBt = pBt;
67580  sCheck.pPager = pBt->pPager;
67581  sCheck.nPage = btreePagecount(sCheck.pBt);
67582  sCheck.mxErr = mxErr;
67583  sCheck.nErr = 0;
67584  sCheck.mallocFailed = 0;
67585  sCheck.zPfx = 0;
67586  sCheck.v1 = 0;
67587  sCheck.v2 = 0;
67588  sCheck.aPgRef = 0;
67589  sCheck.heap = 0;
67590  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
67592  if( sCheck.nPage==0 ){
67593  goto integrity_ck_cleanup;
67594  }
67595 
67596  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
67597  if( !sCheck.aPgRef ){
67598  sCheck.mallocFailed = 1;
67599  goto integrity_ck_cleanup;
67600  }
67601  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
67602  if( sCheck.heap==0 ){
67603  sCheck.mallocFailed = 1;
67604  goto integrity_ck_cleanup;
67605  }
67606 
67607  i = PENDING_BYTE_PAGE(pBt);
67608  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
67609 
67610  /* Check the integrity of the freelist
67611  */
67612  sCheck.zPfx = "Main freelist: ";
67613  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
67614  get4byte(&pBt->pPage1->aData[36]));
67615  sCheck.zPfx = 0;
67616 
67617  /* Check all the tables.
67618  */
67619  testcase( pBt->db->flags & SQLITE_CellSizeCk );
67620  pBt->db->flags &= ~SQLITE_CellSizeCk;
67621  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
67622  i64 notUsed;
67623  if( aRoot[i]==0 ) continue;
67624 #ifndef SQLITE_OMIT_AUTOVACUUM
67625  if( pBt->autoVacuum && aRoot[i]>1 ){
67626  checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
67627  }
67628 #endif
67629  checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
67630  }
67631  pBt->db->flags = savedDbFlags;
67632 
67633  /* Make sure every page in the file is referenced
67634  */
67635  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
67636 #ifdef SQLITE_OMIT_AUTOVACUUM
67637  if( getPageReferenced(&sCheck, i)==0 ){
67638  checkAppendMsg(&sCheck, "Page %d is never used", i);
67639  }
67640 #else
67641  /* If the database supports auto-vacuum, make sure no tables contain
67642  ** references to pointer-map pages.
67643  */
67644  if( getPageReferenced(&sCheck, i)==0 &&
67645  (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
67646  checkAppendMsg(&sCheck, "Page %d is never used", i);
67647  }
67648  if( getPageReferenced(&sCheck, i)!=0 &&
67649  (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
67650  checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
67651  }
67652 #endif
67653  }
67654 
67655  /* Clean up and report errors.
67656  */
67657 integrity_ck_cleanup:
67658  sqlite3PageFree(sCheck.heap);
67659  sqlite3_free(sCheck.aPgRef);
67660  if( sCheck.mallocFailed ){
67661  sqlite3StrAccumReset(&sCheck.errMsg);
67662  sCheck.nErr++;
67663  }
67664  *pnErr = sCheck.nErr;
67665  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
67666  /* Make sure this analysis did not leave any unref() pages. */
67667  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
67668  sqlite3BtreeLeave(p);
67669  return sqlite3StrAccumFinish(&sCheck.errMsg);
67670 }
67671 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67672 
67673 /*
67674 ** Return the full pathname of the underlying database file. Return
67675 ** an empty string if the database is in-memory or a TEMP database.
67676 **
67677 ** The pager filename is invariant as long as the pager is
67678 ** open so it is safe to access without the BtShared mutex.
67679 */
67681  assert( p->pBt->pPager!=0 );
67682  return sqlite3PagerFilename(p->pBt->pPager, 1);
67683 }
67684 
67685 /*
67686 ** Return the pathname of the journal file for this database. The return
67687 ** value of this routine is the same regardless of whether the journal file
67688 ** has been created or not.
67689 **
67690 ** The pager journal filename is invariant as long as the pager is
67691 ** open so it is safe to access without the BtShared mutex.
67692 */
67694  assert( p->pBt->pPager!=0 );
67695  return sqlite3PagerJournalname(p->pBt->pPager);
67696 }
67697 
67698 /*
67699 ** Return non-zero if a transaction is active.
67700 */
67702  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
67703  return (p && (p->inTrans==TRANS_WRITE));
67704 }
67705 
67706 #ifndef SQLITE_OMIT_WAL
67707 /*
67708 ** Run a checkpoint on the Btree passed as the first argument.
67709 **
67710 ** Return SQLITE_LOCKED if this or any other connection has an open
67711 ** transaction on the shared-cache the argument Btree is connected to.
67712 **
67713 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
67714 */
67715 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
67716  int rc = SQLITE_OK;
67717  if( p ){
67718  BtShared *pBt = p->pBt;
67719  sqlite3BtreeEnter(p);
67720  if( pBt->inTransaction!=TRANS_NONE ){
67721  rc = SQLITE_LOCKED;
67722  }else{
67723  rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
67724  }
67725  sqlite3BtreeLeave(p);
67726  }
67727  return rc;
67728 }
67729 #endif
67730 
67731 /*
67732 ** Return non-zero if a read (or write) transaction is active.
67733 */
67735  assert( p );
67736  assert( sqlite3_mutex_held(p->db->mutex) );
67737  return p->inTrans!=TRANS_NONE;
67738 }
67739 
67741  assert( p );
67742  assert( sqlite3_mutex_held(p->db->mutex) );
67743  return p->nBackup!=0;
67744 }
67745 
67746 /*
67747 ** This function returns a pointer to a blob of memory associated with
67748 ** a single shared-btree. The memory is used by client code for its own
67749 ** purposes (for example, to store a high-level schema associated with
67750 ** the shared-btree). The btree layer manages reference counting issues.
67751 **
67752 ** The first time this is called on a shared-btree, nBytes bytes of memory
67753 ** are allocated, zeroed, and returned to the caller. For each subsequent
67754 ** call the nBytes parameter is ignored and a pointer to the same blob
67755 ** of memory returned.
67756 **
67757 ** If the nBytes parameter is 0 and the blob of memory has not yet been
67758 ** allocated, a null pointer is returned. If the blob has already been
67759 ** allocated, it is returned as normal.
67760 **
67761 ** Just before the shared-btree is closed, the function passed as the
67762 ** xFree argument when the memory allocation was made is invoked on the
67763 ** blob of allocated memory. The xFree function should not call sqlite3_free()
67764 ** on the memory, the btree layer does that.
67765 */
67766 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
67767  BtShared *pBt = p->pBt;
67768  sqlite3BtreeEnter(p);
67769  if( !pBt->pSchema && nBytes ){
67770  pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
67771  pBt->xFreeSchema = xFree;
67772  }
67773  sqlite3BtreeLeave(p);
67774  return pBt->pSchema;
67775 }
67776 
67777 /*
67778 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
67779 ** btree as the argument handle holds an exclusive lock on the
67780 ** sqlite_master table. Otherwise SQLITE_OK.
67781 */
67783  int rc;
67784  assert( sqlite3_mutex_held(p->db->mutex) );
67785  sqlite3BtreeEnter(p);
67787  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
67788  sqlite3BtreeLeave(p);
67789  return rc;
67790 }
67791 
67792 
67793 #ifndef SQLITE_OMIT_SHARED_CACHE
67794 /*
67795 ** Obtain a lock on the table whose root page is iTab. The
67796 ** lock is a write lock if isWritelock is true or a read lock
67797 ** if it is false.
67798 */
67799 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
67800  int rc = SQLITE_OK;
67801  assert( p->inTrans!=TRANS_NONE );
67802  if( p->sharable ){
67803  u8 lockType = READ_LOCK + isWriteLock;
67804  assert( READ_LOCK+1==WRITE_LOCK );
67805  assert( isWriteLock==0 || isWriteLock==1 );
67806 
67807  sqlite3BtreeEnter(p);
67808  rc = querySharedCacheTableLock(p, iTab, lockType);
67809  if( rc==SQLITE_OK ){
67810  rc = setSharedCacheTableLock(p, iTab, lockType);
67811  }
67812  sqlite3BtreeLeave(p);
67813  }
67814  return rc;
67815 }
67816 #endif
67817 
67818 #ifndef SQLITE_OMIT_INCRBLOB
67819 /*
67820 ** Argument pCsr must be a cursor opened for writing on an
67821 ** INTKEY table currently pointing at a valid table entry.
67822 ** This function modifies the data stored as part of that entry.
67823 **
67824 ** Only the data content may only be modified, it is not possible to
67825 ** change the length of the data stored. If this function is called with
67826 ** parameters that attempt to write past the end of the existing data,
67827 ** no modifications are made and SQLITE_CORRUPT is returned.
67828 */
67829 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
67830  int rc;
67831  assert( cursorOwnsBtShared(pCsr) );
67832  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
67833  assert( pCsr->curFlags & BTCF_Incrblob );
67834 
67835  rc = restoreCursorPosition(pCsr);
67836  if( rc!=SQLITE_OK ){
67837  return rc;
67838  }
67839  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
67840  if( pCsr->eState!=CURSOR_VALID ){
67841  return SQLITE_ABORT;
67842  }
67843 
67844  /* Save the positions of all other cursors open on this table. This is
67845  ** required in case any of them are holding references to an xFetch
67846  ** version of the b-tree page modified by the accessPayload call below.
67847  **
67848  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
67849  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
67850  ** saveAllCursors can only return SQLITE_OK.
67851  */
67852  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
67853  assert( rc==SQLITE_OK );
67854 
67855  /* Check some assumptions:
67856  ** (a) the cursor is open for writing,
67857  ** (b) there is a read/write transaction open,
67858  ** (c) the connection holds a write-lock on the table (if required),
67859  ** (d) there are no conflicting read-locks, and
67860  ** (e) the cursor points at a valid row of an intKey table.
67861  */
67862  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
67863  return SQLITE_READONLY;
67864  }
67865  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
67866  && pCsr->pBt->inTransaction==TRANS_WRITE );
67867  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
67868  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
67869  assert( pCsr->apPage[pCsr->iPage]->intKey );
67870 
67871  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
67872 }
67873 
67874 /*
67875 ** Mark this cursor as an incremental blob cursor.
67876 */
67878  pCur->curFlags |= BTCF_Incrblob;
67879  pCur->pBtree->hasIncrblobCur = 1;
67880 }
67881 #endif
67882 
67883 /*
67884 ** Set both the "read version" (single byte at byte offset 18) and
67885 ** "write version" (single byte at byte offset 19) fields in the database
67886 ** header to iVersion.
67887 */
67888 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
67889  BtShared *pBt = pBtree->pBt;
67890  int rc; /* Return code */
67891 
67892  assert( iVersion==1 || iVersion==2 );
67893 
67894  /* If setting the version fields to 1, do not automatically open the
67895  ** WAL connection, even if the version fields are currently set to 2.
67896  */
67897  pBt->btsFlags &= ~BTS_NO_WAL;
67898  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
67899 
67900  rc = sqlite3BtreeBeginTrans(pBtree, 0);
67901  if( rc==SQLITE_OK ){
67902  u8 *aData = pBt->pPage1->aData;
67903  if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
67904  rc = sqlite3BtreeBeginTrans(pBtree, 2);
67905  if( rc==SQLITE_OK ){
67906  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
67907  if( rc==SQLITE_OK ){
67908  aData[18] = (u8)iVersion;
67909  aData[19] = (u8)iVersion;
67910  }
67911  }
67912  }
67913  }
67914 
67915  pBt->btsFlags &= ~BTS_NO_WAL;
67916  return rc;
67917 }
67918 
67919 /*
67920 ** Return true if the cursor has a hint specified. This routine is
67921 ** only used from within assert() statements
67922 */
67923 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
67924  return (pCsr->hints & mask)!=0;
67925 }
67926 
67927 /*
67928 ** Return true if the given Btree is read-only.
67929 */
67931  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
67932 }
67933 
67934 /*
67935 ** Return the size of the header added to each page by this module.
67936 */
67938 
67939 #if !defined(SQLITE_OMIT_SHARED_CACHE)
67940 /*
67941 ** Return true if the Btree passed as the only argument is sharable.
67942 */
67944  return p->sharable;
67945 }
67946 
67947 /*
67948 ** Return the number of connections to the BtShared object accessed by
67949 ** the Btree handle passed as the only argument. For private caches
67950 ** this is always 1. For shared caches it may be 1 or greater.
67951 */
67953  testcase( p->sharable );
67954  return p->pBt->nRef;
67955 }
67956 #endif
67957 
67958 /************** End of btree.c ***********************************************/
67959 /************** Begin file backup.c ******************************************/
67960 /*
67961 ** 2009 January 28
67962 **
67963 ** The author disclaims copyright to this source code. In place of
67964 ** a legal notice, here is a blessing:
67965 **
67966 ** May you do good and not evil.
67967 ** May you find forgiveness for yourself and forgive others.
67968 ** May you share freely, never taking more than you give.
67969 **
67970 *************************************************************************
67971 ** This file contains the implementation of the sqlite3_backup_XXX()
67972 ** API functions and the related features.
67973 */
67974 /* #include "sqliteInt.h" */
67975 /* #include "btreeInt.h" */
67976 
67977 /*
67978 ** Structure allocated for each backup operation.
67979 */
67981  sqlite3* pDestDb; /* Destination database handle */
67982  Btree *pDest; /* Destination b-tree file */
67983  u32 iDestSchema; /* Original schema cookie in destination */
67984  int bDestLocked; /* True once a write-transaction is open on pDest */
67985 
67986  Pgno iNext; /* Page number of the next source page to copy */
67987  sqlite3* pSrcDb; /* Source database handle */
67988  Btree *pSrc; /* Source b-tree file */
67989 
67990  int rc; /* Backup process error code */
67991 
67992  /* These two variables are set by every call to backup_step(). They are
67993  ** read by calls to backup_remaining() and backup_pagecount().
67994  */
67995  Pgno nRemaining; /* Number of pages left to copy */
67996  Pgno nPagecount; /* Total number of pages to copy */
67997 
67998  int isAttached; /* True once backup has been registered with pager */
67999  sqlite3_backup *pNext; /* Next backup associated with source pager */
68000 };
68001 
68002 /*
68003 ** THREAD SAFETY NOTES:
68004 **
68005 ** Once it has been created using backup_init(), a single sqlite3_backup
68006 ** structure may be accessed via two groups of thread-safe entry points:
68007 **
68008 ** * Via the sqlite3_backup_XXX() API function backup_step() and
68009 ** backup_finish(). Both these functions obtain the source database
68010 ** handle mutex and the mutex associated with the source BtShared
68011 ** structure, in that order.
68012 **
68013 ** * Via the BackupUpdate() and BackupRestart() functions, which are
68014 ** invoked by the pager layer to report various state changes in
68015 ** the page cache associated with the source database. The mutex
68016 ** associated with the source database BtShared structure will always
68017 ** be held when either of these functions are invoked.
68018 **
68019 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
68020 ** backup_pagecount() are not thread-safe functions. If they are called
68021 ** while some other thread is calling backup_step() or backup_finish(),
68022 ** the values returned may be invalid. There is no way for a call to
68023 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
68024 ** or backup_pagecount().
68025 **
68026 ** Depending on the SQLite configuration, the database handles and/or
68027 ** the Btree objects may have their own mutexes that require locking.
68028 ** Non-sharable Btrees (in-memory databases for example), do not have
68029 ** associated mutexes.
68030 */
68031 
68032 /*
68033 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
68034 ** in connection handle pDb. If such a database cannot be found, return
68035 ** a NULL pointer and write an error message to pErrorDb.
68036 **
68037 ** If the "temp" database is requested, it may need to be opened by this
68038 ** function. If an error occurs while doing so, return 0 and write an
68039 ** error message to pErrorDb.
68040 */
68041 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
68042  int i = sqlite3FindDbName(pDb, zDb);
68043 
68044  if( i==1 ){
68045  Parse sParse;
68046  int rc = 0;
68047  memset(&sParse, 0, sizeof(sParse));
68048  sParse.db = pDb;
68049  if( sqlite3OpenTempDatabase(&sParse) ){
68050  sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
68051  rc = SQLITE_ERROR;
68052  }
68053  sqlite3DbFree(pErrorDb, sParse.zErrMsg);
68054  sqlite3ParserReset(&sParse);
68055  if( rc ){
68056  return 0;
68057  }
68058  }
68059 
68060  if( i<0 ){
68061  sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
68062  return 0;
68063  }
68064 
68065  return pDb->aDb[i].pBt;
68066 }
68067 
68068 /*
68069 ** Attempt to set the page size of the destination to match the page size
68070 ** of the source.
68071 */
68073  int rc;
68075  return rc;
68076 }
68077 
68078 /*
68079 ** Check that there is no open read-transaction on the b-tree passed as the
68080 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
68081 ** is an open read-transaction, return SQLITE_ERROR and leave an error
68082 ** message in database handle db.
68083 */
68084 static int checkReadTransaction(sqlite3 *db, Btree *p){
68085  if( sqlite3BtreeIsInReadTrans(p) ){
68086  sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
68087  return SQLITE_ERROR;
68088  }
68089  return SQLITE_OK;
68090 }
68091 
68092 /*
68093 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
68094 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
68095 ** a pointer to the new sqlite3_backup object.
68096 **
68097 ** If an error occurs, NULL is returned and an error code and error message
68098 ** stored in database handle pDestDb.
68099 */
68101  sqlite3* pDestDb, /* Database to write to */
68102  const char *zDestDb, /* Name of database within pDestDb */
68103  sqlite3* pSrcDb, /* Database connection to read from */
68104  const char *zSrcDb /* Name of database within pSrcDb */
68105 ){
68106  sqlite3_backup *p; /* Value to return */
68107 
68108 #ifdef SQLITE_ENABLE_API_ARMOR
68109  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
68110  (void)SQLITE_MISUSE_BKPT;
68111  return 0;
68112  }
68113 #endif
68114 
68115  /* Lock the source database handle. The destination database
68116  ** handle is not locked in this routine, but it is locked in
68117  ** sqlite3_backup_step(). The user is required to ensure that no
68118  ** other thread accesses the destination handle for the duration
68119  ** of the backup operation. Any attempt to use the destination
68120  ** database connection while a backup is in progress may cause
68121  ** a malfunction or a deadlock.
68122  */
68123  sqlite3_mutex_enter(pSrcDb->mutex);
68124  sqlite3_mutex_enter(pDestDb->mutex);
68125 
68126  if( pSrcDb==pDestDb ){
68128  pDestDb, SQLITE_ERROR, "source and destination must be distinct"
68129  );
68130  p = 0;
68131  }else {
68132  /* Allocate space for a new sqlite3_backup object...
68133  ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68134  ** call to sqlite3_backup_init() and is destroyed by a call to
68135  ** sqlite3_backup_finish(). */
68137  if( !p ){
68138  sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
68139  }
68140  }
68141 
68142  /* If the allocation succeeded, populate the new object. */
68143  if( p ){
68144  p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
68145  p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
68146  p->pDestDb = pDestDb;
68147  p->pSrcDb = pSrcDb;
68148  p->iNext = 1;
68149  p->isAttached = 0;
68150 
68151  if( 0==p->pSrc || 0==p->pDest
68152  || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
68153  ){
68154  /* One (or both) of the named databases did not exist or an OOM
68155  ** error was hit. Or there is a transaction open on the destination
68156  ** database. The error has already been written into the pDestDb
68157  ** handle. All that is left to do here is free the sqlite3_backup
68158  ** structure. */
68159  sqlite3_free(p);
68160  p = 0;
68161  }
68162  }
68163  if( p ){
68164  p->pSrc->nBackup++;
68165  }
68166 
68167  sqlite3_mutex_leave(pDestDb->mutex);
68168  sqlite3_mutex_leave(pSrcDb->mutex);
68169  return p;
68170 }
68171 
68172 /*
68173 ** Argument rc is an SQLite error code. Return true if this error is
68174 ** considered fatal if encountered during a backup operation. All errors
68175 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
68176 */
68177 static int isFatalError(int rc){
68178  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
68179 }
68180 
68181 /*
68182 ** Parameter zSrcData points to a buffer containing the data for
68183 ** page iSrcPg from the source database. Copy this data into the
68184 ** destination database.
68185 */
68186 static int backupOnePage(
68187  sqlite3_backup *p, /* Backup handle */
68188  Pgno iSrcPg, /* Source database page to backup */
68189  const u8 *zSrcData, /* Source database page data */
68190  int bUpdate /* True for an update, false otherwise */
68191 ){
68192  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
68193  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
68194  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
68195  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
68196  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
68197 #ifdef SQLITE_HAS_CODEC
68198  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
68199  ** guaranteed that the shared-mutex is held by this thread, handle
68200  ** p->pSrc may not actually be the owner. */
68201  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
68202  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
68203 #endif
68204  int rc = SQLITE_OK;
68205  i64 iOff;
68206 
68207  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
68208  assert( p->bDestLocked );
68209  assert( !isFatalError(p->rc) );
68210  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
68211  assert( zSrcData );
68212 
68213  /* Catch the case where the destination is an in-memory database and the
68214  ** page sizes of the source and destination differ.
68215  */
68216  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
68217  rc = SQLITE_READONLY;
68218  }
68219 
68220 #ifdef SQLITE_HAS_CODEC
68221  /* Backup is not possible if the page size of the destination is changing
68222  ** and a codec is in use.
68223  */
68224  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
68225  rc = SQLITE_READONLY;
68226  }
68227 
68228  /* Backup is not possible if the number of bytes of reserve space differ
68229  ** between source and destination. If there is a difference, try to
68230  ** fix the destination to agree with the source. If that is not possible,
68231  ** then the backup cannot proceed.
68232  */
68233  if( nSrcReserve!=nDestReserve ){
68234  u32 newPgsz = nSrcPgsz;
68235  rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
68236  if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
68237  }
68238 #endif
68239 
68240  /* This loop runs once for each destination page spanned by the source
68241  ** page. For each iteration, variable iOff is set to the byte offset
68242  ** of the destination page.
68243  */
68244  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
68245  DbPage *pDestPg = 0;
68246  Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
68247  if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
68248  if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
68249  && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
68250  ){
68251  const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
68252  u8 *zDestData = sqlite3PagerGetData(pDestPg);
68253  u8 *zOut = &zDestData[iOff%nDestPgsz];
68254 
68255  /* Copy the data from the source page into the destination page.
68256  ** Then clear the Btree layer MemPage.isInit flag. Both this module
68257  ** and the pager code use this trick (clearing the first byte
68258  ** of the page 'extra' space to invalidate the Btree layers
68259  ** cached parse of the page). MemPage.isInit is marked
68260  ** "MUST BE FIRST" for this purpose.
68261  */
68262  memcpy(zOut, zIn, nCopy);
68263  ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
68264  if( iOff==0 && bUpdate==0 ){
68265  sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
68266  }
68267  }
68268  sqlite3PagerUnref(pDestPg);
68269  }
68270 
68271  return rc;
68272 }
68273 
68274 /*
68275 ** If pFile is currently larger than iSize bytes, then truncate it to
68276 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
68277 ** this function is a no-op.
68278 **
68279 ** Return SQLITE_OK if everything is successful, or an SQLite error
68280 ** code if an error occurs.
68281 */
68282 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
68283  i64 iCurrent;
68284  int rc = sqlite3OsFileSize(pFile, &iCurrent);
68285  if( rc==SQLITE_OK && iCurrent>iSize ){
68286  rc = sqlite3OsTruncate(pFile, iSize);
68287  }
68288  return rc;
68289 }
68290 
68291 /*
68292 ** Register this backup object with the associated source pager for
68293 ** callbacks when pages are changed or the cache invalidated.
68294 */
68296  sqlite3_backup **pp;
68297  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
68299  p->pNext = *pp;
68300  *pp = p;
68301  p->isAttached = 1;
68302 }
68303 
68304 /*
68305 ** Copy nPage pages from the source b-tree to the destination.
68306 */
68308  int rc;
68309  int destMode; /* Destination journal mode */
68310  int pgszSrc = 0; /* Source page size */
68311  int pgszDest = 0; /* Destination page size */
68312 
68313 #ifdef SQLITE_ENABLE_API_ARMOR
68314  if( p==0 ) return SQLITE_MISUSE_BKPT;
68315 #endif
68317  sqlite3BtreeEnter(p->pSrc);
68318  if( p->pDestDb ){
68320  }
68321 
68322  rc = p->rc;
68323  if( !isFatalError(rc) ){
68324  Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
68325  Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
68326  int ii; /* Iterator variable */
68327  int nSrcPage = -1; /* Size of source db in pages */
68328  int bCloseTrans = 0; /* True if src db requires unlocking */
68329 
68330  /* If the source pager is currently in a write-transaction, return
68331  ** SQLITE_BUSY immediately.
68332  */
68333  if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
68334  rc = SQLITE_BUSY;
68335  }else{
68336  rc = SQLITE_OK;
68337  }
68338 
68339  /* If there is no open read-transaction on the source database, open
68340  ** one now. If a transaction is opened here, then it will be closed
68341  ** before this function exits.
68342  */
68343  if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
68344  rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
68345  bCloseTrans = 1;
68346  }
68347 
68348  /* If the destination database has not yet been locked (i.e. if this
68349  ** is the first call to backup_step() for the current backup operation),
68350  ** try to set its page size to the same as the source database. This
68351  ** is especially important on ZipVFS systems, as in that case it is
68352  ** not possible to create a database file that uses one page size by
68353  ** writing to it with another. */
68354  if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
68355  rc = SQLITE_NOMEM;
68356  }
68357 
68358  /* Lock the destination database, if it is not locked already. */
68359  if( SQLITE_OK==rc && p->bDestLocked==0
68360  && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
68361  ){
68362  p->bDestLocked = 1;
68364  }
68365 
68366  /* Do not allow backup if the destination database is in WAL mode
68367  ** and the page sizes are different between source and destination */
68368  pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
68369  pgszDest = sqlite3BtreeGetPageSize(p->pDest);
68371  if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
68372  rc = SQLITE_READONLY;
68373  }
68374 
68375  /* Now that there is a read-lock on the source database, query the
68376  ** source pager for the number of pages in the database.
68377  */
68378  nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
68379  assert( nSrcPage>=0 );
68380  for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
68381  const Pgno iSrcPg = p->iNext; /* Source page number */
68382  if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
68383  DbPage *pSrcPg; /* Source page object */
68384  rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
68385  if( rc==SQLITE_OK ){
68386  rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
68387  sqlite3PagerUnref(pSrcPg);
68388  }
68389  }
68390  p->iNext++;
68391  }
68392  if( rc==SQLITE_OK ){
68393  p->nPagecount = nSrcPage;
68394  p->nRemaining = nSrcPage+1-p->iNext;
68395  if( p->iNext>(Pgno)nSrcPage ){
68396  rc = SQLITE_DONE;
68397  }else if( !p->isAttached ){
68398  attachBackupObject(p);
68399  }
68400  }
68401 
68402  /* Update the schema version field in the destination database. This
68403  ** is to make sure that the schema-version really does change in
68404  ** the case where the source and destination databases have the
68405  ** same schema version.
68406  */
68407  if( rc==SQLITE_DONE ){
68408  if( nSrcPage==0 ){
68409  rc = sqlite3BtreeNewDb(p->pDest);
68410  nSrcPage = 1;
68411  }
68412  if( rc==SQLITE_OK || rc==SQLITE_DONE ){
68413  rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
68414  }
68415  if( rc==SQLITE_OK ){
68416  if( p->pDestDb ){
68418  }
68419  if( destMode==PAGER_JOURNALMODE_WAL ){
68420  rc = sqlite3BtreeSetVersion(p->pDest, 2);
68421  }
68422  }
68423  if( rc==SQLITE_OK ){
68424  int nDestTruncate;
68425  /* Set nDestTruncate to the final number of pages in the destination
68426  ** database. The complication here is that the destination page
68427  ** size may be different to the source page size.
68428  **
68429  ** If the source page size is smaller than the destination page size,
68430  ** round up. In this case the call to sqlite3OsTruncate() below will
68431  ** fix the size of the file. However it is important to call
68432  ** sqlite3PagerTruncateImage() here so that any pages in the
68433  ** destination file that lie beyond the nDestTruncate page mark are
68434  ** journalled by PagerCommitPhaseOne() before they are destroyed
68435  ** by the file truncation.
68436  */
68437  assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
68438  assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
68439  if( pgszSrc<pgszDest ){
68440  int ratio = pgszDest/pgszSrc;
68441  nDestTruncate = (nSrcPage+ratio-1)/ratio;
68442  if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
68443  nDestTruncate--;
68444  }
68445  }else{
68446  nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
68447  }
68448  assert( nDestTruncate>0 );
68449 
68450  if( pgszSrc<pgszDest ){
68451  /* If the source page-size is smaller than the destination page-size,
68452  ** two extra things may need to happen:
68453  **
68454  ** * The destination may need to be truncated, and
68455  **
68456  ** * Data stored on the pages immediately following the
68457  ** pending-byte page in the source database may need to be
68458  ** copied into the destination database.
68459  */
68460  const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
68461  sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
68462  Pgno iPg;
68463  int nDstPage;
68464  i64 iOff;
68465  i64 iEnd;
68466 
68467  assert( pFile );
68468  assert( nDestTruncate==0
68469  || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
68470  nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
68471  && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
68472  ));
68473 
68474  /* This block ensures that all data required to recreate the original
68475  ** database has been stored in the journal for pDestPager and the
68476  ** journal synced to disk. So at this point we may safely modify
68477  ** the database file in any way, knowing that if a power failure
68478  ** occurs, the original database will be reconstructed from the
68479  ** journal file. */
68480  sqlite3PagerPagecount(pDestPager, &nDstPage);
68481  for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
68482  if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
68483  DbPage *pPg;
68484  rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
68485  if( rc==SQLITE_OK ){
68486  rc = sqlite3PagerWrite(pPg);
68487  sqlite3PagerUnref(pPg);
68488  }
68489  }
68490  }
68491  if( rc==SQLITE_OK ){
68492  rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
68493  }
68494 
68495  /* Write the extra pages and truncate the database file as required */
68496  iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
68497  for(
68498  iOff=PENDING_BYTE+pgszSrc;
68499  rc==SQLITE_OK && iOff<iEnd;
68500  iOff+=pgszSrc
68501  ){
68502  PgHdr *pSrcPg = 0;
68503  const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
68504  rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
68505  if( rc==SQLITE_OK ){
68506  u8 *zData = sqlite3PagerGetData(pSrcPg);
68507  rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
68508  }
68509  sqlite3PagerUnref(pSrcPg);
68510  }
68511  if( rc==SQLITE_OK ){
68512  rc = backupTruncateFile(pFile, iSize);
68513  }
68514 
68515  /* Sync the database file to disk. */
68516  if( rc==SQLITE_OK ){
68517  rc = sqlite3PagerSync(pDestPager, 0);
68518  }
68519  }else{
68520  sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
68521  rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
68522  }
68523 
68524  /* Finish committing the transaction to the destination database. */
68525  if( SQLITE_OK==rc
68526  && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
68527  ){
68528  rc = SQLITE_DONE;
68529  }
68530  }
68531  }
68532 
68533  /* If bCloseTrans is true, then this function opened a read transaction
68534  ** on the source database. Close the read transaction here. There is
68535  ** no need to check the return values of the btree methods here, as
68536  ** "committing" a read-only transaction cannot fail.
68537  */
68538  if( bCloseTrans ){
68539  TESTONLY( int rc2 );
68540  TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
68541  TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
68542  assert( rc2==SQLITE_OK );
68543  }
68544 
68545  if( rc==SQLITE_IOERR_NOMEM ){
68546  rc = SQLITE_NOMEM_BKPT;
68547  }
68548  p->rc = rc;
68549  }
68550  if( p->pDestDb ){
68552  }
68553  sqlite3BtreeLeave(p->pSrc);
68555  return rc;
68556 }
68557 
68558 /*
68559 ** Release all resources associated with an sqlite3_backup* handle.
68560 */
68562  sqlite3_backup **pp; /* Ptr to head of pagers backup list */
68563  sqlite3 *pSrcDb; /* Source database connection */
68564  int rc; /* Value to return */
68565 
68566  /* Enter the mutexes */
68567  if( p==0 ) return SQLITE_OK;
68568  pSrcDb = p->pSrcDb;
68569  sqlite3_mutex_enter(pSrcDb->mutex);
68570  sqlite3BtreeEnter(p->pSrc);
68571  if( p->pDestDb ){
68573  }
68574 
68575  /* Detach this backup from the source pager. */
68576  if( p->pDestDb ){
68577  p->pSrc->nBackup--;
68578  }
68579  if( p->isAttached ){
68581  while( *pp!=p ){
68582  pp = &(*pp)->pNext;
68583  }
68584  *pp = p->pNext;
68585  }
68586 
68587  /* If a transaction is still open on the Btree, roll it back. */
68589 
68590  /* Set the error code of the destination database handle. */
68591  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
68592  if( p->pDestDb ){
68593  sqlite3Error(p->pDestDb, rc);
68594 
68595  /* Exit the mutexes and free the backup context structure. */
68597  }
68598  sqlite3BtreeLeave(p->pSrc);
68599  if( p->pDestDb ){
68600  /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68601  ** call to sqlite3_backup_init() and is destroyed by a call to
68602  ** sqlite3_backup_finish(). */
68603  sqlite3_free(p);
68604  }
68606  return rc;
68607 }
68608 
68609 /*
68610 ** Return the number of pages still to be backed up as of the most recent
68611 ** call to sqlite3_backup_step().
68612 */
68614 #ifdef SQLITE_ENABLE_API_ARMOR
68615  if( p==0 ){
68616  (void)SQLITE_MISUSE_BKPT;
68617  return 0;
68618  }
68619 #endif
68620  return p->nRemaining;
68621 }
68622 
68623 /*
68624 ** Return the total number of pages in the source database as of the most
68625 ** recent call to sqlite3_backup_step().
68626 */
68628 #ifdef SQLITE_ENABLE_API_ARMOR
68629  if( p==0 ){
68630  (void)SQLITE_MISUSE_BKPT;
68631  return 0;
68632  }
68633 #endif
68634  return p->nPagecount;
68635 }
68636 
68637 /*
68638 ** This function is called after the contents of page iPage of the
68639 ** source database have been modified. If page iPage has already been
68640 ** copied into the destination database, then the data written to the
68641 ** destination is now invalidated. The destination copy of iPage needs
68642 ** to be updated with the new data before the backup operation is
68643 ** complete.
68644 **
68645 ** It is assumed that the mutex associated with the BtShared object
68646 ** corresponding to the source database is held when this function is
68647 ** called.
68648 */
68650  sqlite3_backup *p,
68651  Pgno iPage,
68652  const u8 *aData
68653 ){
68654  assert( p!=0 );
68655  do{
68656  assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68657  if( !isFatalError(p->rc) && iPage<p->iNext ){
68658  /* The backup process p has already copied page iPage. But now it
68659  ** has been modified by a transaction on the source pager. Copy
68660  ** the new data into the backup.
68661  */
68662  int rc;
68663  assert( p->pDestDb );
68665  rc = backupOnePage(p, iPage, aData, 1);
68667  assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
68668  if( rc!=SQLITE_OK ){
68669  p->rc = rc;
68670  }
68671  }
68672  }while( (p = p->pNext)!=0 );
68673 }
68674 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
68675  if( pBackup ) backupUpdate(pBackup, iPage, aData);
68676 }
68677 
68678 /*
68679 ** Restart the backup process. This is called when the pager layer
68680 ** detects that the database has been modified by an external database
68681 ** connection. In this case there is no way of knowing which of the
68682 ** pages that have been copied into the destination database are still
68683 ** valid and which are not, so the entire process needs to be restarted.
68684 **
68685 ** It is assumed that the mutex associated with the BtShared object
68686 ** corresponding to the source database is held when this function is
68687 ** called.
68688 */
68690  sqlite3_backup *p; /* Iterator variable */
68691  for(p=pBackup; p; p=p->pNext){
68692  assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68693  p->iNext = 1;
68694  }
68695 }
68696 
68697 #ifndef SQLITE_OMIT_VACUUM
68698 /*
68699 ** Copy the complete content of pBtFrom into pBtTo. A transaction
68700 ** must be active for both files.
68701 **
68702 ** The size of file pTo may be reduced by this operation. If anything
68703 ** goes wrong, the transaction on pTo is rolled back. If successful, the
68704 ** transaction is committed before returning.
68705 */
68707  int rc;
68708  sqlite3_file *pFd; /* File descriptor for database pTo */
68709  sqlite3_backup b;
68710  sqlite3BtreeEnter(pTo);
68711  sqlite3BtreeEnter(pFrom);
68712 
68713  assert( sqlite3BtreeIsInTrans(pTo) );
68714  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
68715  if( pFd->pMethods ){
68716  i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
68717  rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
68718  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
68719  if( rc ) goto copy_finished;
68720  }
68721 
68722  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
68723  ** to 0. This is used by the implementations of sqlite3_backup_step()
68724  ** and sqlite3_backup_finish() to detect that they are being called
68725  ** from this function, not directly by the user.
68726  */
68727  memset(&b, 0, sizeof(b));
68728  b.pSrcDb = pFrom->db;
68729  b.pSrc = pFrom;
68730  b.pDest = pTo;
68731  b.iNext = 1;
68732 
68733 #ifdef SQLITE_HAS_CODEC
68734  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
68735 #endif
68736 
68737  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
68738  ** file. By passing this as the number of pages to copy to
68739  ** sqlite3_backup_step(), we can guarantee that the copy finishes
68740  ** within a single call (unless an error occurs). The assert() statement
68741  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
68742  ** or an error code. */
68743  sqlite3_backup_step(&b, 0x7FFFFFFF);
68744  assert( b.rc!=SQLITE_OK );
68745 
68746  rc = sqlite3_backup_finish(&b);
68747  if( rc==SQLITE_OK ){
68748  pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
68749  }else{
68751  }
68752 
68753  assert( sqlite3BtreeIsInTrans(pTo)==0 );
68754 copy_finished:
68755  sqlite3BtreeLeave(pFrom);
68756  sqlite3BtreeLeave(pTo);
68757  return rc;
68758 }
68759 #endif /* SQLITE_OMIT_VACUUM */
68760 
68761 /************** End of backup.c **********************************************/
68762 /************** Begin file vdbemem.c *****************************************/
68763 /*
68764 ** 2004 May 26
68765 **
68766 ** The author disclaims copyright to this source code. In place of
68767 ** a legal notice, here is a blessing:
68768 **
68769 ** May you do good and not evil.
68770 ** May you find forgiveness for yourself and forgive others.
68771 ** May you share freely, never taking more than you give.
68772 **
68773 *************************************************************************
68774 **
68775 ** This file contains code use to manipulate "Mem" structure. A "Mem"
68776 ** stores a single value in the VDBE. Mem is an opaque structure visible
68777 ** only within the VDBE. Interface routines refer to a Mem using the
68778 ** name sqlite_value
68779 */
68780 /* #include "sqliteInt.h" */
68781 /* #include "vdbeInt.h" */
68782 
68783 #ifdef SQLITE_DEBUG
68784 /*
68785 ** Check invariants on a Mem object.
68786 **
68787 ** This routine is intended for use inside of assert() statements, like
68788 ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
68789 */
68790 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
68791  /* If MEM_Dyn is set then Mem.xDel!=0.
68792  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
68793  */
68794  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
68795 
68796  /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
68797  ** ensure that if Mem.szMalloc>0 then it is safe to do
68798  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
68799  ** That saves a few cycles in inner loops. */
68800  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
68801 
68802  /* Cannot be both MEM_Int and MEM_Real at the same time */
68803  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
68804 
68805  /* The szMalloc field holds the correct memory allocation size */
68806  assert( p->szMalloc==0
68807  || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
68808 
68809  /* If p holds a string or blob, the Mem.z must point to exactly
68810  ** one of the following:
68811  **
68812  ** (1) Memory in Mem.zMalloc and managed by the Mem object
68813  ** (2) Memory to be freed using Mem.xDel
68814  ** (3) An ephemeral string or blob
68815  ** (4) A static string or blob
68816  */
68817  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
68818  assert(
68819  ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
68820  ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
68821  ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
68822  ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
68823  );
68824  }
68825  return 1;
68826 }
68827 #endif
68828 
68829 
68830 /*
68831 ** If pMem is an object with a valid string representation, this routine
68832 ** ensures the internal encoding for the string representation is
68833 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
68834 **
68835 ** If pMem is not a string object, or the encoding of the string
68836 ** representation is already stored using the requested encoding, then this
68837 ** routine is a no-op.
68838 **
68839 ** SQLITE_OK is returned if the conversion is successful (or not required).
68840 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
68841 ** between formats.
68842 */
68843 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
68844 #ifndef SQLITE_OMIT_UTF16
68845  int rc;
68846 #endif
68847  assert( (pMem->flags&MEM_RowSet)==0 );
68848  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
68849  || desiredEnc==SQLITE_UTF16BE );
68850  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
68851  return SQLITE_OK;
68852  }
68853  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68854 #ifdef SQLITE_OMIT_UTF16
68855  return SQLITE_ERROR;
68856 #else
68857 
68858  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
68859  ** then the encoding of the value may not have changed.
68860  */
68861  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
68862  assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
68863  assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
68864  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
68865  return rc;
68866 #endif
68867 }
68868 
68869 /*
68870 ** Make sure pMem->z points to a writable allocation of at least
68871 ** min(n,32) bytes.
68872 **
68873 ** If the bPreserve argument is true, then copy of the content of
68874 ** pMem->z into the new allocation. pMem must be either a string or
68875 ** blob if bPreserve is true. If bPreserve is false, any prior content
68876 ** in pMem->z is discarded.
68877 */
68878 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
68879  assert( sqlite3VdbeCheckMemInvariants(pMem) );
68880  assert( (pMem->flags&MEM_RowSet)==0 );
68881  testcase( pMem->db==0 );
68882 
68883  /* If the bPreserve flag is set to true, then the memory cell must already
68884  ** contain a valid string or blob value. */
68885  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
68886  testcase( bPreserve && pMem->z==0 );
68887 
68888  assert( pMem->szMalloc==0
68889  || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
68890  if( pMem->szMalloc<n ){
68891  if( n<32 ) n = 32;
68892  if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
68893  pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
68894  bPreserve = 0;
68895  }else{
68896  if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68897  pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
68898  }
68899  if( pMem->zMalloc==0 ){
68900  sqlite3VdbeMemSetNull(pMem);
68901  pMem->z = 0;
68902  pMem->szMalloc = 0;
68903  return SQLITE_NOMEM_BKPT;
68904  }else{
68905  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
68906  }
68907  }
68908 
68909  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
68910  memcpy(pMem->zMalloc, pMem->z, pMem->n);
68911  }
68912  if( (pMem->flags&MEM_Dyn)!=0 ){
68913  assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
68914  pMem->xDel((void *)(pMem->z));
68915  }
68916 
68917  pMem->z = pMem->zMalloc;
68918  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
68919  return SQLITE_OK;
68920 }
68921 
68922 /*
68923 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
68924 ** If pMem->zMalloc already meets or exceeds the requested size, this
68925 ** routine is a no-op.
68926 **
68927 ** Any prior string or blob content in the pMem object may be discarded.
68928 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
68929 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
68930 ** values are preserved.
68931 **
68932 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
68933 ** if unable to complete the resizing.
68934 */
68936  assert( szNew>0 );
68937  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
68938  if( pMem->szMalloc<szNew ){
68939  return sqlite3VdbeMemGrow(pMem, szNew, 0);
68940  }
68941  assert( (pMem->flags & MEM_Dyn)==0 );
68942  pMem->z = pMem->zMalloc;
68943  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
68944  return SQLITE_OK;
68945 }
68946 
68947 /*
68948 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
68949 ** MEM.zMalloc, where it can be safely written.
68950 **
68951 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
68952 */
68954  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68955  assert( (pMem->flags&MEM_RowSet)==0 );
68956  if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
68957  if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
68958  if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
68959  if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
68960  return SQLITE_NOMEM_BKPT;
68961  }
68962  pMem->z[pMem->n] = 0;
68963  pMem->z[pMem->n+1] = 0;
68964  pMem->flags |= MEM_Term;
68965  }
68966  }
68967  pMem->flags &= ~MEM_Ephem;
68968 #ifdef SQLITE_DEBUG
68969  pMem->pScopyFrom = 0;
68970 #endif
68971 
68972  return SQLITE_OK;
68973 }
68974 
68975 /*
68976 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
68977 ** blob stored in dynamically allocated space.
68978 */
68979 #ifndef SQLITE_OMIT_INCRBLOB
68981  int nByte;
68982  assert( pMem->flags & MEM_Zero );
68983  assert( pMem->flags&MEM_Blob );
68984  assert( (pMem->flags&MEM_RowSet)==0 );
68985  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68986 
68987  /* Set nByte to the number of bytes required to store the expanded blob. */
68988  nByte = pMem->n + pMem->u.nZero;
68989  if( nByte<=0 ){
68990  nByte = 1;
68991  }
68992  if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
68993  return SQLITE_NOMEM_BKPT;
68994  }
68995 
68996  memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
68997  pMem->n += pMem->u.nZero;
68998  pMem->flags &= ~(MEM_Zero|MEM_Term);
68999  return SQLITE_OK;
69000 }
69001 #endif
69002 
69003 /*
69004 ** It is already known that pMem contains an unterminated string.
69005 ** Add the zero terminator.
69006 */
69008  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
69009  return SQLITE_NOMEM_BKPT;
69010  }
69011  pMem->z[pMem->n] = 0;
69012  pMem->z[pMem->n+1] = 0;
69013  pMem->flags |= MEM_Term;
69014  return SQLITE_OK;
69015 }
69016 
69017 /*
69018 ** Make sure the given Mem is \u0000 terminated.
69019 */
69021  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69022  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
69023  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
69024  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
69025  return SQLITE_OK; /* Nothing to do */
69026  }else{
69027  return vdbeMemAddTerminator(pMem);
69028  }
69029 }
69030 
69031 /*
69032 ** Add MEM_Str to the set of representations for the given Mem. Numbers
69033 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
69034 ** is a no-op.
69035 **
69036 ** Existing representations MEM_Int and MEM_Real are invalidated if
69037 ** bForce is true but are retained if bForce is false.
69038 **
69039 ** A MEM_Null value will never be passed to this function. This function is
69040 ** used for converting values to text for returning to the user (i.e. via
69041 ** sqlite3_value_text()), or for ensuring that values to be used as btree
69042 ** keys are strings. In the former case a NULL pointer is returned the
69043 ** user and the latter is an internal programming error.
69044 */
69045 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
69046  int fg = pMem->flags;
69047  const int nByte = 32;
69048 
69049  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69050  assert( !(fg&MEM_Zero) );
69051  assert( !(fg&(MEM_Str|MEM_Blob)) );
69052  assert( fg&(MEM_Int|MEM_Real) );
69053  assert( (pMem->flags&MEM_RowSet)==0 );
69054  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69055 
69056 
69057  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
69058  pMem->enc = 0;
69059  return SQLITE_NOMEM_BKPT;
69060  }
69061 
69062  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
69063  ** string representation of the value. Then, if the required encoding
69064  ** is UTF-16le or UTF-16be do a translation.
69065  **
69066  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
69067  */
69068  if( fg & MEM_Int ){
69069  sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
69070  }else{
69071  assert( fg & MEM_Real );
69072  sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
69073  }
69074  pMem->n = sqlite3Strlen30(pMem->z);
69075  pMem->enc = SQLITE_UTF8;
69076  pMem->flags |= MEM_Str|MEM_Term;
69077  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
69078  sqlite3VdbeChangeEncoding(pMem, enc);
69079  return SQLITE_OK;
69080 }
69081 
69082 /*
69083 ** Memory cell pMem contains the context of an aggregate function.
69084 ** This routine calls the finalize method for that function. The
69085 ** result of the aggregate is stored back into pMem.
69086 **
69087 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
69088 ** otherwise.
69089 */
69091  int rc = SQLITE_OK;
69092  if( ALWAYS(pFunc && pFunc->xFinalize) ){
69093  sqlite3_context ctx;
69094  Mem t;
69095  assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
69096  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69097  memset(&ctx, 0, sizeof(ctx));
69098  memset(&t, 0, sizeof(t));
69099  t.flags = MEM_Null;
69100  t.db = pMem->db;
69101  ctx.pOut = &t;
69102  ctx.pMem = pMem;
69103  ctx.pFunc = pFunc;
69104  pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
69105  assert( (pMem->flags & MEM_Dyn)==0 );
69106  if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
69107  memcpy(pMem, &t, sizeof(t));
69108  rc = ctx.isError;
69109  }
69110  return rc;
69111 }
69112 
69113 /*
69114 ** If the memory cell contains a value that must be freed by
69115 ** invoking the external callback in Mem.xDel, then this routine
69116 ** will free that value. It also sets Mem.flags to MEM_Null.
69117 **
69118 ** This is a helper routine for sqlite3VdbeMemSetNull() and
69119 ** for sqlite3VdbeMemRelease(). Use those other routines as the
69120 ** entry point for releasing Mem resources.
69121 */
69123  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
69124  assert( VdbeMemDynamic(p) );
69125  if( p->flags&MEM_Agg ){
69126  sqlite3VdbeMemFinalize(p, p->u.pDef);
69127  assert( (p->flags & MEM_Agg)==0 );
69128  testcase( p->flags & MEM_Dyn );
69129  }
69130  if( p->flags&MEM_Dyn ){
69131  assert( (p->flags&MEM_RowSet)==0 );
69132  assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
69133  p->xDel((void *)p->z);
69134  }else if( p->flags&MEM_RowSet ){
69136  }else if( p->flags&MEM_Frame ){
69137  VdbeFrame *pFrame = p->u.pFrame;
69138  pFrame->pParent = pFrame->v->pDelFrame;
69139  pFrame->v->pDelFrame = pFrame;
69140  }
69141  p->flags = MEM_Null;
69142 }
69143 
69144 /*
69145 ** Release memory held by the Mem p, both external memory cleared
69146 ** by p->xDel and memory in p->zMalloc.
69147 **
69148 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
69149 ** the unusual case where there really is memory in p that needs
69150 ** to be freed.
69151 */
69153  if( VdbeMemDynamic(p) ){
69155  }
69156  if( p->szMalloc ){
69157  sqlite3DbFree(p->db, p->zMalloc);
69158  p->szMalloc = 0;
69159  }
69160  p->z = 0;
69161 }
69162 
69163 /*
69164 ** Release any memory resources held by the Mem. Both the memory that is
69165 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
69166 **
69167 ** Use this routine prior to clean up prior to abandoning a Mem, or to
69168 ** reset a Mem back to its minimum memory utilization.
69169 **
69170 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
69171 ** prior to inserting new content into the Mem.
69172 */
69174  assert( sqlite3VdbeCheckMemInvariants(p) );
69175  if( VdbeMemDynamic(p) || p->szMalloc ){
69176  vdbeMemClear(p);
69177  }
69178 }
69179 
69180 /*
69181 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
69182 ** If the double is out of range of a 64-bit signed integer then
69183 ** return the closest available 64-bit signed integer.
69184 */
69185 static i64 doubleToInt64(double r){
69186 #ifdef SQLITE_OMIT_FLOATING_POINT
69187  /* When floating-point is omitted, double and int64 are the same thing */
69188  return r;
69189 #else
69190  /*
69191  ** Many compilers we encounter do not define constants for the
69192  ** minimum and maximum 64-bit integers, or they define them
69193  ** inconsistently. And many do not understand the "LL" notation.
69194  ** So we define our own static constants here using nothing
69195  ** larger than a 32-bit integer constant.
69196  */
69197  static const i64 maxInt = LARGEST_INT64;
69198  static const i64 minInt = SMALLEST_INT64;
69199 
69200  if( r<=(double)minInt ){
69201  return minInt;
69202  }else if( r>=(double)maxInt ){
69203  return maxInt;
69204  }else{
69205  return (i64)r;
69206  }
69207 #endif
69208 }
69209 
69210 /*
69211 ** Return some kind of integer value which is the best we can do
69212 ** at representing the value that *pMem describes as an integer.
69213 ** If pMem is an integer, then the value is exact. If pMem is
69214 ** a floating-point then the value returned is the integer part.
69215 ** If pMem is a string or blob, then we make an attempt to convert
69216 ** it into an integer and return that. If pMem represents an
69217 ** an SQL-NULL value, return 0.
69218 **
69219 ** If pMem represents a string value, its encoding might be changed.
69220 */
69222  int flags;
69223  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69224  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69225  flags = pMem->flags;
69226  if( flags & MEM_Int ){
69227  return pMem->u.i;
69228  }else if( flags & MEM_Real ){
69229  return doubleToInt64(pMem->u.r);
69230  }else if( flags & (MEM_Str|MEM_Blob) ){
69231  i64 value = 0;
69232  assert( pMem->z || pMem->n==0 );
69233  sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
69234  return value;
69235  }else{
69236  return 0;
69237  }
69238 }
69239 
69240 /*
69241 ** Return the best representation of pMem that we can get into a
69242 ** double. If pMem is already a double or an integer, return its
69243 ** value. If it is a string or blob, try to convert it to a double.
69244 ** If it is a NULL, return 0.0.
69245 */
69247  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69248  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69249  if( pMem->flags & MEM_Real ){
69250  return pMem->u.r;
69251  }else if( pMem->flags & MEM_Int ){
69252  return (double)pMem->u.i;
69253  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
69254  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69255  double val = (double)0;
69256  sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
69257  return val;
69258  }else{
69259  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69260  return (double)0;
69261  }
69262 }
69263 
69264 /*
69265 ** The MEM structure is already a MEM_Real. Try to also make it a
69266 ** MEM_Int if we can.
69267 */
69269  i64 ix;
69270  assert( pMem->flags & MEM_Real );
69271  assert( (pMem->flags & MEM_RowSet)==0 );
69272  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69273  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69274 
69275  ix = doubleToInt64(pMem->u.r);
69276 
69277  /* Only mark the value as an integer if
69278  **
69279  ** (1) the round-trip conversion real->int->real is a no-op, and
69280  ** (2) The integer is neither the largest nor the smallest
69281  ** possible integer (ticket #3922)
69282  **
69283  ** The second and third terms in the following conditional enforces
69284  ** the second condition under the assumption that addition overflow causes
69285  ** values to wrap around.
69286  */
69287  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
69288  pMem->u.i = ix;
69289  MemSetTypeFlag(pMem, MEM_Int);
69290  }
69291 }
69292 
69293 /*
69294 ** Convert pMem to type integer. Invalidate any prior representations.
69295 */
69297  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69298  assert( (pMem->flags & MEM_RowSet)==0 );
69299  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69300 
69301  pMem->u.i = sqlite3VdbeIntValue(pMem);
69302  MemSetTypeFlag(pMem, MEM_Int);
69303  return SQLITE_OK;
69304 }
69305 
69306 /*
69307 ** Convert pMem so that it is of type MEM_Real.
69308 ** Invalidate any prior representations.
69309 */
69311  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69312  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69313 
69314  pMem->u.r = sqlite3VdbeRealValue(pMem);
69315  MemSetTypeFlag(pMem, MEM_Real);
69316  return SQLITE_OK;
69317 }
69318 
69319 /*
69320 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
69321 ** Invalidate any prior representations.
69322 **
69323 ** Every effort is made to force the conversion, even if the input
69324 ** is a string that does not look completely like a number. Convert
69325 ** as much of the string as we can and ignore the rest.
69326 */
69328  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
69329  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
69330  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69331  if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
69332  MemSetTypeFlag(pMem, MEM_Int);
69333  }else{
69334  pMem->u.r = sqlite3VdbeRealValue(pMem);
69335  MemSetTypeFlag(pMem, MEM_Real);
69337  }
69338  }
69339  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
69340  pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
69341  return SQLITE_OK;
69342 }
69343 
69344 /*
69345 ** Cast the datatype of the value in pMem according to the affinity
69346 ** "aff". Casting is different from applying affinity in that a cast
69347 ** is forced. In other words, the value is converted into the desired
69348 ** affinity even if that results in loss of data. This routine is
69349 ** used (for example) to implement the SQL "cast()" operator.
69350 */
69351 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
69352  if( pMem->flags & MEM_Null ) return;
69353  switch( aff ){
69354  case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
69355  if( (pMem->flags & MEM_Blob)==0 ){
69356  sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69357  assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69358  if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
69359  }else{
69360  pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
69361  }
69362  break;
69363  }
69364  case SQLITE_AFF_NUMERIC: {
69365  sqlite3VdbeMemNumerify(pMem);
69366  break;
69367  }
69368  case SQLITE_AFF_INTEGER: {
69370  break;
69371  }
69372  case SQLITE_AFF_REAL: {
69373  sqlite3VdbeMemRealify(pMem);
69374  break;
69375  }
69376  default: {
69377  assert( aff==SQLITE_AFF_TEXT );
69378  assert( MEM_Str==(MEM_Blob>>3) );
69379  pMem->flags |= (pMem->flags&MEM_Blob)>>3;
69380  sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69381  assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69382  pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
69383  break;
69384  }
69385  }
69386 }
69387 
69388 /*
69389 ** Initialize bulk memory to be a consistent Mem object.
69390 **
69391 ** The minimum amount of initialization feasible is performed.
69392 */
69393 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
69394  assert( (flags & ~MEM_TypeMask)==0 );
69395  pMem->flags = flags;
69396  pMem->db = db;
69397  pMem->szMalloc = 0;
69398 }
69399 
69400 
69401 /*
69402 ** Delete any previous value and set the value stored in *pMem to NULL.
69403 **
69404 ** This routine calls the Mem.xDel destructor to dispose of values that
69405 ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
69406 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
69407 ** routine to invoke the destructor and deallocates Mem.zMalloc.
69408 **
69409 ** Use this routine to reset the Mem prior to insert a new value.
69410 **
69411 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
69412 */
69414  if( VdbeMemDynamic(pMem) ){
69416  }else{
69417  pMem->flags = MEM_Null;
69418  }
69419 }
69421  sqlite3VdbeMemSetNull((Mem*)p);
69422 }
69423 
69424 /*
69425 ** Delete any previous value and set the value to be a BLOB of length
69426 ** n containing all zeros.
69427 */
69429  sqlite3VdbeMemRelease(pMem);
69430  pMem->flags = MEM_Blob|MEM_Zero;
69431  pMem->n = 0;
69432  if( n<0 ) n = 0;
69433  pMem->u.nZero = n;
69434  pMem->enc = SQLITE_UTF8;
69435  pMem->z = 0;
69436 }
69437 
69438 /*
69439 ** The pMem is known to contain content that needs to be destroyed prior
69440 ** to a value change. So invoke the destructor, then set the value to
69441 ** a 64-bit integer.
69442 */
69443 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
69444  sqlite3VdbeMemSetNull(pMem);
69445  pMem->u.i = val;
69446  pMem->flags = MEM_Int;
69447 }
69448 
69449 /*
69450 ** Delete any previous value and set the value stored in *pMem to val,
69451 ** manifest type INTEGER.
69452 */
69454  if( VdbeMemDynamic(pMem) ){
69455  vdbeReleaseAndSetInt64(pMem, val);
69456  }else{
69457  pMem->u.i = val;
69458  pMem->flags = MEM_Int;
69459  }
69460 }
69461 
69462 #ifndef SQLITE_OMIT_FLOATING_POINT
69463 /*
69464 ** Delete any previous value and set the value stored in *pMem to val,
69465 ** manifest type REAL.
69466 */
69468  sqlite3VdbeMemSetNull(pMem);
69469  if( !sqlite3IsNaN(val) ){
69470  pMem->u.r = val;
69471  pMem->flags = MEM_Real;
69472  }
69473 }
69474 #endif
69475 
69476 /*
69477 ** Delete any previous value and set the value of pMem to be an
69478 ** empty boolean index.
69479 */
69481  sqlite3 *db = pMem->db;
69482  assert( db!=0 );
69483  assert( (pMem->flags & MEM_RowSet)==0 );
69484  sqlite3VdbeMemRelease(pMem);
69485  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
69486  if( db->mallocFailed ){
69487  pMem->flags = MEM_Null;
69488  pMem->szMalloc = 0;
69489  }else{
69490  assert( pMem->zMalloc );
69491  pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
69492  pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
69493  assert( pMem->u.pRowSet!=0 );
69494  pMem->flags = MEM_RowSet;
69495  }
69496 }
69497 
69498 /*
69499 ** Return true if the Mem object contains a TEXT or BLOB that is
69500 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
69501 */
69503  assert( p->db!=0 );
69504  if( p->flags & (MEM_Str|MEM_Blob) ){
69505  int n = p->n;
69506  if( p->flags & MEM_Zero ){
69507  n += p->u.nZero;
69508  }
69509  return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
69510  }
69511  return 0;
69512 }
69513 
69514 #ifdef SQLITE_DEBUG
69515 /*
69516 ** This routine prepares a memory cell for modification by breaking
69517 ** its link to a shallow copy and by marking any current shallow
69518 ** copies of this cell as invalid.
69519 **
69520 ** This is used for testing and debugging only - to make sure shallow
69521 ** copies are not misused.
69522 */
69523 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
69524  int i;
69525  Mem *pX;
69526  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
69527  if( pX->pScopyFrom==pMem ){
69528  pX->flags |= MEM_Undefined;
69529  pX->pScopyFrom = 0;
69530  }
69531  }
69532  pMem->pScopyFrom = 0;
69533 }
69534 #endif /* SQLITE_DEBUG */
69535 
69536 
69537 /*
69538 ** Make an shallow copy of pFrom into pTo. Prior contents of
69539 ** pTo are freed. The pFrom->z field is not duplicated. If
69540 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
69541 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
69542 */
69543 static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
69545  assert( !VdbeMemDynamic(pTo) );
69546  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
69547 }
69548 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
69549  assert( (pFrom->flags & MEM_RowSet)==0 );
69550  assert( pTo->db==pFrom->db );
69551  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
69552  memcpy(pTo, pFrom, MEMCELLSIZE);
69553  if( (pFrom->flags&MEM_Static)==0 ){
69554  pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
69555  assert( srcType==MEM_Ephem || srcType==MEM_Static );
69556  pTo->flags |= srcType;
69557  }
69558 }
69559 
69560 /*
69561 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
69562 ** freed before the copy is made.
69563 */
69564 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
69565  int rc = SQLITE_OK;
69566 
69567  assert( (pFrom->flags & MEM_RowSet)==0 );
69569  memcpy(pTo, pFrom, MEMCELLSIZE);
69570  pTo->flags &= ~MEM_Dyn;
69571  if( pTo->flags&(MEM_Str|MEM_Blob) ){
69572  if( 0==(pFrom->flags&MEM_Static) ){
69573  pTo->flags |= MEM_Ephem;
69574  rc = sqlite3VdbeMemMakeWriteable(pTo);
69575  }
69576  }
69577 
69578  return rc;
69579 }
69580 
69581 /*
69582 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
69583 ** freed. If pFrom contains ephemeral data, a copy is made.
69584 **
69585 ** pFrom contains an SQL NULL when this routine returns.
69586 */
69588  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
69589  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
69590  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
69591 
69592  sqlite3VdbeMemRelease(pTo);
69593  memcpy(pTo, pFrom, sizeof(Mem));
69594  pFrom->flags = MEM_Null;
69595  pFrom->szMalloc = 0;
69596 }
69597 
69598 /*
69599 ** Change the value of a Mem to be a string or a BLOB.
69600 **
69601 ** The memory management strategy depends on the value of the xDel
69602 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
69603 ** string is copied into a (possibly existing) buffer managed by the
69604 ** Mem structure. Otherwise, any existing buffer is freed and the
69605 ** pointer copied.
69606 **
69607 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
69608 ** size limit) then no memory allocation occurs. If the string can be
69609 ** stored without allocating memory, then it is. If a memory allocation
69610 ** is required to store the string, then value of pMem is unchanged. In
69611 ** either case, SQLITE_TOOBIG is returned.
69612 */
69614  Mem *pMem, /* Memory cell to set to string value */
69615  const char *z, /* String pointer */
69616  int n, /* Bytes in string, or negative */
69617  u8 enc, /* Encoding of z. 0 for BLOBs */
69618  void (*xDel)(void*) /* Destructor function */
69619 ){
69620  int nByte = n; /* New value for pMem->n */
69621  int iLimit; /* Maximum allowed string or blob size */
69622  u16 flags = 0; /* New value for pMem->flags */
69623 
69624  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69625  assert( (pMem->flags & MEM_RowSet)==0 );
69626 
69627  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
69628  if( !z ){
69629  sqlite3VdbeMemSetNull(pMem);
69630  return SQLITE_OK;
69631  }
69632 
69633  if( pMem->db ){
69634  iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
69635  }else{
69636  iLimit = SQLITE_MAX_LENGTH;
69637  }
69638  flags = (enc==0?MEM_Blob:MEM_Str);
69639  if( nByte<0 ){
69640  assert( enc!=0 );
69641  if( enc==SQLITE_UTF8 ){
69642  nByte = sqlite3Strlen30(z);
69643  if( nByte>iLimit ) nByte = iLimit+1;
69644  }else{
69645  for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
69646  }
69647  flags |= MEM_Term;
69648  }
69649 
69650  /* The following block sets the new values of Mem.z and Mem.xDel. It
69651  ** also sets a flag in local variable "flags" to indicate the memory
69652  ** management (one of MEM_Dyn or MEM_Static).
69653  */
69654  if( xDel==SQLITE_TRANSIENT ){
69655  int nAlloc = nByte;
69656  if( flags&MEM_Term ){
69657  nAlloc += (enc==SQLITE_UTF8?1:2);
69658  }
69659  if( nByte>iLimit ){
69660  return SQLITE_TOOBIG;
69661  }
69662  testcase( nAlloc==0 );
69663  testcase( nAlloc==31 );
69664  testcase( nAlloc==32 );
69665  if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
69666  return SQLITE_NOMEM_BKPT;
69667  }
69668  memcpy(pMem->z, z, nAlloc);
69669  }else if( xDel==SQLITE_DYNAMIC ){
69670  sqlite3VdbeMemRelease(pMem);
69671  pMem->zMalloc = pMem->z = (char *)z;
69672  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
69673  }else{
69674  sqlite3VdbeMemRelease(pMem);
69675  pMem->z = (char *)z;
69676  pMem->xDel = xDel;
69677  flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
69678  }
69679 
69680  pMem->n = nByte;
69681  pMem->flags = flags;
69682  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
69683 
69684 #ifndef SQLITE_OMIT_UTF16
69685  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
69686  return SQLITE_NOMEM_BKPT;
69687  }
69688 #endif
69689 
69690  if( nByte>iLimit ){
69691  return SQLITE_TOOBIG;
69692  }
69693 
69694  return SQLITE_OK;
69695 }
69696 
69697 /*
69698 ** Move data out of a btree key or data field and into a Mem structure.
69699 ** The data or key is taken from the entry that pCur is currently pointing
69700 ** to. offset and amt determine what portion of the data or key to retrieve.
69701 ** key is true to get the key or false to get data. The result is written
69702 ** into the pMem element.
69703 **
69704 ** The pMem object must have been initialized. This routine will use
69705 ** pMem->zMalloc to hold the content from the btree, if possible. New
69706 ** pMem->zMalloc space will be allocated if necessary. The calling routine
69707 ** is responsible for making sure that the pMem object is eventually
69708 ** destroyed.
69709 **
69710 ** If this routine fails for any reason (malloc returns NULL or unable
69711 ** to read from the disk) then the pMem is left in an inconsistent state.
69712 */
69714  BtCursor *pCur, /* Cursor pointing at record to retrieve. */
69715  u32 offset, /* Offset from the start of data to return bytes from. */
69716  u32 amt, /* Number of bytes to return. */
69717  int key, /* If true, retrieve from the btree key, not data. */
69718  Mem *pMem /* OUT: Return data in this Mem structure. */
69719 ){
69720  int rc;
69721  pMem->flags = MEM_Null;
69722  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
69723  if( key ){
69724  rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
69725  }else{
69726  rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
69727  }
69728  if( rc==SQLITE_OK ){
69729  pMem->z[amt] = 0;
69730  pMem->z[amt+1] = 0;
69731  pMem->flags = MEM_Blob|MEM_Term;
69732  pMem->n = (int)amt;
69733  }else{
69734  sqlite3VdbeMemRelease(pMem);
69735  }
69736  }
69737  return rc;
69738 }
69740  BtCursor *pCur, /* Cursor pointing at record to retrieve. */
69741  u32 offset, /* Offset from the start of data to return bytes from. */
69742  u32 amt, /* Number of bytes to return. */
69743  int key, /* If true, retrieve from the btree key, not data. */
69744  Mem *pMem /* OUT: Return data in this Mem structure. */
69745 ){
69746  char *zData; /* Data from the btree layer */
69747  u32 available = 0; /* Number of bytes available on the local btree page */
69748  int rc = SQLITE_OK; /* Return code */
69749 
69750  assert( sqlite3BtreeCursorIsValid(pCur) );
69751  assert( !VdbeMemDynamic(pMem) );
69752 
69753  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
69754  ** that both the BtShared and database handle mutexes are held. */
69755  assert( (pMem->flags & MEM_RowSet)==0 );
69756  zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
69757  assert( zData!=0 );
69758 
69759  if( offset+amt<=available ){
69760  pMem->z = &zData[offset];
69761  pMem->flags = MEM_Blob|MEM_Ephem;
69762  pMem->n = (int)amt;
69763  }else{
69764  rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
69765  }
69766 
69767  return rc;
69768 }
69769 
69770 /*
69771 ** The pVal argument is known to be a value other than NULL.
69772 ** Convert it into a string with encoding enc and return a pointer
69773 ** to a zero-terminated version of that string.
69774 */
69775 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
69776  assert( pVal!=0 );
69777  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69778  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69779  assert( (pVal->flags & MEM_RowSet)==0 );
69780  assert( (pVal->flags & (MEM_Null))==0 );
69781  if( pVal->flags & (MEM_Blob|MEM_Str) ){
69782  pVal->flags |= MEM_Str;
69783  if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
69785  }
69786  if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
69787  assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
69789  return 0;
69790  }
69791  }
69792  sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
69793  }else{
69794  sqlite3VdbeMemStringify(pVal, enc, 0);
69795  assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
69796  }
69797  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
69798  || pVal->db->mallocFailed );
69799  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
69800  return pVal->z;
69801  }else{
69802  return 0;
69803  }
69804 }
69805 
69806 /* This function is only available internally, it is not part of the
69807 ** external API. It works in a similar way to sqlite3_value_text(),
69808 ** except the data returned is in the encoding specified by the second
69809 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
69810 ** SQLITE_UTF8.
69811 **
69812 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
69813 ** If that is the case, then the result must be aligned on an even byte
69814 ** boundary.
69815 */
69816 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
69817  if( !pVal ) return 0;
69818  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69819  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69820  assert( (pVal->flags & MEM_RowSet)==0 );
69821  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
69822  return pVal->z;
69823  }
69824  if( pVal->flags&MEM_Null ){
69825  return 0;
69826  }
69827  return valueToText(pVal, enc);
69828 }
69829 
69830 /*
69831 ** Create a new sqlite3_value object.
69832 */
69834  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
69835  if( p ){
69836  p->flags = MEM_Null;
69837  p->db = db;
69838  }
69839  return p;
69840 }
69841 
69842 /*
69843 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
69844 ** valueNew(). See comments above valueNew() for details.
69845 */
69850  int iVal;
69851 };
69852 
69853 /*
69854 ** Allocate and return a pointer to a new sqlite3_value object. If
69855 ** the second argument to this function is NULL, the object is allocated
69856 ** by calling sqlite3ValueNew().
69857 **
69858 ** Otherwise, if the second argument is non-zero, then this function is
69859 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
69860 ** already been allocated, allocate the UnpackedRecord structure that
69861 ** that function will return to its caller here. Then return a pointer to
69862 ** an sqlite3_value within the UnpackedRecord.a[] array.
69863 */
69865 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69866  if( p ){
69867  UnpackedRecord *pRec = p->ppRec[0];
69868 
69869  if( pRec==0 ){
69870  Index *pIdx = p->pIdx; /* Index being probed */
69871  int nByte; /* Bytes of space to allocate */
69872  int i; /* Counter variable */
69873  int nCol = pIdx->nColumn; /* Number of index columns including rowid */
69874 
69875  nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
69876  pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
69877  if( pRec ){
69878  pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
69879  if( pRec->pKeyInfo ){
69880  assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
69881  assert( pRec->pKeyInfo->enc==ENC(db) );
69882  pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
69883  for(i=0; i<nCol; i++){
69884  pRec->aMem[i].flags = MEM_Null;
69885  pRec->aMem[i].db = db;
69886  }
69887  }else{
69888  sqlite3DbFree(db, pRec);
69889  pRec = 0;
69890  }
69891  }
69892  if( pRec==0 ) return 0;
69893  p->ppRec[0] = pRec;
69894  }
69895 
69896  pRec->nField = p->iVal+1;
69897  return &pRec->aMem[p->iVal];
69898  }
69899 #else
69900  UNUSED_PARAMETER(p);
69901 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69902  return sqlite3ValueNew(db);
69903 }
69904 
69905 /*
69906 ** The expression object indicated by the second argument is guaranteed
69907 ** to be a scalar SQL function. If
69908 **
69909 ** * all function arguments are SQL literals,
69910 ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
69911 ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
69912 **
69913 ** then this routine attempts to invoke the SQL function. Assuming no
69914 ** error occurs, output parameter (*ppVal) is set to point to a value
69915 ** object containing the result before returning SQLITE_OK.
69916 **
69917 ** Affinity aff is applied to the result of the function before returning.
69918 ** If the result is a text value, the sqlite3_value object uses encoding
69919 ** enc.
69920 **
69921 ** If the conditions above are not met, this function returns SQLITE_OK
69922 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
69923 ** NULL and an SQLite error code returned.
69924 */
69925 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69926 static int valueFromFunction(
69927  sqlite3 *db, /* The database connection */
69928  Expr *p, /* The expression to evaluate */
69929  u8 enc, /* Encoding to use */
69930  u8 aff, /* Affinity to use */
69931  sqlite3_value **ppVal, /* Write the new value here */
69932  struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
69933 ){
69934  sqlite3_context ctx; /* Context object for function invocation */
69935  sqlite3_value **apVal = 0; /* Function arguments */
69936  int nVal = 0; /* Size of apVal[] array */
69937  FuncDef *pFunc = 0; /* Function definition */
69938  sqlite3_value *pVal = 0; /* New value */
69939  int rc = SQLITE_OK; /* Return code */
69940  ExprList *pList = 0; /* Function arguments */
69941  int i; /* Iterator variable */
69942 
69943  assert( pCtx!=0 );
69944  assert( (p->flags & EP_TokenOnly)==0 );
69945  pList = p->x.pList;
69946  if( pList ) nVal = pList->nExpr;
69947  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
69948  assert( pFunc );
69950  || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
69951  ){
69952  return SQLITE_OK;
69953  }
69954 
69955  if( pList ){
69956  apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
69957  if( apVal==0 ){
69958  rc = SQLITE_NOMEM_BKPT;
69959  goto value_from_function_out;
69960  }
69961  for(i=0; i<nVal; i++){
69962  rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
69963  if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
69964  }
69965  }
69966 
69967  pVal = valueNew(db, pCtx);
69968  if( pVal==0 ){
69969  rc = SQLITE_NOMEM_BKPT;
69970  goto value_from_function_out;
69971  }
69972 
69973  assert( pCtx->pParse->rc==SQLITE_OK );
69974  memset(&ctx, 0, sizeof(ctx));
69975  ctx.pOut = pVal;
69976  ctx.pFunc = pFunc;
69977  pFunc->xSFunc(&ctx, nVal, apVal);
69978  if( ctx.isError ){
69979  rc = ctx.isError;
69980  sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
69981  }else{
69983  assert( rc==SQLITE_OK );
69984  rc = sqlite3VdbeChangeEncoding(pVal, enc);
69985  if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
69986  rc = SQLITE_TOOBIG;
69987  pCtx->pParse->nErr++;
69988  }
69989  }
69990  pCtx->pParse->rc = rc;
69991 
69992  value_from_function_out:
69993  if( rc!=SQLITE_OK ){
69994  pVal = 0;
69995  }
69996  if( apVal ){
69997  for(i=0; i<nVal; i++){
69998  sqlite3ValueFree(apVal[i]);
69999  }
70000  sqlite3DbFree(db, apVal);
70001  }
70002 
70003  *ppVal = pVal;
70004  return rc;
70005 }
70006 #else
70007 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
70008 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
70009 
70010 /*
70011 ** Extract a value from the supplied expression in the manner described
70012 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
70013 ** using valueNew().
70014 **
70015 ** If pCtx is NULL and an error occurs after the sqlite3_value object
70016 ** has been allocated, it is freed before returning. Or, if pCtx is not
70017 ** NULL, it is assumed that the caller will free any allocated object
70018 ** in all cases.
70019 */
70020 static int valueFromExpr(
70021  sqlite3 *db, /* The database connection */
70022  Expr *pExpr, /* The expression to evaluate */
70023  u8 enc, /* Encoding to use */
70024  u8 affinity, /* Affinity to use */
70025  sqlite3_value **ppVal, /* Write the new value here */
70026  struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
70027 ){
70028  int op;
70029  char *zVal = 0;
70030  sqlite3_value *pVal = 0;
70031  int negInt = 1;
70032  const char *zNeg = "";
70033  int rc = SQLITE_OK;
70034 
70035  assert( pExpr!=0 );
70036  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
70037  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
70038 
70039  /* Compressed expressions only appear when parsing the DEFAULT clause
70040  ** on a table column definition, and hence only when pCtx==0. This
70041  ** check ensures that an EP_TokenOnly expression is never passed down
70042  ** into valueFromFunction(). */
70043  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
70044 
70045  if( op==TK_CAST ){
70046  u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
70047  rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
70048  testcase( rc!=SQLITE_OK );
70049  if( *ppVal ){
70050  sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
70051  sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
70052  }
70053  return rc;
70054  }
70055 
70056  /* Handle negative integers in a single step. This is needed in the
70057  ** case when the value is -9223372036854775808.
70058  */
70059  if( op==TK_UMINUS
70060  && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
70061  pExpr = pExpr->pLeft;
70062  op = pExpr->op;
70063  negInt = -1;
70064  zNeg = "-";
70065  }
70066 
70067  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
70068  pVal = valueNew(db, pCtx);
70069  if( pVal==0 ) goto no_mem;
70070  if( ExprHasProperty(pExpr, EP_IntValue) ){
70071  sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
70072  }else{
70073  zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
70074  if( zVal==0 ) goto no_mem;
70075  sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
70076  }
70077  if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
70079  }else{
70080  sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
70081  }
70082  if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
70083  if( enc!=SQLITE_UTF8 ){
70084  rc = sqlite3VdbeChangeEncoding(pVal, enc);
70085  }
70086  }else if( op==TK_UMINUS ) {
70087  /* This branch happens for multiple negative signs. Ex: -(-5) */
70088  if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
70089  && pVal!=0
70090  ){
70091  sqlite3VdbeMemNumerify(pVal);
70092  if( pVal->flags & MEM_Real ){
70093  pVal->u.r = -pVal->u.r;
70094  }else if( pVal->u.i==SMALLEST_INT64 ){
70095  pVal->u.r = -(double)SMALLEST_INT64;
70096  MemSetTypeFlag(pVal, MEM_Real);
70097  }else{
70098  pVal->u.i = -pVal->u.i;
70099  }
70100  sqlite3ValueApplyAffinity(pVal, affinity, enc);
70101  }
70102  }else if( op==TK_NULL ){
70103  pVal = valueNew(db, pCtx);
70104  if( pVal==0 ) goto no_mem;
70105  }
70106 #ifndef SQLITE_OMIT_BLOB_LITERAL
70107  else if( op==TK_BLOB ){
70108  int nVal;
70109  assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70110  assert( pExpr->u.zToken[1]=='\'' );
70111  pVal = valueNew(db, pCtx);
70112  if( !pVal ) goto no_mem;
70113  zVal = &pExpr->u.zToken[2];
70114  nVal = sqlite3Strlen30(zVal)-1;
70115  assert( zVal[nVal]=='\'' );
70116  sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
70117  0, SQLITE_DYNAMIC);
70118  }
70119 #endif
70120 
70121 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70122  else if( op==TK_FUNCTION && pCtx!=0 ){
70123  rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
70124  }
70125 #endif
70126 
70127  *ppVal = pVal;
70128  return rc;
70129 
70130 no_mem:
70131  sqlite3OomFault(db);
70132  sqlite3DbFree(db, zVal);
70133  assert( *ppVal==0 );
70134 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70135  if( pCtx==0 ) sqlite3ValueFree(pVal);
70136 #else
70137  assert( pCtx==0 ); sqlite3ValueFree(pVal);
70138 #endif
70139  return SQLITE_NOMEM_BKPT;
70140 }
70141 
70142 /*
70143 ** Create a new sqlite3_value object, containing the value of pExpr.
70144 **
70145 ** This only works for very simple expressions that consist of one constant
70146 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
70147 ** be converted directly into a value, then the value is allocated and
70148 ** a pointer written to *ppVal. The caller is responsible for deallocating
70149 ** the value by passing it to sqlite3ValueFree() later on. If the expression
70150 ** cannot be converted to a value, then *ppVal is set to NULL.
70151 */
70153  sqlite3 *db, /* The database connection */
70154  Expr *pExpr, /* The expression to evaluate */
70155  u8 enc, /* Encoding to use */
70156  u8 affinity, /* Affinity to use */
70157  sqlite3_value **ppVal /* Write the new value here */
70158 ){
70159  return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
70160 }
70161 
70162 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70163 /*
70164 ** The implementation of the sqlite_record() function. This function accepts
70165 ** a single argument of any type. The return value is a formatted database
70166 ** record (a blob) containing the argument value.
70167 **
70168 ** This is used to convert the value stored in the 'sample' column of the
70169 ** sqlite_stat3 table to the record format SQLite uses internally.
70170 */
70171 static void recordFunc(
70172  sqlite3_context *context,
70173  int argc,
70174  sqlite3_value **argv
70175 ){
70176  const int file_format = 1;
70177  u32 iSerial; /* Serial type */
70178  int nSerial; /* Bytes of space for iSerial as varint */
70179  u32 nVal; /* Bytes of space required for argv[0] */
70180  int nRet;
70181  sqlite3 *db;
70182  u8 *aRet;
70183 
70184  UNUSED_PARAMETER( argc );
70185  iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
70186  nSerial = sqlite3VarintLen(iSerial);
70187  db = sqlite3_context_db_handle(context);
70188 
70189  nRet = 1 + nSerial + nVal;
70190  aRet = sqlite3DbMallocRawNN(db, nRet);
70191  if( aRet==0 ){
70192  sqlite3_result_error_nomem(context);
70193  }else{
70194  aRet[0] = nSerial+1;
70195  putVarint32(&aRet[1], iSerial);
70196  sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
70197  sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
70198  sqlite3DbFree(db, aRet);
70199  }
70200 }
70201 
70202 /*
70203 ** Register built-in functions used to help read ANALYZE data.
70204 */
70205 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
70206  static FuncDef aAnalyzeTableFuncs[] = {
70207  FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
70208  };
70209  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
70210 }
70211 
70212 /*
70213 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
70214 **
70215 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
70216 ** pAlloc if one does not exist and the new value is added to the
70217 ** UnpackedRecord object.
70218 **
70219 ** A value is extracted in the following cases:
70220 **
70221 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70222 **
70223 ** * The expression is a bound variable, and this is a reprepare, or
70224 **
70225 ** * The expression is a literal value.
70226 **
70227 ** On success, *ppVal is made to point to the extracted value. The caller
70228 ** is responsible for ensuring that the value is eventually freed.
70229 */
70230 static int stat4ValueFromExpr(
70231  Parse *pParse, /* Parse context */
70232  Expr *pExpr, /* The expression to extract a value from */
70233  u8 affinity, /* Affinity to use */
70234  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
70235  sqlite3_value **ppVal /* OUT: New value object (or NULL) */
70236 ){
70237  int rc = SQLITE_OK;
70238  sqlite3_value *pVal = 0;
70239  sqlite3 *db = pParse->db;
70240 
70241  /* Skip over any TK_COLLATE nodes */
70242  pExpr = sqlite3ExprSkipCollate(pExpr);
70243 
70244  if( !pExpr ){
70245  pVal = valueNew(db, pAlloc);
70246  if( pVal ){
70247  sqlite3VdbeMemSetNull((Mem*)pVal);
70248  }
70249  }else if( pExpr->op==TK_VARIABLE
70250  || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
70251  ){
70252  Vdbe *v;
70253  int iBindVar = pExpr->iColumn;
70254  sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
70255  if( (v = pParse->pReprepare)!=0 ){
70256  pVal = valueNew(db, pAlloc);
70257  if( pVal ){
70258  rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
70259  if( rc==SQLITE_OK ){
70260  sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
70261  }
70262  pVal->db = pParse->db;
70263  }
70264  }
70265  }else{
70266  rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
70267  }
70268 
70269  assert( pVal==0 || pVal->db==db );
70270  *ppVal = pVal;
70271  return rc;
70272 }
70273 
70274 /*
70275 ** This function is used to allocate and populate UnpackedRecord
70276 ** structures intended to be compared against sample index keys stored
70277 ** in the sqlite_stat4 table.
70278 **
70279 ** A single call to this function populates zero or more fields of the
70280 ** record starting with field iVal (fields are numbered from left to
70281 ** right starting with 0). A single field is populated if:
70282 **
70283 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70284 **
70285 ** * The expression is a bound variable, and this is a reprepare, or
70286 **
70287 ** * The sqlite3ValueFromExpr() function is able to extract a value
70288 ** from the expression (i.e. the expression is a literal value).
70289 **
70290 ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
70291 ** vector components that match either of the two latter criteria listed
70292 ** above.
70293 **
70294 ** Before any value is appended to the record, the affinity of the
70295 ** corresponding column within index pIdx is applied to it. Before
70296 ** this function returns, output parameter *pnExtract is set to the
70297 ** number of values appended to the record.
70298 **
70299 ** When this function is called, *ppRec must either point to an object
70300 ** allocated by an earlier call to this function, or must be NULL. If it
70301 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
70302 ** is allocated (and *ppRec set to point to it) before returning.
70303 **
70304 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
70305 ** error if a value cannot be extracted from pExpr. If an error does
70306 ** occur, an SQLite error code is returned.
70307 */
70308 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
70309  Parse *pParse, /* Parse context */
70310  Index *pIdx, /* Index being probed */
70311  UnpackedRecord **ppRec, /* IN/OUT: Probe record */
70312  Expr *pExpr, /* The expression to extract a value from */
70313  int nElem, /* Maximum number of values to append */
70314  int iVal, /* Array element to populate */
70315  int *pnExtract /* OUT: Values appended to the record */
70316 ){
70317  int rc = SQLITE_OK;
70318  int nExtract = 0;
70319 
70320  if( pExpr==0 || pExpr->op!=TK_SELECT ){
70321  int i;
70322  struct ValueNewStat4Ctx alloc;
70323 
70324  alloc.pParse = pParse;
70325  alloc.pIdx = pIdx;
70326  alloc.ppRec = ppRec;
70327 
70328  for(i=0; i<nElem; i++){
70329  sqlite3_value *pVal = 0;
70330  Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
70331  u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
70332  alloc.iVal = iVal+i;
70333  rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
70334  if( !pVal ) break;
70335  nExtract++;
70336  }
70337  }
70338 
70339  *pnExtract = nExtract;
70340  return rc;
70341 }
70342 
70343 /*
70344 ** Attempt to extract a value from expression pExpr using the methods
70345 ** as described for sqlite3Stat4ProbeSetValue() above.
70346 **
70347 ** If successful, set *ppVal to point to a new value object and return
70348 ** SQLITE_OK. If no value can be extracted, but no other error occurs
70349 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
70350 ** does occur, return an SQLite error code. The final value of *ppVal
70351 ** is undefined in this case.
70352 */
70353 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
70354  Parse *pParse, /* Parse context */
70355  Expr *pExpr, /* The expression to extract a value from */
70356  u8 affinity, /* Affinity to use */
70357  sqlite3_value **ppVal /* OUT: New value object (or NULL) */
70358 ){
70359  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
70360 }
70361 
70362 /*
70363 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
70364 ** the column value into *ppVal. If *ppVal is initially NULL then a new
70365 ** sqlite3_value object is allocated.
70366 **
70367 ** If *ppVal is initially NULL then the caller is responsible for
70368 ** ensuring that the value written into *ppVal is eventually freed.
70369 */
70370 SQLITE_PRIVATE int sqlite3Stat4Column(
70371  sqlite3 *db, /* Database handle */
70372  const void *pRec, /* Pointer to buffer containing record */
70373  int nRec, /* Size of buffer pRec in bytes */
70374  int iCol, /* Column to extract */
70375  sqlite3_value **ppVal /* OUT: Extracted value */
70376 ){
70377  u32 t; /* a column type code */
70378  int nHdr; /* Size of the header in the record */
70379  int iHdr; /* Next unread header byte */
70380  int iField; /* Next unread data byte */
70381  int szField; /* Size of the current data field */
70382  int i; /* Column index */
70383  u8 *a = (u8*)pRec; /* Typecast byte array */
70384  Mem *pMem = *ppVal; /* Write result into this Mem object */
70385 
70386  assert( iCol>0 );
70387  iHdr = getVarint32(a, nHdr);
70388  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
70389  iField = nHdr;
70390  for(i=0; i<=iCol; i++){
70391  iHdr += getVarint32(&a[iHdr], t);
70392  testcase( iHdr==nHdr );
70393  testcase( iHdr==nHdr+1 );
70394  if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
70395  szField = sqlite3VdbeSerialTypeLen(t);
70396  iField += szField;
70397  }
70398  testcase( iField==nRec );
70399  testcase( iField==nRec+1 );
70400  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
70401  if( pMem==0 ){
70402  pMem = *ppVal = sqlite3ValueNew(db);
70403  if( pMem==0 ) return SQLITE_NOMEM_BKPT;
70404  }
70405  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
70406  pMem->enc = ENC(db);
70407  return SQLITE_OK;
70408 }
70409 
70410 /*
70411 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
70412 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
70413 ** the object.
70414 */
70415 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
70416  if( pRec ){
70417  int i;
70418  int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
70419  Mem *aMem = pRec->aMem;
70420  sqlite3 *db = aMem[0].db;
70421  for(i=0; i<nCol; i++){
70422  sqlite3VdbeMemRelease(&aMem[i]);
70423  }
70425  sqlite3DbFree(db, pRec);
70426  }
70427 }
70428 #endif /* ifdef SQLITE_ENABLE_STAT4 */
70429 
70430 /*
70431 ** Change the string value of an sqlite3_value object
70432 */
70434  sqlite3_value *v, /* Value to be set */
70435  int n, /* Length of string z */
70436  const void *z, /* Text of the new string */
70437  u8 enc, /* Encoding to use */
70438  void (*xDel)(void*) /* Destructor for the string */
70439 ){
70440  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
70441 }
70442 
70443 /*
70444 ** Free an sqlite3_value object
70445 */
70447  if( !v ) return;
70448  sqlite3VdbeMemRelease((Mem *)v);
70449  sqlite3DbFree(((Mem*)v)->db, v);
70450 }
70451 
70452 /*
70453 ** The sqlite3ValueBytes() routine returns the number of bytes in the
70454 ** sqlite3_value object assuming that it uses the encoding "enc".
70455 ** The valueBytes() routine is a helper function.
70456 */
70457 static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
70458  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
70459 }
70461  Mem *p = (Mem*)pVal;
70462  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
70463  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
70464  return p->n;
70465  }
70466  if( (p->flags & MEM_Blob)!=0 ){
70467  if( p->flags & MEM_Zero ){
70468  return p->n + p->u.nZero;
70469  }else{
70470  return p->n;
70471  }
70472  }
70473  if( p->flags & MEM_Null ) return 0;
70474  return valueBytes(pVal, enc);
70475 }
70476 
70477 /************** End of vdbemem.c *********************************************/
70478 /************** Begin file vdbeaux.c *****************************************/
70479 /*
70480 ** 2003 September 6
70481 **
70482 ** The author disclaims copyright to this source code. In place of
70483 ** a legal notice, here is a blessing:
70484 **
70485 ** May you do good and not evil.
70486 ** May you find forgiveness for yourself and forgive others.
70487 ** May you share freely, never taking more than you give.
70488 **
70489 *************************************************************************
70490 ** This file contains code used for creating, destroying, and populating
70491 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
70492 */
70493 /* #include "sqliteInt.h" */
70494 /* #include "vdbeInt.h" */
70495 
70496 /*
70497 ** Create a new virtual database engine.
70498 */
70500  sqlite3 *db = pParse->db;
70501  Vdbe *p;
70502  p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
70503  if( p==0 ) return 0;
70504  memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
70505  p->db = db;
70506  if( db->pVdbe ){
70507  db->pVdbe->pPrev = p;
70508  }
70509  p->pNext = db->pVdbe;
70510  p->pPrev = 0;
70511  db->pVdbe = p;
70512  p->magic = VDBE_MAGIC_INIT;
70513  p->pParse = pParse;
70514  assert( pParse->aLabel==0 );
70515  assert( pParse->nLabel==0 );
70516  assert( pParse->nOpAlloc==0 );
70517  assert( pParse->szOpAlloc==0 );
70518  return p;
70519 }
70520 
70521 /*
70522 ** Change the error string stored in Vdbe.zErrMsg
70523 */
70524 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
70525  va_list ap;
70526  sqlite3DbFree(p->db, p->zErrMsg);
70527  va_start(ap, zFormat);
70528  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
70529  va_end(ap);
70530 }
70531 
70532 /*
70533 ** Remember the SQL string for a prepared statement.
70534 */
70535 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
70536  assert( isPrepareV2==1 || isPrepareV2==0 );
70537  if( p==0 ) return;
70538 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
70539  if( !isPrepareV2 ) return;
70540 #endif
70541  assert( p->zSql==0 );
70542  p->zSql = sqlite3DbStrNDup(p->db, z, n);
70543  p->isPrepareV2 = (u8)isPrepareV2;
70544 }
70545 
70546 /*
70547 ** Swap all content between two VDBE structures.
70548 */
70550  Vdbe tmp, *pTmp;
70551  char *zTmp;
70552  assert( pA->db==pB->db );
70553  tmp = *pA;
70554  *pA = *pB;
70555  *pB = tmp;
70556  pTmp = pA->pNext;
70557  pA->pNext = pB->pNext;
70558  pB->pNext = pTmp;
70559  pTmp = pA->pPrev;
70560  pA->pPrev = pB->pPrev;
70561  pB->pPrev = pTmp;
70562  zTmp = pA->zSql;
70563  pA->zSql = pB->zSql;
70564  pB->zSql = zTmp;
70565  pB->isPrepareV2 = pA->isPrepareV2;
70566 }
70567 
70568 /*
70569 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
70570 ** than its current size. nOp is guaranteed to be less than or equal
70571 ** to 1024/sizeof(Op).
70572 **
70573 ** If an out-of-memory error occurs while resizing the array, return
70574 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
70575 ** unchanged (this is so that any opcodes already allocated can be
70576 ** correctly deallocated along with the rest of the Vdbe).
70577 */
70578 static int growOpArray(Vdbe *v, int nOp){
70579  VdbeOp *pNew;
70580  Parse *p = v->pParse;
70581 
70582  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
70583  ** more frequent reallocs and hence provide more opportunities for
70584  ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
70585  ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
70586  ** by the minimum* amount required until the size reaches 512. Normal
70587  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
70588  ** size of the op array or add 1KB of space, whichever is smaller. */
70589 #ifdef SQLITE_TEST_REALLOC_STRESS
70590  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
70591 #else
70592  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
70593  UNUSED_PARAMETER(nOp);
70594 #endif
70595 
70596  assert( nOp<=(1024/sizeof(Op)) );
70597  assert( nNew>=(p->nOpAlloc+nOp) );
70598  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
70599  if( pNew ){
70600  p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
70601  p->nOpAlloc = p->szOpAlloc/sizeof(Op);
70602  v->aOp = pNew;
70603  }
70604  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
70605 }
70606 
70607 #ifdef SQLITE_DEBUG
70608 /* This routine is just a convenient place to set a breakpoint that will
70609 ** fire after each opcode is inserted and displayed using
70610 ** "PRAGMA vdbe_addoptrace=on".
70611 */
70612 static void test_addop_breakpoint(void){
70613  static int n = 0;
70614  n++;
70615 }
70616 #endif
70617 
70618 /*
70619 ** Add a new instruction to the list of instructions current in the
70620 ** VDBE. Return the address of the new instruction.
70621 **
70622 ** Parameters:
70623 **
70624 ** p Pointer to the VDBE
70625 **
70626 ** op The opcode for this instruction
70627 **
70628 ** p1, p2, p3 Operands
70629 **
70630 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
70631 ** the sqlite3VdbeChangeP4() function to change the value of the P4
70632 ** operand.
70633 */
70634 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
70635  assert( p->pParse->nOpAlloc<=p->nOp );
70636  if( growOpArray(p, 1) ) return 1;
70637  assert( p->pParse->nOpAlloc>p->nOp );
70638  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70639 }
70640 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
70641  int i;
70642  VdbeOp *pOp;
70643 
70644  i = p->nOp;
70645  assert( p->magic==VDBE_MAGIC_INIT );
70646  assert( op>=0 && op<0xff );
70647  if( p->pParse->nOpAlloc<=i ){
70648  return growOp3(p, op, p1, p2, p3);
70649  }
70650  p->nOp++;
70651  pOp = &p->aOp[i];
70652  pOp->opcode = (u8)op;
70653  pOp->p5 = 0;
70654  pOp->p1 = p1;
70655  pOp->p2 = p2;
70656  pOp->p3 = p3;
70657  pOp->p4.p = 0;
70658  pOp->p4type = P4_NOTUSED;
70659 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70660  pOp->zComment = 0;
70661 #endif
70662 #ifdef SQLITE_DEBUG
70663  if( p->db->flags & SQLITE_VdbeAddopTrace ){
70664  int jj, kk;
70665  Parse *pParse = p->pParse;
70666  for(jj=kk=0; jj<pParse->nColCache; jj++){
70667  struct yColCache *x = pParse->aColCache + jj;
70668  printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
70669  kk++;
70670  }
70671  if( kk ) printf("\n");
70672  sqlite3VdbePrintOp(0, i, &p->aOp[i]);
70673  test_addop_breakpoint();
70674  }
70675 #endif
70676 #ifdef VDBE_PROFILE
70677  pOp->cycles = 0;
70678  pOp->cnt = 0;
70679 #endif
70680 #ifdef SQLITE_VDBE_COVERAGE
70681  pOp->iSrcLine = 0;
70682 #endif
70683  return i;
70684 }
70686  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
70687 }
70688 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
70689  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
70690 }
70691 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
70692  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
70693 }
70694 
70695 /* Generate code for an unconditional jump to instruction iDest
70696 */
70698  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
70699 }
70700 
70701 /* Generate code to cause the string zStr to be loaded into
70702 ** register iDest
70703 */
70704 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
70705  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
70706 }
70707 
70708 /*
70709 ** Generate code that initializes multiple registers to string or integer
70710 ** constants. The registers begin with iDest and increase consecutively.
70711 ** One register is initialized for each characgter in zTypes[]. For each
70712 ** "s" character in zTypes[], the register is a string if the argument is
70713 ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
70714 ** in zTypes[], the register is initialized to an integer.
70715 */
70716 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
70717  va_list ap;
70718  int i;
70719  char c;
70720  va_start(ap, zTypes);
70721  for(i=0; (c = zTypes[i])!=0; i++){
70722  if( c=='s' ){
70723  const char *z = va_arg(ap, const char*);
70724  sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
70725  }else{
70726  assert( c=='i' );
70727  sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
70728  }
70729  }
70730  va_end(ap);
70731 }
70732 
70733 /*
70734 ** Add an opcode that includes the p4 value as a pointer.
70735 */
70737  Vdbe *p, /* Add the opcode to this VM */
70738  int op, /* The new opcode */
70739  int p1, /* The P1 operand */
70740  int p2, /* The P2 operand */
70741  int p3, /* The P3 operand */
70742  const char *zP4, /* The P4 operand */
70743  int p4type /* P4 operand type */
70744 ){
70745  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70746  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
70747  return addr;
70748 }
70749 
70750 /*
70751 ** Add an opcode that includes the p4 value with a P4_INT64 or
70752 ** P4_REAL type.
70753 */
70755  Vdbe *p, /* Add the opcode to this VM */
70756  int op, /* The new opcode */
70757  int p1, /* The P1 operand */
70758  int p2, /* The P2 operand */
70759  int p3, /* The P3 operand */
70760  const u8 *zP4, /* The P4 operand */
70761  int p4type /* P4 operand type */
70762 ){
70763  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
70764  if( p4copy ) memcpy(p4copy, zP4, 8);
70765  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
70766 }
70767 
70768 /*
70769 ** Add an OP_ParseSchema opcode. This routine is broken out from
70770 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
70771 ** as having been used.
70772 **
70773 ** The zWhere string must have been obtained from sqlite3_malloc().
70774 ** This routine will take ownership of the allocated memory.
70775 */
70776 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
70777  int j;
70778  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70779  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
70780 }
70781 
70782 /*
70783 ** Add an opcode that includes the p4 value as an integer.
70784 */
70786  Vdbe *p, /* Add the opcode to this VM */
70787  int op, /* The new opcode */
70788  int p1, /* The P1 operand */
70789  int p2, /* The P2 operand */
70790  int p3, /* The P3 operand */
70791  int p4 /* The P4 operand as an integer */
70792 ){
70793  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70795  return addr;
70796 }
70797 
70798 /* Insert the end of a co-routine
70799 */
70801  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
70802 
70803  /* Clear the temporary register cache, thereby ensuring that each
70804  ** co-routine has its own independent set of registers, because co-routines
70805  ** might expect their registers to be preserved across an OP_Yield, and
70806  ** that could cause problems if two or more co-routines are using the same
70807  ** temporary register.
70808  */
70809  v->pParse->nTempReg = 0;
70810  v->pParse->nRangeReg = 0;
70811 }
70812 
70813 /*
70814 ** Create a new symbolic label for an instruction that has yet to be
70815 ** coded. The symbolic label is really just a negative number. The
70816 ** label can be used as the P2 value of an operation. Later, when
70817 ** the label is resolved to a specific address, the VDBE will scan
70818 ** through its operation list and change all values of P2 which match
70819 ** the label into the resolved address.
70820 **
70821 ** The VDBE knows that a P2 value is a label because labels are
70822 ** always negative and P2 values are suppose to be non-negative.
70823 ** Hence, a negative P2 value is a label that has yet to be resolved.
70824 **
70825 ** Zero is returned if a malloc() fails.
70826 */
70828  Parse *p = v->pParse;
70829  int i = p->nLabel++;
70830  assert( v->magic==VDBE_MAGIC_INIT );
70831  if( (i & (i-1))==0 ){
70832  p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
70833  (i*2+1)*sizeof(p->aLabel[0]));
70834  }
70835  if( p->aLabel ){
70836  p->aLabel[i] = -1;
70837  }
70838  return ADDR(i);
70839 }
70840 
70841 /*
70842 ** Resolve label "x" to be the address of the next instruction to
70843 ** be inserted. The parameter "x" must have been obtained from
70844 ** a prior call to sqlite3VdbeMakeLabel().
70845 */
70847  Parse *p = v->pParse;
70848  int j = ADDR(x);
70849  assert( v->magic==VDBE_MAGIC_INIT );
70850  assert( j<p->nLabel );
70851  assert( j>=0 );
70852  if( p->aLabel ){
70853  p->aLabel[j] = v->nOp;
70854  }
70855 }
70856 
70857 /*
70858 ** Mark the VDBE as one that can only be run one time.
70859 */
70861  p->runOnlyOnce = 1;
70862 }
70863 
70864 /*
70865 ** Mark the VDBE as one that can only be run multiple times.
70866 */
70868  p->runOnlyOnce = 0;
70869 }
70870 
70871 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
70872 
70873 /*
70874 ** The following type and function are used to iterate through all opcodes
70875 ** in a Vdbe main program and each of the sub-programs (triggers) it may
70876 ** invoke directly or indirectly. It should be used as follows:
70877 **
70878 ** Op *pOp;
70879 ** VdbeOpIter sIter;
70880 **
70881 ** memset(&sIter, 0, sizeof(sIter));
70882 ** sIter.v = v; // v is of type Vdbe*
70883 ** while( (pOp = opIterNext(&sIter)) ){
70884 ** // Do something with pOp
70885 ** }
70886 ** sqlite3DbFree(v->db, sIter.apSub);
70887 **
70888 */
70889 typedef struct VdbeOpIter VdbeOpIter;
70890 struct VdbeOpIter {
70891  Vdbe *v; /* Vdbe to iterate through the opcodes of */
70892  SubProgram **apSub; /* Array of subprograms */
70893  int nSub; /* Number of entries in apSub */
70894  int iAddr; /* Address of next instruction to return */
70895  int iSub; /* 0 = main program, 1 = first sub-program etc. */
70896 };
70897 static Op *opIterNext(VdbeOpIter *p){
70898  Vdbe *v = p->v;
70899  Op *pRet = 0;
70900  Op *aOp;
70901  int nOp;
70902 
70903  if( p->iSub<=p->nSub ){
70904 
70905  if( p->iSub==0 ){
70906  aOp = v->aOp;
70907  nOp = v->nOp;
70908  }else{
70909  aOp = p->apSub[p->iSub-1]->aOp;
70910  nOp = p->apSub[p->iSub-1]->nOp;
70911  }
70912  assert( p->iAddr<nOp );
70913 
70914  pRet = &aOp[p->iAddr];
70915  p->iAddr++;
70916  if( p->iAddr==nOp ){
70917  p->iSub++;
70918  p->iAddr = 0;
70919  }
70920 
70921  if( pRet->p4type==P4_SUBPROGRAM ){
70922  int nByte = (p->nSub+1)*sizeof(SubProgram*);
70923  int j;
70924  for(j=0; j<p->nSub; j++){
70925  if( p->apSub[j]==pRet->p4.pProgram ) break;
70926  }
70927  if( j==p->nSub ){
70928  p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
70929  if( !p->apSub ){
70930  pRet = 0;
70931  }else{
70932  p->apSub[p->nSub++] = pRet->p4.pProgram;
70933  }
70934  }
70935  }
70936  }
70937 
70938  return pRet;
70939 }
70940 
70941 /*
70942 ** Check if the program stored in the VM associated with pParse may
70943 ** throw an ABORT exception (causing the statement, but not entire transaction
70944 ** to be rolled back). This condition is true if the main program or any
70945 ** sub-programs contains any of the following:
70946 **
70947 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70948 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70949 ** * OP_Destroy
70950 ** * OP_VUpdate
70951 ** * OP_VRename
70952 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
70953 ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
70954 **
70955 ** Then check that the value of Parse.mayAbort is true if an
70956 ** ABORT may be thrown, or false otherwise. Return true if it does
70957 ** match, or false otherwise. This function is intended to be used as
70958 ** part of an assert statement in the compiler. Similar to:
70959 **
70960 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
70961 */
70962 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
70963  int hasAbort = 0;
70964  int hasFkCounter = 0;
70965  int hasCreateTable = 0;
70966  int hasInitCoroutine = 0;
70967  Op *pOp;
70968  VdbeOpIter sIter;
70969  memset(&sIter, 0, sizeof(sIter));
70970  sIter.v = v;
70971 
70972  while( (pOp = opIterNext(&sIter))!=0 ){
70973  int opcode = pOp->opcode;
70974  if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
70975  || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
70976  && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
70977  ){
70978  hasAbort = 1;
70979  break;
70980  }
70981  if( opcode==OP_CreateTable ) hasCreateTable = 1;
70982  if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
70983 #ifndef SQLITE_OMIT_FOREIGN_KEY
70984  if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
70985  hasFkCounter = 1;
70986  }
70987 #endif
70988  }
70989  sqlite3DbFree(v->db, sIter.apSub);
70990 
70991  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
70992  ** If malloc failed, then the while() loop above may not have iterated
70993  ** through all opcodes and hasAbort may be set incorrectly. Return
70994  ** true for this case to prevent the assert() in the callers frame
70995  ** from failing. */
70996  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
70997  || (hasCreateTable && hasInitCoroutine) );
70998 }
70999 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
71000 
71001 /*
71002 ** This routine is called after all opcodes have been inserted. It loops
71003 ** through all the opcodes and fixes up some details.
71004 **
71005 ** (1) For each jump instruction with a negative P2 value (a label)
71006 ** resolve the P2 value to an actual address.
71007 **
71008 ** (2) Compute the maximum number of arguments used by any SQL function
71009 ** and store that value in *pMaxFuncArgs.
71010 **
71011 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
71012 ** indicate what the prepared statement actually does.
71013 **
71014 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
71015 **
71016 ** (5) Reclaim the memory allocated for storing labels.
71017 **
71018 ** This routine will only function correctly if the mkopcodeh.tcl generator
71019 ** script numbers the opcodes correctly. Changes to this routine must be
71020 ** coordinated with changes to mkopcodeh.tcl.
71021 */
71022 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
71023  int nMaxArgs = *pMaxFuncArgs;
71024  Op *pOp;
71025  Parse *pParse = p->pParse;
71026  int *aLabel = pParse->aLabel;
71027  p->readOnly = 1;
71028  p->bIsReader = 0;
71029  pOp = &p->aOp[p->nOp-1];
71030  while(1){
71031 
71032  /* Only JUMP opcodes and the short list of special opcodes in the switch
71033  ** below need to be considered. The mkopcodeh.tcl generator script groups
71034  ** all these opcodes together near the front of the opcode list. Skip
71035  ** any opcode that does not need processing by virtual of the fact that
71036  ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
71037  */
71038  if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
71039  /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
71040  ** cases from this switch! */
71041  switch( pOp->opcode ){
71042  case OP_Transaction: {
71043  if( pOp->p2!=0 ) p->readOnly = 0;
71044  /* fall thru */
71045  }
71046  case OP_AutoCommit:
71047  case OP_Savepoint: {
71048  p->bIsReader = 1;
71049  break;
71050  }
71051 #ifndef SQLITE_OMIT_WAL
71052  case OP_Checkpoint:
71053 #endif
71054  case OP_Vacuum:
71055  case OP_JournalMode: {
71056  p->readOnly = 0;
71057  p->bIsReader = 1;
71058  break;
71059  }
71060 #ifndef SQLITE_OMIT_VIRTUALTABLE
71061  case OP_VUpdate: {
71062  if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
71063  break;
71064  }
71065  case OP_VFilter: {
71066  int n;
71067  assert( (pOp - p->aOp) >= 3 );
71068  assert( pOp[-1].opcode==OP_Integer );
71069  n = pOp[-1].p1;
71070  if( n>nMaxArgs ) nMaxArgs = n;
71071  break;
71072  }
71073 #endif
71074  case OP_Next:
71075  case OP_NextIfOpen:
71076  case OP_SorterNext: {
71077  pOp->p4.xAdvance = sqlite3BtreeNext;
71078  pOp->p4type = P4_ADVANCE;
71079  break;
71080  }
71081  case OP_Prev:
71082  case OP_PrevIfOpen: {
71084  pOp->p4type = P4_ADVANCE;
71085  break;
71086  }
71087  }
71088  if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
71089  assert( ADDR(pOp->p2)<pParse->nLabel );
71090  pOp->p2 = aLabel[ADDR(pOp->p2)];
71091  }
71092  }
71093  if( pOp==p->aOp ) break;
71094  pOp--;
71095  }
71096  sqlite3DbFree(p->db, pParse->aLabel);
71097  pParse->aLabel = 0;
71098  pParse->nLabel = 0;
71099  *pMaxFuncArgs = nMaxArgs;
71100  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
71101 }
71102 
71103 /*
71104 ** Return the address of the next instruction to be inserted.
71105 */
71107  assert( p->magic==VDBE_MAGIC_INIT );
71108  return p->nOp;
71109 }
71110 
71111 /*
71112 ** Verify that at least N opcode slots are available in p without
71113 ** having to malloc for more space (except when compiled using
71114 ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
71115 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
71116 ** fail due to a OOM fault and hence that the return value from
71117 ** sqlite3VdbeAddOpList() will always be non-NULL.
71118 */
71119 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
71121  assert( p->nOp + N <= p->pParse->nOpAlloc );
71122 }
71123 #endif
71124 
71125 /*
71126 ** This function returns a pointer to the array of opcodes associated with
71127 ** the Vdbe passed as the first argument. It is the callers responsibility
71128 ** to arrange for the returned array to be eventually freed using the
71129 ** vdbeFreeOpArray() function.
71130 **
71131 ** Before returning, *pnOp is set to the number of entries in the returned
71132 ** array. Also, *pnMaxArg is set to the larger of its current value and
71133 ** the number of entries in the Vdbe.apArg[] array required to execute the
71134 ** returned program.
71135 */
71136 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
71137  VdbeOp *aOp = p->aOp;
71138  assert( aOp && !p->db->mallocFailed );
71139 
71140  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
71141  assert( DbMaskAllZero(p->btreeMask) );
71142 
71143  resolveP2Values(p, pnMaxArg);
71144  *pnOp = p->nOp;
71145  p->aOp = 0;
71146  return aOp;
71147 }
71148 
71149 /*
71150 ** Add a whole list of operations to the operation stack. Return a
71151 ** pointer to the first operation inserted.
71152 **
71153 ** Non-zero P2 arguments to jump instructions are automatically adjusted
71154 ** so that the jump target is relative to the first operation inserted.
71155 */
71157  Vdbe *p, /* Add opcodes to the prepared statement */
71158  int nOp, /* Number of opcodes to add */
71159  VdbeOpList const *aOp, /* The opcodes to be added */
71160  int iLineno /* Source-file line number of first opcode */
71161 ){
71162  int i;
71163  VdbeOp *pOut, *pFirst;
71164  assert( nOp>0 );
71165  assert( p->magic==VDBE_MAGIC_INIT );
71166  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
71167  return 0;
71168  }
71169  pFirst = pOut = &p->aOp[p->nOp];
71170  for(i=0; i<nOp; i++, aOp++, pOut++){
71171  pOut->opcode = aOp->opcode;
71172  pOut->p1 = aOp->p1;
71173  pOut->p2 = aOp->p2;
71174  assert( aOp->p2>=0 );
71175  if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
71176  pOut->p2 += p->nOp;
71177  }
71178  pOut->p3 = aOp->p3;
71179  pOut->p4type = P4_NOTUSED;
71180  pOut->p4.p = 0;
71181  pOut->p5 = 0;
71182 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71183  pOut->zComment = 0;
71184 #endif
71185 #ifdef SQLITE_VDBE_COVERAGE
71186  pOut->iSrcLine = iLineno+i;
71187 #else
71188  (void)iLineno;
71189 #endif
71190 #ifdef SQLITE_DEBUG
71191  if( p->db->flags & SQLITE_VdbeAddopTrace ){
71192  sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
71193  }
71194 #endif
71195  }
71196  p->nOp += nOp;
71197  return pFirst;
71198 }
71199 
71200 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
71201 /*
71202 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
71203 */
71205  Vdbe *p, /* VM to add scanstatus() to */
71206  int addrExplain, /* Address of OP_Explain (or 0) */
71207  int addrLoop, /* Address of loop counter */
71208  int addrVisit, /* Address of rows visited counter */
71209  LogEst nEst, /* Estimated number of output rows */
71210  const char *zName /* Name of table or index being scanned */
71211 ){
71212  int nByte = (p->nScan+1) * sizeof(ScanStatus);
71213  ScanStatus *aNew;
71214  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
71215  if( aNew ){
71216  ScanStatus *pNew = &aNew[p->nScan++];
71217  pNew->addrExplain = addrExplain;
71218  pNew->addrLoop = addrLoop;
71219  pNew->addrVisit = addrVisit;
71220  pNew->nEst = nEst;
71221  pNew->zName = sqlite3DbStrDup(p->db, zName);
71222  p->aScan = aNew;
71223  }
71224 }
71225 #endif
71226 
71227 
71228 /*
71229 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
71230 ** for a specific instruction.
71231 */
71232 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
71233  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
71234 }
71235 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
71236  sqlite3VdbeGetOp(p,addr)->p1 = val;
71237 }
71238 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
71239  sqlite3VdbeGetOp(p,addr)->p2 = val;
71240 }
71241 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
71242  sqlite3VdbeGetOp(p,addr)->p3 = val;
71243 }
71245  assert( p->nOp>0 || p->db->mallocFailed );
71246  if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
71247 }
71248 
71249 /*
71250 ** Change the P2 operand of instruction addr so that it points to
71251 ** the address of the next instruction to be coded.
71252 */
71254  sqlite3VdbeChangeP2(p, addr, p->nOp);
71255 }
71256 
71257 
71258 /*
71259 ** If the input FuncDef structure is ephemeral, then free it. If
71260 ** the FuncDef is not ephermal, then do nothing.
71261 */
71262 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
71263  if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
71264  sqlite3DbFree(db, pDef);
71265  }
71266 }
71267 
71268 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
71269 
71270 /*
71271 ** Delete a P4 value if necessary.
71272 */
71273 static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
71274  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71275  sqlite3DbFree(db, p);
71276 }
71278  freeEphemeralFunction(db, p->pFunc);
71279  sqlite3DbFree(db, p);
71280 }
71281 static void freeP4(sqlite3 *db, int p4type, void *p4){
71282  assert( db );
71283  switch( p4type ){
71284  case P4_FUNCCTX: {
71285  freeP4FuncCtx(db, (sqlite3_context*)p4);
71286  break;
71287  }
71288  case P4_REAL:
71289  case P4_INT64:
71290  case P4_DYNAMIC:
71291  case P4_INTARRAY: {
71292  sqlite3DbFree(db, p4);
71293  break;
71294  }
71295  case P4_KEYINFO: {
71296  if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
71297  break;
71298  }
71299 #ifdef SQLITE_ENABLE_CURSOR_HINTS
71300  case P4_EXPR: {
71301  sqlite3ExprDelete(db, (Expr*)p4);
71302  break;
71303  }
71304 #endif
71305  case P4_MPRINTF: {
71306  if( db->pnBytesFreed==0 ) sqlite3_free(p4);
71307  break;
71308  }
71309  case P4_FUNCDEF: {
71310  freeEphemeralFunction(db, (FuncDef*)p4);
71311  break;
71312  }
71313  case P4_MEM: {
71314  if( db->pnBytesFreed==0 ){
71316  }else{
71317  freeP4Mem(db, (Mem*)p4);
71318  }
71319  break;
71320  }
71321  case P4_VTAB : {
71322  if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
71323  break;
71324  }
71325  }
71326 }
71327 
71328 /*
71329 ** Free the space allocated for aOp and any p4 values allocated for the
71330 ** opcodes contained within. If aOp is not NULL it is assumed to contain
71331 ** nOp entries.
71332 */
71333 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
71334  if( aOp ){
71335  Op *pOp;
71336  for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
71337  if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
71338 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71339  sqlite3DbFree(db, pOp->zComment);
71340 #endif
71341  }
71342  }
71343  sqlite3DbFree(db, aOp);
71344 }
71345 
71346 /*
71347 ** Link the SubProgram object passed as the second argument into the linked
71348 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
71349 ** objects when the VM is no longer required.
71350 */
71352  p->pNext = pVdbe->pProgram;
71353  pVdbe->pProgram = p;
71354 }
71355 
71356 /*
71357 ** Change the opcode at addr into OP_Noop
71358 */
71360  VdbeOp *pOp;
71361  if( p->db->mallocFailed ) return 0;
71362  assert( addr>=0 && addr<p->nOp );
71363  pOp = &p->aOp[addr];
71364  freeP4(p->db, pOp->p4type, pOp->p4.p);
71365  pOp->p4type = P4_NOTUSED;
71366  pOp->p4.z = 0;
71367  pOp->opcode = OP_Noop;
71368  return 1;
71369 }
71370 
71371 /*
71372 ** If the last opcode is "op" and it is not a jump destination,
71373 ** then remove it. Return true if and only if an opcode was removed.
71374 */
71376  if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
71377  return sqlite3VdbeChangeToNoop(p, p->nOp-1);
71378  }else{
71379  return 0;
71380  }
71381 }
71382 
71383 /*
71384 ** Change the value of the P4 operand for a specific instruction.
71385 ** This routine is useful when a large program is loaded from a
71386 ** static array using sqlite3VdbeAddOpList but we want to make a
71387 ** few minor changes to the program.
71388 **
71389 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
71390 ** the string is made into memory obtained from sqlite3_malloc().
71391 ** A value of n==0 means copy bytes of zP4 up to and including the
71392 ** first null byte. If n>0 then copy n+1 bytes of zP4.
71393 **
71394 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
71395 ** to a string or structure that is guaranteed to exist for the lifetime of
71396 ** the Vdbe. In these cases we can just copy the pointer.
71397 **
71398 ** If addr<0 then change P4 on the most recently inserted instruction.
71399 */
71401  Vdbe *p,
71402  Op *pOp,
71403  const char *zP4,
71404  int n
71405 ){
71406  if( pOp->p4type ){
71407  freeP4(p->db, pOp->p4type, pOp->p4.p);
71408  pOp->p4type = 0;
71409  pOp->p4.p = 0;
71410  }
71411  if( n<0 ){
71412  sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
71413  }else{
71414  if( n==0 ) n = sqlite3Strlen30(zP4);
71415  pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
71416  pOp->p4type = P4_DYNAMIC;
71417  }
71418 }
71419 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
71420  Op *pOp;
71421  sqlite3 *db;
71422  assert( p!=0 );
71423  db = p->db;
71424  assert( p->magic==VDBE_MAGIC_INIT );
71425  assert( p->aOp!=0 || db->mallocFailed );
71426  if( db->mallocFailed ){
71427  if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
71428  return;
71429  }
71430  assert( p->nOp>0 );
71431  assert( addr<p->nOp );
71432  if( addr<0 ){
71433  addr = p->nOp - 1;
71434  }
71435  pOp = &p->aOp[addr];
71436  if( n>=0 || pOp->p4type ){
71437  vdbeChangeP4Full(p, pOp, zP4, n);
71438  return;
71439  }
71440  if( n==P4_INT32 ){
71441  /* Note: this cast is safe, because the origin data point was an int
71442  ** that was cast to a (const char *). */
71443  pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
71444  pOp->p4type = P4_INT32;
71445  }else if( zP4!=0 ){
71446  assert( n<0 );
71447  pOp->p4.p = (void*)zP4;
71448  pOp->p4type = (signed char)n;
71449  if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
71450  }
71451 }
71452 
71453 /*
71454 ** Set the P4 on the most recently added opcode to the KeyInfo for the
71455 ** index given.
71456 */
71458  Vdbe *v = pParse->pVdbe;
71459  assert( v!=0 );
71460  assert( pIdx!=0 );
71461  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
71462  P4_KEYINFO);
71463 }
71464 
71465 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71466 /*
71467 ** Change the comment on the most recently coded instruction. Or
71468 ** insert a No-op and add the comment to that new instruction. This
71469 ** makes the code easier to read during debugging. None of this happens
71470 ** in a production build.
71471 */
71472 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
71473  assert( p->nOp>0 || p->aOp==0 );
71474  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
71475  if( p->nOp ){
71476  assert( p->aOp );
71477  sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
71478  p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
71479  }
71480 }
71481 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
71482  va_list ap;
71483  if( p ){
71484  va_start(ap, zFormat);
71485  vdbeVComment(p, zFormat, ap);
71486  va_end(ap);
71487  }
71488 }
71489 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
71490  va_list ap;
71491  if( p ){
71493  va_start(ap, zFormat);
71494  vdbeVComment(p, zFormat, ap);
71495  va_end(ap);
71496  }
71497 }
71498 #endif /* NDEBUG */
71499 
71500 #ifdef SQLITE_VDBE_COVERAGE
71501 /*
71502 ** Set the value if the iSrcLine field for the previously coded instruction.
71503 */
71504 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
71505  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
71506 }
71507 #endif /* SQLITE_VDBE_COVERAGE */
71508 
71509 /*
71510 ** Return the opcode for a given address. If the address is -1, then
71511 ** return the most recently inserted opcode.
71512 **
71513 ** If a memory allocation error has occurred prior to the calling of this
71514 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
71515 ** is readable but not writable, though it is cast to a writable value.
71516 ** The return of a dummy opcode allows the call to continue functioning
71517 ** after an OOM fault without having to check to see if the return from
71518 ** this routine is a valid pointer. But because the dummy.opcode is 0,
71519 ** dummy will never be written to. This is verified by code inspection and
71520 ** by running with Valgrind.
71521 */
71523  /* C89 specifies that the constant "dummy" will be initialized to all
71524  ** zeros, which is correct. MSVC generates a warning, nevertheless. */
71525  static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
71526  assert( p->magic==VDBE_MAGIC_INIT );
71527  if( addr<0 ){
71528  addr = p->nOp - 1;
71529  }
71530  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
71531  if( p->db->mallocFailed ){
71532  return (VdbeOp*)&dummy;
71533  }else{
71534  return &p->aOp[addr];
71535  }
71536 }
71537 
71538 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
71539 /*
71540 ** Return an integer value for one of the parameters to the opcode pOp
71541 ** determined by character c.
71542 */
71543 static int translateP(char c, const Op *pOp){
71544  if( c=='1' ) return pOp->p1;
71545  if( c=='2' ) return pOp->p2;
71546  if( c=='3' ) return pOp->p3;
71547  if( c=='4' ) return pOp->p4.i;
71548  return pOp->p5;
71549 }
71550 
71551 /*
71552 ** Compute a string for the "comment" field of a VDBE opcode listing.
71553 **
71554 ** The Synopsis: field in comments in the vdbe.c source file gets converted
71555 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
71556 ** absence of other comments, this synopsis becomes the comment on the opcode.
71557 ** Some translation occurs:
71558 **
71559 ** "PX" -> "r[X]"
71560 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
71561 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
71562 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
71563 */
71564 static int displayComment(
71565  const Op *pOp, /* The opcode to be commented */
71566  const char *zP4, /* Previously obtained value for P4 */
71567  char *zTemp, /* Write result here */
71568  int nTemp /* Space available in zTemp[] */
71569 ){
71570  const char *zOpName;
71571  const char *zSynopsis;
71572  int nOpName;
71573  int ii, jj;
71574  char zAlt[50];
71575  zOpName = sqlite3OpcodeName(pOp->opcode);
71576  nOpName = sqlite3Strlen30(zOpName);
71577  if( zOpName[nOpName+1] ){
71578  int seenCom = 0;
71579  char c;
71580  zSynopsis = zOpName += nOpName + 1;
71581  if( strncmp(zSynopsis,"IF ",3)==0 ){
71582  if( pOp->p5 & SQLITE_STOREP2 ){
71583  sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
71584  }else{
71585  sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
71586  }
71587  zSynopsis = zAlt;
71588  }
71589  for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
71590  if( c=='P' ){
71591  c = zSynopsis[++ii];
71592  if( c=='4' ){
71593  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
71594  }else if( c=='X' ){
71595  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
71596  seenCom = 1;
71597  }else{
71598  int v1 = translateP(c, pOp);
71599  int v2;
71600  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
71601  if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
71602  ii += 3;
71603  jj += sqlite3Strlen30(zTemp+jj);
71604  v2 = translateP(zSynopsis[ii], pOp);
71605  if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
71606  ii += 2;
71607  v2++;
71608  }
71609  if( v2>1 ){
71610  sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
71611  }
71612  }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
71613  ii += 4;
71614  }
71615  }
71616  jj += sqlite3Strlen30(zTemp+jj);
71617  }else{
71618  zTemp[jj++] = c;
71619  }
71620  }
71621  if( !seenCom && jj<nTemp-5 && pOp->zComment ){
71622  sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
71623  jj += sqlite3Strlen30(zTemp+jj);
71624  }
71625  if( jj<nTemp ) zTemp[jj] = 0;
71626  }else if( pOp->zComment ){
71627  sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
71628  jj = sqlite3Strlen30(zTemp);
71629  }else{
71630  zTemp[0] = 0;
71631  jj = 0;
71632  }
71633  return jj;
71634 }
71635 #endif /* SQLITE_DEBUG */
71636 
71637 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
71638 /*
71639 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
71640 ** that can be displayed in the P4 column of EXPLAIN output.
71641 */
71642 static void displayP4Expr(StrAccum *p, Expr *pExpr){
71643  const char *zOp = 0;
71644  switch( pExpr->op ){
71645  case TK_STRING:
71646  sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
71647  break;
71648  case TK_INTEGER:
71649  sqlite3XPrintf(p, "%d", pExpr->u.iValue);
71650  break;
71651  case TK_NULL:
71652  sqlite3XPrintf(p, "NULL");
71653  break;
71654  case TK_REGISTER: {
71655  sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
71656  break;
71657  }
71658  case TK_COLUMN: {
71659  if( pExpr->iColumn<0 ){
71660  sqlite3XPrintf(p, "rowid");
71661  }else{
71662  sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
71663  }
71664  break;
71665  }
71666  case TK_LT: zOp = "LT"; break;
71667  case TK_LE: zOp = "LE"; break;
71668  case TK_GT: zOp = "GT"; break;
71669  case TK_GE: zOp = "GE"; break;
71670  case TK_NE: zOp = "NE"; break;
71671  case TK_EQ: zOp = "EQ"; break;
71672  case TK_IS: zOp = "IS"; break;
71673  case TK_ISNOT: zOp = "ISNOT"; break;
71674  case TK_AND: zOp = "AND"; break;
71675  case TK_OR: zOp = "OR"; break;
71676  case TK_PLUS: zOp = "ADD"; break;
71677  case TK_STAR: zOp = "MUL"; break;
71678  case TK_MINUS: zOp = "SUB"; break;
71679  case TK_REM: zOp = "REM"; break;
71680  case TK_BITAND: zOp = "BITAND"; break;
71681  case TK_BITOR: zOp = "BITOR"; break;
71682  case TK_SLASH: zOp = "DIV"; break;
71683  case TK_LSHIFT: zOp = "LSHIFT"; break;
71684  case TK_RSHIFT: zOp = "RSHIFT"; break;
71685  case TK_CONCAT: zOp = "CONCAT"; break;
71686  case TK_UMINUS: zOp = "MINUS"; break;
71687  case TK_UPLUS: zOp = "PLUS"; break;
71688  case TK_BITNOT: zOp = "BITNOT"; break;
71689  case TK_NOT: zOp = "NOT"; break;
71690  case TK_ISNULL: zOp = "ISNULL"; break;
71691  case TK_NOTNULL: zOp = "NOTNULL"; break;
71692 
71693  default:
71694  sqlite3XPrintf(p, "%s", "expr");
71695  break;
71696  }
71697 
71698  if( zOp ){
71699  sqlite3XPrintf(p, "%s(", zOp);
71700  displayP4Expr(p, pExpr->pLeft);
71701  if( pExpr->pRight ){
71702  sqlite3StrAccumAppend(p, ",", 1);
71703  displayP4Expr(p, pExpr->pRight);
71704  }
71705  sqlite3StrAccumAppend(p, ")", 1);
71706  }
71707 }
71708 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
71709 
71710 
71711 #if VDBE_DISPLAY_P4
71712 /*
71713 ** Compute a string that describes the P4 parameter for an opcode.
71714 ** Use zTemp for any required temporary buffer space.
71715 */
71716 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
71717  char *zP4 = zTemp;
71718  StrAccum x;
71719  assert( nTemp>=20 );
71720  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
71721  switch( pOp->p4type ){
71722  case P4_KEYINFO: {
71723  int j;
71724  KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
71725  assert( pKeyInfo->aSortOrder!=0 );
71726  sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
71727  for(j=0; j<pKeyInfo->nField; j++){
71728  CollSeq *pColl = pKeyInfo->aColl[j];
71729  const char *zColl = pColl ? pColl->zName : "";
71730  if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
71731  sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
71732  }
71733  sqlite3StrAccumAppend(&x, ")", 1);
71734  break;
71735  }
71736 #ifdef SQLITE_ENABLE_CURSOR_HINTS
71737  case P4_EXPR: {
71738  displayP4Expr(&x, pOp->p4.pExpr);
71739  break;
71740  }
71741 #endif
71742  case P4_COLLSEQ: {
71743  CollSeq *pColl = pOp->p4.pColl;
71744  sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
71745  break;
71746  }
71747  case P4_FUNCDEF: {
71748  FuncDef *pDef = pOp->p4.pFunc;
71749  sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71750  break;
71751  }
71752 #ifdef SQLITE_DEBUG
71753  case P4_FUNCCTX: {
71754  FuncDef *pDef = pOp->p4.pCtx->pFunc;
71755  sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71756  break;
71757  }
71758 #endif
71759  case P4_INT64: {
71760  sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
71761  break;
71762  }
71763  case P4_INT32: {
71764  sqlite3XPrintf(&x, "%d", pOp->p4.i);
71765  break;
71766  }
71767  case P4_REAL: {
71768  sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
71769  break;
71770  }
71771  case P4_MEM: {
71772  Mem *pMem = pOp->p4.pMem;
71773  if( pMem->flags & MEM_Str ){
71774  zP4 = pMem->z;
71775  }else if( pMem->flags & MEM_Int ){
71776  sqlite3XPrintf(&x, "%lld", pMem->u.i);
71777  }else if( pMem->flags & MEM_Real ){
71778  sqlite3XPrintf(&x, "%.16g", pMem->u.r);
71779  }else if( pMem->flags & MEM_Null ){
71780  zP4 = "NULL";
71781  }else{
71782  assert( pMem->flags & MEM_Blob );
71783  zP4 = "(blob)";
71784  }
71785  break;
71786  }
71787 #ifndef SQLITE_OMIT_VIRTUALTABLE
71788  case P4_VTAB: {
71789  sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
71790  sqlite3XPrintf(&x, "vtab:%p", pVtab);
71791  break;
71792  }
71793 #endif
71794  case P4_INTARRAY: {
71795  int i;
71796  int *ai = pOp->p4.ai;
71797  int n = ai[0]; /* The first element of an INTARRAY is always the
71798  ** count of the number of elements to follow */
71799  for(i=1; i<n; i++){
71800  sqlite3XPrintf(&x, ",%d", ai[i]);
71801  }
71802  zTemp[0] = '[';
71803  sqlite3StrAccumAppend(&x, "]", 1);
71804  break;
71805  }
71806  case P4_SUBPROGRAM: {
71807  sqlite3XPrintf(&x, "program");
71808  break;
71809  }
71810  case P4_ADVANCE: {
71811  zTemp[0] = 0;
71812  break;
71813  }
71814  case P4_TABLE: {
71815  sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71816  break;
71817  }
71818  default: {
71819  zP4 = pOp->p4.z;
71820  if( zP4==0 ){
71821  zP4 = zTemp;
71822  zTemp[0] = 0;
71823  }
71824  }
71825  }
71827  assert( zP4!=0 );
71828  return zP4;
71829 }
71830 #endif /* VDBE_DISPLAY_P4 */
71831 
71832 /*
71833 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
71834 **
71835 ** The prepared statements need to know in advance the complete set of
71836 ** attached databases that will be use. A mask of these databases
71837 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
71838 ** p->btreeMask of databases that will require a lock.
71839 */
71841  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
71842  assert( i<(int)sizeof(p->btreeMask)*8 );
71843  DbMaskSet(p->btreeMask, i);
71844  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
71845  DbMaskSet(p->lockMask, i);
71846  }
71847 }
71848 
71849 #if !defined(SQLITE_OMIT_SHARED_CACHE)
71850 /*
71851 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
71852 ** this routine obtains the mutex associated with each BtShared structure
71853 ** that may be accessed by the VM passed as an argument. In doing so it also
71854 ** sets the BtShared.db member of each of the BtShared structures, ensuring
71855 ** that the correct busy-handler callback is invoked if required.
71856 **
71857 ** If SQLite is not threadsafe but does support shared-cache mode, then
71858 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
71859 ** of all of BtShared structures accessible via the database handle
71860 ** associated with the VM.
71861 **
71862 ** If SQLite is not threadsafe and does not support shared-cache mode, this
71863 ** function is a no-op.
71864 **
71865 ** The p->btreeMask field is a bitmask of all btrees that the prepared
71866 ** statement p will ever use. Let N be the number of bits in p->btreeMask
71867 ** corresponding to btrees that use shared cache. Then the runtime of
71868 ** this routine is N*N. But as N is rarely more than 1, this should not
71869 ** be a problem.
71870 */
71872  int i;
71873  sqlite3 *db;
71874  Db *aDb;
71875  int nDb;
71876  if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
71877  db = p->db;
71878  aDb = db->aDb;
71879  nDb = db->nDb;
71880  for(i=0; i<nDb; i++){
71881  if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71882  sqlite3BtreeEnter(aDb[i].pBt);
71883  }
71884  }
71885 }
71886 #endif
71887 
71888 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
71889 /*
71890 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
71891 */
71893  int i;
71894  sqlite3 *db;
71895  Db *aDb;
71896  int nDb;
71897  db = p->db;
71898  aDb = db->aDb;
71899  nDb = db->nDb;
71900  for(i=0; i<nDb; i++){
71901  if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71902  sqlite3BtreeLeave(aDb[i].pBt);
71903  }
71904  }
71905 }
71907  if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
71908  vdbeLeave(p);
71909 }
71910 #endif
71911 
71912 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
71913 /*
71914 ** Print a single opcode. This routine is used for debugging only.
71915 */
71916 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
71917  char *zP4;
71918  char zPtr[50];
71919  char zCom[100];
71920  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
71921  if( pOut==0 ) pOut = stdout;
71922  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
71923 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71924  displayComment(pOp, zP4, zCom, sizeof(zCom));
71925 #else
71926  zCom[0] = 0;
71927 #endif
71928  /* NB: The sqlite3OpcodeName() function is implemented by code created
71929  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
71930  ** information from the vdbe.c source text */
71931  fprintf(pOut, zFormat1, pc,
71932  sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
71933  zCom
71934  );
71935  fflush(pOut);
71936 }
71937 #endif
71938 
71939 /*
71940 ** Initialize an array of N Mem element.
71941 */
71942 static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
71943  while( (N--)>0 ){
71944  p->db = db;
71945  p->flags = flags;
71946  p->szMalloc = 0;
71947 #ifdef SQLITE_DEBUG
71948  p->pScopyFrom = 0;
71949 #endif
71950  p++;
71951  }
71952 }
71953 
71954 /*
71955 ** Release an array of N Mem elements
71956 */
71957 static void releaseMemArray(Mem *p, int N){
71958  if( p && N ){
71959  Mem *pEnd = &p[N];
71960  sqlite3 *db = p->db;
71961  if( db->pnBytesFreed ){
71962  do{
71963  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71964  }while( (++p)<pEnd );
71965  return;
71966  }
71967  do{
71968  assert( (&p[1])==pEnd || p[0].db==p[1].db );
71969  assert( sqlite3VdbeCheckMemInvariants(p) );
71970 
71971  /* This block is really an inlined version of sqlite3VdbeMemRelease()
71972  ** that takes advantage of the fact that the memory cell value is
71973  ** being set to NULL after releasing any dynamic resources.
71974  **
71975  ** The justification for duplicating code is that according to
71976  ** callgrind, this causes a certain test case to hit the CPU 4.7
71977  ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
71978  ** sqlite3MemRelease() were called from here. With -O2, this jumps
71979  ** to 6.6 percent. The test case is inserting 1000 rows into a table
71980  ** with no indexes using a single prepared INSERT statement, bind()
71981  ** and reset(). Inserts are grouped into a transaction.
71982  */
71983  testcase( p->flags & MEM_Agg );
71984  testcase( p->flags & MEM_Dyn );
71985  testcase( p->flags & MEM_Frame );
71986  testcase( p->flags & MEM_RowSet );
71989  }else if( p->szMalloc ){
71990  sqlite3DbFree(db, p->zMalloc);
71991  p->szMalloc = 0;
71992  }
71993 
71994  p->flags = MEM_Undefined;
71995  }while( (++p)<pEnd );
71996  }
71997 }
71998 
71999 /*
72000 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
72001 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
72002 */
72004  int i;
72005  Mem *aMem = VdbeFrameMem(p);
72006  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
72007  for(i=0; i<p->nChildCsr; i++){
72008  sqlite3VdbeFreeCursor(p->v, apCsr[i]);
72009  }
72010  releaseMemArray(aMem, p->nChildMem);
72011  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
72012  sqlite3DbFree(p->v->db, p);
72013 }
72014 
72015 #ifndef SQLITE_OMIT_EXPLAIN
72016 /*
72017 ** Give a listing of the program in the virtual machine.
72018 **
72019 ** The interface is the same as sqlite3VdbeExec(). But instead of
72020 ** running the code, it invokes the callback once for each instruction.
72021 ** This feature is used to implement "EXPLAIN".
72022 **
72023 ** When p->explain==1, each instruction is listed. When
72024 ** p->explain==2, only OP_Explain instructions are listed and these
72025 ** are shown in a different format. p->explain==2 is used to implement
72026 ** EXPLAIN QUERY PLAN.
72027 **
72028 ** When p->explain==1, first the main program is listed, then each of
72029 ** the trigger subprograms are listed one by one.
72030 */
72032  Vdbe *p /* The VDBE */
72033 ){
72034  int nRow; /* Stop when row count reaches this */
72035  int nSub = 0; /* Number of sub-vdbes seen so far */
72036  SubProgram **apSub = 0; /* Array of sub-vdbes */
72037  Mem *pSub = 0; /* Memory cell hold array of subprogs */
72038  sqlite3 *db = p->db; /* The database connection */
72039  int i; /* Loop counter */
72040  int rc = SQLITE_OK; /* Return code */
72041  Mem *pMem = &p->aMem[1]; /* First Mem of result set */
72042 
72043  assert( p->explain );
72044  assert( p->magic==VDBE_MAGIC_RUN );
72045  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
72046 
72047  /* Even though this opcode does not use dynamic strings for
72048  ** the result, result columns may become dynamic if the user calls
72049  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
72050  */
72051  releaseMemArray(pMem, 8);
72052  p->pResultSet = 0;
72053 
72054  if( p->rc==SQLITE_NOMEM_BKPT ){
72055  /* This happens if a malloc() inside a call to sqlite3_column_text() or
72056  ** sqlite3_column_text16() failed. */
72057  sqlite3OomFault(db);
72058  return SQLITE_ERROR;
72059  }
72060 
72061  /* When the number of output rows reaches nRow, that means the
72062  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
72063  ** nRow is the sum of the number of rows in the main program, plus
72064  ** the sum of the number of rows in all trigger subprograms encountered
72065  ** so far. The nRow value will increase as new trigger subprograms are
72066  ** encountered, but p->pc will eventually catch up to nRow.
72067  */
72068  nRow = p->nOp;
72069  if( p->explain==1 ){
72070  /* The first 8 memory cells are used for the result set. So we will
72071  ** commandeer the 9th cell to use as storage for an array of pointers
72072  ** to trigger subprograms. The VDBE is guaranteed to have at least 9
72073  ** cells. */
72074  assert( p->nMem>9 );
72075  pSub = &p->aMem[9];
72076  if( pSub->flags&MEM_Blob ){
72077  /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
72078  ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
72079  nSub = pSub->n/sizeof(Vdbe*);
72080  apSub = (SubProgram **)pSub->z;
72081  }
72082  for(i=0; i<nSub; i++){
72083  nRow += apSub[i]->nOp;
72084  }
72085  }
72086 
72087  do{
72088  i = p->pc++;
72089  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
72090  if( i>=nRow ){
72091  p->rc = SQLITE_OK;
72092  rc = SQLITE_DONE;
72093  }else if( db->u1.isInterrupted ){
72094  p->rc = SQLITE_INTERRUPT;
72095  rc = SQLITE_ERROR;
72097  }else{
72098  char *zP4;
72099  Op *pOp;
72100  if( i<p->nOp ){
72101  /* The output line number is small enough that we are still in the
72102  ** main program. */
72103  pOp = &p->aOp[i];
72104  }else{
72105  /* We are currently listing subprograms. Figure out which one and
72106  ** pick up the appropriate opcode. */
72107  int j;
72108  i -= p->nOp;
72109  for(j=0; i>=apSub[j]->nOp; j++){
72110  i -= apSub[j]->nOp;
72111  }
72112  pOp = &apSub[j]->aOp[i];
72113  }
72114  if( p->explain==1 ){
72115  pMem->flags = MEM_Int;
72116  pMem->u.i = i; /* Program counter */
72117  pMem++;
72118 
72119  pMem->flags = MEM_Static|MEM_Str|MEM_Term;
72120  pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
72121  assert( pMem->z!=0 );
72122  pMem->n = sqlite3Strlen30(pMem->z);
72123  pMem->enc = SQLITE_UTF8;
72124  pMem++;
72125 
72126  /* When an OP_Program opcode is encounter (the only opcode that has
72127  ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
72128  ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
72129  ** has not already been seen.
72130  */
72131  if( pOp->p4type==P4_SUBPROGRAM ){
72132  int nByte = (nSub+1)*sizeof(SubProgram*);
72133  int j;
72134  for(j=0; j<nSub; j++){
72135  if( apSub[j]==pOp->p4.pProgram ) break;
72136  }
72137  if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
72138  apSub = (SubProgram **)pSub->z;
72139  apSub[nSub++] = pOp->p4.pProgram;
72140  pSub->flags |= MEM_Blob;
72141  pSub->n = nSub*sizeof(SubProgram*);
72142  }
72143  }
72144  }
72145 
72146  pMem->flags = MEM_Int;
72147  pMem->u.i = pOp->p1; /* P1 */
72148  pMem++;
72149 
72150  pMem->flags = MEM_Int;
72151  pMem->u.i = pOp->p2; /* P2 */
72152  pMem++;
72153 
72154  pMem->flags = MEM_Int;
72155  pMem->u.i = pOp->p3; /* P3 */
72156  pMem++;
72157 
72158  if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
72159  assert( p->db->mallocFailed );
72160  return SQLITE_ERROR;
72161  }
72162  pMem->flags = MEM_Str|MEM_Term;
72163  zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
72164  if( zP4!=pMem->z ){
72165  pMem->n = 0;
72166  sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
72167  }else{
72168  assert( pMem->z!=0 );
72169  pMem->n = sqlite3Strlen30(pMem->z);
72170  pMem->enc = SQLITE_UTF8;
72171  }
72172  pMem++;
72173 
72174  if( p->explain==1 ){
72175  if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
72176  assert( p->db->mallocFailed );
72177  return SQLITE_ERROR;
72178  }
72179  pMem->flags = MEM_Str|MEM_Term;
72180  pMem->n = 2;
72181  sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
72182  pMem->enc = SQLITE_UTF8;
72183  pMem++;
72184 
72185 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72186  if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
72187  assert( p->db->mallocFailed );
72188  return SQLITE_ERROR;
72189  }
72190  pMem->flags = MEM_Str|MEM_Term;
72191  pMem->n = displayComment(pOp, zP4, pMem->z, 500);
72192  pMem->enc = SQLITE_UTF8;
72193 #else
72194  pMem->flags = MEM_Null; /* Comment */
72195 #endif
72196  }
72197 
72198  p->nResColumn = 8 - 4*(p->explain-1);
72199  p->pResultSet = &p->aMem[1];
72200  p->rc = SQLITE_OK;
72201  rc = SQLITE_ROW;
72202  }
72203  return rc;
72204 }
72205 #endif /* SQLITE_OMIT_EXPLAIN */
72206 
72207 #ifdef SQLITE_DEBUG
72208 /*
72209 ** Print the SQL that was used to generate a VDBE program.
72210 */
72211 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
72212  const char *z = 0;
72213  if( p->zSql ){
72214  z = p->zSql;
72215  }else if( p->nOp>=1 ){
72216  const VdbeOp *pOp = &p->aOp[0];
72217  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72218  z = pOp->p4.z;
72219  while( sqlite3Isspace(*z) ) z++;
72220  }
72221  }
72222  if( z ) printf("SQL: [%s]\n", z);
72223 }
72224 #endif
72225 
72226 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
72227 /*
72228 ** Print an IOTRACE message showing SQL content.
72229 */
72231  int nOp = p->nOp;
72232  VdbeOp *pOp;
72233  if( sqlite3IoTrace==0 ) return;
72234  if( nOp<1 ) return;
72235  pOp = &p->aOp[0];
72236  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72237  int i, j;
72238  char z[1000];
72239  sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
72240  for(i=0; sqlite3Isspace(z[i]); i++){}
72241  for(j=0; z[i]; i++){
72242  if( sqlite3Isspace(z[i]) ){
72243  if( z[i-1]!=' ' ){
72244  z[j++] = ' ';
72245  }
72246  }else{
72247  z[j++] = z[i];
72248  }
72249  }
72250  z[j] = 0;
72251  sqlite3IoTrace("SQL %s\n", z);
72252  }
72253 }
72254 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
72255 
72256 /* An instance of this object describes bulk memory available for use
72257 ** by subcomponents of a prepared statement. Space is allocated out
72258 ** of a ReusableSpace object by the allocSpace() routine below.
72259 */
72261  u8 *pSpace; /* Available memory */
72262  int nFree; /* Bytes of available memory */
72263  int nNeeded; /* Total bytes that could not be allocated */
72264 };
72265 
72266 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
72267 ** from the ReusableSpace object. Return a pointer to the allocated
72268 ** memory on success. If insufficient memory is available in the
72269 ** ReusableSpace object, increase the ReusableSpace.nNeeded
72270 ** value by the amount needed and return NULL.
72271 **
72272 ** If pBuf is not initially NULL, that means that the memory has already
72273 ** been allocated by a prior call to this routine, so just return a copy
72274 ** of pBuf and leave ReusableSpace unchanged.
72275 **
72276 ** This allocator is employed to repurpose unused slots at the end of the
72277 ** opcode array of prepared state for other memory needs of the prepared
72278 ** statement.
72279 */
72280 static void *allocSpace(
72281  struct ReusableSpace *p, /* Bulk memory available for allocation */
72282  void *pBuf, /* Pointer to a prior allocation */
72283  int nByte /* Bytes of memory needed */
72284 ){
72285  assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
72286  if( pBuf==0 ){
72287  nByte = ROUND8(nByte);
72288  if( nByte <= p->nFree ){
72289  p->nFree -= nByte;
72290  pBuf = &p->pSpace[p->nFree];
72291  }else{
72292  p->nNeeded += nByte;
72293  }
72294  }
72295  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
72296  return pBuf;
72297 }
72298 
72299 /*
72300 ** Rewind the VDBE back to the beginning in preparation for
72301 ** running it.
72302 */
72304 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
72305  int i;
72306 #endif
72307  assert( p!=0 );
72308  assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
72309 
72310  /* There should be at least one opcode.
72311  */
72312  assert( p->nOp>0 );
72313 
72314  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
72315  p->magic = VDBE_MAGIC_RUN;
72316 
72317 #ifdef SQLITE_DEBUG
72318  for(i=0; i<p->nMem; i++){
72319  assert( p->aMem[i].db==p->db );
72320  }
72321 #endif
72322  p->pc = -1;
72323  p->rc = SQLITE_OK;
72324  p->errorAction = OE_Abort;
72325  p->nChange = 0;
72326  p->cacheCtr = 1;
72327  p->minWriteFileFormat = 255;
72328  p->iStatement = 0;
72329  p->nFkConstraint = 0;
72330 #ifdef VDBE_PROFILE
72331  for(i=0; i<p->nOp; i++){
72332  p->aOp[i].cnt = 0;
72333  p->aOp[i].cycles = 0;
72334  }
72335 #endif
72336 }
72337 
72338 /*
72339 ** Prepare a virtual machine for execution for the first time after
72340 ** creating the virtual machine. This involves things such
72341 ** as allocating registers and initializing the program counter.
72342 ** After the VDBE has be prepped, it can be executed by one or more
72343 ** calls to sqlite3VdbeExec().
72344 **
72345 ** This function may be called exactly once on each virtual machine.
72346 ** After this routine is called the VM has been "packaged" and is ready
72347 ** to run. After this routine is called, further calls to
72348 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
72349 ** the Vdbe from the Parse object that helped generate it so that the
72350 ** the Vdbe becomes an independent entity and the Parse object can be
72351 ** destroyed.
72352 **
72353 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
72354 ** to its initial state after it has been run.
72355 */
72357  Vdbe *p, /* The VDBE */
72358  Parse *pParse /* Parsing context */
72359 ){
72360  sqlite3 *db; /* The database connection */
72361  int nVar; /* Number of parameters */
72362  int nMem; /* Number of VM memory registers */
72363  int nCursor; /* Number of cursors required */
72364  int nArg; /* Number of arguments in subprograms */
72365  int n; /* Loop counter */
72366  struct ReusableSpace x; /* Reusable bulk memory */
72367 
72368  assert( p!=0 );
72369  assert( p->nOp>0 );
72370  assert( pParse!=0 );
72371  assert( p->magic==VDBE_MAGIC_INIT );
72372  assert( pParse==p->pParse );
72373  db = p->db;
72374  assert( db->mallocFailed==0 );
72375  nVar = pParse->nVar;
72376  nMem = pParse->nMem;
72377  nCursor = pParse->nTab;
72378  nArg = pParse->nMaxArg;
72379 
72380  /* Each cursor uses a memory cell. The first cursor (cursor 0) can
72381  ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
72382  ** space at the end of aMem[] for cursors 1 and greater.
72383  ** See also: allocateCursor().
72384  */
72385  nMem += nCursor;
72386  if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
72387 
72388  /* Figure out how much reusable memory is available at the end of the
72389  ** opcode array. This extra memory will be reallocated for other elements
72390  ** of the prepared statement.
72391  */
72392  n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
72393  x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
72394  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
72395  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
72396  assert( x.nFree>=0 );
72397  assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
72398 
72399  resolveP2Values(p, &nArg);
72400  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
72401  if( pParse->explain && nMem<10 ){
72402  nMem = 10;
72403  }
72404  p->expired = 0;
72405 
72406  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
72407  ** passes. On the first pass, we try to reuse unused memory at the
72408  ** end of the opcode array. If we are unable to satisfy all memory
72409  ** requirements by reusing the opcode array tail, then the second
72410  ** pass will fill in the remainder using a fresh memory allocation.
72411  **
72412  ** This two-pass approach that reuses as much memory as possible from
72413  ** the leftover memory at the end of the opcode array. This can significantly
72414  ** reduce the amount of memory held by a prepared statement.
72415  */
72416  do {
72417  x.nNeeded = 0;
72418  p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
72419  p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
72420  p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
72421  p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
72422 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72423  p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
72424 #endif
72425  if( x.nNeeded==0 ) break;
72426  x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
72427  x.nFree = x.nNeeded;
72428  }while( !db->mallocFailed );
72429 
72430  p->nzVar = pParse->nzVar;
72431  p->azVar = pParse->azVar;
72432  pParse->nzVar = 0;
72433  pParse->azVar = 0;
72434  p->explain = pParse->explain;
72435  if( db->mallocFailed ){
72436  p->nVar = 0;
72437  p->nCursor = 0;
72438  p->nMem = 0;
72439  }else{
72440  p->nCursor = nCursor;
72441  p->nVar = (ynVar)nVar;
72442  initMemArray(p->aVar, nVar, db, MEM_Null);
72443  p->nMem = nMem;
72444  initMemArray(p->aMem, nMem, db, MEM_Undefined);
72445  memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
72446 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72447  memset(p->anExec, 0, p->nOp*sizeof(i64));
72448 #endif
72449  }
72450  sqlite3VdbeRewind(p);
72451 }
72452 
72453 /*
72454 ** Close a VDBE cursor and release all the resources that cursor
72455 ** happens to hold.
72456 */
72458  if( pCx==0 ){
72459  return;
72460  }
72461  assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
72462  switch( pCx->eCurType ){
72463  case CURTYPE_SORTER: {
72464  sqlite3VdbeSorterClose(p->db, pCx);
72465  break;
72466  }
72467  case CURTYPE_BTREE: {
72468  if( pCx->pBt ){
72469  sqlite3BtreeClose(pCx->pBt);
72470  /* The pCx->pCursor will be close automatically, if it exists, by
72471  ** the call above. */
72472  }else{
72473  assert( pCx->uc.pCursor!=0 );
72475  }
72476  break;
72477  }
72478 #ifndef SQLITE_OMIT_VIRTUALTABLE
72479  case CURTYPE_VTAB: {
72480  sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
72481  const sqlite3_module *pModule = pVCur->pVtab->pModule;
72482  assert( pVCur->pVtab->nRef>0 );
72483  pVCur->pVtab->nRef--;
72484  pModule->xClose(pVCur);
72485  break;
72486  }
72487 #endif
72488  }
72489 }
72490 
72491 /*
72492 ** Close all cursors in the current frame.
72493 */
72494 static void closeCursorsInFrame(Vdbe *p){
72495  if( p->apCsr ){
72496  int i;
72497  for(i=0; i<p->nCursor; i++){
72498  VdbeCursor *pC = p->apCsr[i];
72499  if( pC ){
72500  sqlite3VdbeFreeCursor(p, pC);
72501  p->apCsr[i] = 0;
72502  }
72503  }
72504  }
72505 }
72506 
72507 /*
72508 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
72509 ** is used, for example, when a trigger sub-program is halted to restore
72510 ** control to the main program.
72511 */
72513  Vdbe *v = pFrame->v;
72515 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72516  v->anExec = pFrame->anExec;
72517 #endif
72518  v->aOp = pFrame->aOp;
72519  v->nOp = pFrame->nOp;
72520  v->aMem = pFrame->aMem;
72521  v->nMem = pFrame->nMem;
72522  v->apCsr = pFrame->apCsr;
72523  v->nCursor = pFrame->nCursor;
72524  v->db->lastRowid = pFrame->lastRowid;
72525  v->nChange = pFrame->nChange;
72526  v->db->nChange = pFrame->nDbChange;
72527  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
72528  v->pAuxData = pFrame->pAuxData;
72529  pFrame->pAuxData = 0;
72530  return pFrame->pc;
72531 }
72532 
72533 /*
72534 ** Close all cursors.
72535 **
72536 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
72537 ** cell array. This is necessary as the memory cell array may contain
72538 ** pointers to VdbeFrame objects, which may in turn contain pointers to
72539 ** open cursors.
72540 */
72541 static void closeAllCursors(Vdbe *p){
72542  if( p->pFrame ){
72543  VdbeFrame *pFrame;
72544  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
72545  sqlite3VdbeFrameRestore(pFrame);
72546  p->pFrame = 0;
72547  p->nFrame = 0;
72548  }
72549  assert( p->nFrame==0 );
72551  if( p->aMem ){
72552  releaseMemArray(p->aMem, p->nMem);
72553  }
72554  while( p->pDelFrame ){
72555  VdbeFrame *pDel = p->pDelFrame;
72556  p->pDelFrame = pDel->pParent;
72557  sqlite3VdbeFrameDelete(pDel);
72558  }
72559 
72560  /* Delete any auxdata allocations made by the VM */
72561  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
72562  assert( p->pAuxData==0 );
72563 }
72564 
72565 /*
72566 ** Clean up the VM after a single run.
72567 */
72568 static void Cleanup(Vdbe *p){
72569  sqlite3 *db = p->db;
72570 
72571 #ifdef SQLITE_DEBUG
72572  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
72573  ** Vdbe.aMem[] arrays have already been cleaned up. */
72574  int i;
72575  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
72576  if( p->aMem ){
72577  for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
72578  }
72579 #endif
72580 
72581  sqlite3DbFree(db, p->zErrMsg);
72582  p->zErrMsg = 0;
72583  p->pResultSet = 0;
72584 }
72585 
72586 /*
72587 ** Set the number of result columns that will be returned by this SQL
72588 ** statement. This is now set at compile time, rather than during
72589 ** execution of the vdbe program so that sqlite3_column_count() can
72590 ** be called on an SQL statement before sqlite3_step().
72591 */
72592 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
72593  Mem *pColName;
72594  int n;
72595  sqlite3 *db = p->db;
72596 
72598  sqlite3DbFree(db, p->aColName);
72599  n = nResColumn*COLNAME_N;
72600  p->nResColumn = (u16)nResColumn;
72601  p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
72602  if( p->aColName==0 ) return;
72603  initMemArray(p->aColName, n, p->db, MEM_Null);
72604 }
72605 
72606 /*
72607 ** Set the name of the idx'th column to be returned by the SQL statement.
72608 ** zName must be a pointer to a nul terminated string.
72609 **
72610 ** This call must be made after a call to sqlite3VdbeSetNumCols().
72611 **
72612 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
72613 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
72614 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
72615 */
72617  Vdbe *p, /* Vdbe being configured */
72618  int idx, /* Index of column zName applies to */
72619  int var, /* One of the COLNAME_* constants */
72620  const char *zName, /* Pointer to buffer containing name */
72621  void (*xDel)(void*) /* Memory management strategy for zName */
72622 ){
72623  int rc;
72624  Mem *pColName;
72625  assert( idx<p->nResColumn );
72626  assert( var<COLNAME_N );
72627  if( p->db->mallocFailed ){
72628  assert( !zName || xDel!=SQLITE_DYNAMIC );
72629  return SQLITE_NOMEM_BKPT;
72630  }
72631  assert( p->aColName!=0 );
72632  pColName = &(p->aColName[idx+var*p->nResColumn]);
72633  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
72634  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
72635  return rc;
72636 }
72637 
72638 /*
72639 ** A read or write transaction may or may not be active on database handle
72640 ** db. If a transaction is active, commit it. If there is a
72641 ** write-transaction spanning more than one database file, this routine
72642 ** takes care of the master journal trickery.
72643 */
72644 static int vdbeCommit(sqlite3 *db, Vdbe *p){
72645  int i;
72646  int nTrans = 0; /* Number of databases with an active write-transaction
72647  ** that are candidates for a two-phase commit using a
72648  ** master-journal */
72649  int rc = SQLITE_OK;
72650  int needXcommit = 0;
72651 
72652 #ifdef SQLITE_OMIT_VIRTUALTABLE
72653  /* With this option, sqlite3VtabSync() is defined to be simply
72654  ** SQLITE_OK so p is not used.
72655  */
72656  UNUSED_PARAMETER(p);
72657 #endif
72658 
72659  /* Before doing anything else, call the xSync() callback for any
72660  ** virtual module tables written in this transaction. This has to
72661  ** be done before determining whether a master journal file is
72662  ** required, as an xSync() callback may add an attached database
72663  ** to the transaction.
72664  */
72665  rc = sqlite3VtabSync(db, p);
72666 
72667  /* This loop determines (a) if the commit hook should be invoked and
72668  ** (b) how many database files have open write transactions, not
72669  ** including the temp database. (b) is important because if more than
72670  ** one database file has an open write transaction, a master journal
72671  ** file is required for an atomic commit.
72672  */
72673  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72674  Btree *pBt = db->aDb[i].pBt;
72675  if( sqlite3BtreeIsInTrans(pBt) ){
72676  /* Whether or not a database might need a master journal depends upon
72677  ** its journal mode (among other things). This matrix determines which
72678  ** journal modes use a master journal and which do not */
72679  static const u8 aMJNeeded[] = {
72680  /* DELETE */ 1,
72681  /* PERSIST */ 1,
72682  /* OFF */ 0,
72683  /* TRUNCATE */ 1,
72684  /* MEMORY */ 0,
72685  /* WAL */ 0
72686  };
72687  Pager *pPager; /* Pager associated with pBt */
72688  needXcommit = 1;
72689  sqlite3BtreeEnter(pBt);
72690  pPager = sqlite3BtreePager(pBt);
72692  && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
72693  ){
72694  assert( i!=1 );
72695  nTrans++;
72696  }
72697  rc = sqlite3PagerExclusiveLock(pPager);
72698  sqlite3BtreeLeave(pBt);
72699  }
72700  }
72701  if( rc!=SQLITE_OK ){
72702  return rc;
72703  }
72704 
72705  /* If there are any write-transactions at all, invoke the commit hook */
72706  if( needXcommit && db->xCommitCallback ){
72707  rc = db->xCommitCallback(db->pCommitArg);
72708  if( rc ){
72710  }
72711  }
72712 
72713  /* The simple case - no more than one database file (not counting the
72714  ** TEMP database) has a transaction active. There is no need for the
72715  ** master-journal.
72716  **
72717  ** If the return value of sqlite3BtreeGetFilename() is a zero length
72718  ** string, it means the main database is :memory: or a temp file. In
72719  ** that case we do not support atomic multi-file commits, so use the
72720  ** simple case then too.
72721  */
72723  || nTrans<=1
72724  ){
72725  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72726  Btree *pBt = db->aDb[i].pBt;
72727  if( pBt ){
72728  rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
72729  }
72730  }
72731 
72732  /* Do the commit only if all databases successfully complete phase 1.
72733  ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
72734  ** IO error while deleting or truncating a journal file. It is unlikely,
72735  ** but could happen. In this case abandon processing and return the error.
72736  */
72737  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72738  Btree *pBt = db->aDb[i].pBt;
72739  if( pBt ){
72740  rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
72741  }
72742  }
72743  if( rc==SQLITE_OK ){
72744  sqlite3VtabCommit(db);
72745  }
72746  }
72747 
72748  /* The complex case - There is a multi-file write-transaction active.
72749  ** This requires a master journal file to ensure the transaction is
72750  ** committed atomically.
72751  */
72752 #ifndef SQLITE_OMIT_DISKIO
72753  else{
72754  sqlite3_vfs *pVfs = db->pVfs;
72755  char *zMaster = 0; /* File-name for the master journal */
72756  char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
72757  sqlite3_file *pMaster = 0;
72758  i64 offset = 0;
72759  int res;
72760  int retryCount = 0;
72761  int nMainFile;
72762 
72763  /* Select a master journal file name */
72764  nMainFile = sqlite3Strlen30(zMainFile);
72765  zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
72766  if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
72767  do {
72768  u32 iRandom;
72769  if( retryCount ){
72770  if( retryCount>100 ){
72771  sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
72772  sqlite3OsDelete(pVfs, zMaster, 0);
72773  break;
72774  }else if( retryCount==1 ){
72775  sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
72776  }
72777  }
72778  retryCount++;
72779  sqlite3_randomness(sizeof(iRandom), &iRandom);
72780  sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
72781  (iRandom>>8)&0xffffff, iRandom&0xff);
72782  /* The antipenultimate character of the master journal name must
72783  ** be "9" to avoid name collisions when using 8+3 filenames. */
72784  assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
72785  sqlite3FileSuffix3(zMainFile, zMaster);
72786  rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
72787  }while( rc==SQLITE_OK && res );
72788  if( rc==SQLITE_OK ){
72789  /* Open the master journal. */
72790  rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
72793  );
72794  }
72795  if( rc!=SQLITE_OK ){
72796  sqlite3DbFree(db, zMaster);
72797  return rc;
72798  }
72799 
72800  /* Write the name of each database file in the transaction into the new
72801  ** master journal file. If an error occurs at this point close
72802  ** and delete the master journal file. All the individual journal files
72803  ** still have 'null' as the master journal pointer, so they will roll
72804  ** back independently if a failure occurs.
72805  */
72806  for(i=0; i<db->nDb; i++){
72807  Btree *pBt = db->aDb[i].pBt;
72808  if( sqlite3BtreeIsInTrans(pBt) ){
72809  char const *zFile = sqlite3BtreeGetJournalname(pBt);
72810  if( zFile==0 ){
72811  continue; /* Ignore TEMP and :memory: databases */
72812  }
72813  assert( zFile[0]!=0 );
72814  rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
72815  offset += sqlite3Strlen30(zFile)+1;
72816  if( rc!=SQLITE_OK ){
72817  sqlite3OsCloseFree(pMaster);
72818  sqlite3OsDelete(pVfs, zMaster, 0);
72819  sqlite3DbFree(db, zMaster);
72820  return rc;
72821  }
72822  }
72823  }
72824 
72825  /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
72826  ** flag is set this is not required.
72827  */
72829  && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
72830  ){
72831  sqlite3OsCloseFree(pMaster);
72832  sqlite3OsDelete(pVfs, zMaster, 0);
72833  sqlite3DbFree(db, zMaster);
72834  return rc;
72835  }
72836 
72837  /* Sync all the db files involved in the transaction. The same call
72838  ** sets the master journal pointer in each individual journal. If
72839  ** an error occurs here, do not delete the master journal file.
72840  **
72841  ** If the error occurs during the first call to
72842  ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
72843  ** master journal file will be orphaned. But we cannot delete it,
72844  ** in case the master journal file name was written into the journal
72845  ** file before the failure occurred.
72846  */
72847  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72848  Btree *pBt = db->aDb[i].pBt;
72849  if( pBt ){
72850  rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
72851  }
72852  }
72853  sqlite3OsCloseFree(pMaster);
72854  assert( rc!=SQLITE_BUSY );
72855  if( rc!=SQLITE_OK ){
72856  sqlite3DbFree(db, zMaster);
72857  return rc;
72858  }
72859 
72860  /* Delete the master journal file. This commits the transaction. After
72861  ** doing this the directory is synced again before any individual
72862  ** transaction files are deleted.
72863  */
72864  rc = sqlite3OsDelete(pVfs, zMaster, 1);
72865  sqlite3DbFree(db, zMaster);
72866  zMaster = 0;
72867  if( rc ){
72868  return rc;
72869  }
72870 
72871  /* All files and directories have already been synced, so the following
72872  ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
72873  ** deleting or truncating journals. If something goes wrong while
72874  ** this is happening we don't really care. The integrity of the
72875  ** transaction is already guaranteed, but some stray 'cold' journals
72876  ** may be lying around. Returning an error code won't help matters.
72877  */
72880  for(i=0; i<db->nDb; i++){
72881  Btree *pBt = db->aDb[i].pBt;
72882  if( pBt ){
72884  }
72885  }
72888 
72889  sqlite3VtabCommit(db);
72890  }
72891 #endif
72892 
72893  return rc;
72894 }
72895 
72896 /*
72897 ** This routine checks that the sqlite3.nVdbeActive count variable
72898 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
72899 ** currently active. An assertion fails if the two counts do not match.
72900 ** This is an internal self-check only - it is not an essential processing
72901 ** step.
72902 **
72903 ** This is a no-op if NDEBUG is defined.
72904 */
72905 #ifndef NDEBUG
72906 static void checkActiveVdbeCnt(sqlite3 *db){
72907  Vdbe *p;
72908  int cnt = 0;
72909  int nWrite = 0;
72910  int nRead = 0;
72911  p = db->pVdbe;
72912  while( p ){
72913  if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
72914  cnt++;
72915  if( p->readOnly==0 ) nWrite++;
72916  if( p->bIsReader ) nRead++;
72917  }
72918  p = p->pNext;
72919  }
72920  assert( cnt==db->nVdbeActive );
72921  assert( nWrite==db->nVdbeWrite );
72922  assert( nRead==db->nVdbeRead );
72923 }
72924 #else
72925 #define checkActiveVdbeCnt(x)
72926 #endif
72927 
72928 /*
72929 ** If the Vdbe passed as the first argument opened a statement-transaction,
72930 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
72931 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
72932 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
72933 ** statement transaction is committed.
72934 **
72935 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
72936 ** Otherwise SQLITE_OK.
72937 */
72939  sqlite3 *const db = p->db;
72940  int rc = SQLITE_OK;
72941 
72942  /* If p->iStatement is greater than zero, then this Vdbe opened a
72943  ** statement transaction that should be closed here. The only exception
72944  ** is that an IO error may have occurred, causing an emergency rollback.
72945  ** In this case (db->nStatement==0), and there is nothing to do.
72946  */
72947  if( db->nStatement && p->iStatement ){
72948  int i;
72949  const int iSavepoint = p->iStatement-1;
72950 
72951  assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
72952  assert( db->nStatement>0 );
72953  assert( p->iStatement==(db->nStatement+db->nSavepoint) );
72954 
72955  for(i=0; i<db->nDb; i++){
72956  int rc2 = SQLITE_OK;
72957  Btree *pBt = db->aDb[i].pBt;
72958  if( pBt ){
72959  if( eOp==SAVEPOINT_ROLLBACK ){
72960  rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
72961  }
72962  if( rc2==SQLITE_OK ){
72963  rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
72964  }
72965  if( rc==SQLITE_OK ){
72966  rc = rc2;
72967  }
72968  }
72969  }
72970  db->nStatement--;
72971  p->iStatement = 0;
72972 
72973  if( rc==SQLITE_OK ){
72974  if( eOp==SAVEPOINT_ROLLBACK ){
72975  rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
72976  }
72977  if( rc==SQLITE_OK ){
72978  rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
72979  }
72980  }
72981 
72982  /* If the statement transaction is being rolled back, also restore the
72983  ** database handles deferred constraint counter to the value it had when
72984  ** the statement transaction was opened. */
72985  if( eOp==SAVEPOINT_ROLLBACK ){
72986  db->nDeferredCons = p->nStmtDefCons;
72988  }
72989  }
72990  return rc;
72991 }
72992 
72993 /*
72994 ** This function is called when a transaction opened by the database
72995 ** handle associated with the VM passed as an argument is about to be
72996 ** committed. If there are outstanding deferred foreign key constraint
72997 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
72998 **
72999 ** If there are outstanding FK violations and this function returns
73000 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
73001 ** and write an error message to it. Then return SQLITE_ERROR.
73002 */
73003 #ifndef SQLITE_OMIT_FOREIGN_KEY
73005  sqlite3 *db = p->db;
73006  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
73007  || (!deferred && p->nFkConstraint>0)
73008  ){
73010  p->errorAction = OE_Abort;
73011  sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
73012  return SQLITE_ERROR;
73013  }
73014  return SQLITE_OK;
73015 }
73016 #endif
73017 
73018 /*
73019 ** This routine is called the when a VDBE tries to halt. If the VDBE
73020 ** has made changes and is in autocommit mode, then commit those
73021 ** changes. If a rollback is needed, then do the rollback.
73022 **
73023 ** This routine is the only way to move the state of a VM from
73024 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
73025 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
73026 **
73027 ** Return an error code. If the commit could not complete because of
73028 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
73029 ** means the close did not happen and needs to be repeated.
73030 */
73032  int rc; /* Used to store transient return codes */
73033  sqlite3 *db = p->db;
73034 
73035  /* This function contains the logic that determines if a statement or
73036  ** transaction will be committed or rolled back as a result of the
73037  ** execution of this virtual machine.
73038  **
73039  ** If any of the following errors occur:
73040  **
73041  ** SQLITE_NOMEM
73042  ** SQLITE_IOERR
73043  ** SQLITE_FULL
73044  ** SQLITE_INTERRUPT
73045  **
73046  ** Then the internal cache might have been left in an inconsistent
73047  ** state. We need to rollback the statement transaction, if there is
73048  ** one, or the complete transaction if there is no statement transaction.
73049  */
73050 
73051  if( db->mallocFailed ){
73052  p->rc = SQLITE_NOMEM_BKPT;
73053  }
73054  closeAllCursors(p);
73055  if( p->magic!=VDBE_MAGIC_RUN ){
73056  return SQLITE_OK;
73057  }
73058  checkActiveVdbeCnt(db);
73059 
73060  /* No commit or rollback needed if the program never started or if the
73061  ** SQL statement does not read or write a database file. */
73062  if( p->pc>=0 && p->bIsReader ){
73063  int mrc; /* Primary error code from p->rc */
73064  int eStatementOp = 0;
73065  int isSpecialError; /* Set to true if a 'special' error */
73066 
73067  /* Lock all btrees used by the statement */
73068  sqlite3VdbeEnter(p);
73069 
73070  /* Check for one of the special errors */
73071  mrc = p->rc & 0xff;
73072  isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
73073  || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
73074  if( isSpecialError ){
73075  /* If the query was read-only and the error code is SQLITE_INTERRUPT,
73076  ** no rollback is necessary. Otherwise, at least a savepoint
73077  ** transaction must be rolled back to restore the database to a
73078  ** consistent state.
73079  **
73080  ** Even if the statement is read-only, it is important to perform
73081  ** a statement or transaction rollback operation. If the error
73082  ** occurred while writing to the journal, sub-journal or database
73083  ** file as part of an effort to free up cache space (see function
73084  ** pagerStress() in pager.c), the rollback is required to restore
73085  ** the pager to a consistent state.
73086  */
73087  if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
73088  if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
73089  eStatementOp = SAVEPOINT_ROLLBACK;
73090  }else{
73091  /* We are forced to roll back the active transaction. Before doing
73092  ** so, abort any other statements this handle currently has active.
73093  */
73096  db->autoCommit = 1;
73097  p->nChange = 0;
73098  }
73099  }
73100  }
73101 
73102  /* Check for immediate foreign key violations. */
73103  if( p->rc==SQLITE_OK ){
73104  sqlite3VdbeCheckFk(p, 0);
73105  }
73106 
73107  /* If the auto-commit flag is set and this is the only active writer
73108  ** VM, then we do either a commit or rollback of the current transaction.
73109  **
73110  ** Note: This block also runs if one of the special errors handled
73111  ** above has occurred.
73112  */
73113  if( !sqlite3VtabInSync(db)
73114  && db->autoCommit
73115  && db->nVdbeWrite==(p->readOnly==0)
73116  ){
73117  if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
73118  rc = sqlite3VdbeCheckFk(p, 1);
73119  if( rc!=SQLITE_OK ){
73120  if( NEVER(p->readOnly) ){
73121  sqlite3VdbeLeave(p);
73122  return SQLITE_ERROR;
73123  }
73125  }else{
73126  /* The auto-commit flag is true, the vdbe program was successful
73127  ** or hit an 'OR FAIL' constraint and there are no deferred foreign
73128  ** key constraints to hold up the transaction. This means a commit
73129  ** is required. */
73130  rc = vdbeCommit(db, p);
73131  }
73132  if( rc==SQLITE_BUSY && p->readOnly ){
73133  sqlite3VdbeLeave(p);
73134  return SQLITE_BUSY;
73135  }else if( rc!=SQLITE_OK ){
73136  p->rc = rc;
73138  p->nChange = 0;
73139  }else{
73140  db->nDeferredCons = 0;
73141  db->nDeferredImmCons = 0;
73142  db->flags &= ~SQLITE_DeferFKs;
73144  }
73145  }else{
73147  p->nChange = 0;
73148  }
73149  db->nStatement = 0;
73150  }else if( eStatementOp==0 ){
73151  if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
73152  eStatementOp = SAVEPOINT_RELEASE;
73153  }else if( p->errorAction==OE_Abort ){
73154  eStatementOp = SAVEPOINT_ROLLBACK;
73155  }else{
73158  db->autoCommit = 1;
73159  p->nChange = 0;
73160  }
73161  }
73162 
73163  /* If eStatementOp is non-zero, then a statement transaction needs to
73164  ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
73165  ** do so. If this operation returns an error, and the current statement
73166  ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
73167  ** current statement error code.
73168  */
73169  if( eStatementOp ){
73170  rc = sqlite3VdbeCloseStatement(p, eStatementOp);
73171  if( rc ){
73172  if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
73173  p->rc = rc;
73174  sqlite3DbFree(db, p->zErrMsg);
73175  p->zErrMsg = 0;
73176  }
73179  db->autoCommit = 1;
73180  p->nChange = 0;
73181  }
73182  }
73183 
73184  /* If this was an INSERT, UPDATE or DELETE and no statement transaction
73185  ** has been rolled back, update the database connection change-counter.
73186  */
73187  if( p->changeCntOn ){
73188  if( eStatementOp!=SAVEPOINT_ROLLBACK ){
73190  }else{
73191  sqlite3VdbeSetChanges(db, 0);
73192  }
73193  p->nChange = 0;
73194  }
73195 
73196  /* Release the locks */
73197  sqlite3VdbeLeave(p);
73198  }
73199 
73200  /* We have successfully halted and closed the VM. Record this fact. */
73201  if( p->pc>=0 ){
73202  db->nVdbeActive--;
73203  if( !p->readOnly ) db->nVdbeWrite--;
73204  if( p->bIsReader ) db->nVdbeRead--;
73205  assert( db->nVdbeActive>=db->nVdbeRead );
73206  assert( db->nVdbeRead>=db->nVdbeWrite );
73207  assert( db->nVdbeWrite>=0 );
73208  }
73209  p->magic = VDBE_MAGIC_HALT;
73210  checkActiveVdbeCnt(db);
73211  if( db->mallocFailed ){
73212  p->rc = SQLITE_NOMEM_BKPT;
73213  }
73214 
73215  /* If the auto-commit flag is set to true, then any locks that were held
73216  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
73217  ** to invoke any required unlock-notify callbacks.
73218  */
73219  if( db->autoCommit ){
73221  }
73222 
73223  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
73224  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
73225 }
73226 
73227 
73228 /*
73229 ** Each VDBE holds the result of the most recent sqlite3_step() call
73230 ** in p->rc. This routine sets that result back to SQLITE_OK.
73231 */
73233  p->rc = SQLITE_OK;
73234 }
73235 
73236 /*
73237 ** Copy the error code and error message belonging to the VDBE passed
73238 ** as the first argument to its database handle (so that they will be
73239 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
73240 **
73241 ** This function does not clear the VDBE error code or message, just
73242 ** copies them to the database handle.
73243 */
73245  sqlite3 *db = p->db;
73246  int rc = p->rc;
73247  if( p->zErrMsg ){
73248  db->bBenignMalloc++;
73250  if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
73253  db->bBenignMalloc--;
73254  db->errCode = rc;
73255  }else{
73256  sqlite3Error(db, rc);
73257  }
73258  return rc;
73259 }
73260 
73261 #ifdef SQLITE_ENABLE_SQLLOG
73262 /*
73263 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
73264 ** invoke it.
73265 */
73266 static void vdbeInvokeSqllog(Vdbe *v){
73267  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
73268  char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
73269  assert( v->db->init.busy==0 );
73270  if( zExpanded ){
73271  sqlite3GlobalConfig.xSqllog(
73272  sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
73273  );
73274  sqlite3DbFree(v->db, zExpanded);
73275  }
73276  }
73277 }
73278 #else
73279 # define vdbeInvokeSqllog(x)
73280 #endif
73281 
73282 /*
73283 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
73284 ** Write any error messages into *pzErrMsg. Return the result code.
73285 **
73286 ** After this routine is run, the VDBE should be ready to be executed
73287 ** again.
73288 **
73289 ** To look at it another way, this routine resets the state of the
73290 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
73291 ** VDBE_MAGIC_INIT.
73292 */
73294  sqlite3 *db;
73295  db = p->db;
73296 
73297  /* If the VM did not run to completion or if it encountered an
73298  ** error, then it might not have been halted properly. So halt
73299  ** it now.
73300  */
73301  sqlite3VdbeHalt(p);
73302 
73303  /* If the VDBE has be run even partially, then transfer the error code
73304  ** and error message from the VDBE into the main database structure. But
73305  ** if the VDBE has just been set to run but has not actually executed any
73306  ** instructions yet, leave the main database error information unchanged.
73307  */
73308  if( p->pc>=0 ){
73309  vdbeInvokeSqllog(p);
73311  sqlite3DbFree(db, p->zErrMsg);
73312  p->zErrMsg = 0;
73313  if( p->runOnlyOnce ) p->expired = 1;
73314  }else if( p->rc && p->expired ){
73315  /* The expired flag was set on the VDBE before the first call
73316  ** to sqlite3_step(). For consistency (since sqlite3_step() was
73317  ** called), set the database error in this case as well.
73318  */
73319  sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
73320  sqlite3DbFree(db, p->zErrMsg);
73321  p->zErrMsg = 0;
73322  }
73323 
73324  /* Reclaim all memory used by the VDBE
73325  */
73326  Cleanup(p);
73327 
73328  /* Save profiling information from this VDBE run.
73329  */
73330 #ifdef VDBE_PROFILE
73331  {
73332  FILE *out = fopen("vdbe_profile.out", "a");
73333  if( out ){
73334  int i;
73335  fprintf(out, "---- ");
73336  for(i=0; i<p->nOp; i++){
73337  fprintf(out, "%02x", p->aOp[i].opcode);
73338  }
73339  fprintf(out, "\n");
73340  if( p->zSql ){
73341  char c, pc = 0;
73342  fprintf(out, "-- ");
73343  for(i=0; (c = p->zSql[i])!=0; i++){
73344  if( pc=='\n' ) fprintf(out, "-- ");
73345  putc(c, out);
73346  pc = c;
73347  }
73348  if( pc!='\n' ) fprintf(out, "\n");
73349  }
73350  for(i=0; i<p->nOp; i++){
73351  char zHdr[100];
73352  sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
73353  p->aOp[i].cnt,
73354  p->aOp[i].cycles,
73355  p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
73356  );
73357  fprintf(out, "%s", zHdr);
73358  sqlite3VdbePrintOp(out, i, &p->aOp[i]);
73359  }
73360  fclose(out);
73361  }
73362  }
73363 #endif
73364  p->iCurrentTime = 0;
73365  p->magic = VDBE_MAGIC_RESET;
73366  return p->rc & db->errMask;
73367 }
73368 
73369 /*
73370 ** Clean up and delete a VDBE after execution. Return an integer which is
73371 ** the result code. Write any error message text into *pzErrMsg.
73372 */
73374  int rc = SQLITE_OK;
73375  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
73376  rc = sqlite3VdbeReset(p);
73377  assert( (rc & p->db->errMask)==rc );
73378  }
73379  sqlite3VdbeDelete(p);
73380  return rc;
73381 }
73382 
73383 /*
73384 ** If parameter iOp is less than zero, then invoke the destructor for
73385 ** all auxiliary data pointers currently cached by the VM passed as
73386 ** the first argument.
73387 **
73388 ** Or, if iOp is greater than or equal to zero, then the destructor is
73389 ** only invoked for those auxiliary data pointers created by the user
73390 ** function invoked by the OP_Function opcode at instruction iOp of
73391 ** VM pVdbe, and only then if:
73392 **
73393 ** * the associated function parameter is the 32nd or later (counting
73394 ** from left to right), or
73395 **
73396 ** * the corresponding bit in argument mask is clear (where the first
73397 ** function parameter corresponds to bit 0 etc.).
73398 */
73399 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
73400  while( *pp ){
73401  AuxData *pAux = *pp;
73402  if( (iOp<0)
73403  || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
73404  ){
73405  testcase( pAux->iArg==31 );
73406  if( pAux->xDelete ){
73407  pAux->xDelete(pAux->pAux);
73408  }
73409  *pp = pAux->pNext;
73410  sqlite3DbFree(db, pAux);
73411  }else{
73412  pp= &pAux->pNext;
73413  }
73414  }
73415 }
73416 
73417 /*
73418 ** Free all memory associated with the Vdbe passed as the second argument,
73419 ** except for object itself, which is preserved.
73420 **
73421 ** The difference between this function and sqlite3VdbeDelete() is that
73422 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
73423 ** the database connection and frees the object itself.
73424 */
73426  SubProgram *pSub, *pNext;
73427  int i;
73428  assert( p->db==0 || p->db==db );
73430  for(pSub=p->pProgram; pSub; pSub=pNext){
73431  pNext = pSub->pNext;
73432  vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
73433  sqlite3DbFree(db, pSub);
73434  }
73435  if( p->magic!=VDBE_MAGIC_INIT ){
73436  releaseMemArray(p->aVar, p->nVar);
73437  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
73438  sqlite3DbFree(db, p->azVar);
73439  sqlite3DbFree(db, p->pFree);
73440  }
73441  vdbeFreeOpArray(db, p->aOp, p->nOp);
73442  sqlite3DbFree(db, p->aColName);
73443  sqlite3DbFree(db, p->zSql);
73444 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73445  for(i=0; i<p->nScan; i++){
73446  sqlite3DbFree(db, p->aScan[i].zName);
73447  }
73448  sqlite3DbFree(db, p->aScan);
73449 #endif
73450 }
73451 
73452 /*
73453 ** Delete an entire VDBE.
73454 */
73456  sqlite3 *db;
73457 
73458  if( NEVER(p==0) ) return;
73459  db = p->db;
73460  assert( sqlite3_mutex_held(db->mutex) );
73461  sqlite3VdbeClearObject(db, p);
73462  if( p->pPrev ){
73463  p->pPrev->pNext = p->pNext;
73464  }else{
73465  assert( db->pVdbe==p );
73466  db->pVdbe = p->pNext;
73467  }
73468  if( p->pNext ){
73469  p->pNext->pPrev = p->pPrev;
73470  }
73471  p->magic = VDBE_MAGIC_DEAD;
73472  p->db = 0;
73473  sqlite3DbFree(db, p);
73474 }
73475 
73476 /*
73477 ** The cursor "p" has a pending seek operation that has not yet been
73478 ** carried out. Seek the cursor now. If an error occurs, return
73479 ** the appropriate error code.
73480 */
73482  int res, rc;
73483 #ifdef SQLITE_TEST
73484  extern int sqlite3_search_count;
73485 #endif
73486  assert( p->deferredMoveto );
73487  assert( p->isTable );
73488  assert( p->eCurType==CURTYPE_BTREE );
73489  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
73490  if( rc ) return rc;
73491  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
73492 #ifdef SQLITE_TEST
73493  sqlite3_search_count++;
73494 #endif
73495  p->deferredMoveto = 0;
73496  p->cacheStatus = CACHE_STALE;
73497  return SQLITE_OK;
73498 }
73499 
73500 /*
73501 ** Something has moved cursor "p" out of place. Maybe the row it was
73502 ** pointed to was deleted out from under it. Or maybe the btree was
73503 ** rebalanced. Whatever the cause, try to restore "p" to the place it
73504 ** is supposed to be pointing. If the row was deleted out from under the
73505 ** cursor, set the cursor to point to a NULL row.
73506 */
73508  int isDifferentRow, rc;
73509  assert( p->eCurType==CURTYPE_BTREE );
73510  assert( p->uc.pCursor!=0 );
73511  assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
73512  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
73513  p->cacheStatus = CACHE_STALE;
73514  if( isDifferentRow ) p->nullRow = 1;
73515  return rc;
73516 }
73517 
73518 /*
73519 ** Check to ensure that the cursor is valid. Restore the cursor
73520 ** if need be. Return any I/O error from the restore operation.
73521 */
73523  assert( p->eCurType==CURTYPE_BTREE );
73525  return handleMovedCursor(p);
73526  }
73527  return SQLITE_OK;
73528 }
73529 
73530 /*
73531 ** Make sure the cursor p is ready to read or write the row to which it
73532 ** was last positioned. Return an error code if an OOM fault or I/O error
73533 ** prevents us from positioning the cursor to its correct position.
73534 **
73535 ** If a MoveTo operation is pending on the given cursor, then do that
73536 ** MoveTo now. If no move is pending, check to see if the row has been
73537 ** deleted out from under the cursor and if it has, mark the row as
73538 ** a NULL row.
73539 **
73540 ** If the cursor is already pointing to the correct row and that row has
73541 ** not been deleted out from under the cursor, then this routine is a no-op.
73542 */
73544  VdbeCursor *p = *pp;
73545  if( p->eCurType==CURTYPE_BTREE ){
73546  if( p->deferredMoveto ){
73547  int iMap;
73548  if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
73549  *pp = p->pAltCursor;
73550  *piCol = iMap - 1;
73551  return SQLITE_OK;
73552  }
73553  return handleDeferredMoveto(p);
73554  }
73556  return handleMovedCursor(p);
73557  }
73558  }
73559  return SQLITE_OK;
73560 }
73561 
73562 /*
73563 ** The following functions:
73564 **
73565 ** sqlite3VdbeSerialType()
73566 ** sqlite3VdbeSerialTypeLen()
73567 ** sqlite3VdbeSerialLen()
73568 ** sqlite3VdbeSerialPut()
73569 ** sqlite3VdbeSerialGet()
73570 **
73571 ** encapsulate the code that serializes values for storage in SQLite
73572 ** data and index records. Each serialized value consists of a
73573 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
73574 ** integer, stored as a varint.
73575 **
73576 ** In an SQLite index record, the serial type is stored directly before
73577 ** the blob of data that it corresponds to. In a table record, all serial
73578 ** types are stored at the start of the record, and the blobs of data at
73579 ** the end. Hence these functions allow the caller to handle the
73580 ** serial-type and data blob separately.
73581 **
73582 ** The following table describes the various storage classes for data:
73583 **
73584 ** serial type bytes of data type
73585 ** -------------- --------------- ---------------
73586 ** 0 0 NULL
73587 ** 1 1 signed integer
73588 ** 2 2 signed integer
73589 ** 3 3 signed integer
73590 ** 4 4 signed integer
73591 ** 5 6 signed integer
73592 ** 6 8 signed integer
73593 ** 7 8 IEEE float
73594 ** 8 0 Integer constant 0
73595 ** 9 0 Integer constant 1
73596 ** 10,11 reserved for expansion
73597 ** N>=12 and even (N-12)/2 BLOB
73598 ** N>=13 and odd (N-13)/2 text
73599 **
73600 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
73601 ** of SQLite will not understand those serial types.
73602 */
73603 
73604 /*
73605 ** Return the serial-type for the value stored in pMem.
73606 */
73607 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
73608  int flags = pMem->flags;
73609  u32 n;
73610 
73611  assert( pLen!=0 );
73612  if( flags&MEM_Null ){
73613  *pLen = 0;
73614  return 0;
73615  }
73616  if( flags&MEM_Int ){
73617  /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
73618 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
73619  i64 i = pMem->u.i;
73620  u64 u;
73621  if( i<0 ){
73622  u = ~i;
73623  }else{
73624  u = i;
73625  }
73626  if( u<=127 ){
73627  if( (i&1)==i && file_format>=4 ){
73628  *pLen = 0;
73629  return 8+(u32)u;
73630  }else{
73631  *pLen = 1;
73632  return 1;
73633  }
73634  }
73635  if( u<=32767 ){ *pLen = 2; return 2; }
73636  if( u<=8388607 ){ *pLen = 3; return 3; }
73637  if( u<=2147483647 ){ *pLen = 4; return 4; }
73638  if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
73639  *pLen = 8;
73640  return 6;
73641  }
73642  if( flags&MEM_Real ){
73643  *pLen = 8;
73644  return 7;
73645  }
73646  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
73647  assert( pMem->n>=0 );
73648  n = (u32)pMem->n;
73649  if( flags & MEM_Zero ){
73650  n += pMem->u.nZero;
73651  }
73652  *pLen = n;
73653  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
73654 }
73655 
73656 /*
73657 ** The sizes for serial types less than 128
73658 */
73659 static const u8 sqlite3SmallTypeSizes[] = {
73660  /* 0 1 2 3 4 5 6 7 8 9 */
73661 /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
73662 /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
73663 /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
73664 /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
73665 /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
73666 /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
73667 /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
73668 /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
73669 /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
73670 /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
73671 /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
73672 /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
73673 /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
73674 };
73675 
73676 /*
73677 ** Return the length of the data corresponding to the supplied serial-type.
73678 */
73680  if( serial_type>=128 ){
73681  return (serial_type-12)/2;
73682  }else{
73683  assert( serial_type<12
73684  || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
73685  return sqlite3SmallTypeSizes[serial_type];
73686  }
73687 }
73689  assert( serial_type<128 );
73690  return sqlite3SmallTypeSizes[serial_type];
73691 }
73692 
73693 /*
73694 ** If we are on an architecture with mixed-endian floating
73695 ** points (ex: ARM7) then swap the lower 4 bytes with the
73696 ** upper 4 bytes. Return the result.
73697 **
73698 ** For most architectures, this is a no-op.
73699 **
73700 ** (later): It is reported to me that the mixed-endian problem
73701 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
73702 ** that early versions of GCC stored the two words of a 64-bit
73703 ** float in the wrong order. And that error has been propagated
73704 ** ever since. The blame is not necessarily with GCC, though.
73705 ** GCC might have just copying the problem from a prior compiler.
73706 ** I am also told that newer versions of GCC that follow a different
73707 ** ABI get the byte order right.
73708 **
73709 ** Developers using SQLite on an ARM7 should compile and run their
73710 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
73711 ** enabled, some asserts below will ensure that the byte order of
73712 ** floating point values is correct.
73713 **
73714 ** (2007-08-30) Frank van Vugt has studied this problem closely
73715 ** and has send his findings to the SQLite developers. Frank
73716 ** writes that some Linux kernels offer floating point hardware
73717 ** emulation that uses only 32-bit mantissas instead of a full
73718 ** 48-bits as required by the IEEE standard. (This is the
73719 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
73720 ** byte swapping becomes very complicated. To avoid problems,
73721 ** the necessary byte swapping is carried out using a 64-bit integer
73722 ** rather than a 64-bit float. Frank assures us that the code here
73723 ** works for him. We, the developers, have no way to independently
73724 ** verify this, but Frank seems to know what he is talking about
73725 ** so we trust him.
73726 */
73727 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
73728 static u64 floatSwap(u64 in){
73729  union {
73730  u64 r;
73731  u32 i[2];
73732  } u;
73733  u32 t;
73734 
73735  u.r = in;
73736  t = u.i[0];
73737  u.i[0] = u.i[1];
73738  u.i[1] = t;
73739  return u.r;
73740 }
73741 # define swapMixedEndianFloat(X) X = floatSwap(X)
73742 #else
73743 # define swapMixedEndianFloat(X)
73744 #endif
73745 
73746 /*
73747 ** Write the serialized data blob for the value stored in pMem into
73748 ** buf. It is assumed that the caller has allocated sufficient space.
73749 ** Return the number of bytes written.
73750 **
73751 ** nBuf is the amount of space left in buf[]. The caller is responsible
73752 ** for allocating enough space to buf[] to hold the entire field, exclusive
73753 ** of the pMem->u.nZero bytes for a MEM_Zero value.
73754 **
73755 ** Return the number of bytes actually written into buf[]. The number
73756 ** of bytes in the zero-filled tail is included in the return value only
73757 ** if those bytes were zeroed in buf[].
73758 */
73759 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
73760  u32 len;
73761 
73762  /* Integer and Real */
73763  if( serial_type<=7 && serial_type>0 ){
73764  u64 v;
73765  u32 i;
73766  if( serial_type==7 ){
73767  assert( sizeof(v)==sizeof(pMem->u.r) );
73768  memcpy(&v, &pMem->u.r, sizeof(v));
73770  }else{
73771  v = pMem->u.i;
73772  }
73773  len = i = sqlite3SmallTypeSizes[serial_type];
73774  assert( i>0 );
73775  do{
73776  buf[--i] = (u8)(v&0xFF);
73777  v >>= 8;
73778  }while( i );
73779  return len;
73780  }
73781 
73782  /* String or blob */
73783  if( serial_type>=12 ){
73784  assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
73785  == (int)sqlite3VdbeSerialTypeLen(serial_type) );
73786  len = pMem->n;
73787  if( len>0 ) memcpy(buf, pMem->z, len);
73788  return len;
73789  }
73790 
73791  /* NULL or constants 0 or 1 */
73792  return 0;
73793 }
73794 
73795 /* Input "x" is a sequence of unsigned characters that represent a
73796 ** big-endian integer. Return the equivalent native integer
73797 */
73798 #define ONE_BYTE_INT(x) ((i8)(x)[0])
73799 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
73800 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
73801 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73802 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73803 
73804 /*
73805 ** Deserialize the data blob pointed to by buf as serial type serial_type
73806 ** and store the result in pMem. Return the number of bytes read.
73807 **
73808 ** This function is implemented as two separate routines for performance.
73809 ** The few cases that require local variables are broken out into a separate
73810 ** routine so that in most cases the overhead of moving the stack pointer
73811 ** is avoided.
73812 */
73814  const unsigned char *buf, /* Buffer to deserialize from */
73815  u32 serial_type, /* Serial type to deserialize */
73816  Mem *pMem /* Memory cell to write value into */
73817 ){
73818  u64 x = FOUR_BYTE_UINT(buf);
73819  u32 y = FOUR_BYTE_UINT(buf+4);
73820  x = (x<<32) + y;
73821  if( serial_type==6 ){
73822  /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
73823  ** twos-complement integer. */
73824  pMem->u.i = *(i64*)&x;
73825  pMem->flags = MEM_Int;
73826  testcase( pMem->u.i<0 );
73827  }else{
73828  /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
73829  ** floating point number. */
73830 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
73831  /* Verify that integers and floating point values use the same
73832  ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
73833  ** defined that 64-bit floating point values really are mixed
73834  ** endian.
73835  */
73836  static const u64 t1 = ((u64)0x3ff00000)<<32;
73837  static const double r1 = 1.0;
73838  u64 t2 = t1;
73840  assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
73841 #endif
73842  assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
73844  memcpy(&pMem->u.r, &x, sizeof(x));
73845  pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
73846  }
73847  return 8;
73848 }
73850  const unsigned char *buf, /* Buffer to deserialize from */
73851  u32 serial_type, /* Serial type to deserialize */
73852  Mem *pMem /* Memory cell to write value into */
73853 ){
73854  switch( serial_type ){
73855  case 10: /* Reserved for future use */
73856  case 11: /* Reserved for future use */
73857  case 0: { /* Null */
73858  /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
73859  pMem->flags = MEM_Null;
73860  break;
73861  }
73862  case 1: {
73863  /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
73864  ** integer. */
73865  pMem->u.i = ONE_BYTE_INT(buf);
73866  pMem->flags = MEM_Int;
73867  testcase( pMem->u.i<0 );
73868  return 1;
73869  }
73870  case 2: { /* 2-byte signed integer */
73871  /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
73872  ** twos-complement integer. */
73873  pMem->u.i = TWO_BYTE_INT(buf);
73874  pMem->flags = MEM_Int;
73875  testcase( pMem->u.i<0 );
73876  return 2;
73877  }
73878  case 3: { /* 3-byte signed integer */
73879  /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
73880  ** twos-complement integer. */
73881  pMem->u.i = THREE_BYTE_INT(buf);
73882  pMem->flags = MEM_Int;
73883  testcase( pMem->u.i<0 );
73884  return 3;
73885  }
73886  case 4: { /* 4-byte signed integer */
73887  /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
73888  ** twos-complement integer. */
73889  pMem->u.i = FOUR_BYTE_INT(buf);
73890 #ifdef __HP_cc
73891  /* Work around a sign-extension bug in the HP compiler for HP/UX */
73892  if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
73893 #endif
73894  pMem->flags = MEM_Int;
73895  testcase( pMem->u.i<0 );
73896  return 4;
73897  }
73898  case 5: { /* 6-byte signed integer */
73899  /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
73900  ** twos-complement integer. */
73901  pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
73902  pMem->flags = MEM_Int;
73903  testcase( pMem->u.i<0 );
73904  return 6;
73905  }
73906  case 6: /* 8-byte signed integer */
73907  case 7: { /* IEEE floating point */
73908  /* These use local variables, so do them in a separate routine
73909  ** to avoid having to move the frame pointer in the common case */
73910  return serialGet(buf,serial_type,pMem);
73911  }
73912  case 8: /* Integer 0 */
73913  case 9: { /* Integer 1 */
73914  /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
73915  /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
73916  pMem->u.i = serial_type-8;
73917  pMem->flags = MEM_Int;
73918  return 0;
73919  }
73920  default: {
73921  /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
73922  ** length.
73923  ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
73924  ** (N-13)/2 bytes in length. */
73925  static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
73926  pMem->z = (char *)buf;
73927  pMem->n = (serial_type-12)/2;
73928  pMem->flags = aFlag[serial_type&1];
73929  return pMem->n;
73930  }
73931  }
73932  return 0;
73933 }
73934 /*
73935 ** This routine is used to allocate sufficient space for an UnpackedRecord
73936 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
73937 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
73938 **
73939 ** The space is either allocated using sqlite3DbMallocRaw() or from within
73940 ** the unaligned buffer passed via the second and third arguments (presumably
73941 ** stack space). If the former, then *ppFree is set to a pointer that should
73942 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
73943 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
73944 ** before returning.
73945 **
73946 ** If an OOM error occurs, NULL is returned.
73947 */
73949  KeyInfo *pKeyInfo, /* Description of the record */
73950  char *pSpace, /* Unaligned space available */
73951  int szSpace, /* Size of pSpace[] in bytes */
73952  char **ppFree /* OUT: Caller should free this pointer */
73953 ){
73954  UnpackedRecord *p; /* Unpacked record to return */
73955  int nOff; /* Increment pSpace by nOff to align it */
73956  int nByte; /* Number of bytes required for *p */
73957 
73958  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
73959  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
73960  ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
73961  */
73962  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
73963  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
73964  if( nByte>szSpace+nOff ){
73965  p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
73966  *ppFree = (char *)p;
73967  if( !p ) return 0;
73968  }else{
73969  p = (UnpackedRecord*)&pSpace[nOff];
73970  *ppFree = 0;
73971  }
73972 
73973  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
73974  assert( pKeyInfo->aSortOrder!=0 );
73975  p->pKeyInfo = pKeyInfo;
73976  p->nField = pKeyInfo->nField + 1;
73977  return p;
73978 }
73979 
73980 /*
73981 ** Given the nKey-byte encoding of a record in pKey[], populate the
73982 ** UnpackedRecord structure indicated by the fourth argument with the
73983 ** contents of the decoded record.
73984 */
73986  KeyInfo *pKeyInfo, /* Information about the record format */
73987  int nKey, /* Size of the binary record */
73988  const void *pKey, /* The binary record */
73989  UnpackedRecord *p /* Populate this structure before returning. */
73990 ){
73991  const unsigned char *aKey = (const unsigned char *)pKey;
73992  int d;
73993  u32 idx; /* Offset in aKey[] to read from */
73994  u16 u; /* Unsigned loop counter */
73995  u32 szHdr;
73996  Mem *pMem = p->aMem;
73997 
73998  p->default_rc = 0;
73999  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
74000  idx = getVarint32(aKey, szHdr);
74001  d = szHdr;
74002  u = 0;
74003  while( idx<szHdr && d<=nKey ){
74004  u32 serial_type;
74005 
74006  idx += getVarint32(&aKey[idx], serial_type);
74007  pMem->enc = pKeyInfo->enc;
74008  pMem->db = pKeyInfo->db;
74009  /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
74010  pMem->szMalloc = 0;
74011  pMem->z = 0;
74012  d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
74013  pMem++;
74014  if( (++u)>=p->nField ) break;
74015  }
74016  assert( u<=pKeyInfo->nField + 1 );
74017  p->nField = u;
74018 }
74019 
74020 #if SQLITE_DEBUG
74021 /*
74022 ** This function compares two index or table record keys in the same way
74023 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
74024 ** this function deserializes and compares values using the
74025 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
74026 ** in assert() statements to ensure that the optimized code in
74027 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
74028 **
74029 ** Return true if the result of comparison is equivalent to desiredResult.
74030 ** Return false if there is a disagreement.
74031 */
74032 static int vdbeRecordCompareDebug(
74033  int nKey1, const void *pKey1, /* Left key */
74034  const UnpackedRecord *pPKey2, /* Right key */
74035  int desiredResult /* Correct answer */
74036 ){
74037  u32 d1; /* Offset into aKey[] of next data element */
74038  u32 idx1; /* Offset into aKey[] of next header element */
74039  u32 szHdr1; /* Number of bytes in header */
74040  int i = 0;
74041  int rc = 0;
74042  const unsigned char *aKey1 = (const unsigned char *)pKey1;
74043  KeyInfo *pKeyInfo;
74044  Mem mem1;
74045 
74046  pKeyInfo = pPKey2->pKeyInfo;
74047  if( pKeyInfo->db==0 ) return 1;
74048  mem1.enc = pKeyInfo->enc;
74049  mem1.db = pKeyInfo->db;
74050  /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
74051  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74052 
74053  /* Compilers may complain that mem1.u.i is potentially uninitialized.
74054  ** We could initialize it, as shown here, to silence those complaints.
74055  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
74056  ** the unnecessary initialization has a measurable negative performance
74057  ** impact, since this routine is a very high runner. And so, we choose
74058  ** to ignore the compiler warnings and leave this variable uninitialized.
74059  */
74060  /* mem1.u.i = 0; // not needed, here to silence compiler warning */
74061 
74062  idx1 = getVarint32(aKey1, szHdr1);
74063  if( szHdr1>98307 ) return SQLITE_CORRUPT;
74064  d1 = szHdr1;
74065  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
74066  assert( pKeyInfo->aSortOrder!=0 );
74067  assert( pKeyInfo->nField>0 );
74068  assert( idx1<=szHdr1 || CORRUPT_DB );
74069  do{
74070  u32 serial_type1;
74071 
74072  /* Read the serial types for the next element in each key. */
74073  idx1 += getVarint32( aKey1+idx1, serial_type1 );
74074 
74075  /* Verify that there is enough key space remaining to avoid
74076  ** a buffer overread. The "d1+serial_type1+2" subexpression will
74077  ** always be greater than or equal to the amount of required key space.
74078  ** Use that approximation to avoid the more expensive call to
74079  ** sqlite3VdbeSerialTypeLen() in the common case.
74080  */
74081  if( d1+serial_type1+2>(u32)nKey1
74082  && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
74083  ){
74084  break;
74085  }
74086 
74087  /* Extract the values to be compared.
74088  */
74089  d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
74090 
74091  /* Do the comparison
74092  */
74093  rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
74094  if( rc!=0 ){
74095  assert( mem1.szMalloc==0 ); /* See comment below */
74096  if( pKeyInfo->aSortOrder[i] ){
74097  rc = -rc; /* Invert the result for DESC sort order. */
74098  }
74099  goto debugCompareEnd;
74100  }
74101  i++;
74102  }while( idx1<szHdr1 && i<pPKey2->nField );
74103 
74104  /* No memory allocation is ever used on mem1. Prove this using
74105  ** the following assert(). If the assert() fails, it indicates a
74106  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
74107  */
74108  assert( mem1.szMalloc==0 );
74109 
74110  /* rc==0 here means that one of the keys ran out of fields and
74111  ** all the fields up to that point were equal. Return the default_rc
74112  ** value. */
74113  rc = pPKey2->default_rc;
74114 
74115 debugCompareEnd:
74116  if( desiredResult==0 && rc==0 ) return 1;
74117  if( desiredResult<0 && rc<0 ) return 1;
74118  if( desiredResult>0 && rc>0 ) return 1;
74119  if( CORRUPT_DB ) return 1;
74120  if( pKeyInfo->db->mallocFailed ) return 1;
74121  return 0;
74122 }
74123 #endif
74124 
74125 #if SQLITE_DEBUG
74126 /*
74127 ** Count the number of fields (a.k.a. columns) in the record given by
74128 ** pKey,nKey. The verify that this count is less than or equal to the
74129 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
74130 **
74131 ** If this constraint is not satisfied, it means that the high-speed
74132 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
74133 ** not work correctly. If this assert() ever fires, it probably means
74134 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
74135 ** incorrectly.
74136 */
74138  int nKey, const void *pKey, /* The record to verify */
74139  const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
74140 ){
74141  int nField = 0;
74142  u32 szHdr;
74143  u32 idx;
74144  u32 notUsed;
74145  const unsigned char *aKey = (const unsigned char*)pKey;
74146 
74147  if( CORRUPT_DB ) return;
74148  idx = getVarint32(aKey, szHdr);
74149  assert( nKey>=0 );
74150  assert( szHdr<=(u32)nKey );
74151  while( idx<szHdr ){
74152  idx += getVarint32(aKey+idx, notUsed);
74153  nField++;
74154  }
74155  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
74156 }
74157 #else
74158 # define vdbeAssertFieldCountWithinLimits(A,B,C)
74159 #endif
74160 
74161 /*
74162 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
74163 ** using the collation sequence pColl. As usual, return a negative , zero
74164 ** or positive value if *pMem1 is less than, equal to or greater than
74165 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
74166 */
74168  const Mem *pMem1,
74169  const Mem *pMem2,
74170  const CollSeq *pColl,
74171  u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
74172 ){
74173  if( pMem1->enc==pColl->enc ){
74174  /* The strings are already in the correct encoding. Call the
74175  ** comparison function directly */
74176  return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
74177  }else{
74178  int rc;
74179  const void *v1, *v2;
74180  int n1, n2;
74181  Mem c1;
74182  Mem c2;
74183  sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
74184  sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
74185  sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
74186  sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
74187  v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
74188  n1 = v1==0 ? 0 : c1.n;
74189  v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
74190  n2 = v2==0 ? 0 : c2.n;
74191  rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
74192  if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
74193  sqlite3VdbeMemRelease(&c1);
74194  sqlite3VdbeMemRelease(&c2);
74195  return rc;
74196  }
74197 }
74198 
74199 /*
74200 ** The input pBlob is guaranteed to be a Blob that is not marked
74201 ** with MEM_Zero. Return true if it could be a zero-blob.
74202 */
74203 static int isAllZero(const char *z, int n){
74204  int i;
74205  for(i=0; i<n; i++){
74206  if( z[i] ) return 0;
74207  }
74208  return 1;
74209 }
74210 
74211 /*
74212 ** Compare two blobs. Return negative, zero, or positive if the first
74213 ** is less than, equal to, or greater than the second, respectively.
74214 ** If one blob is a prefix of the other, then the shorter is the lessor.
74215 */
74216 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
74217  int c;
74218  int n1 = pB1->n;
74219  int n2 = pB2->n;
74220 
74221  /* It is possible to have a Blob value that has some non-zero content
74222  ** followed by zero content. But that only comes up for Blobs formed
74223  ** by the OP_MakeRecord opcode, and such Blobs never get passed into
74224  ** sqlite3MemCompare(). */
74225  assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
74226  assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
74227 
74228  if( (pB1->flags|pB2->flags) & MEM_Zero ){
74229  if( pB1->flags & pB2->flags & MEM_Zero ){
74230  return pB1->u.nZero - pB2->u.nZero;
74231  }else if( pB1->flags & MEM_Zero ){
74232  if( !isAllZero(pB2->z, pB2->n) ) return -1;
74233  return pB1->u.nZero - n2;
74234  }else{
74235  if( !isAllZero(pB1->z, pB1->n) ) return +1;
74236  return n1 - pB2->u.nZero;
74237  }
74238  }
74239  c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
74240  if( c ) return c;
74241  return n1 - n2;
74242 }
74243 
74244 /*
74245 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
74246 ** number. Return negative, zero, or positive if the first (i64) is less than,
74247 ** equal to, or greater than the second (double).
74248 */
74249 static int sqlite3IntFloatCompare(i64 i, double r){
74250  if( sizeof(LONGDOUBLE_TYPE)>8 ){
74252  if( x<r ) return -1;
74253  if( x>r ) return +1;
74254  return 0;
74255  }else{
74256  i64 y;
74257  double s;
74258  if( r<-9223372036854775808.0 ) return +1;
74259  if( r>9223372036854775807.0 ) return -1;
74260  y = (i64)r;
74261  if( i<y ) return -1;
74262  if( i>y ){
74263  if( y==SMALLEST_INT64 && r>0.0 ) return -1;
74264  return +1;
74265  }
74266  s = (double)i;
74267  if( s<r ) return -1;
74268  if( s>r ) return +1;
74269  return 0;
74270  }
74271 }
74272 
74273 /*
74274 ** Compare the values contained by the two memory cells, returning
74275 ** negative, zero or positive if pMem1 is less than, equal to, or greater
74276 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
74277 ** and reals) sorted numerically, followed by text ordered by the collating
74278 ** sequence pColl and finally blob's ordered by memcmp().
74279 **
74280 ** Two NULL values are considered equal by this function.
74281 */
74282 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
74283  int f1, f2;
74284  int combined_flags;
74285 
74286  f1 = pMem1->flags;
74287  f2 = pMem2->flags;
74288  combined_flags = f1|f2;
74289  assert( (combined_flags & MEM_RowSet)==0 );
74290 
74291  /* If one value is NULL, it is less than the other. If both values
74292  ** are NULL, return 0.
74293  */
74294  if( combined_flags&MEM_Null ){
74295  return (f2&MEM_Null) - (f1&MEM_Null);
74296  }
74297 
74298  /* At least one of the two values is a number
74299  */
74300  if( combined_flags&(MEM_Int|MEM_Real) ){
74301  if( (f1 & f2 & MEM_Int)!=0 ){
74302  if( pMem1->u.i < pMem2->u.i ) return -1;
74303  if( pMem1->u.i > pMem2->u.i ) return +1;
74304  return 0;
74305  }
74306  if( (f1 & f2 & MEM_Real)!=0 ){
74307  if( pMem1->u.r < pMem2->u.r ) return -1;
74308  if( pMem1->u.r > pMem2->u.r ) return +1;
74309  return 0;
74310  }
74311  if( (f1&MEM_Int)!=0 ){
74312  if( (f2&MEM_Real)!=0 ){
74313  return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
74314  }else{
74315  return -1;
74316  }
74317  }
74318  if( (f1&MEM_Real)!=0 ){
74319  if( (f2&MEM_Int)!=0 ){
74320  return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
74321  }else{
74322  return -1;
74323  }
74324  }
74325  return +1;
74326  }
74327 
74328  /* If one value is a string and the other is a blob, the string is less.
74329  ** If both are strings, compare using the collating functions.
74330  */
74331  if( combined_flags&MEM_Str ){
74332  if( (f1 & MEM_Str)==0 ){
74333  return 1;
74334  }
74335  if( (f2 & MEM_Str)==0 ){
74336  return -1;
74337  }
74338 
74339  assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
74340  assert( pMem1->enc==SQLITE_UTF8 ||
74341  pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
74342 
74343  /* The collation sequence must be defined at this point, even if
74344  ** the user deletes the collation sequence after the vdbe program is
74345  ** compiled (this was not always the case).
74346  */
74347  assert( !pColl || pColl->xCmp );
74348 
74349  if( pColl ){
74350  return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
74351  }
74352  /* If a NULL pointer was passed as the collate function, fall through
74353  ** to the blob case and use memcmp(). */
74354  }
74355 
74356  /* Both values must be blobs. Compare using memcmp(). */
74357  return sqlite3BlobCompare(pMem1, pMem2);
74358 }
74359 
74360 
74361 /*
74362 ** The first argument passed to this function is a serial-type that
74363 ** corresponds to an integer - all values between 1 and 9 inclusive
74364 ** except 7. The second points to a buffer containing an integer value
74365 ** serialized according to serial_type. This function deserializes
74366 ** and returns the value.
74367 */
74368 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
74369  u32 y;
74370  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
74371  switch( serial_type ){
74372  case 0:
74373  case 1:
74374  testcase( aKey[0]&0x80 );
74375  return ONE_BYTE_INT(aKey);
74376  case 2:
74377  testcase( aKey[0]&0x80 );
74378  return TWO_BYTE_INT(aKey);
74379  case 3:
74380  testcase( aKey[0]&0x80 );
74381  return THREE_BYTE_INT(aKey);
74382  case 4: {
74383  testcase( aKey[0]&0x80 );
74384  y = FOUR_BYTE_UINT(aKey);
74385  return (i64)*(int*)&y;
74386  }
74387  case 5: {
74388  testcase( aKey[0]&0x80 );
74389  return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74390  }
74391  case 6: {
74392  u64 x = FOUR_BYTE_UINT(aKey);
74393  testcase( aKey[0]&0x80 );
74394  x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74395  return (i64)*(i64*)&x;
74396  }
74397  }
74398 
74399  return (serial_type - 8);
74400 }
74401 
74402 /*
74403 ** This function compares the two table rows or index records
74404 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
74405 ** or positive integer if key1 is less than, equal to or
74406 ** greater than key2. The {nKey1, pKey1} key must be a blob
74407 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
74408 ** key must be a parsed key such as obtained from
74409 ** sqlite3VdbeParseRecord.
74410 **
74411 ** If argument bSkip is non-zero, it is assumed that the caller has already
74412 ** determined that the first fields of the keys are equal.
74413 **
74414 ** Key1 and Key2 do not have to contain the same number of fields. If all
74415 ** fields that appear in both keys are equal, then pPKey2->default_rc is
74416 ** returned.
74417 **
74418 ** If database corruption is discovered, set pPKey2->errCode to
74419 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
74420 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
74421 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
74422 */
74424  int nKey1, const void *pKey1, /* Left key */
74425  UnpackedRecord *pPKey2, /* Right key */
74426  int bSkip /* If true, skip the first field */
74427 ){
74428  u32 d1; /* Offset into aKey[] of next data element */
74429  int i; /* Index of next field to compare */
74430  u32 szHdr1; /* Size of record header in bytes */
74431  u32 idx1; /* Offset of first type in header */
74432  int rc = 0; /* Return value */
74433  Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
74434  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
74435  const unsigned char *aKey1 = (const unsigned char *)pKey1;
74436  Mem mem1;
74437 
74438  /* If bSkip is true, then the caller has already determined that the first
74439  ** two elements in the keys are equal. Fix the various stack variables so
74440  ** that this routine begins comparing at the second field. */
74441  if( bSkip ){
74442  u32 s1;
74443  idx1 = 1 + getVarint32(&aKey1[1], s1);
74444  szHdr1 = aKey1[0];
74445  d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
74446  i = 1;
74447  pRhs++;
74448  }else{
74449  idx1 = getVarint32(aKey1, szHdr1);
74450  d1 = szHdr1;
74451  if( d1>(unsigned)nKey1 ){
74452  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74453  return 0; /* Corruption */
74454  }
74455  i = 0;
74456  }
74457 
74458  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74459  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
74460  || CORRUPT_DB );
74461  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
74462  assert( pPKey2->pKeyInfo->nField>0 );
74463  assert( idx1<=szHdr1 || CORRUPT_DB );
74464  do{
74465  u32 serial_type;
74466 
74467  /* RHS is an integer */
74468  if( pRhs->flags & MEM_Int ){
74469  serial_type = aKey1[idx1];
74470  testcase( serial_type==12 );
74471  if( serial_type>=10 ){
74472  rc = +1;
74473  }else if( serial_type==0 ){
74474  rc = -1;
74475  }else if( serial_type==7 ){
74476  sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74477  rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
74478  }else{
74479  i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
74480  i64 rhs = pRhs->u.i;
74481  if( lhs<rhs ){
74482  rc = -1;
74483  }else if( lhs>rhs ){
74484  rc = +1;
74485  }
74486  }
74487  }
74488 
74489  /* RHS is real */
74490  else if( pRhs->flags & MEM_Real ){
74491  serial_type = aKey1[idx1];
74492  if( serial_type>=10 ){
74493  /* Serial types 12 or greater are strings and blobs (greater than
74494  ** numbers). Types 10 and 11 are currently "reserved for future
74495  ** use", so it doesn't really matter what the results of comparing
74496  ** them to numberic values are. */
74497  rc = +1;
74498  }else if( serial_type==0 ){
74499  rc = -1;
74500  }else{
74501  sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74502  if( serial_type==7 ){
74503  if( mem1.u.r<pRhs->u.r ){
74504  rc = -1;
74505  }else if( mem1.u.r>pRhs->u.r ){
74506  rc = +1;
74507  }
74508  }else{
74509  rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
74510  }
74511  }
74512  }
74513 
74514  /* RHS is a string */
74515  else if( pRhs->flags & MEM_Str ){
74516  getVarint32(&aKey1[idx1], serial_type);
74517  testcase( serial_type==12 );
74518  if( serial_type<12 ){
74519  rc = -1;
74520  }else if( !(serial_type & 0x01) ){
74521  rc = +1;
74522  }else{
74523  mem1.n = (serial_type - 12) / 2;
74524  testcase( (d1+mem1.n)==(unsigned)nKey1 );
74525  testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
74526  if( (d1+mem1.n) > (unsigned)nKey1 ){
74527  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74528  return 0; /* Corruption */
74529  }else if( pKeyInfo->aColl[i] ){
74530  mem1.enc = pKeyInfo->enc;
74531  mem1.db = pKeyInfo->db;
74532  mem1.flags = MEM_Str;
74533  mem1.z = (char*)&aKey1[d1];
74534  rc = vdbeCompareMemString(
74535  &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
74536  );
74537  }else{
74538  int nCmp = MIN(mem1.n, pRhs->n);
74539  rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74540  if( rc==0 ) rc = mem1.n - pRhs->n;
74541  }
74542  }
74543  }
74544 
74545  /* RHS is a blob */
74546  else if( pRhs->flags & MEM_Blob ){
74547  assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
74548  getVarint32(&aKey1[idx1], serial_type);
74549  testcase( serial_type==12 );
74550  if( serial_type<12 || (serial_type & 0x01) ){
74551  rc = -1;
74552  }else{
74553  int nStr = (serial_type - 12) / 2;
74554  testcase( (d1+nStr)==(unsigned)nKey1 );
74555  testcase( (d1+nStr+1)==(unsigned)nKey1 );
74556  if( (d1+nStr) > (unsigned)nKey1 ){
74557  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74558  return 0; /* Corruption */
74559  }else if( pRhs->flags & MEM_Zero ){
74560  if( !isAllZero((const char*)&aKey1[d1],nStr) ){
74561  rc = 1;
74562  }else{
74563  rc = nStr - pRhs->u.nZero;
74564  }
74565  }else{
74566  int nCmp = MIN(nStr, pRhs->n);
74567  rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74568  if( rc==0 ) rc = nStr - pRhs->n;
74569  }
74570  }
74571  }
74572 
74573  /* RHS is null */
74574  else{
74575  serial_type = aKey1[idx1];
74576  rc = (serial_type!=0);
74577  }
74578 
74579  if( rc!=0 ){
74580  if( pKeyInfo->aSortOrder[i] ){
74581  rc = -rc;
74582  }
74583  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
74584  assert( mem1.szMalloc==0 ); /* See comment below */
74585  return rc;
74586  }
74587 
74588  i++;
74589  pRhs++;
74590  d1 += sqlite3VdbeSerialTypeLen(serial_type);
74591  idx1 += sqlite3VarintLen(serial_type);
74592  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
74593 
74594  /* No memory allocation is ever used on mem1. Prove this using
74595  ** the following assert(). If the assert() fails, it indicates a
74596  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
74597  assert( mem1.szMalloc==0 );
74598 
74599  /* rc==0 here means that one or both of the keys ran out of fields and
74600  ** all the fields up to that point were equal. Return the default_rc
74601  ** value. */
74602  assert( CORRUPT_DB
74603  || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
74604  || pKeyInfo->db->mallocFailed
74605  );
74606  pPKey2->eqSeen = 1;
74607  return pPKey2->default_rc;
74608 }
74610  int nKey1, const void *pKey1, /* Left key */
74611  UnpackedRecord *pPKey2 /* Right key */
74612 ){
74613  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
74614 }
74615 
74616 
74617 /*
74618 ** This function is an optimized version of sqlite3VdbeRecordCompare()
74619 ** that (a) the first field of pPKey2 is an integer, and (b) the
74620 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
74621 ** byte (i.e. is less than 128).
74622 **
74623 ** To avoid concerns about buffer overreads, this routine is only used
74624 ** on schemas where the maximum valid header size is 63 bytes or less.
74625 */
74627  int nKey1, const void *pKey1, /* Left key */
74628  UnpackedRecord *pPKey2 /* Right key */
74629 ){
74630  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
74631  int serial_type = ((const u8*)pKey1)[1];
74632  int res;
74633  u32 y;
74634  u64 x;
74635  i64 v;
74636  i64 lhs;
74637 
74638  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74639  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
74640  switch( serial_type ){
74641  case 1: { /* 1-byte signed integer */
74642  lhs = ONE_BYTE_INT(aKey);
74643  testcase( lhs<0 );
74644  break;
74645  }
74646  case 2: { /* 2-byte signed integer */
74647  lhs = TWO_BYTE_INT(aKey);
74648  testcase( lhs<0 );
74649  break;
74650  }
74651  case 3: { /* 3-byte signed integer */
74652  lhs = THREE_BYTE_INT(aKey);
74653  testcase( lhs<0 );
74654  break;
74655  }
74656  case 4: { /* 4-byte signed integer */
74657  y = FOUR_BYTE_UINT(aKey);
74658  lhs = (i64)*(int*)&y;
74659  testcase( lhs<0 );
74660  break;
74661  }
74662  case 5: { /* 6-byte signed integer */
74663  lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74664  testcase( lhs<0 );
74665  break;
74666  }
74667  case 6: { /* 8-byte signed integer */
74668  x = FOUR_BYTE_UINT(aKey);
74669  x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74670  lhs = *(i64*)&x;
74671  testcase( lhs<0 );
74672  break;
74673  }
74674  case 8:
74675  lhs = 0;
74676  break;
74677  case 9:
74678  lhs = 1;
74679  break;
74680 
74681  /* This case could be removed without changing the results of running
74682  ** this code. Including it causes gcc to generate a faster switch
74683  ** statement (since the range of switch targets now starts at zero and
74684  ** is contiguous) but does not cause any duplicate code to be generated
74685  ** (as gcc is clever enough to combine the two like cases). Other
74686  ** compilers might be similar. */
74687  case 0: case 7:
74688  return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74689 
74690  default:
74691  return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74692  }
74693 
74694  v = pPKey2->aMem[0].u.i;
74695  if( v>lhs ){
74696  res = pPKey2->r1;
74697  }else if( v<lhs ){
74698  res = pPKey2->r2;
74699  }else if( pPKey2->nField>1 ){
74700  /* The first fields of the two keys are equal. Compare the trailing
74701  ** fields. */
74702  res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74703  }else{
74704  /* The first fields of the two keys are equal and there are no trailing
74705  ** fields. Return pPKey2->default_rc in this case. */
74706  res = pPKey2->default_rc;
74707  pPKey2->eqSeen = 1;
74708  }
74709 
74710  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
74711  return res;
74712 }
74713 
74714 /*
74715 ** This function is an optimized version of sqlite3VdbeRecordCompare()
74716 ** that (a) the first field of pPKey2 is a string, that (b) the first field
74717 ** uses the collation sequence BINARY and (c) that the size-of-header varint
74718 ** at the start of (pKey1/nKey1) fits in a single byte.
74719 */
74721  int nKey1, const void *pKey1, /* Left key */
74722  UnpackedRecord *pPKey2 /* Right key */
74723 ){
74724  const u8 *aKey1 = (const u8*)pKey1;
74725  int serial_type;
74726  int res;
74727 
74728  assert( pPKey2->aMem[0].flags & MEM_Str );
74729  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74730  getVarint32(&aKey1[1], serial_type);
74731  if( serial_type<12 ){
74732  res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
74733  }else if( !(serial_type & 0x01) ){
74734  res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
74735  }else{
74736  int nCmp;
74737  int nStr;
74738  int szHdr = aKey1[0];
74739 
74740  nStr = (serial_type-12) / 2;
74741  if( (szHdr + nStr) > nKey1 ){
74742  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74743  return 0; /* Corruption */
74744  }
74745  nCmp = MIN( pPKey2->aMem[0].n, nStr );
74746  res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
74747 
74748  if( res==0 ){
74749  res = nStr - pPKey2->aMem[0].n;
74750  if( res==0 ){
74751  if( pPKey2->nField>1 ){
74752  res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74753  }else{
74754  res = pPKey2->default_rc;
74755  pPKey2->eqSeen = 1;
74756  }
74757  }else if( res>0 ){
74758  res = pPKey2->r2;
74759  }else{
74760  res = pPKey2->r1;
74761  }
74762  }else if( res>0 ){
74763  res = pPKey2->r2;
74764  }else{
74765  res = pPKey2->r1;
74766  }
74767  }
74768 
74769  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
74770  || CORRUPT_DB
74771  || pPKey2->pKeyInfo->db->mallocFailed
74772  );
74773  return res;
74774 }
74775 
74776 /*
74777 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
74778 ** suitable for comparing serialized records to the unpacked record passed
74779 ** as the only argument.
74780 */
74782  /* varintRecordCompareInt() and varintRecordCompareString() both assume
74783  ** that the size-of-header varint that occurs at the start of each record
74784  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
74785  ** also assumes that it is safe to overread a buffer by at least the
74786  ** maximum possible legal header size plus 8 bytes. Because there is
74787  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
74788  ** buffer passed to varintRecordCompareInt() this makes it convenient to
74789  ** limit the size of the header to 64 bytes in cases where the first field
74790  ** is an integer.
74791  **
74792  ** The easiest way to enforce this limit is to consider only records with
74793  ** 13 fields or less. If the first field is an integer, the maximum legal
74794  ** header size is (12*5 + 1 + 1) bytes. */
74795  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
74796  int flags = p->aMem[0].flags;
74797  if( p->pKeyInfo->aSortOrder[0] ){
74798  p->r1 = 1;
74799  p->r2 = -1;
74800  }else{
74801  p->r1 = -1;
74802  p->r2 = 1;
74803  }
74804  if( (flags & MEM_Int) ){
74805  return vdbeRecordCompareInt;
74806  }
74807  testcase( flags & MEM_Real );
74808  testcase( flags & MEM_Null );
74809  testcase( flags & MEM_Blob );
74810  if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
74811  assert( flags & MEM_Str );
74812  return vdbeRecordCompareString;
74813  }
74814  }
74815 
74816  return sqlite3VdbeRecordCompare;
74817 }
74818 
74819 /*
74820 ** pCur points at an index entry created using the OP_MakeRecord opcode.
74821 ** Read the rowid (the last field in the record) and store it in *rowid.
74822 ** Return SQLITE_OK if everything works, or an error code otherwise.
74823 **
74824 ** pCur might be pointing to text obtained from a corrupt database file.
74825 ** So the content cannot be trusted. Do appropriate checks on the content.
74826 */
74828  i64 nCellKey = 0;
74829  int rc;
74830  u32 szHdr; /* Size of the header */
74831  u32 typeRowid; /* Serial type of the rowid */
74832  u32 lenRowid; /* Size of the rowid */
74833  Mem m, v;
74834 
74835  /* Get the size of the index entry. Only indices entries of less
74836  ** than 2GiB are support - anything large must be database corruption.
74837  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
74838  ** this code can safely assume that nCellKey is 32-bits
74839  */
74840  assert( sqlite3BtreeCursorIsValid(pCur) );
74841  nCellKey = sqlite3BtreePayloadSize(pCur);
74842  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
74843 
74844  /* Read in the complete content of the index entry */
74845  sqlite3VdbeMemInit(&m, db, 0);
74846  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74847  if( rc ){
74848  return rc;
74849  }
74850 
74851  /* The index entry must begin with a header size */
74852  (void)getVarint32((u8*)m.z, szHdr);
74853  testcase( szHdr==3 );
74854  testcase( szHdr==m.n );
74855  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
74856  goto idx_rowid_corruption;
74857  }
74858 
74859  /* The last field of the index should be an integer - the ROWID.
74860  ** Verify that the last entry really is an integer. */
74861  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
74862  testcase( typeRowid==1 );
74863  testcase( typeRowid==2 );
74864  testcase( typeRowid==3 );
74865  testcase( typeRowid==4 );
74866  testcase( typeRowid==5 );
74867  testcase( typeRowid==6 );
74868  testcase( typeRowid==8 );
74869  testcase( typeRowid==9 );
74870  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
74871  goto idx_rowid_corruption;
74872  }
74873  lenRowid = sqlite3SmallTypeSizes[typeRowid];
74874  testcase( (u32)m.n==szHdr+lenRowid );
74875  if( unlikely((u32)m.n<szHdr+lenRowid) ){
74876  goto idx_rowid_corruption;
74877  }
74878 
74879  /* Fetch the integer off the end of the index record */
74880  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
74881  *rowid = v.u.i;
74883  return SQLITE_OK;
74884 
74885  /* Jump here if database corruption is detected after m has been
74886  ** allocated. Free the m object and return SQLITE_CORRUPT. */
74887 idx_rowid_corruption:
74888  testcase( m.szMalloc!=0 );
74890  return SQLITE_CORRUPT_BKPT;
74891 }
74892 
74893 /*
74894 ** Compare the key of the index entry that cursor pC is pointing to against
74895 ** the key string in pUnpacked. Write into *pRes a number
74896 ** that is negative, zero, or positive if pC is less than, equal to,
74897 ** or greater than pUnpacked. Return SQLITE_OK on success.
74898 **
74899 ** pUnpacked is either created without a rowid or is truncated so that it
74900 ** omits the rowid at the end. The rowid at the end of the index entry
74901 ** is ignored as well. Hence, this routine only compares the prefixes
74902 ** of the keys prior to the final rowid, not the entire key.
74903 */
74905  sqlite3 *db, /* Database connection */
74906  VdbeCursor *pC, /* The cursor to compare against */
74907  UnpackedRecord *pUnpacked, /* Unpacked version of key */
74908  int *res /* Write the comparison result here */
74909 ){
74910  i64 nCellKey = 0;
74911  int rc;
74912  BtCursor *pCur;
74913  Mem m;
74914 
74915  assert( pC->eCurType==CURTYPE_BTREE );
74916  pCur = pC->uc.pCursor;
74917  assert( sqlite3BtreeCursorIsValid(pCur) );
74918  nCellKey = sqlite3BtreePayloadSize(pCur);
74919  /* nCellKey will always be between 0 and 0xffffffff because of the way
74920  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
74921  if( nCellKey<=0 || nCellKey>0x7fffffff ){
74922  *res = 0;
74923  return SQLITE_CORRUPT_BKPT;
74924  }
74925  sqlite3VdbeMemInit(&m, db, 0);
74926  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74927  if( rc ){
74928  return rc;
74929  }
74930  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
74932  return SQLITE_OK;
74933 }
74934 
74935 /*
74936 ** This routine sets the value to be returned by subsequent calls to
74937 ** sqlite3_changes() on the database handle 'db'.
74938 */
74940  assert( sqlite3_mutex_held(db->mutex) );
74941  db->nChange = nChange;
74942  db->nTotalChange += nChange;
74943 }
74944 
74945 /*
74946 ** Set a flag in the vdbe to update the change counter when it is finalised
74947 ** or reset.
74948 */
74950  v->changeCntOn = 1;
74951 }
74952 
74953 /*
74954 ** Mark every prepared statement associated with a database connection
74955 ** as expired.
74956 **
74957 ** An expired statement means that recompilation of the statement is
74958 ** recommend. Statements expire when things happen that make their
74959 ** programs obsolete. Removing user-defined functions or collating
74960 ** sequences, or changing an authorization function are the types of
74961 ** things that make prepared statements obsolete.
74962 */
74964  Vdbe *p;
74965  for(p = db->pVdbe; p; p=p->pNext){
74966  p->expired = 1;
74967  }
74968 }
74969 
74970 /*
74971 ** Return the database associated with the Vdbe.
74972 */
74974  return v->db;
74975 }
74976 
74977 /*
74978 ** Return a pointer to an sqlite3_value structure containing the value bound
74979 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
74980 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
74981 ** constants) to the value before returning it.
74982 **
74983 ** The returned value must be freed by the caller using sqlite3ValueFree().
74984 */
74986  assert( iVar>0 );
74987  if( v ){
74988  Mem *pMem = &v->aVar[iVar-1];
74989  if( 0==(pMem->flags & MEM_Null) ){
74990  sqlite3_value *pRet = sqlite3ValueNew(v->db);
74991  if( pRet ){
74992  sqlite3VdbeMemCopy((Mem *)pRet, pMem);
74994  }
74995  return pRet;
74996  }
74997  }
74998  return 0;
74999 }
75000 
75001 /*
75002 ** Configure SQL variable iVar so that binding a new value to it signals
75003 ** to sqlite3_reoptimize() that re-preparing the statement may result
75004 ** in a better query plan.
75005 */
75007  assert( iVar>0 );
75008  if( iVar>32 ){
75009  v->expmask = 0xffffffff;
75010  }else{
75011  v->expmask |= ((u32)1 << (iVar-1));
75012  }
75013 }
75014 
75015 #ifndef SQLITE_OMIT_VIRTUALTABLE
75016 /*
75017 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
75018 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
75019 ** in memory obtained from sqlite3DbMalloc).
75020 */
75022  if( pVtab->zErrMsg ){
75023  sqlite3 *db = p->db;
75024  sqlite3DbFree(db, p->zErrMsg);
75025  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
75026  sqlite3_free(pVtab->zErrMsg);
75027  pVtab->zErrMsg = 0;
75028  }
75029 }
75030 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75031 
75032 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
75033 
75034 /*
75035 ** If the second argument is not NULL, release any allocations associated
75036 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
75037 ** structure itself, using sqlite3DbFree().
75038 **
75039 ** This function is used to free UnpackedRecord structures allocated by
75040 ** the vdbeUnpackRecord() function found in vdbeapi.c.
75041 */
75042 static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
75043  if( p ){
75044  int i;
75045  for(i=0; i<p->nField; i++){
75046  Mem *pMem = &p->aMem[i];
75047  if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
75048  }
75049  sqlite3DbFree(db, p);
75050  }
75051 }
75052 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
75053 
75054 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
75055 /*
75056 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
75057 ** then cursor passed as the second argument should point to the row about
75058 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
75059 ** the required value will be read from the row the cursor points to.
75060 */
75061 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
75062  Vdbe *v, /* Vdbe pre-update hook is invoked by */
75063  VdbeCursor *pCsr, /* Cursor to grab old.* values from */
75064  int op, /* SQLITE_INSERT, UPDATE or DELETE */
75065  const char *zDb, /* Database name */
75066  Table *pTab, /* Modified table */
75067  i64 iKey1, /* Initial key value */
75068  int iReg /* Register for new.* record */
75069 ){
75070  sqlite3 *db = v->db;
75071  i64 iKey2;
75072  PreUpdate preupdate;
75073  const char *zTbl = pTab->zName;
75074  static const u8 fakeSortOrder = 0;
75075 
75076  assert( db->pPreUpdate==0 );
75077  memset(&preupdate, 0, sizeof(PreUpdate));
75078  if( op==SQLITE_UPDATE ){
75079  iKey2 = v->aMem[iReg].u.i;
75080  }else{
75081  iKey2 = iKey1;
75082  }
75083 
75084  assert( pCsr->nField==pTab->nCol
75085  || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
75086  );
75087 
75088  preupdate.v = v;
75089  preupdate.pCsr = pCsr;
75090  preupdate.op = op;
75091  preupdate.iNewReg = iReg;
75092  preupdate.keyinfo.db = db;
75093  preupdate.keyinfo.enc = ENC(db);
75094  preupdate.keyinfo.nField = pTab->nCol;
75095  preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
75096  preupdate.iKey1 = iKey1;
75097  preupdate.iKey2 = iKey2;
75098  preupdate.pTab = pTab;
75099 
75100  db->pPreUpdate = &preupdate;
75101  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
75102  db->pPreUpdate = 0;
75103  sqlite3DbFree(db, preupdate.aRecord);
75104  vdbeFreeUnpacked(db, preupdate.pUnpacked);
75105  vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
75106  if( preupdate.aNew ){
75107  int i;
75108  for(i=0; i<pCsr->nField; i++){
75109  sqlite3VdbeMemRelease(&preupdate.aNew[i]);
75110  }
75111  sqlite3DbFree(db, preupdate.aNew);
75112  }
75113 }
75114 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
75115 
75116 /************** End of vdbeaux.c *********************************************/
75117 /************** Begin file vdbeapi.c *****************************************/
75118 /*
75119 ** 2004 May 26
75120 **
75121 ** The author disclaims copyright to this source code. In place of
75122 ** a legal notice, here is a blessing:
75123 **
75124 ** May you do good and not evil.
75125 ** May you find forgiveness for yourself and forgive others.
75126 ** May you share freely, never taking more than you give.
75127 **
75128 *************************************************************************
75129 **
75130 ** This file contains code use to implement APIs that are part of the
75131 ** VDBE.
75132 */
75133 /* #include "sqliteInt.h" */
75134 /* #include "vdbeInt.h" */
75135 
75136 #ifndef SQLITE_OMIT_DEPRECATED
75137 /*
75138 ** Return TRUE (non-zero) of the statement supplied as an argument needs
75139 ** to be recompiled. A statement needs to be recompiled whenever the
75140 ** execution environment changes in a way that would alter the program
75141 ** that sqlite3_prepare() generates. For example, if new functions or
75142 ** collating sequences are registered or if an authorizer function is
75143 ** added or changed.
75144 */
75146  Vdbe *p = (Vdbe*)pStmt;
75147  return p==0 || p->expired;
75148 }
75149 #endif
75150 
75151 /*
75152 ** Check on a Vdbe to make sure it has not been finalized. Log
75153 ** an error and return true if it has been finalized (or is otherwise
75154 ** invalid). Return false if it is ok.
75155 */
75156 static int vdbeSafety(Vdbe *p){
75157  if( p->db==0 ){
75158  sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
75159  return 1;
75160  }else{
75161  return 0;
75162  }
75163 }
75164 static int vdbeSafetyNotNull(Vdbe *p){
75165  if( p==0 ){
75166  sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
75167  return 1;
75168  }else{
75169  return vdbeSafety(p);
75170  }
75171 }
75172 
75173 #ifndef SQLITE_OMIT_TRACE
75174 /*
75175 ** Invoke the profile callback. This routine is only called if we already
75176 ** know that the profile callback is defined and needs to be invoked.
75177 */
75179  sqlite3_int64 iNow;
75180  sqlite3_int64 iElapse;
75181  assert( p->startTime>0 );
75182  assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
75183  assert( db->init.busy==0 );
75184  assert( p->zSql!=0 );
75185  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
75186  iElapse = (iNow - p->startTime)*1000000;
75187  if( db->xProfile ){
75188  db->xProfile(db->pProfileArg, p->zSql, iElapse);
75189  }
75190  if( db->mTrace & SQLITE_TRACE_PROFILE ){
75191  db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
75192  }
75193  p->startTime = 0;
75194 }
75195 /*
75196 ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
75197 ** is needed, and it invokes the callback if it is needed.
75198 */
75199 # define checkProfileCallback(DB,P) \
75200  if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
75201 #else
75202 # define checkProfileCallback(DB,P) /*no-op*/
75203 #endif
75204 
75205 /*
75206 ** The following routine destroys a virtual machine that is created by
75207 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
75208 ** success/failure code that describes the result of executing the virtual
75209 ** machine.
75210 **
75211 ** This routine sets the error code and string returned by
75212 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75213 */
75215  int rc;
75216  if( pStmt==0 ){
75217  /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
75218  ** pointer is a harmless no-op. */
75219  rc = SQLITE_OK;
75220  }else{
75221  Vdbe *v = (Vdbe*)pStmt;
75222  sqlite3 *db = v->db;
75223  if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
75225  checkProfileCallback(db, v);
75226  rc = sqlite3VdbeFinalize(v);
75227  rc = sqlite3ApiExit(db, rc);
75229  }
75230  return rc;
75231 }
75232 
75233 /*
75234 ** Terminate the current execution of an SQL statement and reset it
75235 ** back to its starting state so that it can be reused. A success code from
75236 ** the prior execution is returned.
75237 **
75238 ** This routine sets the error code and string returned by
75239 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75240 */
75242  int rc;
75243  if( pStmt==0 ){
75244  rc = SQLITE_OK;
75245  }else{
75246  Vdbe *v = (Vdbe*)pStmt;
75247  sqlite3 *db = v->db;
75249  checkProfileCallback(db, v);
75250  rc = sqlite3VdbeReset(v);
75251  sqlite3VdbeRewind(v);
75252  assert( (rc & (db->errMask))==rc );
75253  rc = sqlite3ApiExit(db, rc);
75255  }
75256  return rc;
75257 }
75258 
75259 /*
75260 ** Set all the parameters in the compiled SQL statement to NULL.
75261 */
75263  int i;
75264  int rc = SQLITE_OK;
75265  Vdbe *p = (Vdbe*)pStmt;
75266 #if SQLITE_THREADSAFE
75267  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
75268 #endif
75269  sqlite3_mutex_enter(mutex);
75270  for(i=0; i<p->nVar; i++){
75271  sqlite3VdbeMemRelease(&p->aVar[i]);
75272  p->aVar[i].flags = MEM_Null;
75273  }
75274  if( p->isPrepareV2 && p->expmask ){
75275  p->expired = 1;
75276  }
75277  sqlite3_mutex_leave(mutex);
75278  return rc;
75279 }
75280 
75281 
75282 /**************************** sqlite3_value_ *******************************
75283 ** The following routines extract information from a Mem or sqlite3_value
75284 ** structure.
75285 */
75287  Mem *p = (Mem*)pVal;
75288  if( p->flags & (MEM_Blob|MEM_Str) ){
75289  if( ExpandBlob(p)!=SQLITE_OK ){
75290  assert( p->flags==MEM_Null && p->z==0 );
75291  return 0;
75292  }
75293  p->flags |= MEM_Blob;
75294  return p->n ? p->z : 0;
75295  }else{
75296  return sqlite3_value_text(pVal);
75297  }
75298 }
75300  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
75301 }
75303  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
75304 }
75306  return sqlite3VdbeRealValue((Mem*)pVal);
75307 }
75309  return (int)sqlite3VdbeIntValue((Mem*)pVal);
75310 }
75312  return sqlite3VdbeIntValue((Mem*)pVal);
75313 }
75315  Mem *pMem = (Mem*)pVal;
75316  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
75317 }
75318 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
75319  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
75320 }
75321 #ifndef SQLITE_OMIT_UTF16
75323  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
75324 }
75326  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
75327 }
75329  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
75330 }
75331 #endif /* SQLITE_OMIT_UTF16 */
75332 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
75333 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
75334 ** point number string BLOB NULL
75335 */
75337  static const u8 aType[] = {
75338  SQLITE_BLOB, /* 0x00 */
75339  SQLITE_NULL, /* 0x01 */
75340  SQLITE_TEXT, /* 0x02 */
75341  SQLITE_NULL, /* 0x03 */
75342  SQLITE_INTEGER, /* 0x04 */
75343  SQLITE_NULL, /* 0x05 */
75344  SQLITE_INTEGER, /* 0x06 */
75345  SQLITE_NULL, /* 0x07 */
75346  SQLITE_FLOAT, /* 0x08 */
75347  SQLITE_NULL, /* 0x09 */
75348  SQLITE_FLOAT, /* 0x0a */
75349  SQLITE_NULL, /* 0x0b */
75350  SQLITE_INTEGER, /* 0x0c */
75351  SQLITE_NULL, /* 0x0d */
75352  SQLITE_INTEGER, /* 0x0e */
75353  SQLITE_NULL, /* 0x0f */
75354  SQLITE_BLOB, /* 0x10 */
75355  SQLITE_NULL, /* 0x11 */
75356  SQLITE_TEXT, /* 0x12 */
75357  SQLITE_NULL, /* 0x13 */
75358  SQLITE_INTEGER, /* 0x14 */
75359  SQLITE_NULL, /* 0x15 */
75360  SQLITE_INTEGER, /* 0x16 */
75361  SQLITE_NULL, /* 0x17 */
75362  SQLITE_FLOAT, /* 0x18 */
75363  SQLITE_NULL, /* 0x19 */
75364  SQLITE_FLOAT, /* 0x1a */
75365  SQLITE_NULL, /* 0x1b */
75366  SQLITE_INTEGER, /* 0x1c */
75367  SQLITE_NULL, /* 0x1d */
75368  SQLITE_INTEGER, /* 0x1e */
75369  SQLITE_NULL, /* 0x1f */
75370  };
75371  return aType[pVal->flags&MEM_AffMask];
75372 }
75373 
75374 /* Make a copy of an sqlite3_value object
75375 */
75377  sqlite3_value *pNew;
75378  if( pOrig==0 ) return 0;
75379  pNew = sqlite3_malloc( sizeof(*pNew) );
75380  if( pNew==0 ) return 0;
75381  memset(pNew, 0, sizeof(*pNew));
75382  memcpy(pNew, pOrig, MEMCELLSIZE);
75383  pNew->flags &= ~MEM_Dyn;
75384  pNew->db = 0;
75385  if( pNew->flags&(MEM_Str|MEM_Blob) ){
75386  pNew->flags &= ~(MEM_Static|MEM_Dyn);
75387  pNew->flags |= MEM_Ephem;
75389  sqlite3ValueFree(pNew);
75390  pNew = 0;
75391  }
75392  }
75393  return pNew;
75394 }
75395 
75396 /* Destroy an sqlite3_value object previously obtained from
75397 ** sqlite3_value_dup().
75398 */
75400  sqlite3ValueFree(pOld);
75401 }
75402 
75403 
75404 /**************************** sqlite3_result_ *******************************
75405 ** The following routines are used by user-defined functions to specify
75406 ** the function result.
75407 **
75408 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
75409 ** result as a string or blob but if the string or blob is too large, it
75410 ** then sets the error code to SQLITE_TOOBIG
75411 **
75412 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
75413 ** on value P is not going to be used and need to be destroyed.
75414 */
75416  sqlite3_context *pCtx, /* Function context */
75417  const char *z, /* String pointer */
75418  int n, /* Bytes in string, or negative */
75419  u8 enc, /* Encoding of z. 0 for BLOBs */
75420  void (*xDel)(void*) /* Destructor function */
75421 ){
75422  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
75424  }
75425 }
75427  const void *p, /* Value to destroy */
75428  void (*xDel)(void*), /* The destructor */
75429  sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
75430 ){
75431  assert( xDel!=SQLITE_DYNAMIC );
75432  if( xDel==0 ){
75433  /* noop */
75434  }else if( xDel==SQLITE_TRANSIENT ){
75435  /* noop */
75436  }else{
75437  xDel((void*)p);
75438  }
75439  if( pCtx ) sqlite3_result_error_toobig(pCtx);
75440  return SQLITE_TOOBIG;
75441 }
75443  sqlite3_context *pCtx,
75444  const void *z,
75445  int n,
75446  void (*xDel)(void *)
75447 ){
75448  assert( n>=0 );
75449  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75450  setResultStrOrError(pCtx, z, n, 0, xDel);
75451 }
75453  sqlite3_context *pCtx,
75454  const void *z,
75455  sqlite3_uint64 n,
75456  void (*xDel)(void *)
75457 ){
75458  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75459  assert( xDel!=SQLITE_DYNAMIC );
75460  if( n>0x7fffffff ){
75461  (void)invokeValueDestructor(z, xDel, pCtx);
75462  }else{
75463  setResultStrOrError(pCtx, z, (int)n, 0, xDel);
75464  }
75465 }
75467  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75468  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
75469 }
75470 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
75471  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75472  pCtx->isError = SQLITE_ERROR;
75473  pCtx->fErrorOrAux = 1;
75475 }
75476 #ifndef SQLITE_OMIT_UTF16
75477 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
75478  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75479  pCtx->isError = SQLITE_ERROR;
75480  pCtx->fErrorOrAux = 1;
75482 }
75483 #endif
75485  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75486  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
75487 }
75489  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75490  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
75491 }
75493  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75494  sqlite3VdbeMemSetNull(pCtx->pOut);
75495 }
75496 SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
75497  Mem *pOut = pCtx->pOut;
75498  assert( sqlite3_mutex_held(pOut->db->mutex) );
75499  pOut->eSubtype = eSubtype & 0xff;
75500  pOut->flags |= MEM_Subtype;
75501 }
75503  sqlite3_context *pCtx,
75504  const char *z,
75505  int n,
75506  void (*xDel)(void *)
75507 ){
75508  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75509  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
75510 }
75512  sqlite3_context *pCtx,
75513  const char *z,
75514  sqlite3_uint64 n,
75515  void (*xDel)(void *),
75516  unsigned char enc
75517 ){
75518  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75519  assert( xDel!=SQLITE_DYNAMIC );
75520  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
75521  if( n>0x7fffffff ){
75522  (void)invokeValueDestructor(z, xDel, pCtx);
75523  }else{
75524  setResultStrOrError(pCtx, z, (int)n, enc, xDel);
75525  }
75526 }
75527 #ifndef SQLITE_OMIT_UTF16
75529  sqlite3_context *pCtx,
75530  const void *z,
75531  int n,
75532  void (*xDel)(void *)
75533 ){
75534  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75535  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
75536 }
75538  sqlite3_context *pCtx,
75539  const void *z,
75540  int n,
75541  void (*xDel)(void *)
75542 ){
75543  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75544  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
75545 }
75547  sqlite3_context *pCtx,
75548  const void *z,
75549  int n,
75550  void (*xDel)(void *)
75551 ){
75552  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75553  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
75554 }
75555 #endif /* SQLITE_OMIT_UTF16 */
75557  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75558  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
75559 }
75561  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75562  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
75563 }
75565  Mem *pOut = pCtx->pOut;
75566  assert( sqlite3_mutex_held(pOut->db->mutex) );
75567  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
75568  return SQLITE_TOOBIG;
75569  }
75570  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
75571  return SQLITE_OK;
75572 }
75574  pCtx->isError = errCode;
75575  pCtx->fErrorOrAux = 1;
75576 #ifdef SQLITE_DEBUG
75577  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
75578 #endif
75579  if( pCtx->pOut->flags & MEM_Null ){
75580  sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
75582  }
75583 }
75584 
75585 /* Force an SQLITE_TOOBIG error. */
75587  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75588  pCtx->isError = SQLITE_TOOBIG;
75589  pCtx->fErrorOrAux = 1;
75590  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
75592 }
75593 
75594 /* An SQLITE_NOMEM error. */
75596  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75597  sqlite3VdbeMemSetNull(pCtx->pOut);
75598  pCtx->isError = SQLITE_NOMEM_BKPT;
75599  pCtx->fErrorOrAux = 1;
75600  sqlite3OomFault(pCtx->pOut->db);
75601 }
75602 
75603 /*
75604 ** This function is called after a transaction has been committed. It
75605 ** invokes callbacks registered with sqlite3_wal_hook() as required.
75606 */
75607 static int doWalCallbacks(sqlite3 *db){
75608  int rc = SQLITE_OK;
75609 #ifndef SQLITE_OMIT_WAL
75610  int i;
75611  for(i=0; i<db->nDb; i++){
75612  Btree *pBt = db->aDb[i].pBt;
75613  if( pBt ){
75614  int nEntry;
75615  sqlite3BtreeEnter(pBt);
75617  sqlite3BtreeLeave(pBt);
75618  if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
75619  rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
75620  }
75621  }
75622  }
75623 #endif
75624  return rc;
75625 }
75626 
75627 
75628 /*
75629 ** Execute the statement pStmt, either until a row of data is ready, the
75630 ** statement is completely executed or an error occurs.
75631 **
75632 ** This routine implements the bulk of the logic behind the sqlite_step()
75633 ** API. The only thing omitted is the automatic recompile if a
75634 ** schema change has occurred. That detail is handled by the
75635 ** outer sqlite3_step() wrapper procedure.
75636 */
75637 static int sqlite3Step(Vdbe *p){
75638  sqlite3 *db;
75639  int rc;
75640 
75641  assert(p);
75642  if( p->magic!=VDBE_MAGIC_RUN ){
75643  /* We used to require that sqlite3_reset() be called before retrying
75644  ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
75645  ** with version 3.7.0, we changed this so that sqlite3_reset() would
75646  ** be called automatically instead of throwing the SQLITE_MISUSE error.
75647  ** This "automatic-reset" change is not technically an incompatibility,
75648  ** since any application that receives an SQLITE_MISUSE is broken by
75649  ** definition.
75650  **
75651  ** Nevertheless, some published applications that were originally written
75652  ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
75653  ** returns, and those were broken by the automatic-reset change. As a
75654  ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
75655  ** legacy behavior of returning SQLITE_MISUSE for cases where the
75656  ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
75657  ** or SQLITE_BUSY error.
75658  */
75659 #ifdef SQLITE_OMIT_AUTORESET
75660  if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
75662  }else{
75663  return SQLITE_MISUSE_BKPT;
75664  }
75665 #else
75667 #endif
75668  }
75669 
75670  /* Check that malloc() has not failed. If it has, return early. */
75671  db = p->db;
75672  if( db->mallocFailed ){
75673  p->rc = SQLITE_NOMEM;
75674  return SQLITE_NOMEM_BKPT;
75675  }
75676 
75677  if( p->pc<=0 && p->expired ){
75678  p->rc = SQLITE_SCHEMA;
75679  rc = SQLITE_ERROR;
75680  goto end_of_step;
75681  }
75682  if( p->pc<0 ){
75683  /* If there are no other statements currently running, then
75684  ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
75685  ** from interrupting a statement that has not yet started.
75686  */
75687  if( db->nVdbeActive==0 ){
75688  db->u1.isInterrupted = 0;
75689  }
75690 
75691  assert( db->nVdbeWrite>0 || db->autoCommit==0
75692  || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
75693  );
75694 
75695 #ifndef SQLITE_OMIT_TRACE
75696  if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
75697  && !db->init.busy && p->zSql ){
75699  }else{
75700  assert( p->startTime==0 );
75701  }
75702 #endif
75703 
75704  db->nVdbeActive++;
75705  if( p->readOnly==0 ) db->nVdbeWrite++;
75706  if( p->bIsReader ) db->nVdbeRead++;
75707  p->pc = 0;
75708  }
75709 #ifdef SQLITE_DEBUG
75710  p->rcApp = SQLITE_OK;
75711 #endif
75712 #ifndef SQLITE_OMIT_EXPLAIN
75713  if( p->explain ){
75714  rc = sqlite3VdbeList(p);
75715  }else
75716 #endif /* SQLITE_OMIT_EXPLAIN */
75717  {
75718  db->nVdbeExec++;
75719  rc = sqlite3VdbeExec(p);
75720  db->nVdbeExec--;
75721  }
75722 
75723 #ifndef SQLITE_OMIT_TRACE
75724  /* If the statement completed successfully, invoke the profile callback */
75725  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
75726 #endif
75727 
75728  if( rc==SQLITE_DONE ){
75729  assert( p->rc==SQLITE_OK );
75730  p->rc = doWalCallbacks(db);
75731  if( p->rc!=SQLITE_OK ){
75732  rc = SQLITE_ERROR;
75733  }
75734  }
75735 
75736  db->errCode = rc;
75737  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
75738  p->rc = SQLITE_NOMEM_BKPT;
75739  }
75740 end_of_step:
75741  /* At this point local variable rc holds the value that should be
75742  ** returned if this statement was compiled using the legacy
75743  ** sqlite3_prepare() interface. According to the docs, this can only
75744  ** be one of the values in the first assert() below. Variable p->rc
75745  ** contains the value that would be returned if sqlite3_finalize()
75746  ** were called on statement p.
75747  */
75748  assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
75749  || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
75750  );
75751  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
75752  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
75753  /* If this statement was prepared using sqlite3_prepare_v2(), and an
75754  ** error has occurred, then return the error code in p->rc to the
75755  ** caller. Set the error code in the database handle to the same value.
75756  */
75757  rc = sqlite3VdbeTransferError(p);
75758  }
75759  return (rc&db->errMask);
75760 }
75761 
75762 /*
75763 ** This is the top-level implementation of sqlite3_step(). Call
75764 ** sqlite3Step() to do most of the work. If a schema error occurs,
75765 ** call sqlite3Reprepare() and try again.
75766 */
75768  int rc = SQLITE_OK; /* Result from sqlite3Step() */
75769  int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
75770  Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
75771  int cnt = 0; /* Counter to prevent infinite loop of reprepares */
75772  sqlite3 *db; /* The database connection */
75773 
75774  if( vdbeSafetyNotNull(v) ){
75775  return SQLITE_MISUSE_BKPT;
75776  }
75777  db = v->db;
75779  v->doingRerun = 0;
75780  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
75781  && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
75782  int savedPc = v->pc;
75783  rc2 = rc = sqlite3Reprepare(v);
75784  if( rc!=SQLITE_OK) break;
75785  sqlite3_reset(pStmt);
75786  if( savedPc>=0 ) v->doingRerun = 1;
75787  assert( v->expired==0 );
75788  }
75789  if( rc2!=SQLITE_OK ){
75790  /* This case occurs after failing to recompile an sql statement.
75791  ** The error message from the SQL compiler has already been loaded
75792  ** into the database handle. This block copies the error message
75793  ** from the database handle into the statement and sets the statement
75794  ** program counter to 0 to ensure that when the statement is
75795  ** finalized or reset the parser error message is available via
75796  ** sqlite3_errmsg() and sqlite3_errcode().
75797  */
75798  const char *zErr = (const char *)sqlite3_value_text(db->pErr);
75799  sqlite3DbFree(db, v->zErrMsg);
75800  if( !db->mallocFailed ){
75801  v->zErrMsg = sqlite3DbStrDup(db, zErr);
75802  v->rc = rc2;
75803  } else {
75804  v->zErrMsg = 0;
75805  v->rc = rc = SQLITE_NOMEM_BKPT;
75806  }
75807  }
75808  rc = sqlite3ApiExit(db, rc);
75810  return rc;
75811 }
75812 
75813 
75814 /*
75815 ** Extract the user data from a sqlite3_context structure and return a
75816 ** pointer to it.
75817 */
75819  assert( p && p->pFunc );
75820  return p->pFunc->pUserData;
75821 }
75822 
75823 /*
75824 ** Extract the user data from a sqlite3_context structure and return a
75825 ** pointer to it.
75826 **
75827 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
75828 ** returns a copy of the pointer to the database connection (the 1st
75829 ** parameter) of the sqlite3_create_function() and
75830 ** sqlite3_create_function16() routines that originally registered the
75831 ** application defined function.
75832 */
75834  assert( p && p->pOut );
75835  return p->pOut->db;
75836 }
75837 
75838 /*
75839 ** Return the current time for a statement. If the current time
75840 ** is requested more than once within the same run of a single prepared
75841 ** statement, the exact same time is returned for each invocation regardless
75842 ** of the amount of time that elapses between invocations. In other words,
75843 ** the time returned is always the time of the first call.
75844 */
75846  int rc;
75847 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
75848  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
75849  assert( p->pVdbe!=0 );
75850 #else
75851  sqlite3_int64 iTime = 0;
75852  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
75853 #endif
75854  if( *piTime==0 ){
75855  rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
75856  if( rc ) *piTime = 0;
75857  }
75858  return *piTime;
75859 }
75860 
75861 /*
75862 ** The following is the implementation of an SQL function that always
75863 ** fails with an error message stating that the function is used in the
75864 ** wrong context. The sqlite3_overload_function() API might construct
75865 ** SQL function that use this routine so that the functions will exist
75866 ** for name resolution but are actually overloaded by the xFindFunction
75867 ** method of virtual tables.
75868 */
75870  sqlite3_context *context, /* The function calling context */
75871  int NotUsed, /* Number of arguments to the function */
75872  sqlite3_value **NotUsed2 /* Value of each argument */
75873 ){
75874  const char *zName = context->pFunc->zName;
75875  char *zErr;
75876  UNUSED_PARAMETER2(NotUsed, NotUsed2);
75877  zErr = sqlite3_mprintf(
75878  "unable to use function %s in the requested context", zName);
75879  sqlite3_result_error(context, zErr, -1);
75880  sqlite3_free(zErr);
75881 }
75882 
75883 /*
75884 ** Create a new aggregate context for p and return a pointer to
75885 ** its pMem->z element.
75886 */
75888  Mem *pMem = p->pMem;
75889  assert( (pMem->flags & MEM_Agg)==0 );
75890  if( nByte<=0 ){
75891  sqlite3VdbeMemSetNull(pMem);
75892  pMem->z = 0;
75893  }else{
75894  sqlite3VdbeMemClearAndResize(pMem, nByte);
75895  pMem->flags = MEM_Agg;
75896  pMem->u.pDef = p->pFunc;
75897  if( pMem->z ){
75898  memset(pMem->z, 0, nByte);
75899  }
75900  }
75901  return (void*)pMem->z;
75902 }
75903 
75904 /*
75905 ** Allocate or return the aggregate context for a user function. A new
75906 ** context is allocated on the first call. Subsequent calls return the
75907 ** same context that was returned on prior calls.
75908 */
75910  assert( p && p->pFunc && p->pFunc->xFinalize );
75911  assert( sqlite3_mutex_held(p->pOut->db->mutex) );
75912  testcase( nByte<0 );
75913  if( (p->pMem->flags & MEM_Agg)==0 ){
75914  return createAggContext(p, nByte);
75915  }else{
75916  return (void*)p->pMem->z;
75917  }
75918 }
75919 
75920 /*
75921 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
75922 ** the user-function defined by pCtx.
75923 */
75925  AuxData *pAuxData;
75926 
75927  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75928 #if SQLITE_ENABLE_STAT3_OR_STAT4
75929  if( pCtx->pVdbe==0 ) return 0;
75930 #else
75931  assert( pCtx->pVdbe!=0 );
75932 #endif
75933  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75934  if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75935  }
75936 
75937  return (pAuxData ? pAuxData->pAux : 0);
75938 }
75939 
75940 /*
75941 ** Set the auxiliary data pointer and delete function, for the iArg'th
75942 ** argument to the user-function defined by pCtx. Any previous value is
75943 ** deleted by calling the delete function specified when it was set.
75944 */
75946  sqlite3_context *pCtx,
75947  int iArg,
75948  void *pAux,
75949  void (*xDelete)(void*)
75950 ){
75951  AuxData *pAuxData;
75952  Vdbe *pVdbe = pCtx->pVdbe;
75953 
75954  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75955  if( iArg<0 ) goto failed;
75956 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
75957  if( pVdbe==0 ) goto failed;
75958 #else
75959  assert( pVdbe!=0 );
75960 #endif
75961 
75962  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75963  if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75964  }
75965  if( pAuxData==0 ){
75966  pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
75967  if( !pAuxData ) goto failed;
75968  pAuxData->iOp = pCtx->iOp;
75969  pAuxData->iArg = iArg;
75970  pAuxData->pNext = pVdbe->pAuxData;
75971  pVdbe->pAuxData = pAuxData;
75972  if( pCtx->fErrorOrAux==0 ){
75973  pCtx->isError = 0;
75974  pCtx->fErrorOrAux = 1;
75975  }
75976  }else if( pAuxData->xDelete ){
75977  pAuxData->xDelete(pAuxData->pAux);
75978  }
75979 
75980  pAuxData->pAux = pAux;
75981  pAuxData->xDelete = xDelete;
75982  return;
75983 
75984 failed:
75985  if( xDelete ){
75986  xDelete(pAux);
75987  }
75988 }
75989 
75990 #ifndef SQLITE_OMIT_DEPRECATED
75991 /*
75992 ** Return the number of times the Step function of an aggregate has been
75993 ** called.
75994 **
75995 ** This function is deprecated. Do not use it for new code. It is
75996 ** provide only to avoid breaking legacy code. New aggregate function
75997 ** implementations should keep their own counts within their aggregate
75998 ** context.
75999 */
76001  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
76002  return p->pMem->n;
76003 }
76004 #endif
76005 
76006 /*
76007 ** Return the number of columns in the result set for the statement pStmt.
76008 */
76010  Vdbe *pVm = (Vdbe *)pStmt;
76011  return pVm ? pVm->nResColumn : 0;
76012 }
76013 
76014 /*
76015 ** Return the number of values available from the current row of the
76016 ** currently executing statement pStmt.
76017 */
76019  Vdbe *pVm = (Vdbe *)pStmt;
76020  if( pVm==0 || pVm->pResultSet==0 ) return 0;
76021  return pVm->nResColumn;
76022 }
76023 
76024 /*
76025 ** Return a pointer to static memory containing an SQL NULL value.
76026 */
76027 static const Mem *columnNullValue(void){
76028  /* Even though the Mem structure contains an element
76029  ** of type i64, on certain architectures (x86) with certain compiler
76030  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
76031  ** instead of an 8-byte one. This all works fine, except that when
76032  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
76033  ** that a Mem structure is located on an 8-byte boundary. To prevent
76034  ** these assert()s from failing, when building with SQLITE_DEBUG defined
76035  ** using gcc, we force nullMem to be 8-byte aligned using the magical
76036  ** __attribute__((aligned(8))) macro. */
76037  static const Mem nullMem
76038 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
76039  __attribute__((aligned(8)))
76040 #endif
76041  = {
76042  /* .u = */ {0},
76043  /* .flags = */ (u16)MEM_Null,
76044  /* .enc = */ (u8)0,
76045  /* .eSubtype = */ (u8)0,
76046  /* .n = */ (int)0,
76047  /* .z = */ (char*)0,
76048  /* .zMalloc = */ (char*)0,
76049  /* .szMalloc = */ (int)0,
76050  /* .uTemp = */ (u32)0,
76051  /* .db = */ (sqlite3*)0,
76052  /* .xDel = */ (void(*)(void*))0,
76053 #ifdef SQLITE_DEBUG
76054  /* .pScopyFrom = */ (Mem*)0,
76055  /* .pFiller = */ (void*)0,
76056 #endif
76057  };
76058  return &nullMem;
76059 }
76060 
76061 /*
76062 ** Check to see if column iCol of the given statement is valid. If
76063 ** it is, return a pointer to the Mem for the value of that column.
76064 ** If iCol is not valid, return a pointer to a Mem which has a value
76065 ** of NULL.
76066 */
76067 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
76068  Vdbe *pVm;
76069  Mem *pOut;
76070 
76071  pVm = (Vdbe *)pStmt;
76072  if( pVm==0 ) return (Mem*)columnNullValue();
76073  assert( pVm->db );
76074  sqlite3_mutex_enter(pVm->db->mutex);
76075  if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
76076  pOut = &pVm->pResultSet[i];
76077  }else{
76078  sqlite3Error(pVm->db, SQLITE_RANGE);
76079  pOut = (Mem*)columnNullValue();
76080  }
76081  return pOut;
76082 }
76083 
76084 /*
76085 ** This function is called after invoking an sqlite3_value_XXX function on a
76086 ** column value (i.e. a value returned by evaluating an SQL expression in the
76087 ** select list of a SELECT statement) that may cause a malloc() failure. If
76088 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
76089 ** code of statement pStmt set to SQLITE_NOMEM.
76090 **
76091 ** Specifically, this is called from within:
76092 **
76093 ** sqlite3_column_int()
76094 ** sqlite3_column_int64()
76095 ** sqlite3_column_text()
76096 ** sqlite3_column_text16()
76097 ** sqlite3_column_real()
76098 ** sqlite3_column_bytes()
76099 ** sqlite3_column_bytes16()
76100 ** sqiite3_column_blob()
76101 */
76103 {
76104  /* If malloc() failed during an encoding conversion within an
76105  ** sqlite3_column_XXX API, then set the return code of the statement to
76106  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
76107  ** and _finalize() will return NOMEM.
76108  */
76109  Vdbe *p = (Vdbe *)pStmt;
76110  if( p ){
76111  assert( p->db!=0 );
76112  assert( sqlite3_mutex_held(p->db->mutex) );
76113  p->rc = sqlite3ApiExit(p->db, p->rc);
76115  }
76116 }
76117 
76118 /**************************** sqlite3_column_ *******************************
76119 ** The following routines are used to access elements of the current row
76120 ** in the result set.
76121 */
76122 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
76123  const void *val;
76124  val = sqlite3_value_blob( columnMem(pStmt,i) );
76125  /* Even though there is no encoding conversion, value_blob() might
76126  ** need to call malloc() to expand the result of a zeroblob()
76127  ** expression.
76128  */
76129  columnMallocFailure(pStmt);
76130  return val;
76131 }
76133  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
76134  columnMallocFailure(pStmt);
76135  return val;
76136 }
76138  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
76139  columnMallocFailure(pStmt);
76140  return val;
76141 }
76143  double val = sqlite3_value_double( columnMem(pStmt,i) );
76144  columnMallocFailure(pStmt);
76145  return val;
76146 }
76148  int val = sqlite3_value_int( columnMem(pStmt,i) );
76149  columnMallocFailure(pStmt);
76150  return val;
76151 }
76152 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
76153  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
76154  columnMallocFailure(pStmt);
76155  return val;
76156 }
76157 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
76158  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
76159  columnMallocFailure(pStmt);
76160  return val;
76161 }
76163  Mem *pOut = columnMem(pStmt, i);
76164  if( pOut->flags&MEM_Static ){
76165  pOut->flags &= ~MEM_Static;
76166  pOut->flags |= MEM_Ephem;
76167  }
76168  columnMallocFailure(pStmt);
76169  return (sqlite3_value *)pOut;
76170 }
76171 #ifndef SQLITE_OMIT_UTF16
76172 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
76173  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
76174  columnMallocFailure(pStmt);
76175  return val;
76176 }
76177 #endif /* SQLITE_OMIT_UTF16 */
76179  int iType = sqlite3_value_type( columnMem(pStmt,i) );
76180  columnMallocFailure(pStmt);
76181  return iType;
76182 }
76183 
76184 /*
76185 ** Convert the N-th element of pStmt->pColName[] into a string using
76186 ** xFunc() then return that string. If N is out of range, return 0.
76187 **
76188 ** There are up to 5 names for each column. useType determines which
76189 ** name is returned. Here are the names:
76190 **
76191 ** 0 The column name as it should be displayed for output
76192 ** 1 The datatype name for the column
76193 ** 2 The name of the database that the column derives from
76194 ** 3 The name of the table that the column derives from
76195 ** 4 The name of the table column that the result column derives from
76196 **
76197 ** If the result is not a simple column reference (if it is an expression
76198 ** or a constant) then useTypes 2, 3, and 4 return NULL.
76199 */
76200 static const void *columnName(
76201  sqlite3_stmt *pStmt,
76202  int N,
76203  const void *(*xFunc)(Mem*),
76204  int useType
76205 ){
76206  const void *ret;
76207  Vdbe *p;
76208  int n;
76209  sqlite3 *db;
76210 #ifdef SQLITE_ENABLE_API_ARMOR
76211  if( pStmt==0 ){
76212  (void)SQLITE_MISUSE_BKPT;
76213  return 0;
76214  }
76215 #endif
76216  ret = 0;
76217  p = (Vdbe *)pStmt;
76218  db = p->db;
76219  assert( db!=0 );
76220  n = sqlite3_column_count(pStmt);
76221  if( N<n && N>=0 ){
76222  N += useType*n;
76224  assert( db->mallocFailed==0 );
76225  ret = xFunc(&p->aColName[N]);
76226  /* A malloc may have failed inside of the xFunc() call. If this
76227  ** is the case, clear the mallocFailed flag and return NULL.
76228  */
76229  if( db->mallocFailed ){
76230  sqlite3OomClear(db);
76231  ret = 0;
76232  }
76234  }
76235  return ret;
76236 }
76237 
76238 /*
76239 ** Return the name of the Nth column of the result set returned by SQL
76240 ** statement pStmt.
76241 */
76242 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
76243  return columnName(
76244  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
76245 }
76246 #ifndef SQLITE_OMIT_UTF16
76247 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
76248  return columnName(
76249  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
76250 }
76251 #endif
76252 
76253 /*
76254 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
76255 ** not define OMIT_DECLTYPE.
76256 */
76257 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
76258 # error "Must not define both SQLITE_OMIT_DECLTYPE \
76259  and SQLITE_ENABLE_COLUMN_METADATA"
76260 #endif
76261 
76262 #ifndef SQLITE_OMIT_DECLTYPE
76263 /*
76264 ** Return the column declaration type (if applicable) of the 'i'th column
76265 ** of the result set of SQL statement pStmt.
76266 */
76268  return columnName(
76269  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
76270 }
76271 #ifndef SQLITE_OMIT_UTF16
76273  return columnName(
76274  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
76275 }
76276 #endif /* SQLITE_OMIT_UTF16 */
76277 #endif /* SQLITE_OMIT_DECLTYPE */
76278 
76279 #ifdef SQLITE_ENABLE_COLUMN_METADATA
76280 /*
76281 ** Return the name of the database from which a result column derives.
76282 ** NULL is returned if the result column is an expression or constant or
76283 ** anything else which is not an unambiguous reference to a database column.
76284 */
76285 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
76286  return columnName(
76287  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
76288 }
76289 #ifndef SQLITE_OMIT_UTF16
76290 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
76291  return columnName(
76292  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
76293 }
76294 #endif /* SQLITE_OMIT_UTF16 */
76295 
76296 /*
76297 ** Return the name of the table from which a result column derives.
76298 ** NULL is returned if the result column is an expression or constant or
76299 ** anything else which is not an unambiguous reference to a database column.
76300 */
76301 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
76302  return columnName(
76303  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
76304 }
76305 #ifndef SQLITE_OMIT_UTF16
76306 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
76307  return columnName(
76308  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
76309 }
76310 #endif /* SQLITE_OMIT_UTF16 */
76311 
76312 /*
76313 ** Return the name of the table column from which a result column derives.
76314 ** NULL is returned if the result column is an expression or constant or
76315 ** anything else which is not an unambiguous reference to a database column.
76316 */
76317 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
76318  return columnName(
76319  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
76320 }
76321 #ifndef SQLITE_OMIT_UTF16
76322 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
76323  return columnName(
76324  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
76325 }
76326 #endif /* SQLITE_OMIT_UTF16 */
76327 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
76328 
76329 
76330 /******************************* sqlite3_bind_ ***************************
76331 **
76332 ** Routines used to attach values to wildcards in a compiled SQL statement.
76333 */
76334 /*
76335 ** Unbind the value bound to variable i in virtual machine p. This is the
76336 ** the same as binding a NULL value to the column. If the "i" parameter is
76337 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
76338 **
76339 ** A successful evaluation of this routine acquires the mutex on p.
76340 ** the mutex is released if any kind of error occurs.
76341 **
76342 ** The error code stored in database p->db is overwritten with the return
76343 ** value in any case.
76344 */
76345 static int vdbeUnbind(Vdbe *p, int i){
76346  Mem *pVar;
76347  if( vdbeSafetyNotNull(p) ){
76348  return SQLITE_MISUSE_BKPT;
76349  }
76351  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
76355  "bind on a busy prepared statement: [%s]", p->zSql);
76356  return SQLITE_MISUSE_BKPT;
76357  }
76358  if( i<1 || i>p->nVar ){
76361  return SQLITE_RANGE;
76362  }
76363  i--;
76364  pVar = &p->aVar[i];
76365  sqlite3VdbeMemRelease(pVar);
76366  pVar->flags = MEM_Null;
76367  sqlite3Error(p->db, SQLITE_OK);
76368 
76369  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
76370  ** binding a new value to this variable invalidates the current query plan.
76371  **
76372  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
76373  ** parameter in the WHERE clause might influence the choice of query plan
76374  ** for a statement, then the statement will be automatically recompiled,
76375  ** as if there had been a schema change, on the first sqlite3_step() call
76376  ** following any change to the bindings of that parameter.
76377  */
76378  if( p->isPrepareV2 &&
76379  ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
76380  ){
76381  p->expired = 1;
76382  }
76383  return SQLITE_OK;
76384 }
76385 
76386 /*
76387 ** Bind a text or BLOB value.
76388 */
76389 static int bindText(
76390  sqlite3_stmt *pStmt, /* The statement to bind against */
76391  int i, /* Index of the parameter to bind */
76392  const void *zData, /* Pointer to the data to be bound */
76393  int nData, /* Number of bytes of data to be bound */
76394  void (*xDel)(void*), /* Destructor for the data */
76395  u8 encoding /* Encoding for the data */
76396 ){
76397  Vdbe *p = (Vdbe *)pStmt;
76398  Mem *pVar;
76399  int rc;
76400 
76401  rc = vdbeUnbind(p, i);
76402  if( rc==SQLITE_OK ){
76403  if( zData!=0 ){
76404  pVar = &p->aVar[i-1];
76405  rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
76406  if( rc==SQLITE_OK && encoding!=0 ){
76407  rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
76408  }
76409  sqlite3Error(p->db, rc);
76410  rc = sqlite3ApiExit(p->db, rc);
76411  }
76413  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
76414  xDel((void*)zData);
76415  }
76416  return rc;
76417 }
76418 
76419 
76420 /*
76421 ** Bind a blob value to an SQL statement variable.
76422 */
76424  sqlite3_stmt *pStmt,
76425  int i,
76426  const void *zData,
76427  int nData,
76428  void (*xDel)(void*)
76429 ){
76430 #ifdef SQLITE_ENABLE_API_ARMOR
76431  if( nData<0 ) return SQLITE_MISUSE_BKPT;
76432 #endif
76433  return bindText(pStmt, i, zData, nData, xDel, 0);
76434 }
76436  sqlite3_stmt *pStmt,
76437  int i,
76438  const void *zData,
76439  sqlite3_uint64 nData,
76440  void (*xDel)(void*)
76441 ){
76442  assert( xDel!=SQLITE_DYNAMIC );
76443  if( nData>0x7fffffff ){
76444  return invokeValueDestructor(zData, xDel, 0);
76445  }else{
76446  return bindText(pStmt, i, zData, (int)nData, xDel, 0);
76447  }
76448 }
76449 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
76450  int rc;
76451  Vdbe *p = (Vdbe *)pStmt;
76452  rc = vdbeUnbind(p, i);
76453  if( rc==SQLITE_OK ){
76454  sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
76456  }
76457  return rc;
76458 }
76459 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
76460  return sqlite3_bind_int64(p, i, (i64)iValue);
76461 }
76462 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
76463  int rc;
76464  Vdbe *p = (Vdbe *)pStmt;
76465  rc = vdbeUnbind(p, i);
76466  if( rc==SQLITE_OK ){
76467  sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
76469  }
76470  return rc;
76471 }
76473  int rc;
76474  Vdbe *p = (Vdbe*)pStmt;
76475  rc = vdbeUnbind(p, i);
76476  if( rc==SQLITE_OK ){
76478  }
76479  return rc;
76480 }
76482  sqlite3_stmt *pStmt,
76483  int i,
76484  const char *zData,
76485  int nData,
76486  void (*xDel)(void*)
76487 ){
76488  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
76489 }
76491  sqlite3_stmt *pStmt,
76492  int i,
76493  const char *zData,
76494  sqlite3_uint64 nData,
76495  void (*xDel)(void*),
76496  unsigned char enc
76497 ){
76498  assert( xDel!=SQLITE_DYNAMIC );
76499  if( nData>0x7fffffff ){
76500  return invokeValueDestructor(zData, xDel, 0);
76501  }else{
76502  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
76503  return bindText(pStmt, i, zData, (int)nData, xDel, enc);
76504  }
76505 }
76506 #ifndef SQLITE_OMIT_UTF16
76508  sqlite3_stmt *pStmt,
76509  int i,
76510  const void *zData,
76511  int nData,
76512  void (*xDel)(void*)
76513 ){
76514  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
76515 }
76516 #endif /* SQLITE_OMIT_UTF16 */
76517 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
76518  int rc;
76519  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
76520  case SQLITE_INTEGER: {
76521  rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
76522  break;
76523  }
76524  case SQLITE_FLOAT: {
76525  rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
76526  break;
76527  }
76528  case SQLITE_BLOB: {
76529  if( pValue->flags & MEM_Zero ){
76530  rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
76531  }else{
76532  rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
76533  }
76534  break;
76535  }
76536  case SQLITE_TEXT: {
76537  rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
76538  pValue->enc);
76539  break;
76540  }
76541  default: {
76542  rc = sqlite3_bind_null(pStmt, i);
76543  break;
76544  }
76545  }
76546  return rc;
76547 }
76549  int rc;
76550  Vdbe *p = (Vdbe *)pStmt;
76551  rc = vdbeUnbind(p, i);
76552  if( rc==SQLITE_OK ){
76553  sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
76555  }
76556  return rc;
76557 }
76558 SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
76559  int rc;
76560  Vdbe *p = (Vdbe *)pStmt;
76562  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
76563  rc = SQLITE_TOOBIG;
76564  }else{
76565  assert( (n & 0x7FFFFFFF)==n );
76566  rc = sqlite3_bind_zeroblob(pStmt, i, n);
76567  }
76568  rc = sqlite3ApiExit(p->db, rc);
76570  return rc;
76571 }
76572 
76573 /*
76574 ** Return the number of wildcards that can be potentially bound to.
76575 ** This routine is added to support DBD::SQLite.
76576 */
76578  Vdbe *p = (Vdbe*)pStmt;
76579  return p ? p->nVar : 0;
76580 }
76581 
76582 /*
76583 ** Return the name of a wildcard parameter. Return NULL if the index
76584 ** is out of range or if the wildcard is unnamed.
76585 **
76586 ** The result is always UTF-8.
76587 */
76589  Vdbe *p = (Vdbe*)pStmt;
76590  if( p==0 || i<1 || i>p->nzVar ){
76591  return 0;
76592  }
76593  return p->azVar[i-1];
76594 }
76595 
76596 /*
76597 ** Given a wildcard parameter name, return the index of the variable
76598 ** with that name. If there is no variable with the given name,
76599 ** return 0.
76600 */
76601 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
76602  int i;
76603  if( p==0 ){
76604  return 0;
76605  }
76606  if( zName ){
76607  for(i=0; i<p->nzVar; i++){
76608  const char *z = p->azVar[i];
76609  if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
76610  return i+1;
76611  }
76612  }
76613  }
76614  return 0;
76615 }
76617  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
76618 }
76619 
76620 /*
76621 ** Transfer all bindings from the first statement over to the second.
76622 */
76624  Vdbe *pFrom = (Vdbe*)pFromStmt;
76625  Vdbe *pTo = (Vdbe*)pToStmt;
76626  int i;
76627  assert( pTo->db==pFrom->db );
76628  assert( pTo->nVar==pFrom->nVar );
76629  sqlite3_mutex_enter(pTo->db->mutex);
76630  for(i=0; i<pFrom->nVar; i++){
76631  sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
76632  }
76633  sqlite3_mutex_leave(pTo->db->mutex);
76634  return SQLITE_OK;
76635 }
76636 
76637 #ifndef SQLITE_OMIT_DEPRECATED
76638 /*
76639 ** Deprecated external interface. Internal/core SQLite code
76640 ** should call sqlite3TransferBindings.
76641 **
76642 ** It is misuse to call this routine with statements from different
76643 ** database connections. But as this is a deprecated interface, we
76644 ** will not bother to check for that condition.
76645 **
76646 ** If the two statements contain a different number of bindings, then
76647 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
76648 ** SQLITE_OK is returned.
76649 */
76651  Vdbe *pFrom = (Vdbe*)pFromStmt;
76652  Vdbe *pTo = (Vdbe*)pToStmt;
76653  if( pFrom->nVar!=pTo->nVar ){
76654  return SQLITE_ERROR;
76655  }
76656  if( pTo->isPrepareV2 && pTo->expmask ){
76657  pTo->expired = 1;
76658  }
76659  if( pFrom->isPrepareV2 && pFrom->expmask ){
76660  pFrom->expired = 1;
76661  }
76662  return sqlite3TransferBindings(pFromStmt, pToStmt);
76663 }
76664 #endif
76665 
76666 /*
76667 ** Return the sqlite3* database handle to which the prepared statement given
76668 ** in the argument belongs. This is the same database handle that was
76669 ** the first argument to the sqlite3_prepare() that was used to create
76670 ** the statement in the first place.
76671 */
76673  return pStmt ? ((Vdbe*)pStmt)->db : 0;
76674 }
76675 
76676 /*
76677 ** Return true if the prepared statement is guaranteed to not modify the
76678 ** database.
76679 */
76681  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
76682 }
76683 
76684 /*
76685 ** Return true if the prepared statement is in need of being reset.
76686 */
76688  Vdbe *v = (Vdbe*)pStmt;
76689  return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
76690 }
76691 
76692 /*
76693 ** Return a pointer to the next prepared statement after pStmt associated
76694 ** with database connection pDb. If pStmt is NULL, return the first
76695 ** prepared statement for the database connection. Return NULL if there
76696 ** are no more.
76697 */
76699  sqlite3_stmt *pNext;
76700 #ifdef SQLITE_ENABLE_API_ARMOR
76701  if( !sqlite3SafetyCheckOk(pDb) ){
76702  (void)SQLITE_MISUSE_BKPT;
76703  return 0;
76704  }
76705 #endif
76706  sqlite3_mutex_enter(pDb->mutex);
76707  if( pStmt==0 ){
76708  pNext = (sqlite3_stmt*)pDb->pVdbe;
76709  }else{
76710  pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
76711  }
76712  sqlite3_mutex_leave(pDb->mutex);
76713  return pNext;
76714 }
76715 
76716 /*
76717 ** Return the value of a status counter for a prepared statement
76718 */
76719 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
76720  Vdbe *pVdbe = (Vdbe*)pStmt;
76721  u32 v;
76722 #ifdef SQLITE_ENABLE_API_ARMOR
76723  if( !pStmt ){
76724  (void)SQLITE_MISUSE_BKPT;
76725  return 0;
76726  }
76727 #endif
76728  v = pVdbe->aCounter[op];
76729  if( resetFlag ) pVdbe->aCounter[op] = 0;
76730  return (int)v;
76731 }
76732 
76733 /*
76734 ** Return the SQL associated with a prepared statement
76735 */
76737  Vdbe *p = (Vdbe *)pStmt;
76738  return p ? p->zSql : 0;
76739 }
76740 
76741 /*
76742 ** Return the SQL associated with a prepared statement with
76743 ** bound parameters expanded. Space to hold the returned string is
76744 ** obtained from sqlite3_malloc(). The caller is responsible for
76745 ** freeing the returned string by passing it to sqlite3_free().
76746 **
76747 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
76748 ** expanded bound parameters.
76749 */
76751 #ifdef SQLITE_OMIT_TRACE
76752  return 0;
76753 #else
76754  char *z = 0;
76755  const char *zSql = sqlite3_sql(pStmt);
76756  if( zSql ){
76757  Vdbe *p = (Vdbe *)pStmt;
76759  z = sqlite3VdbeExpandSql(p, zSql);
76761  }
76762  return z;
76763 #endif
76764 }
76765 
76766 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76767 /*
76768 ** Allocate and populate an UnpackedRecord structure based on the serialized
76769 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76770 ** if successful, or a NULL pointer if an OOM error is encountered.
76771 */
76772 static UnpackedRecord *vdbeUnpackRecord(
76773  KeyInfo *pKeyInfo,
76774  int nKey,
76775  const void *pKey
76776 ){
76777  char *dummy; /* Dummy argument for AllocUnpackedRecord() */
76778  UnpackedRecord *pRet; /* Return value */
76779 
76780  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76781  if( pRet ){
76782  memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76783  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76784  }
76785  return pRet;
76786 }
76787 
76788 /*
76789 ** This function is called from within a pre-update callback to retrieve
76790 ** a field of the row currently being updated or deleted.
76791 */
76792 SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76793  PreUpdate *p = db->pPreUpdate;
76794  int rc = SQLITE_OK;
76795 
76796  /* Test that this call is being made from within an SQLITE_DELETE or
76797  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76798  if( !p || p->op==SQLITE_INSERT ){
76799  rc = SQLITE_MISUSE_BKPT;
76800  goto preupdate_old_out;
76801  }
76802  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76803  rc = SQLITE_RANGE;
76804  goto preupdate_old_out;
76805  }
76806 
76807  /* If the old.* record has not yet been loaded into memory, do so now. */
76808  if( p->pUnpacked==0 ){
76809  u32 nRec;
76810  u8 *aRec;
76811 
76812  nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
76813  aRec = sqlite3DbMallocRaw(db, nRec);
76814  if( !aRec ) goto preupdate_old_out;
76815  rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76816  if( rc==SQLITE_OK ){
76817  p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76818  if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76819  }
76820  if( rc!=SQLITE_OK ){
76821  sqlite3DbFree(db, aRec);
76822  goto preupdate_old_out;
76823  }
76824  p->aRecord = aRec;
76825  }
76826 
76827  if( iIdx>=p->pUnpacked->nField ){
76828  *ppValue = (sqlite3_value *)columnNullValue();
76829  }else{
76830  Mem *pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
76831  *ppValue = &p->pUnpacked->aMem[iIdx];
76832  if( iIdx==p->pTab->iPKey ){
76833  sqlite3VdbeMemSetInt64(pMem, p->iKey1);
76834  }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
76835  if( pMem->flags & MEM_Int ){
76836  sqlite3VdbeMemRealify(pMem);
76837  }
76838  }
76839  }
76840 
76841  preupdate_old_out:
76842  sqlite3Error(db, rc);
76843  return sqlite3ApiExit(db, rc);
76844 }
76845 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76846 
76847 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76848 /*
76849 ** This function is called from within a pre-update callback to retrieve
76850 ** the number of columns in the row being updated, deleted or inserted.
76851 */
76853  PreUpdate *p = db->pPreUpdate;
76854  return (p ? p->keyinfo.nField : 0);
76855 }
76856 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76857 
76858 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76859 /*
76860 ** This function is designed to be called from within a pre-update callback
76861 ** only. It returns zero if the change that caused the callback was made
76862 ** immediately by a user SQL statement. Or, if the change was made by a
76863 ** trigger program, it returns the number of trigger programs currently
76864 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
76865 ** top-level trigger etc.).
76866 **
76867 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76868 ** or SET DEFAULT action is considered a trigger.
76869 */
76871  PreUpdate *p = db->pPreUpdate;
76872  return (p ? p->v->nFrame : 0);
76873 }
76874 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76875 
76876 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76877 /*
76878 ** This function is called from within a pre-update callback to retrieve
76879 ** a field of the row currently being updated or inserted.
76880 */
76881 SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76882  PreUpdate *p = db->pPreUpdate;
76883  int rc = SQLITE_OK;
76884  Mem *pMem;
76885 
76886  if( !p || p->op==SQLITE_DELETE ){
76887  rc = SQLITE_MISUSE_BKPT;
76888  goto preupdate_new_out;
76889  }
76890  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76891  rc = SQLITE_RANGE;
76892  goto preupdate_new_out;
76893  }
76894 
76895  if( p->op==SQLITE_INSERT ){
76896  /* For an INSERT, memory cell p->iNewReg contains the serialized record
76897  ** that is being inserted. Deserialize it. */
76898  UnpackedRecord *pUnpack = p->pNewUnpacked;
76899  if( !pUnpack ){
76900  Mem *pData = &p->v->aMem[p->iNewReg];
76901  rc = ExpandBlob(pData);
76902  if( rc!=SQLITE_OK ) goto preupdate_new_out;
76903  pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76904  if( !pUnpack ){
76905  rc = SQLITE_NOMEM;
76906  goto preupdate_new_out;
76907  }
76908  p->pNewUnpacked = pUnpack;
76909  }
76910  if( iIdx>=pUnpack->nField ){
76911  pMem = (sqlite3_value *)columnNullValue();
76912  }else{
76913  pMem = &pUnpack->aMem[iIdx];
76914  if( iIdx==p->pTab->iPKey ){
76915  sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76916  }
76917  }
76918  }else{
76919  /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76920  ** value. Make a copy of the cell contents and return a pointer to it.
76921  ** It is not safe to return a pointer to the memory cell itself as the
76922  ** caller may modify the value text encoding.
76923  */
76924  assert( p->op==SQLITE_UPDATE );
76925  if( !p->aNew ){
76926  p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76927  if( !p->aNew ){
76928  rc = SQLITE_NOMEM;
76929  goto preupdate_new_out;
76930  }
76931  }
76932  assert( iIdx>=0 && iIdx<p->pCsr->nField );
76933  pMem = &p->aNew[iIdx];
76934  if( pMem->flags==0 ){
76935  if( iIdx==p->pTab->iPKey ){
76936  sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76937  }else{
76938  rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76939  if( rc!=SQLITE_OK ) goto preupdate_new_out;
76940  }
76941  }
76942  }
76943  *ppValue = pMem;
76944 
76945  preupdate_new_out:
76946  sqlite3Error(db, rc);
76947  return sqlite3ApiExit(db, rc);
76948 }
76949 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76950 
76951 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76952 /*
76953 ** Return status data for a single loop within query pStmt.
76954 */
76956  sqlite3_stmt *pStmt, /* Prepared statement being queried */
76957  int idx, /* Index of loop to report on */
76958  int iScanStatusOp, /* Which metric to return */
76959  void *pOut /* OUT: Write the answer here */
76960 ){
76961  Vdbe *p = (Vdbe*)pStmt;
76962  ScanStatus *pScan;
76963  if( idx<0 || idx>=p->nScan ) return 1;
76964  pScan = &p->aScan[idx];
76965  switch( iScanStatusOp ){
76966  case SQLITE_SCANSTAT_NLOOP: {
76967  *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
76968  break;
76969  }
76970  case SQLITE_SCANSTAT_NVISIT: {
76971  *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
76972  break;
76973  }
76974  case SQLITE_SCANSTAT_EST: {
76975  double r = 1.0;
76976  LogEst x = pScan->nEst;
76977  while( x<100 ){
76978  x += 10;
76979  r *= 0.5;
76980  }
76981  *(double*)pOut = r*sqlite3LogEstToInt(x);
76982  break;
76983  }
76984  case SQLITE_SCANSTAT_NAME: {
76985  *(const char**)pOut = pScan->zName;
76986  break;
76987  }
76988  case SQLITE_SCANSTAT_EXPLAIN: {
76989  if( pScan->addrExplain ){
76990  *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
76991  }else{
76992  *(const char**)pOut = 0;
76993  }
76994  break;
76995  }
76996  case SQLITE_SCANSTAT_SELECTID: {
76997  if( pScan->addrExplain ){
76998  *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
76999  }else{
77000  *(int*)pOut = -1;
77001  }
77002  break;
77003  }
77004  default: {
77005  return 1;
77006  }
77007  }
77008  return 0;
77009 }
77010 
77011 /*
77012 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
77013 */
77015  Vdbe *p = (Vdbe*)pStmt;
77016  memset(p->anExec, 0, p->nOp * sizeof(i64));
77017 }
77018 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
77019 
77020 /************** End of vdbeapi.c *********************************************/
77021 /************** Begin file vdbetrace.c ***************************************/
77022 /*
77023 ** 2009 November 25
77024 **
77025 ** The author disclaims copyright to this source code. In place of
77026 ** a legal notice, here is a blessing:
77027 **
77028 ** May you do good and not evil.
77029 ** May you find forgiveness for yourself and forgive others.
77030 ** May you share freely, never taking more than you give.
77031 **
77032 *************************************************************************
77033 **
77034 ** This file contains code used to insert the values of host parameters
77035 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
77036 **
77037 ** The Vdbe parse-tree explainer is also found here.
77038 */
77039 /* #include "sqliteInt.h" */
77040 /* #include "vdbeInt.h" */
77041 
77042 #ifndef SQLITE_OMIT_TRACE
77043 
77044 /*
77045 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
77046 ** bytes in this text up to but excluding the first character in
77047 ** a host parameter. If the text contains no host parameters, return
77048 ** the total number of bytes in the text.
77049 */
77050 static int findNextHostParameter(const char *zSql, int *pnToken){
77051  int tokenType;
77052  int nTotal = 0;
77053  int n;
77054 
77055  *pnToken = 0;
77056  while( zSql[0] ){
77057  n = sqlite3GetToken((u8*)zSql, &tokenType);
77058  assert( n>0 && tokenType!=TK_ILLEGAL );
77059  if( tokenType==TK_VARIABLE ){
77060  *pnToken = n;
77061  break;
77062  }
77063  nTotal += n;
77064  zSql += n;
77065  }
77066  return nTotal;
77067 }
77068 
77069 /*
77070 ** This function returns a pointer to a nul-terminated string in memory
77071 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
77072 ** string contains a copy of zRawSql but with host parameters expanded to
77073 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
77074 ** then the returned string holds a copy of zRawSql with "-- " prepended
77075 ** to each line of text.
77076 **
77077 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
77078 ** then long strings and blobs are truncated to that many bytes. This
77079 ** can be used to prevent unreasonably large trace strings when dealing
77080 ** with large (multi-megabyte) strings and blobs.
77081 **
77082 ** The calling function is responsible for making sure the memory returned
77083 ** is eventually freed.
77084 **
77085 ** ALGORITHM: Scan the input string looking for host parameters in any of
77086 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
77087 ** string literals, quoted identifier names, and comments. For text forms,
77088 ** the host parameter index is found by scanning the prepared
77089 ** statement for the corresponding OP_Variable opcode. Once the host
77090 ** parameter index is known, locate the value in p->aVar[]. Then render
77091 ** the value as a literal in place of the host parameter name.
77092 */
77094  Vdbe *p, /* The prepared statement being evaluated */
77095  const char *zRawSql /* Raw text of the SQL statement */
77096 ){
77097  sqlite3 *db; /* The database connection */
77098  int idx = 0; /* Index of a host parameter */
77099  int nextIndex = 1; /* Index of next ? host parameter */
77100  int n; /* Length of a token prefix */
77101  int nToken; /* Length of the parameter token */
77102  int i; /* Loop counter */
77103  Mem *pVar; /* Value of a host parameter */
77104  StrAccum out; /* Accumulate the output here */
77105 #ifndef SQLITE_OMIT_UTF16
77106  Mem utf8; /* Used to convert UTF16 parameters into UTF8 for display */
77107 #endif
77108  char zBase[100]; /* Initial working space */
77109 
77110  db = p->db;
77111  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
77113  if( db->nVdbeExec>1 ){
77114  while( *zRawSql ){
77115  const char *zStart = zRawSql;
77116  while( *(zRawSql++)!='\n' && *zRawSql );
77117  sqlite3StrAccumAppend(&out, "-- ", 3);
77118  assert( (zRawSql - zStart) > 0 );
77119  sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
77120  }
77121  }else if( p->nVar==0 ){
77122  sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
77123  }else{
77124  while( zRawSql[0] ){
77125  n = findNextHostParameter(zRawSql, &nToken);
77126  assert( n>0 );
77127  sqlite3StrAccumAppend(&out, zRawSql, n);
77128  zRawSql += n;
77129  assert( zRawSql[0] || nToken==0 );
77130  if( nToken==0 ) break;
77131  if( zRawSql[0]=='?' ){
77132  if( nToken>1 ){
77133  assert( sqlite3Isdigit(zRawSql[1]) );
77134  sqlite3GetInt32(&zRawSql[1], &idx);
77135  }else{
77136  idx = nextIndex;
77137  }
77138  }else{
77139  assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
77140  zRawSql[0]=='@' || zRawSql[0]=='#' );
77141  testcase( zRawSql[0]==':' );
77142  testcase( zRawSql[0]=='$' );
77143  testcase( zRawSql[0]=='@' );
77144  testcase( zRawSql[0]=='#' );
77145  idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
77146  assert( idx>0 );
77147  }
77148  zRawSql += nToken;
77149  nextIndex = idx + 1;
77150  assert( idx>0 && idx<=p->nVar );
77151  pVar = &p->aVar[idx-1];
77152  if( pVar->flags & MEM_Null ){
77153  sqlite3StrAccumAppend(&out, "NULL", 4);
77154  }else if( pVar->flags & MEM_Int ){
77155  sqlite3XPrintf(&out, "%lld", pVar->u.i);
77156  }else if( pVar->flags & MEM_Real ){
77157  sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
77158  }else if( pVar->flags & MEM_Str ){
77159  int nOut; /* Number of bytes of the string text to include in output */
77160 #ifndef SQLITE_OMIT_UTF16
77161  u8 enc = ENC(db);
77162  if( enc!=SQLITE_UTF8 ){
77163  memset(&utf8, 0, sizeof(utf8));
77164  utf8.db = db;
77165  sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
77167  out.accError = STRACCUM_NOMEM;
77168  out.nAlloc = 0;
77169  }
77170  pVar = &utf8;
77171  }
77172 #endif
77173  nOut = pVar->n;
77174 #ifdef SQLITE_TRACE_SIZE_LIMIT
77175  if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
77176  nOut = SQLITE_TRACE_SIZE_LIMIT;
77177  while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
77178  }
77179 #endif
77180  sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
77181 #ifdef SQLITE_TRACE_SIZE_LIMIT
77182  if( nOut<pVar->n ){
77183  sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77184  }
77185 #endif
77186 #ifndef SQLITE_OMIT_UTF16
77187  if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
77188 #endif
77189  }else if( pVar->flags & MEM_Zero ){
77190  sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
77191  }else{
77192  int nOut; /* Number of bytes of the blob to include in output */
77193  assert( pVar->flags & MEM_Blob );
77194  sqlite3StrAccumAppend(&out, "x'", 2);
77195  nOut = pVar->n;
77196 #ifdef SQLITE_TRACE_SIZE_LIMIT
77197  if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
77198 #endif
77199  for(i=0; i<nOut; i++){
77200  sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
77201  }
77202  sqlite3StrAccumAppend(&out, "'", 1);
77203 #ifdef SQLITE_TRACE_SIZE_LIMIT
77204  if( nOut<pVar->n ){
77205  sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77206  }
77207 #endif
77208  }
77209  }
77210  }
77211  if( out.accError ) sqlite3StrAccumReset(&out);
77212  return sqlite3StrAccumFinish(&out);
77213 }
77214 
77215 #endif /* #ifndef SQLITE_OMIT_TRACE */
77216 
77217 /************** End of vdbetrace.c *******************************************/
77218 /************** Begin file vdbe.c ********************************************/
77219 /*
77220 ** 2001 September 15
77221 **
77222 ** The author disclaims copyright to this source code. In place of
77223 ** a legal notice, here is a blessing:
77224 **
77225 ** May you do good and not evil.
77226 ** May you find forgiveness for yourself and forgive others.
77227 ** May you share freely, never taking more than you give.
77228 **
77229 *************************************************************************
77230 ** The code in this file implements the function that runs the
77231 ** bytecode of a prepared statement.
77232 **
77233 ** Various scripts scan this source file in order to generate HTML
77234 ** documentation, headers files, or other derived files. The formatting
77235 ** of the code in this file is, therefore, important. See other comments
77236 ** in this file for details. If in doubt, do not deviate from existing
77237 ** commenting and indentation practices when changing or adding code.
77238 */
77239 /* #include "sqliteInt.h" */
77240 /* #include "vdbeInt.h" */
77241 
77242 /*
77243 ** Invoke this macro on memory cells just prior to changing the
77244 ** value of the cell. This macro verifies that shallow copies are
77245 ** not misused. A shallow copy of a string or blob just copies a
77246 ** pointer to the string or blob, not the content. If the original
77247 ** is changed while the copy is still in use, the string or blob might
77248 ** be changed out from under the copy. This macro verifies that nothing
77249 ** like that ever happens.
77250 */
77251 #ifdef SQLITE_DEBUG
77252 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
77253 #else
77254 # define memAboutToChange(P,M)
77255 #endif
77256 
77257 /*
77258 ** The following global variable is incremented every time a cursor
77259 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
77260 ** procedures use this information to make sure that indices are
77261 ** working correctly. This variable has no function other than to
77262 ** help verify the correct operation of the library.
77263 */
77264 #ifdef SQLITE_TEST
77265 SQLITE_API int sqlite3_search_count = 0;
77266 #endif
77267 
77268 /*
77269 ** When this global variable is positive, it gets decremented once before
77270 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
77271 ** field of the sqlite3 structure is set in order to simulate an interrupt.
77272 **
77273 ** This facility is used for testing purposes only. It does not function
77274 ** in an ordinary build.
77275 */
77276 #ifdef SQLITE_TEST
77277 SQLITE_API int sqlite3_interrupt_count = 0;
77278 #endif
77279 
77280 /*
77281 ** The next global variable is incremented each type the OP_Sort opcode
77282 ** is executed. The test procedures use this information to make sure that
77283 ** sorting is occurring or not occurring at appropriate times. This variable
77284 ** has no function other than to help verify the correct operation of the
77285 ** library.
77286 */
77287 #ifdef SQLITE_TEST
77288 SQLITE_API int sqlite3_sort_count = 0;
77289 #endif
77290 
77291 /*
77292 ** The next global variable records the size of the largest MEM_Blob
77293 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
77294 ** use this information to make sure that the zero-blob functionality
77295 ** is working correctly. This variable has no function other than to
77296 ** help verify the correct operation of the library.
77297 */
77298 #ifdef SQLITE_TEST
77299 SQLITE_API int sqlite3_max_blobsize = 0;
77300 static void updateMaxBlobsize(Mem *p){
77301  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
77302  sqlite3_max_blobsize = p->n;
77303  }
77304 }
77305 #endif
77306 
77307 /*
77308 ** This macro evaluates to true if either the update hook or the preupdate
77309 ** hook are enabled for database connect DB.
77310 */
77311 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77312 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
77313 #else
77314 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
77315 #endif
77316 
77317 /*
77318 ** The next global variable is incremented each time the OP_Found opcode
77319 ** is executed. This is used to test whether or not the foreign key
77320 ** operation implemented using OP_FkIsZero is working. This variable
77321 ** has no function other than to help verify the correct operation of the
77322 ** library.
77323 */
77324 #ifdef SQLITE_TEST
77325 SQLITE_API int sqlite3_found_count = 0;
77326 #endif
77327 
77328 /*
77329 ** Test a register to see if it exceeds the current maximum blob size.
77330 ** If it does, record the new maximum blob size.
77331 */
77332 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
77333 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
77334 #else
77335 # define UPDATE_MAX_BLOBSIZE(P)
77336 #endif
77337 
77338 /*
77339 ** Invoke the VDBE coverage callback, if that callback is defined. This
77340 ** feature is used for test suite validation only and does not appear an
77341 ** production builds.
77342 **
77343 ** M is an integer, 2 or 3, that indices how many different ways the
77344 ** branch can go. It is usually 2. "I" is the direction the branch
77345 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
77346 ** second alternative branch is taken.
77347 **
77348 ** iSrcLine is the source code line (from the __LINE__ macro) that
77349 ** generated the VDBE instruction. This instrumentation assumes that all
77350 ** source code is in a single file (the amalgamation). Special values 1
77351 ** and 2 for the iSrcLine parameter mean that this particular branch is
77352 ** always taken or never taken, respectively.
77353 */
77354 #if !defined(SQLITE_VDBE_COVERAGE)
77355 # define VdbeBranchTaken(I,M)
77356 #else
77357 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
77358  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
77359  if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
77360  M = iSrcLine;
77361  /* Assert the truth of VdbeCoverageAlwaysTaken() and
77362  ** VdbeCoverageNeverTaken() */
77363  assert( (M & I)==I );
77364  }else{
77365  if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
77366  sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
77367  iSrcLine,I,M);
77368  }
77369  }
77370 #endif
77371 
77372 /*
77373 ** Convert the given register into a string if it isn't one
77374 ** already. Return non-zero if a malloc() fails.
77375 */
77376 #define Stringify(P, enc) \
77377  if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
77378  { goto no_mem; }
77379 
77380 /*
77381 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
77382 ** a pointer to a dynamically allocated string where some other entity
77383 ** is responsible for deallocating that string. Because the register
77384 ** does not control the string, it might be deleted without the register
77385 ** knowing it.
77386 **
77387 ** This routine converts an ephemeral string into a dynamically allocated
77388 ** string that the register itself controls. In other words, it
77389 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
77390 */
77391 #define Deephemeralize(P) \
77392  if( ((P)->flags&MEM_Ephem)!=0 \
77393  && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
77394 
77395 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
77396 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
77397 
77398 /*
77399 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
77400 ** if we run out of memory.
77401 */
77403  Vdbe *p, /* The virtual machine */
77404  int iCur, /* Index of the new VdbeCursor */
77405  int nField, /* Number of fields in the table or index */
77406  int iDb, /* Database the cursor belongs to, or -1 */
77407  u8 eCurType /* Type of the new cursor */
77408 ){
77409  /* Find the memory cell that will be used to store the blob of memory
77410  ** required for this VdbeCursor structure. It is convenient to use a
77411  ** vdbe memory cell to manage the memory allocation required for a
77412  ** VdbeCursor structure for the following reasons:
77413  **
77414  ** * Sometimes cursor numbers are used for a couple of different
77415  ** purposes in a vdbe program. The different uses might require
77416  ** different sized allocations. Memory cells provide growable
77417  ** allocations.
77418  **
77419  ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
77420  ** be freed lazily via the sqlite3_release_memory() API. This
77421  ** minimizes the number of malloc calls made by the system.
77422  **
77423  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
77424  ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
77425  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
77426  */
77427  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
77428 
77429  int nByte;
77430  VdbeCursor *pCx = 0;
77431  nByte =
77432  ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
77433  (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
77434 
77435  assert( iCur>=0 && iCur<p->nCursor );
77436  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
77437  sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
77438  p->apCsr[iCur] = 0;
77439  }
77440  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
77441  p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
77442  memset(pCx, 0, sizeof(VdbeCursor));
77443  pCx->eCurType = eCurType;
77444  pCx->iDb = iDb;
77445  pCx->nField = nField;
77446  pCx->aOffset = &pCx->aType[nField];
77447  if( eCurType==CURTYPE_BTREE ){
77448  pCx->uc.pCursor = (BtCursor*)
77449  &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
77451  }
77452  }
77453  return pCx;
77454 }
77455 
77456 /*
77457 ** Try to convert a value into a numeric representation if we can
77458 ** do so without loss of information. In other words, if the string
77459 ** looks like a number, convert it into a number. If it does not
77460 ** look like a number, leave it alone.
77461 **
77462 ** If the bTryForInt flag is true, then extra effort is made to give
77463 ** an integer representation. Strings that look like floating point
77464 ** values but which have no fractional component (example: '48.00')
77465 ** will have a MEM_Int representation when bTryForInt is true.
77466 **
77467 ** If bTryForInt is false, then if the input string contains a decimal
77468 ** point or exponential notation, the result is only MEM_Real, even
77469 ** if there is an exact integer representation of the quantity.
77470 */
77471 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
77472  double rValue;
77473  i64 iValue;
77474  u8 enc = pRec->enc;
77475  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
77476  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
77477  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
77478  pRec->u.i = iValue;
77479  pRec->flags |= MEM_Int;
77480  }else{
77481  pRec->u.r = rValue;
77482  pRec->flags |= MEM_Real;
77483  if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
77484  }
77485 }
77486 
77487 /*
77488 ** Processing is determine by the affinity parameter:
77489 **
77490 ** SQLITE_AFF_INTEGER:
77491 ** SQLITE_AFF_REAL:
77492 ** SQLITE_AFF_NUMERIC:
77493 ** Try to convert pRec to an integer representation or a
77494 ** floating-point representation if an integer representation
77495 ** is not possible. Note that the integer representation is
77496 ** always preferred, even if the affinity is REAL, because
77497 ** an integer representation is more space efficient on disk.
77498 **
77499 ** SQLITE_AFF_TEXT:
77500 ** Convert pRec to a text representation.
77501 **
77502 ** SQLITE_AFF_BLOB:
77503 ** No-op. pRec is unchanged.
77504 */
77505 static void applyAffinity(
77506  Mem *pRec, /* The value to apply affinity to */
77507  char affinity, /* The affinity to be applied */
77508  u8 enc /* Use this text encoding */
77509 ){
77510  if( affinity>=SQLITE_AFF_NUMERIC ){
77511  assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
77512  || affinity==SQLITE_AFF_NUMERIC );
77513  if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
77514  if( (pRec->flags & MEM_Real)==0 ){
77515  if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
77516  }else{
77518  }
77519  }
77520  }else if( affinity==SQLITE_AFF_TEXT ){
77521  /* Only attempt the conversion to TEXT if there is an integer or real
77522  ** representation (blob and NULL do not get converted) but no string
77523  ** representation. It would be harmless to repeat the conversion if
77524  ** there is already a string rep, but it is pointless to waste those
77525  ** CPU cycles. */
77526  if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
77527  if( (pRec->flags&(MEM_Real|MEM_Int)) ){
77528  sqlite3VdbeMemStringify(pRec, enc, 1);
77529  }
77530  }
77531  pRec->flags &= ~(MEM_Real|MEM_Int);
77532  }
77533 }
77534 
77535 /*
77536 ** Try to convert the type of a function argument or a result column
77537 ** into a numeric representation. Use either INTEGER or REAL whichever
77538 ** is appropriate. But only do the conversion if it is possible without
77539 ** loss of information and return the revised type of the argument.
77540 */
77542  int eType = sqlite3_value_type(pVal);
77543  if( eType==SQLITE_TEXT ){
77544  Mem *pMem = (Mem*)pVal;
77545  applyNumericAffinity(pMem, 0);
77546  eType = sqlite3_value_type(pVal);
77547  }
77548  return eType;
77549 }
77550 
77551 /*
77552 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
77553 ** not the internal Mem* type.
77554 */
77556  sqlite3_value *pVal,
77557  u8 affinity,
77558  u8 enc
77559 ){
77560  applyAffinity((Mem *)pVal, affinity, enc);
77561 }
77562 
77563 /*
77564 ** pMem currently only holds a string type (or maybe a BLOB that we can
77565 ** interpret as a string if we want to). Compute its corresponding
77566 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
77567 ** accordingly.
77568 */
77570  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
77571  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
77572  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
77573  return 0;
77574  }
77575  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
77576  return MEM_Int;
77577  }
77578  return MEM_Real;
77579 }
77580 
77581 /*
77582 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
77583 ** none.
77584 **
77585 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
77586 ** But it does set pMem->u.r and pMem->u.i appropriately.
77587 */
77588 static u16 numericType(Mem *pMem){
77589  if( pMem->flags & (MEM_Int|MEM_Real) ){
77590  return pMem->flags & (MEM_Int|MEM_Real);
77591  }
77592  if( pMem->flags & (MEM_Str|MEM_Blob) ){
77593  return computeNumericType(pMem);
77594  }
77595  return 0;
77596 }
77597 
77598 #ifdef SQLITE_DEBUG
77599 /*
77600 ** Write a nice string representation of the contents of cell pMem
77601 ** into buffer zBuf, length nBuf.
77602 */
77603 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
77604  char *zCsr = zBuf;
77605  int f = pMem->flags;
77606 
77607  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
77608 
77609  if( f&MEM_Blob ){
77610  int i;
77611  char c;
77612  if( f & MEM_Dyn ){
77613  c = 'z';
77614  assert( (f & (MEM_Static|MEM_Ephem))==0 );
77615  }else if( f & MEM_Static ){
77616  c = 't';
77617  assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77618  }else if( f & MEM_Ephem ){
77619  c = 'e';
77620  assert( (f & (MEM_Static|MEM_Dyn))==0 );
77621  }else{
77622  c = 's';
77623  }
77624 
77625  sqlite3_snprintf(100, zCsr, "%c", c);
77626  zCsr += sqlite3Strlen30(zCsr);
77627  sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
77628  zCsr += sqlite3Strlen30(zCsr);
77629  for(i=0; i<16 && i<pMem->n; i++){
77630  sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
77631  zCsr += sqlite3Strlen30(zCsr);
77632  }
77633  for(i=0; i<16 && i<pMem->n; i++){
77634  char z = pMem->z[i];
77635  if( z<32 || z>126 ) *zCsr++ = '.';
77636  else *zCsr++ = z;
77637  }
77638 
77639  sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
77640  zCsr += sqlite3Strlen30(zCsr);
77641  if( f & MEM_Zero ){
77642  sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
77643  zCsr += sqlite3Strlen30(zCsr);
77644  }
77645  *zCsr = '\0';
77646  }else if( f & MEM_Str ){
77647  int j, k;
77648  zBuf[0] = ' ';
77649  if( f & MEM_Dyn ){
77650  zBuf[1] = 'z';
77651  assert( (f & (MEM_Static|MEM_Ephem))==0 );
77652  }else if( f & MEM_Static ){
77653  zBuf[1] = 't';
77654  assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77655  }else if( f & MEM_Ephem ){
77656  zBuf[1] = 'e';
77657  assert( (f & (MEM_Static|MEM_Dyn))==0 );
77658  }else{
77659  zBuf[1] = 's';
77660  }
77661  k = 2;
77662  sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
77663  k += sqlite3Strlen30(&zBuf[k]);
77664  zBuf[k++] = '[';
77665  for(j=0; j<15 && j<pMem->n; j++){
77666  u8 c = pMem->z[j];
77667  if( c>=0x20 && c<0x7f ){
77668  zBuf[k++] = c;
77669  }else{
77670  zBuf[k++] = '.';
77671  }
77672  }
77673  zBuf[k++] = ']';
77674  sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
77675  k += sqlite3Strlen30(&zBuf[k]);
77676  zBuf[k++] = 0;
77677  }
77678 }
77679 #endif
77680 
77681 #ifdef SQLITE_DEBUG
77682 /*
77683 ** Print the value of a register for tracing purposes:
77684 */
77685 static void memTracePrint(Mem *p){
77686  if( p->flags & MEM_Undefined ){
77687  printf(" undefined");
77688  }else if( p->flags & MEM_Null ){
77689  printf(" NULL");
77690  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
77691  printf(" si:%lld", p->u.i);
77692  }else if( p->flags & MEM_Int ){
77693  printf(" i:%lld", p->u.i);
77694 #ifndef SQLITE_OMIT_FLOATING_POINT
77695  }else if( p->flags & MEM_Real ){
77696  printf(" r:%g", p->u.r);
77697 #endif
77698  }else if( p->flags & MEM_RowSet ){
77699  printf(" (rowset)");
77700  }else{
77701  char zBuf[200];
77702  sqlite3VdbeMemPrettyPrint(p, zBuf);
77703  printf(" %s", zBuf);
77704  }
77705  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
77706 }
77707 static void registerTrace(int iReg, Mem *p){
77708  printf("REG[%d] = ", iReg);
77709  memTracePrint(p);
77710  printf("\n");
77711 }
77712 #endif
77713 
77714 #ifdef SQLITE_DEBUG
77715 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
77716 #else
77717 # define REGISTER_TRACE(R,M)
77718 #endif
77719 
77720 
77721 #ifdef VDBE_PROFILE
77722 
77723 /*
77724 ** hwtime.h contains inline assembler code for implementing
77725 ** high-performance timing routines.
77726 */
77727 /************** Include hwtime.h in the middle of vdbe.c *********************/
77728 /************** Begin file hwtime.h ******************************************/
77729 /*
77730 ** 2008 May 27
77731 **
77732 ** The author disclaims copyright to this source code. In place of
77733 ** a legal notice, here is a blessing:
77734 **
77735 ** May you do good and not evil.
77736 ** May you find forgiveness for yourself and forgive others.
77737 ** May you share freely, never taking more than you give.
77738 **
77739 ******************************************************************************
77740 **
77741 ** This file contains inline asm code for retrieving "high-performance"
77742 ** counters for x86 class CPUs.
77743 */
77744 #ifndef SQLITE_HWTIME_H
77745 #define SQLITE_HWTIME_H
77746 
77747 /*
77748 ** The following routine only works on pentium-class (or newer) processors.
77749 ** It uses the RDTSC opcode to read the cycle count value out of the
77750 ** processor and returns that value. This can be used for high-res
77751 ** profiling.
77752 */
77753 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
77754  (defined(i386) || defined(__i386__) || defined(_M_IX86))
77755 
77756  #if defined(__GNUC__)
77757 
77758  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77759  unsigned int lo, hi;
77760  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
77761  return (sqlite_uint64)hi << 32 | lo;
77762  }
77763 
77764  #elif defined(_MSC_VER)
77765 
77766  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
77767  __asm {
77768  rdtsc
77769  ret ; return value at EDX:EAX
77770  }
77771  }
77772 
77773  #endif
77774 
77775 #elif (defined(__GNUC__) && defined(__x86_64__))
77776 
77777  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77778  unsigned long val;
77779  __asm__ __volatile__ ("rdtsc" : "=A" (val));
77780  return val;
77781  }
77782 
77783 #elif (defined(__GNUC__) && defined(__ppc__))
77784 
77785  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77786  unsigned long long retval;
77787  unsigned long junk;
77788  __asm__ __volatile__ ("\n\
77789  1: mftbu %1\n\
77790  mftb %L0\n\
77791  mftbu %0\n\
77792  cmpw %0,%1\n\
77793  bne 1b"
77794  : "=r" (retval), "=r" (junk));
77795  return retval;
77796  }
77797 
77798 #else
77799 
77800  #error Need implementation of sqlite3Hwtime() for your platform.
77801 
77802  /*
77803  ** To compile without implementing sqlite3Hwtime() for your platform,
77804  ** you can remove the above #error and use the following
77805  ** stub function. You will lose timing support for many
77806  ** of the debugging and testing utilities, but it should at
77807  ** least compile and run.
77808  */
77809 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
77810 
77811 #endif
77812 
77813 #endif /* !defined(SQLITE_HWTIME_H) */
77814 
77815 /************** End of hwtime.h **********************************************/
77816 /************** Continuing where we left off in vdbe.c ***********************/
77817 
77818 #endif
77819 
77820 #ifndef NDEBUG
77821 /*
77822 ** This function is only called from within an assert() expression. It
77823 ** checks that the sqlite3.nTransaction variable is correctly set to
77824 ** the number of non-transaction savepoints currently in the
77825 ** linked list starting at sqlite3.pSavepoint.
77826 **
77827 ** Usage:
77828 **
77829 ** assert( checkSavepointCount(db) );
77830 */
77831 static int checkSavepointCount(sqlite3 *db){
77832  int n = 0;
77833  Savepoint *p;
77834  for(p=db->pSavepoint; p; p=p->pNext) n++;
77835  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
77836  return 1;
77837 }
77838 #endif
77839 
77840 /*
77841 ** Return the register of pOp->p2 after first preparing it to be
77842 ** overwritten with an integer value.
77843 */
77845  sqlite3VdbeMemSetNull(pOut);
77846  pOut->flags = MEM_Int;
77847  return pOut;
77848 }
77849 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
77850  Mem *pOut;
77851  assert( pOp->p2>0 );
77852  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77853  pOut = &p->aMem[pOp->p2];
77854  memAboutToChange(p, pOut);
77855  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
77856  return out2PrereleaseWithClear(pOut);
77857  }else{
77858  pOut->flags = MEM_Int;
77859  return pOut;
77860  }
77861 }
77862 
77863 
77864 /*
77865 ** Execute as much of a VDBE program as we can.
77866 ** This is the core of sqlite3_step().
77867 */
77869  Vdbe *p /* The VDBE */
77870 ){
77871  Op *aOp = p->aOp; /* Copy of p->aOp */
77872  Op *pOp = aOp; /* Current operation */
77873 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77874  Op *pOrigOp; /* Value of pOp at the top of the loop */
77875 #endif
77876 #ifdef SQLITE_DEBUG
77877  int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
77878 #endif
77879  int rc = SQLITE_OK; /* Value to return */
77880  sqlite3 *db = p->db; /* The database */
77881  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
77882  u8 encoding = ENC(db); /* The database encoding */
77883  int iCompare = 0; /* Result of last comparison */
77884  unsigned nVmStep = 0; /* Number of virtual machine steps */
77885 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77886  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
77887 #endif
77888  Mem *aMem = p->aMem; /* Copy of p->aMem */
77889  Mem *pIn1 = 0; /* 1st input operand */
77890  Mem *pIn2 = 0; /* 2nd input operand */
77891  Mem *pIn3 = 0; /* 3rd input operand */
77892  Mem *pOut = 0; /* Output operand */
77893  int *aPermute = 0; /* Permutation of columns for OP_Compare */
77894  i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
77895 #ifdef VDBE_PROFILE
77896  u64 start; /* CPU clock count at start of opcode */
77897 #endif
77898  /*** INSERT STACK UNION HERE ***/
77899 
77900  assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
77901  sqlite3VdbeEnter(p);
77902  if( p->rc==SQLITE_NOMEM ){
77903  /* This happens if a malloc() inside a call to sqlite3_column_text() or
77904  ** sqlite3_column_text16() failed. */
77905  goto no_mem;
77906  }
77907  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
77908  assert( p->bIsReader || p->readOnly!=0 );
77909  p->rc = SQLITE_OK;
77910  p->iCurrentTime = 0;
77911  assert( p->explain==0 );
77912  p->pResultSet = 0;
77913  db->busyHandler.nBusy = 0;
77914  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77916 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77917  if( db->xProgress ){
77918  u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
77919  assert( 0 < db->nProgressOps );
77920  nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
77921  }
77922 #endif
77923 #ifdef SQLITE_DEBUG
77925  if( p->pc==0
77927  ){
77928  int i;
77929  int once = 1;
77930  sqlite3VdbePrintSql(p);
77931  if( p->db->flags & SQLITE_VdbeListing ){
77932  printf("VDBE Program Listing:\n");
77933  for(i=0; i<p->nOp; i++){
77934  sqlite3VdbePrintOp(stdout, i, &aOp[i]);
77935  }
77936  }
77937  if( p->db->flags & SQLITE_VdbeEQP ){
77938  for(i=0; i<p->nOp; i++){
77939  if( aOp[i].opcode==OP_Explain ){
77940  if( once ) printf("VDBE Query Plan:\n");
77941  printf("%s\n", aOp[i].p4.z);
77942  once = 0;
77943  }
77944  }
77945  }
77946  if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
77947  }
77949 #endif
77950  for(pOp=&aOp[p->pc]; 1; pOp++){
77951  /* Errors are detected by individual opcodes, with an immediate
77952  ** jumps to abort_due_to_error. */
77953  assert( rc==SQLITE_OK );
77954 
77955  assert( pOp>=aOp && pOp<&aOp[p->nOp]);
77956 #ifdef VDBE_PROFILE
77957  start = sqlite3Hwtime();
77958 #endif
77959  nVmStep++;
77960 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
77961  if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
77962 #endif
77963 
77964  /* Only allow tracing if SQLITE_DEBUG is defined.
77965  */
77966 #ifdef SQLITE_DEBUG
77967  if( db->flags & SQLITE_VdbeTrace ){
77968  sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
77969  }
77970 #endif
77971 
77972 
77973  /* Check to see if we need to simulate an interrupt. This only happens
77974  ** if we have a special test build.
77975  */
77976 #ifdef SQLITE_TEST
77977  if( sqlite3_interrupt_count>0 ){
77978  sqlite3_interrupt_count--;
77979  if( sqlite3_interrupt_count==0 ){
77980  sqlite3_interrupt(db);
77981  }
77982  }
77983 #endif
77984 
77985  /* Sanity checking on other operands */
77986 #ifdef SQLITE_DEBUG
77987  {
77988  u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
77989  if( (opProperty & OPFLG_IN1)!=0 ){
77990  assert( pOp->p1>0 );
77991  assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
77992  assert( memIsValid(&aMem[pOp->p1]) );
77993  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
77994  REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
77995  }
77996  if( (opProperty & OPFLG_IN2)!=0 ){
77997  assert( pOp->p2>0 );
77998  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77999  assert( memIsValid(&aMem[pOp->p2]) );
78000  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
78001  REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
78002  }
78003  if( (opProperty & OPFLG_IN3)!=0 ){
78004  assert( pOp->p3>0 );
78005  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78006  assert( memIsValid(&aMem[pOp->p3]) );
78007  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
78008  REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
78009  }
78010  if( (opProperty & OPFLG_OUT2)!=0 ){
78011  assert( pOp->p2>0 );
78012  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
78013  memAboutToChange(p, &aMem[pOp->p2]);
78014  }
78015  if( (opProperty & OPFLG_OUT3)!=0 ){
78016  assert( pOp->p3>0 );
78017  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78018  memAboutToChange(p, &aMem[pOp->p3]);
78019  }
78020  }
78021 #endif
78022 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
78023  pOrigOp = pOp;
78024 #endif
78025 
78026  switch( pOp->opcode ){
78027 
78028 /*****************************************************************************
78029 ** What follows is a massive switch statement where each case implements a
78030 ** separate instruction in the virtual machine. If we follow the usual
78031 ** indentation conventions, each case should be indented by 6 spaces. But
78032 ** that is a lot of wasted space on the left margin. So the code within
78033 ** the switch statement will break with convention and be flush-left. Another
78034 ** big comment (similar to this one) will mark the point in the code where
78035 ** we transition back to normal indentation.
78036 **
78037 ** The formatting of each case is important. The makefile for SQLite
78038 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
78039 ** file looking for lines that begin with "case OP_". The opcodes.h files
78040 ** will be filled with #defines that give unique integer values to each
78041 ** opcode and the opcodes.c file is filled with an array of strings where
78042 ** each string is the symbolic name for the corresponding opcode. If the
78043 ** case statement is followed by a comment of the form "/# same as ... #/"
78044 ** that comment is used to determine the particular value of the opcode.
78045 **
78046 ** Other keywords in the comment that follows each case are used to
78047 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
78048 ** Keywords include: in1, in2, in3, out2, out3. See
78049 ** the mkopcodeh.awk script for additional information.
78050 **
78051 ** Documentation about VDBE opcodes is generated by scanning this file
78052 ** for lines of that contain "Opcode:". That line and all subsequent
78053 ** comment lines are used in the generation of the opcode.html documentation
78054 ** file.
78055 **
78056 ** SUMMARY:
78057 **
78058 ** Formatting is important to scripts that scan this file.
78059 ** Do not deviate from the formatting style currently in use.
78060 **
78061 *****************************************************************************/
78062 
78063 /* Opcode: Goto * P2 * * *
78064 **
78065 ** An unconditional jump to address P2.
78066 ** The next instruction executed will be
78067 ** the one at index P2 from the beginning of
78068 ** the program.
78069 **
78070 ** The P1 parameter is not actually used by this opcode. However, it
78071 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
78072 ** that this Goto is the bottom of a loop and that the lines from P2 down
78073 ** to the current line should be indented for EXPLAIN output.
78074 */
78075 case OP_Goto: { /* jump */
78076 jump_to_p2_and_check_for_interrupt:
78077  pOp = &aOp[pOp->p2 - 1];
78078 
78079  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
78080  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
78081  ** completion. Check to see if sqlite3_interrupt() has been called
78082  ** or if the progress callback needs to be invoked.
78083  **
78084  ** This code uses unstructured "goto" statements and does not look clean.
78085  ** But that is not due to sloppy coding habits. The code is written this
78086  ** way for performance, to avoid having to run the interrupt and progress
78087  ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
78088  ** faster according to "valgrind --tool=cachegrind" */
78089 check_for_interrupt:
78090  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
78091 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78092  /* Call the progress callback if it is configured and the required number
78093  ** of VDBE ops have been executed (either since this invocation of
78094  ** sqlite3VdbeExec() or since last time the progress callback was called).
78095  ** If the progress callback returns non-zero, exit the virtual machine with
78096  ** a return code SQLITE_ABORT.
78097  */
78098  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
78099  assert( db->nProgressOps!=0 );
78100  nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
78101  if( db->xProgress(db->pProgressArg) ){
78102  rc = SQLITE_INTERRUPT;
78103  goto abort_due_to_error;
78104  }
78105  }
78106 #endif
78107 
78108  break;
78109 }
78110 
78111 /* Opcode: Gosub P1 P2 * * *
78112 **
78113 ** Write the current address onto register P1
78114 ** and then jump to address P2.
78115 */
78116 case OP_Gosub: { /* jump */
78117  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78118  pIn1 = &aMem[pOp->p1];
78119  assert( VdbeMemDynamic(pIn1)==0 );
78120  memAboutToChange(p, pIn1);
78121  pIn1->flags = MEM_Int;
78122  pIn1->u.i = (int)(pOp-aOp);
78123  REGISTER_TRACE(pOp->p1, pIn1);
78124 
78125  /* Most jump operations do a goto to this spot in order to update
78126  ** the pOp pointer. */
78127 jump_to_p2:
78128  pOp = &aOp[pOp->p2 - 1];
78129  break;
78130 }
78131 
78132 /* Opcode: Return P1 * * * *
78133 **
78134 ** Jump to the next instruction after the address in register P1. After
78135 ** the jump, register P1 becomes undefined.
78136 */
78137 case OP_Return: { /* in1 */
78138  pIn1 = &aMem[pOp->p1];
78139  assert( pIn1->flags==MEM_Int );
78140  pOp = &aOp[pIn1->u.i];
78141  pIn1->flags = MEM_Undefined;
78142  break;
78143 }
78144 
78145 /* Opcode: InitCoroutine P1 P2 P3 * *
78146 **
78147 ** Set up register P1 so that it will Yield to the coroutine
78148 ** located at address P3.
78149 **
78150 ** If P2!=0 then the coroutine implementation immediately follows
78151 ** this opcode. So jump over the coroutine implementation to
78152 ** address P2.
78153 **
78154 ** See also: EndCoroutine
78155 */
78156 case OP_InitCoroutine: { /* jump */
78157  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78158  assert( pOp->p2>=0 && pOp->p2<p->nOp );
78159  assert( pOp->p3>=0 && pOp->p3<p->nOp );
78160  pOut = &aMem[pOp->p1];
78161  assert( !VdbeMemDynamic(pOut) );
78162  pOut->u.i = pOp->p3 - 1;
78163  pOut->flags = MEM_Int;
78164  if( pOp->p2 ) goto jump_to_p2;
78165  break;
78166 }
78167 
78168 /* Opcode: EndCoroutine P1 * * * *
78169 **
78170 ** The instruction at the address in register P1 is a Yield.
78171 ** Jump to the P2 parameter of that Yield.
78172 ** After the jump, register P1 becomes undefined.
78173 **
78174 ** See also: InitCoroutine
78175 */
78176 case OP_EndCoroutine: { /* in1 */
78177  VdbeOp *pCaller;
78178  pIn1 = &aMem[pOp->p1];
78179  assert( pIn1->flags==MEM_Int );
78180  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
78181  pCaller = &aOp[pIn1->u.i];
78182  assert( pCaller->opcode==OP_Yield );
78183  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
78184  pOp = &aOp[pCaller->p2 - 1];
78185  pIn1->flags = MEM_Undefined;
78186  break;
78187 }
78188 
78189 /* Opcode: Yield P1 P2 * * *
78190 **
78191 ** Swap the program counter with the value in register P1. This
78192 ** has the effect of yielding to a coroutine.
78193 **
78194 ** If the coroutine that is launched by this instruction ends with
78195 ** Yield or Return then continue to the next instruction. But if
78196 ** the coroutine launched by this instruction ends with
78197 ** EndCoroutine, then jump to P2 rather than continuing with the
78198 ** next instruction.
78199 **
78200 ** See also: InitCoroutine
78201 */
78202 case OP_Yield: { /* in1, jump */
78203  int pcDest;
78204  pIn1 = &aMem[pOp->p1];
78205  assert( VdbeMemDynamic(pIn1)==0 );
78206  pIn1->flags = MEM_Int;
78207  pcDest = (int)pIn1->u.i;
78208  pIn1->u.i = (int)(pOp - aOp);
78209  REGISTER_TRACE(pOp->p1, pIn1);
78210  pOp = &aOp[pcDest];
78211  break;
78212 }
78213 
78214 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
78215 ** Synopsis: if r[P3]=null halt
78216 **
78217 ** Check the value in register P3. If it is NULL then Halt using
78218 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
78219 ** value in register P3 is not NULL, then this routine is a no-op.
78220 ** The P5 parameter should be 1.
78221 */
78222 case OP_HaltIfNull: { /* in3 */
78223  pIn3 = &aMem[pOp->p3];
78224  if( (pIn3->flags & MEM_Null)==0 ) break;
78225  /* Fall through into OP_Halt */
78226 }
78227 
78228 /* Opcode: Halt P1 P2 * P4 P5
78229 **
78230 ** Exit immediately. All open cursors, etc are closed
78231 ** automatically.
78232 **
78233 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
78234 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
78235 ** For errors, it can be some other value. If P1!=0 then P2 will determine
78236 ** whether or not to rollback the current transaction. Do not rollback
78237 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
78238 ** then back out all changes that have occurred during this execution of the
78239 ** VDBE, but do not rollback the transaction.
78240 **
78241 ** If P4 is not null then it is an error message string.
78242 **
78243 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
78244 **
78245 ** 0: (no change)
78246 ** 1: NOT NULL contraint failed: P4
78247 ** 2: UNIQUE constraint failed: P4
78248 ** 3: CHECK constraint failed: P4
78249 ** 4: FOREIGN KEY constraint failed: P4
78250 **
78251 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
78252 ** omitted.
78253 **
78254 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
78255 ** every program. So a jump past the last instruction of the program
78256 ** is the same as executing Halt.
78257 */
78258 case OP_Halt: {
78259  VdbeFrame *pFrame;
78260  int pcx;
78261 
78262  pcx = (int)(pOp - aOp);
78263  if( pOp->p1==SQLITE_OK && p->pFrame ){
78264  /* Halt the sub-program. Return control to the parent frame. */
78265  pFrame = p->pFrame;
78266  p->pFrame = pFrame->pParent;
78267  p->nFrame--;
78269  pcx = sqlite3VdbeFrameRestore(pFrame);
78270  lastRowid = db->lastRowid;
78271  if( pOp->p2==OE_Ignore ){
78272  /* Instruction pcx is the OP_Program that invoked the sub-program
78273  ** currently being halted. If the p2 instruction of this OP_Halt
78274  ** instruction is set to OE_Ignore, then the sub-program is throwing
78275  ** an IGNORE exception. In this case jump to the address specified
78276  ** as the p2 of the calling OP_Program. */
78277  pcx = p->aOp[pcx].p2-1;
78278  }
78279  aOp = p->aOp;
78280  aMem = p->aMem;
78281  pOp = &aOp[pcx];
78282  break;
78283  }
78284  p->rc = pOp->p1;
78285  p->errorAction = (u8)pOp->p2;
78286  p->pc = pcx;
78287  assert( pOp->p5>=0 && pOp->p5<=4 );
78288  if( p->rc ){
78289  if( pOp->p5 ){
78290  static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
78291  "FOREIGN KEY" };
78292  testcase( pOp->p5==1 );
78293  testcase( pOp->p5==2 );
78294  testcase( pOp->p5==3 );
78295  testcase( pOp->p5==4 );
78296  sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
78297  if( pOp->p4.z ){
78298  p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
78299  }
78300  }else{
78301  sqlite3VdbeError(p, "%s", pOp->p4.z);
78302  }
78303  sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
78304  }
78305  rc = sqlite3VdbeHalt(p);
78306  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
78307  if( rc==SQLITE_BUSY ){
78308  p->rc = SQLITE_BUSY;
78309  }else{
78310  assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
78311  assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
78312  rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
78313  }
78314  goto vdbe_return;
78315 }
78316 
78317 /* Opcode: Integer P1 P2 * * *
78318 ** Synopsis: r[P2]=P1
78319 **
78320 ** The 32-bit integer value P1 is written into register P2.
78321 */
78322 case OP_Integer: { /* out2 */
78323  pOut = out2Prerelease(p, pOp);
78324  pOut->u.i = pOp->p1;
78325  break;
78326 }
78327 
78328 /* Opcode: Int64 * P2 * P4 *
78329 ** Synopsis: r[P2]=P4
78330 **
78331 ** P4 is a pointer to a 64-bit integer value.
78332 ** Write that value into register P2.
78333 */
78334 case OP_Int64: { /* out2 */
78335  pOut = out2Prerelease(p, pOp);
78336  assert( pOp->p4.pI64!=0 );
78337  pOut->u.i = *pOp->p4.pI64;
78338  break;
78339 }
78340 
78341 #ifndef SQLITE_OMIT_FLOATING_POINT
78342 /* Opcode: Real * P2 * P4 *
78343 ** Synopsis: r[P2]=P4
78344 **
78345 ** P4 is a pointer to a 64-bit floating point value.
78346 ** Write that value into register P2.
78347 */
78348 case OP_Real: { /* same as TK_FLOAT, out2 */
78349  pOut = out2Prerelease(p, pOp);
78350  pOut->flags = MEM_Real;
78351  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
78352  pOut->u.r = *pOp->p4.pReal;
78353  break;
78354 }
78355 #endif
78356 
78357 /* Opcode: String8 * P2 * P4 *
78358 ** Synopsis: r[P2]='P4'
78359 **
78360 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
78361 ** into a String opcode before it is executed for the first time. During
78362 ** this transformation, the length of string P4 is computed and stored
78363 ** as the P1 parameter.
78364 */
78365 case OP_String8: { /* same as TK_STRING, out2 */
78366  assert( pOp->p4.z!=0 );
78367  pOut = out2Prerelease(p, pOp);
78368  pOp->opcode = OP_String;
78369  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
78370 
78371 #ifndef SQLITE_OMIT_UTF16
78372  if( encoding!=SQLITE_UTF8 ){
78373  rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
78374  assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
78375  if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
78376  assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
78377  assert( VdbeMemDynamic(pOut)==0 );
78378  pOut->szMalloc = 0;
78379  pOut->flags |= MEM_Static;
78380  if( pOp->p4type==P4_DYNAMIC ){
78381  sqlite3DbFree(db, pOp->p4.z);
78382  }
78383  pOp->p4type = P4_DYNAMIC;
78384  pOp->p4.z = pOut->z;
78385  pOp->p1 = pOut->n;
78386  }
78387  testcase( rc==SQLITE_TOOBIG );
78388 #endif
78389  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78390  goto too_big;
78391  }
78392  assert( rc==SQLITE_OK );
78393  /* Fall through to the next case, OP_String */
78394 }
78395 
78396 /* Opcode: String P1 P2 P3 P4 P5
78397 ** Synopsis: r[P2]='P4' (len=P1)
78398 **
78399 ** The string value P4 of length P1 (bytes) is stored in register P2.
78400 **
78401 ** If P3 is not zero and the content of register P3 is equal to P5, then
78402 ** the datatype of the register P2 is converted to BLOB. The content is
78403 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
78404 ** of a string, as if it had been CAST. In other words:
78405 **
78406 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
78407 */
78408 case OP_String: { /* out2 */
78409  assert( pOp->p4.z!=0 );
78410  pOut = out2Prerelease(p, pOp);
78411  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
78412  pOut->z = pOp->p4.z;
78413  pOut->n = pOp->p1;
78414  pOut->enc = encoding;
78415  UPDATE_MAX_BLOBSIZE(pOut);
78416 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
78417  if( pOp->p3>0 ){
78418  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78419  pIn3 = &aMem[pOp->p3];
78420  assert( pIn3->flags & MEM_Int );
78421  if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
78422  }
78423 #endif
78424  break;
78425 }
78426 
78427 /* Opcode: Null P1 P2 P3 * *
78428 ** Synopsis: r[P2..P3]=NULL
78429 **
78430 ** Write a NULL into registers P2. If P3 greater than P2, then also write
78431 ** NULL into register P3 and every register in between P2 and P3. If P3
78432 ** is less than P2 (typically P3 is zero) then only register P2 is
78433 ** set to NULL.
78434 **
78435 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
78436 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
78437 ** OP_Ne or OP_Eq.
78438 */
78439 case OP_Null: { /* out2 */
78440  int cnt;
78441  u16 nullFlag;
78442  pOut = out2Prerelease(p, pOp);
78443  cnt = pOp->p3-pOp->p2;
78444  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78445  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
78446  pOut->n = 0;
78447  while( cnt>0 ){
78448  pOut++;
78449  memAboutToChange(p, pOut);
78450  sqlite3VdbeMemSetNull(pOut);
78451  pOut->flags = nullFlag;
78452  pOut->n = 0;
78453  cnt--;
78454  }
78455  break;
78456 }
78457 
78458 /* Opcode: SoftNull P1 * * * *
78459 ** Synopsis: r[P1]=NULL
78460 **
78461 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
78462 ** instruction, but do not free any string or blob memory associated with
78463 ** the register, so that if the value was a string or blob that was
78464 ** previously copied using OP_SCopy, the copies will continue to be valid.
78465 */
78466 case OP_SoftNull: {
78467  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78468  pOut = &aMem[pOp->p1];
78469  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
78470  break;
78471 }
78472 
78473 /* Opcode: Blob P1 P2 * P4 *
78474 ** Synopsis: r[P2]=P4 (len=P1)
78475 **
78476 ** P4 points to a blob of data P1 bytes long. Store this
78477 ** blob in register P2.
78478 */
78479 case OP_Blob: { /* out2 */
78480  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
78481  pOut = out2Prerelease(p, pOp);
78482  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
78483  pOut->enc = encoding;
78484  UPDATE_MAX_BLOBSIZE(pOut);
78485  break;
78486 }
78487 
78488 /* Opcode: Variable P1 P2 * P4 *
78489 ** Synopsis: r[P2]=parameter(P1,P4)
78490 **
78491 ** Transfer the values of bound parameter P1 into register P2
78492 **
78493 ** If the parameter is named, then its name appears in P4.
78494 ** The P4 value is used by sqlite3_bind_parameter_name().
78495 */
78496 case OP_Variable: { /* out2 */
78497  Mem *pVar; /* Value being transferred */
78498 
78499  assert( pOp->p1>0 && pOp->p1<=p->nVar );
78500  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
78501  pVar = &p->aVar[pOp->p1 - 1];
78502  if( sqlite3VdbeMemTooBig(pVar) ){
78503  goto too_big;
78504  }
78505  pOut = out2Prerelease(p, pOp);
78507  UPDATE_MAX_BLOBSIZE(pOut);
78508  break;
78509 }
78510 
78511 /* Opcode: Move P1 P2 P3 * *
78512 ** Synopsis: r[P2@P3]=r[P1@P3]
78513 **
78514 ** Move the P3 values in register P1..P1+P3-1 over into
78515 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
78516 ** left holding a NULL. It is an error for register ranges
78517 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
78518 ** for P3 to be less than 1.
78519 */
78520 case OP_Move: {
78521  int n; /* Number of registers left to copy */
78522  int p1; /* Register to copy from */
78523  int p2; /* Register to copy to */
78524 
78525  n = pOp->p3;
78526  p1 = pOp->p1;
78527  p2 = pOp->p2;
78528  assert( n>0 && p1>0 && p2>0 );
78529  assert( p1+n<=p2 || p2+n<=p1 );
78530 
78531  pIn1 = &aMem[p1];
78532  pOut = &aMem[p2];
78533  do{
78534  assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
78535  assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
78536  assert( memIsValid(pIn1) );
78537  memAboutToChange(p, pOut);
78538  sqlite3VdbeMemMove(pOut, pIn1);
78539 #ifdef SQLITE_DEBUG
78540  if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
78541  pOut->pScopyFrom += pOp->p2 - p1;
78542  }
78543 #endif
78544  Deephemeralize(pOut);
78545  REGISTER_TRACE(p2++, pOut);
78546  pIn1++;
78547  pOut++;
78548  }while( --n );
78549  break;
78550 }
78551 
78552 /* Opcode: Copy P1 P2 P3 * *
78553 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
78554 **
78555 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
78556 **
78557 ** This instruction makes a deep copy of the value. A duplicate
78558 ** is made of any string or blob constant. See also OP_SCopy.
78559 */
78560 case OP_Copy: {
78561  int n;
78562 
78563  n = pOp->p3;
78564  pIn1 = &aMem[pOp->p1];
78565  pOut = &aMem[pOp->p2];
78566  assert( pOut!=pIn1 );
78567  while( 1 ){
78568  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78569  Deephemeralize(pOut);
78570 #ifdef SQLITE_DEBUG
78571  pOut->pScopyFrom = 0;
78572 #endif
78573  REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
78574  if( (n--)==0 ) break;
78575  pOut++;
78576  pIn1++;
78577  }
78578  break;
78579 }
78580 
78581 /* Opcode: SCopy P1 P2 * * *
78582 ** Synopsis: r[P2]=r[P1]
78583 **
78584 ** Make a shallow copy of register P1 into register P2.
78585 **
78586 ** This instruction makes a shallow copy of the value. If the value
78587 ** is a string or blob, then the copy is only a pointer to the
78588 ** original and hence if the original changes so will the copy.
78589 ** Worse, if the original is deallocated, the copy becomes invalid.
78590 ** Thus the program must guarantee that the original will not change
78591 ** during the lifetime of the copy. Use OP_Copy to make a complete
78592 ** copy.
78593 */
78594 case OP_SCopy: { /* out2 */
78595  pIn1 = &aMem[pOp->p1];
78596  pOut = &aMem[pOp->p2];
78597  assert( pOut!=pIn1 );
78598  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78599 #ifdef SQLITE_DEBUG
78600  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
78601 #endif
78602  break;
78603 }
78604 
78605 /* Opcode: IntCopy P1 P2 * * *
78606 ** Synopsis: r[P2]=r[P1]
78607 **
78608 ** Transfer the integer value held in register P1 into register P2.
78609 **
78610 ** This is an optimized version of SCopy that works only for integer
78611 ** values.
78612 */
78613 case OP_IntCopy: { /* out2 */
78614  pIn1 = &aMem[pOp->p1];
78615  assert( (pIn1->flags & MEM_Int)!=0 );
78616  pOut = &aMem[pOp->p2];
78617  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
78618  break;
78619 }
78620 
78621 /* Opcode: ResultRow P1 P2 * * *
78622 ** Synopsis: output=r[P1@P2]
78623 **
78624 ** The registers P1 through P1+P2-1 contain a single row of
78625 ** results. This opcode causes the sqlite3_step() call to terminate
78626 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
78627 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
78628 ** the result row.
78629 */
78630 case OP_ResultRow: {
78631  Mem *pMem;
78632  int i;
78633  assert( p->nResColumn==pOp->p2 );
78634  assert( pOp->p1>0 );
78635  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
78636 
78637 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78638  /* Run the progress counter just before returning.
78639  */
78640  if( db->xProgress!=0
78641  && nVmStep>=nProgressLimit
78642  && db->xProgress(db->pProgressArg)!=0
78643  ){
78644  rc = SQLITE_INTERRUPT;
78645  goto abort_due_to_error;
78646  }
78647 #endif
78648 
78649  /* If this statement has violated immediate foreign key constraints, do
78650  ** not return the number of rows modified. And do not RELEASE the statement
78651  ** transaction. It needs to be rolled back. */
78652  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
78653  assert( db->flags&SQLITE_CountRows );
78654  assert( p->usesStmtJournal );
78655  goto abort_due_to_error;
78656  }
78657 
78658  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
78659  ** DML statements invoke this opcode to return the number of rows
78660  ** modified to the user. This is the only way that a VM that
78661  ** opens a statement transaction may invoke this opcode.
78662  **
78663  ** In case this is such a statement, close any statement transaction
78664  ** opened by this VM before returning control to the user. This is to
78665  ** ensure that statement-transactions are always nested, not overlapping.
78666  ** If the open statement-transaction is not closed here, then the user
78667  ** may step another VM that opens its own statement transaction. This
78668  ** may lead to overlapping statement transactions.
78669  **
78670  ** The statement transaction is never a top-level transaction. Hence
78671  ** the RELEASE call below can never fail.
78672  */
78673  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
78675  assert( rc==SQLITE_OK );
78676 
78677  /* Invalidate all ephemeral cursor row caches */
78678  p->cacheCtr = (p->cacheCtr + 2)|1;
78679 
78680  /* Make sure the results of the current row are \000 terminated
78681  ** and have an assigned type. The results are de-ephemeralized as
78682  ** a side effect.
78683  */
78684  pMem = p->pResultSet = &aMem[pOp->p1];
78685  for(i=0; i<pOp->p2; i++){
78686  assert( memIsValid(&pMem[i]) );
78687  Deephemeralize(&pMem[i]);
78688  assert( (pMem[i].flags & MEM_Ephem)==0
78689  || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
78690  sqlite3VdbeMemNulTerminate(&pMem[i]);
78691  REGISTER_TRACE(pOp->p1+i, &pMem[i]);
78692  }
78693  if( db->mallocFailed ) goto no_mem;
78694 
78695  if( db->mTrace & SQLITE_TRACE_ROW ){
78696  db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
78697  }
78698 
78699  /* Return SQLITE_ROW
78700  */
78701  p->pc = (int)(pOp - aOp) + 1;
78702  rc = SQLITE_ROW;
78703  goto vdbe_return;
78704 }
78705 
78706 /* Opcode: Concat P1 P2 P3 * *
78707 ** Synopsis: r[P3]=r[P2]+r[P1]
78708 **
78709 ** Add the text in register P1 onto the end of the text in
78710 ** register P2 and store the result in register P3.
78711 ** If either the P1 or P2 text are NULL then store NULL in P3.
78712 **
78713 ** P3 = P2 || P1
78714 **
78715 ** It is illegal for P1 and P3 to be the same register. Sometimes,
78716 ** if P3 is the same register as P2, the implementation is able
78717 ** to avoid a memcpy().
78718 */
78719 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
78720  i64 nByte;
78721 
78722  pIn1 = &aMem[pOp->p1];
78723  pIn2 = &aMem[pOp->p2];
78724  pOut = &aMem[pOp->p3];
78725  assert( pIn1!=pOut );
78726  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78727  sqlite3VdbeMemSetNull(pOut);
78728  break;
78729  }
78730  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
78731  Stringify(pIn1, encoding);
78732  Stringify(pIn2, encoding);
78733  nByte = pIn1->n + pIn2->n;
78734  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78735  goto too_big;
78736  }
78737  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
78738  goto no_mem;
78739  }
78740  MemSetTypeFlag(pOut, MEM_Str);
78741  if( pOut!=pIn2 ){
78742  memcpy(pOut->z, pIn2->z, pIn2->n);
78743  }
78744  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
78745  pOut->z[nByte]=0;
78746  pOut->z[nByte+1] = 0;
78747  pOut->flags |= MEM_Term;
78748  pOut->n = (int)nByte;
78749  pOut->enc = encoding;
78750  UPDATE_MAX_BLOBSIZE(pOut);
78751  break;
78752 }
78753 
78754 /* Opcode: Add P1 P2 P3 * *
78755 ** Synopsis: r[P3]=r[P1]+r[P2]
78756 **
78757 ** Add the value in register P1 to the value in register P2
78758 ** and store the result in register P3.
78759 ** If either input is NULL, the result is NULL.
78760 */
78761 /* Opcode: Multiply P1 P2 P3 * *
78762 ** Synopsis: r[P3]=r[P1]*r[P2]
78763 **
78764 **
78765 ** Multiply the value in register P1 by the value in register P2
78766 ** and store the result in register P3.
78767 ** If either input is NULL, the result is NULL.
78768 */
78769 /* Opcode: Subtract P1 P2 P3 * *
78770 ** Synopsis: r[P3]=r[P2]-r[P1]
78771 **
78772 ** Subtract the value in register P1 from the value in register P2
78773 ** and store the result in register P3.
78774 ** If either input is NULL, the result is NULL.
78775 */
78776 /* Opcode: Divide P1 P2 P3 * *
78777 ** Synopsis: r[P3]=r[P2]/r[P1]
78778 **
78779 ** Divide the value in register P1 by the value in register P2
78780 ** and store the result in register P3 (P3=P2/P1). If the value in
78781 ** register P1 is zero, then the result is NULL. If either input is
78782 ** NULL, the result is NULL.
78783 */
78784 /* Opcode: Remainder P1 P2 P3 * *
78785 ** Synopsis: r[P3]=r[P2]%r[P1]
78786 **
78787 ** Compute the remainder after integer register P2 is divided by
78788 ** register P1 and store the result in register P3.
78789 ** If the value in register P1 is zero the result is NULL.
78790 ** If either operand is NULL, the result is NULL.
78791 */
78792 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
78793 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
78794 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
78795 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
78796 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
78797  char bIntint; /* Started out as two integer operands */
78798  u16 flags; /* Combined MEM_* flags from both inputs */
78799  u16 type1; /* Numeric type of left operand */
78800  u16 type2; /* Numeric type of right operand */
78801  i64 iA; /* Integer value of left operand */
78802  i64 iB; /* Integer value of right operand */
78803  double rA; /* Real value of left operand */
78804  double rB; /* Real value of right operand */
78805 
78806  pIn1 = &aMem[pOp->p1];
78807  type1 = numericType(pIn1);
78808  pIn2 = &aMem[pOp->p2];
78809  type2 = numericType(pIn2);
78810  pOut = &aMem[pOp->p3];
78811  flags = pIn1->flags | pIn2->flags;
78812  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
78813  if( (type1 & type2 & MEM_Int)!=0 ){
78814  iA = pIn1->u.i;
78815  iB = pIn2->u.i;
78816  bIntint = 1;
78817  switch( pOp->opcode ){
78818  case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
78819  case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
78820  case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
78821  case OP_Divide: {
78822  if( iA==0 ) goto arithmetic_result_is_null;
78823  if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
78824  iB /= iA;
78825  break;
78826  }
78827  default: {
78828  if( iA==0 ) goto arithmetic_result_is_null;
78829  if( iA==-1 ) iA = 1;
78830  iB %= iA;
78831  break;
78832  }
78833  }
78834  pOut->u.i = iB;
78835  MemSetTypeFlag(pOut, MEM_Int);
78836  }else{
78837  bIntint = 0;
78838 fp_math:
78839  rA = sqlite3VdbeRealValue(pIn1);
78840  rB = sqlite3VdbeRealValue(pIn2);
78841  switch( pOp->opcode ){
78842  case OP_Add: rB += rA; break;
78843  case OP_Subtract: rB -= rA; break;
78844  case OP_Multiply: rB *= rA; break;
78845  case OP_Divide: {
78846  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78847  if( rA==(double)0 ) goto arithmetic_result_is_null;
78848  rB /= rA;
78849  break;
78850  }
78851  default: {
78852  iA = (i64)rA;
78853  iB = (i64)rB;
78854  if( iA==0 ) goto arithmetic_result_is_null;
78855  if( iA==-1 ) iA = 1;
78856  rB = (double)(iB % iA);
78857  break;
78858  }
78859  }
78860 #ifdef SQLITE_OMIT_FLOATING_POINT
78861  pOut->u.i = rB;
78862  MemSetTypeFlag(pOut, MEM_Int);
78863 #else
78864  if( sqlite3IsNaN(rB) ){
78865  goto arithmetic_result_is_null;
78866  }
78867  pOut->u.r = rB;
78868  MemSetTypeFlag(pOut, MEM_Real);
78869  if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
78871  }
78872 #endif
78873  }
78874  break;
78875 
78876 arithmetic_result_is_null:
78877  sqlite3VdbeMemSetNull(pOut);
78878  break;
78879 }
78880 
78881 /* Opcode: CollSeq P1 * * P4
78882 **
78883 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
78884 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
78885 ** be returned. This is used by the built-in min(), max() and nullif()
78886 ** functions.
78887 **
78888 ** If P1 is not zero, then it is a register that a subsequent min() or
78889 ** max() aggregate will set to 1 if the current row is not the minimum or
78890 ** maximum. The P1 register is initialized to 0 by this instruction.
78891 **
78892 ** The interface used by the implementation of the aforementioned functions
78893 ** to retrieve the collation sequence set by this opcode is not available
78894 ** publicly. Only built-in functions have access to this feature.
78895 */
78896 case OP_CollSeq: {
78897  assert( pOp->p4type==P4_COLLSEQ );
78898  if( pOp->p1 ){
78899  sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
78900  }
78901  break;
78902 }
78903 
78904 /* Opcode: Function0 P1 P2 P3 P4 P5
78905 ** Synopsis: r[P3]=func(r[P2@P5])
78906 **
78907 ** Invoke a user function (P4 is a pointer to a FuncDef object that
78908 ** defines the function) with P5 arguments taken from register P2 and
78909 ** successors. The result of the function is stored in register P3.
78910 ** Register P3 must not be one of the function inputs.
78911 **
78912 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
78913 ** function was determined to be constant at compile time. If the first
78914 ** argument was constant then bit 0 of P1 is set. This is used to determine
78915 ** whether meta data associated with a user function argument using the
78916 ** sqlite3_set_auxdata() API may be safely retained until the next
78917 ** invocation of this opcode.
78918 **
78919 ** See also: Function, AggStep, AggFinal
78920 */
78921 /* Opcode: Function P1 P2 P3 P4 P5
78922 ** Synopsis: r[P3]=func(r[P2@P5])
78923 **
78924 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
78925 ** contains a pointer to the function to be run) with P5 arguments taken
78926 ** from register P2 and successors. The result of the function is stored
78927 ** in register P3. Register P3 must not be one of the function inputs.
78928 **
78929 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
78930 ** function was determined to be constant at compile time. If the first
78931 ** argument was constant then bit 0 of P1 is set. This is used to determine
78932 ** whether meta data associated with a user function argument using the
78933 ** sqlite3_set_auxdata() API may be safely retained until the next
78934 ** invocation of this opcode.
78935 **
78936 ** SQL functions are initially coded as OP_Function0 with P4 pointing
78937 ** to a FuncDef object. But on first evaluation, the P4 operand is
78938 ** automatically converted into an sqlite3_context object and the operation
78939 ** changed to this OP_Function opcode. In this way, the initialization of
78940 ** the sqlite3_context object occurs only once, rather than once for each
78941 ** evaluation of the function.
78942 **
78943 ** See also: Function0, AggStep, AggFinal
78944 */
78945 case OP_Function0: {
78946  int n;
78947  sqlite3_context *pCtx;
78948 
78949  assert( pOp->p4type==P4_FUNCDEF );
78950  n = pOp->p5;
78951  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
78952  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
78953  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78954  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78955  if( pCtx==0 ) goto no_mem;
78956  pCtx->pOut = 0;
78957  pCtx->pFunc = pOp->p4.pFunc;
78958  pCtx->iOp = (int)(pOp - aOp);
78959  pCtx->pVdbe = p;
78960  pCtx->argc = n;
78961  pOp->p4type = P4_FUNCCTX;
78962  pOp->p4.pCtx = pCtx;
78963  pOp->opcode = OP_Function;
78964  /* Fall through into OP_Function */
78965 }
78966 case OP_Function: {
78967  int i;
78968  sqlite3_context *pCtx;
78969 
78970  assert( pOp->p4type==P4_FUNCCTX );
78971  pCtx = pOp->p4.pCtx;
78972 
78973  /* If this function is inside of a trigger, the register array in aMem[]
78974  ** might change from one evaluation to the next. The next block of code
78975  ** checks to see if the register array has changed, and if so it
78976  ** reinitializes the relavant parts of the sqlite3_context object */
78977  pOut = &aMem[pOp->p3];
78978  if( pCtx->pOut != pOut ){
78979  pCtx->pOut = pOut;
78980  for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
78981  }
78982 
78983  memAboutToChange(p, pCtx->pOut);
78984 #ifdef SQLITE_DEBUG
78985  for(i=0; i<pCtx->argc; i++){
78986  assert( memIsValid(pCtx->argv[i]) );
78987  REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
78988  }
78989 #endif
78990  MemSetTypeFlag(pCtx->pOut, MEM_Null);
78991  pCtx->fErrorOrAux = 0;
78992  db->lastRowid = lastRowid;
78993  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
78994  lastRowid = db->lastRowid; /* Remember rowid changes made by xSFunc */
78995 
78996  /* If the function returned an error, throw an exception */
78997  if( pCtx->fErrorOrAux ){
78998  if( pCtx->isError ){
78999  sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
79000  rc = pCtx->isError;
79001  }
79002  sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
79003  if( rc ) goto abort_due_to_error;
79004  }
79005 
79006  /* Copy the result of the function into register P3 */
79007  if( pOut->flags & (MEM_Str|MEM_Blob) ){
79008  sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
79009  if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
79010  }
79011 
79012  REGISTER_TRACE(pOp->p3, pCtx->pOut);
79013  UPDATE_MAX_BLOBSIZE(pCtx->pOut);
79014  break;
79015 }
79016 
79017 /* Opcode: BitAnd P1 P2 P3 * *
79018 ** Synopsis: r[P3]=r[P1]&r[P2]
79019 **
79020 ** Take the bit-wise AND of the values in register P1 and P2 and
79021 ** store the result in register P3.
79022 ** If either input is NULL, the result is NULL.
79023 */
79024 /* Opcode: BitOr P1 P2 P3 * *
79025 ** Synopsis: r[P3]=r[P1]|r[P2]
79026 **
79027 ** Take the bit-wise OR of the values in register P1 and P2 and
79028 ** store the result in register P3.
79029 ** If either input is NULL, the result is NULL.
79030 */
79031 /* Opcode: ShiftLeft P1 P2 P3 * *
79032 ** Synopsis: r[P3]=r[P2]<<r[P1]
79033 **
79034 ** Shift the integer value in register P2 to the left by the
79035 ** number of bits specified by the integer in register P1.
79036 ** Store the result in register P3.
79037 ** If either input is NULL, the result is NULL.
79038 */
79039 /* Opcode: ShiftRight P1 P2 P3 * *
79040 ** Synopsis: r[P3]=r[P2]>>r[P1]
79041 **
79042 ** Shift the integer value in register P2 to the right by the
79043 ** number of bits specified by the integer in register P1.
79044 ** Store the result in register P3.
79045 ** If either input is NULL, the result is NULL.
79046 */
79047 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
79048 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
79049 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
79050 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
79051  i64 iA;
79052  u64 uA;
79053  i64 iB;
79054  u8 op;
79055 
79056  pIn1 = &aMem[pOp->p1];
79057  pIn2 = &aMem[pOp->p2];
79058  pOut = &aMem[pOp->p3];
79059  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
79060  sqlite3VdbeMemSetNull(pOut);
79061  break;
79062  }
79063  iA = sqlite3VdbeIntValue(pIn2);
79064  iB = sqlite3VdbeIntValue(pIn1);
79065  op = pOp->opcode;
79066  if( op==OP_BitAnd ){
79067  iA &= iB;
79068  }else if( op==OP_BitOr ){
79069  iA |= iB;
79070  }else if( iB!=0 ){
79071  assert( op==OP_ShiftRight || op==OP_ShiftLeft );
79072 
79073  /* If shifting by a negative amount, shift in the other direction */
79074  if( iB<0 ){
79075  assert( OP_ShiftRight==OP_ShiftLeft+1 );
79076  op = 2*OP_ShiftLeft + 1 - op;
79077  iB = iB>(-64) ? -iB : 64;
79078  }
79079 
79080  if( iB>=64 ){
79081  iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
79082  }else{
79083  memcpy(&uA, &iA, sizeof(uA));
79084  if( op==OP_ShiftLeft ){
79085  uA <<= iB;
79086  }else{
79087  uA >>= iB;
79088  /* Sign-extend on a right shift of a negative number */
79089  if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
79090  }
79091  memcpy(&iA, &uA, sizeof(iA));
79092  }
79093  }
79094  pOut->u.i = iA;
79095  MemSetTypeFlag(pOut, MEM_Int);
79096  break;
79097 }
79098 
79099 /* Opcode: AddImm P1 P2 * * *
79100 ** Synopsis: r[P1]=r[P1]+P2
79101 **
79102 ** Add the constant P2 to the value in register P1.
79103 ** The result is always an integer.
79104 **
79105 ** To force any register to be an integer, just add 0.
79106 */
79107 case OP_AddImm: { /* in1 */
79108  pIn1 = &aMem[pOp->p1];
79109  memAboutToChange(p, pIn1);
79111  pIn1->u.i += pOp->p2;
79112  break;
79113 }
79114 
79115 /* Opcode: MustBeInt P1 P2 * * *
79116 **
79117 ** Force the value in register P1 to be an integer. If the value
79118 ** in P1 is not an integer and cannot be converted into an integer
79119 ** without data loss, then jump immediately to P2, or if P2==0
79120 ** raise an SQLITE_MISMATCH exception.
79121 */
79122 case OP_MustBeInt: { /* jump, in1 */
79123  pIn1 = &aMem[pOp->p1];
79124  if( (pIn1->flags & MEM_Int)==0 ){
79125  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
79126  VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
79127  if( (pIn1->flags & MEM_Int)==0 ){
79128  if( pOp->p2==0 ){
79129  rc = SQLITE_MISMATCH;
79130  goto abort_due_to_error;
79131  }else{
79132  goto jump_to_p2;
79133  }
79134  }
79135  }
79136  MemSetTypeFlag(pIn1, MEM_Int);
79137  break;
79138 }
79139 
79140 #ifndef SQLITE_OMIT_FLOATING_POINT
79141 /* Opcode: RealAffinity P1 * * * *
79142 **
79143 ** If register P1 holds an integer convert it to a real value.
79144 **
79145 ** This opcode is used when extracting information from a column that
79146 ** has REAL affinity. Such column values may still be stored as
79147 ** integers, for space efficiency, but after extraction we want them
79148 ** to have only a real value.
79149 */
79150 case OP_RealAffinity: { /* in1 */
79151  pIn1 = &aMem[pOp->p1];
79152  if( pIn1->flags & MEM_Int ){
79153  sqlite3VdbeMemRealify(pIn1);
79154  }
79155  break;
79156 }
79157 #endif
79158 
79159 #ifndef SQLITE_OMIT_CAST
79160 /* Opcode: Cast P1 P2 * * *
79161 ** Synopsis: affinity(r[P1])
79162 **
79163 ** Force the value in register P1 to be the type defined by P2.
79164 **
79165 ** <ul>
79166 ** <li value="97"> TEXT
79167 ** <li value="98"> BLOB
79168 ** <li value="99"> NUMERIC
79169 ** <li value="100"> INTEGER
79170 ** <li value="101"> REAL
79171 ** </ul>
79172 **
79173 ** A NULL value is not changed by this routine. It remains NULL.
79174 */
79175 case OP_Cast: { /* in1 */
79176  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
79177  testcase( pOp->p2==SQLITE_AFF_TEXT );
79178  testcase( pOp->p2==SQLITE_AFF_BLOB );
79179  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
79180  testcase( pOp->p2==SQLITE_AFF_INTEGER );
79181  testcase( pOp->p2==SQLITE_AFF_REAL );
79182  pIn1 = &aMem[pOp->p1];
79183  memAboutToChange(p, pIn1);
79184  rc = ExpandBlob(pIn1);
79185  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
79186  UPDATE_MAX_BLOBSIZE(pIn1);
79187  if( rc ) goto abort_due_to_error;
79188  break;
79189 }
79190 #endif /* SQLITE_OMIT_CAST */
79191 
79192 /* Opcode: Eq P1 P2 P3 P4 P5
79193 ** Synopsis: IF r[P3]==r[P1]
79194 **
79195 ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
79196 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
79197 ** store the result of comparison in register P2.
79198 **
79199 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
79200 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
79201 ** to coerce both inputs according to this affinity before the
79202 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
79203 ** affinity is used. Note that the affinity conversions are stored
79204 ** back into the input registers P1 and P3. So this opcode can cause
79205 ** persistent changes to registers P1 and P3.
79206 **
79207 ** Once any conversions have taken place, and neither value is NULL,
79208 ** the values are compared. If both values are blobs then memcmp() is
79209 ** used to determine the results of the comparison. If both values
79210 ** are text, then the appropriate collating function specified in
79211 ** P4 is used to do the comparison. If P4 is not specified then
79212 ** memcmp() is used to compare text string. If both values are
79213 ** numeric, then a numeric comparison is used. If the two values
79214 ** are of different types, then numbers are considered less than
79215 ** strings and strings are considered less than blobs.
79216 **
79217 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79218 ** true or false and is never NULL. If both operands are NULL then the result
79219 ** of comparison is true. If either operand is NULL then the result is false.
79220 ** If neither operand is NULL the result is the same as it would be if
79221 ** the SQLITE_NULLEQ flag were omitted from P5.
79222 **
79223 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
79224 ** content of r[P2] is only changed if the new value is NULL or 0 (false).
79225 ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
79226 */
79227 /* Opcode: Ne P1 P2 P3 P4 P5
79228 ** Synopsis: IF r[P3]!=r[P1]
79229 **
79230 ** This works just like the Eq opcode except that the jump is taken if
79231 ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
79232 ** additional information.
79233 **
79234 ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
79235 ** content of r[P2] is only changed if the new value is NULL or 1 (true).
79236 ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
79237 */
79238 /* Opcode: Lt P1 P2 P3 P4 P5
79239 ** Synopsis: IF r[P3]<r[P1]
79240 **
79241 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
79242 ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
79243 ** the result of comparison (0 or 1 or NULL) into register P2.
79244 **
79245 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
79246 ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
79247 ** bit is clear then fall through if either operand is NULL.
79248 **
79249 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
79250 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
79251 ** to coerce both inputs according to this affinity before the
79252 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
79253 ** affinity is used. Note that the affinity conversions are stored
79254 ** back into the input registers P1 and P3. So this opcode can cause
79255 ** persistent changes to registers P1 and P3.
79256 **
79257 ** Once any conversions have taken place, and neither value is NULL,
79258 ** the values are compared. If both values are blobs then memcmp() is
79259 ** used to determine the results of the comparison. If both values
79260 ** are text, then the appropriate collating function specified in
79261 ** P4 is used to do the comparison. If P4 is not specified then
79262 ** memcmp() is used to compare text string. If both values are
79263 ** numeric, then a numeric comparison is used. If the two values
79264 ** are of different types, then numbers are considered less than
79265 ** strings and strings are considered less than blobs.
79266 */
79267 /* Opcode: Le P1 P2 P3 P4 P5
79268 ** Synopsis: IF r[P3]<=r[P1]
79269 **
79270 ** This works just like the Lt opcode except that the jump is taken if
79271 ** the content of register P3 is less than or equal to the content of
79272 ** register P1. See the Lt opcode for additional information.
79273 */
79274 /* Opcode: Gt P1 P2 P3 P4 P5
79275 ** Synopsis: IF r[P3]>r[P1]
79276 **
79277 ** This works just like the Lt opcode except that the jump is taken if
79278 ** the content of register P3 is greater than the content of
79279 ** register P1. See the Lt opcode for additional information.
79280 */
79281 /* Opcode: Ge P1 P2 P3 P4 P5
79282 ** Synopsis: IF r[P3]>=r[P1]
79283 **
79284 ** This works just like the Lt opcode except that the jump is taken if
79285 ** the content of register P3 is greater than or equal to the content of
79286 ** register P1. See the Lt opcode for additional information.
79287 */
79288 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
79289 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
79290 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
79291 case OP_Le: /* same as TK_LE, jump, in1, in3 */
79292 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
79293 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
79294  int res, res2; /* Result of the comparison of pIn1 against pIn3 */
79295  char affinity; /* Affinity to use for comparison */
79296  u16 flags1; /* Copy of initial value of pIn1->flags */
79297  u16 flags3; /* Copy of initial value of pIn3->flags */
79298 
79299  pIn1 = &aMem[pOp->p1];
79300  pIn3 = &aMem[pOp->p3];
79301  flags1 = pIn1->flags;
79302  flags3 = pIn3->flags;
79303  if( (flags1 | flags3)&MEM_Null ){
79304  /* One or both operands are NULL */
79305  if( pOp->p5 & SQLITE_NULLEQ ){
79306  /* If SQLITE_NULLEQ is set (which will only happen if the operator is
79307  ** OP_Eq or OP_Ne) then take the jump or not depending on whether
79308  ** or not both operands are null.
79309  */
79310  assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
79311  assert( (flags1 & MEM_Cleared)==0 );
79312  assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
79313  if( (flags1&MEM_Null)!=0
79314  && (flags3&MEM_Null)!=0
79315  && (flags3&MEM_Cleared)==0
79316  ){
79317  res = 0; /* Operands are equal */
79318  }else{
79319  res = 1; /* Operands are not equal */
79320  }
79321  }else{
79322  /* SQLITE_NULLEQ is clear and at least one operand is NULL,
79323  ** then the result is always NULL.
79324  ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
79325  */
79326  if( pOp->p5 & SQLITE_STOREP2 ){
79327  pOut = &aMem[pOp->p2];
79328  iCompare = 1; /* Operands are not equal */
79329  memAboutToChange(p, pOut);
79330  MemSetTypeFlag(pOut, MEM_Null);
79331  REGISTER_TRACE(pOp->p2, pOut);
79332  }else{
79333  VdbeBranchTaken(2,3);
79334  if( pOp->p5 & SQLITE_JUMPIFNULL ){
79335  goto jump_to_p2;
79336  }
79337  }
79338  break;
79339  }
79340  }else{
79341  /* Neither operand is NULL. Do a comparison. */
79342  affinity = pOp->p5 & SQLITE_AFF_MASK;
79343  if( affinity>=SQLITE_AFF_NUMERIC ){
79344  if( (flags1 | flags3)&MEM_Str ){
79345  if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79346  applyNumericAffinity(pIn1,0);
79347  testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
79348  flags3 = pIn3->flags;
79349  }
79350  if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79351  applyNumericAffinity(pIn3,0);
79352  }
79353  }
79354  /* Handle the common case of integer comparison here, as an
79355  ** optimization, to avoid a call to sqlite3MemCompare() */
79356  if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
79357  if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
79358  if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
79359  res = 0;
79360  goto compare_op;
79361  }
79362  }else if( affinity==SQLITE_AFF_TEXT ){
79363  if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
79364  testcase( pIn1->flags & MEM_Int );
79365  testcase( pIn1->flags & MEM_Real );
79366  sqlite3VdbeMemStringify(pIn1, encoding, 1);
79367  testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
79368  flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
79369  assert( pIn1!=pIn3 );
79370  }
79371  if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
79372  testcase( pIn3->flags & MEM_Int );
79373  testcase( pIn3->flags & MEM_Real );
79374  sqlite3VdbeMemStringify(pIn3, encoding, 1);
79375  testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
79376  flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
79377  }
79378  }
79379  assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
79380  res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
79381  }
79382 compare_op:
79383  switch( pOp->opcode ){
79384  case OP_Eq: res2 = res==0; break;
79385  case OP_Ne: res2 = res; break;
79386  case OP_Lt: res2 = res<0; break;
79387  case OP_Le: res2 = res<=0; break;
79388  case OP_Gt: res2 = res>0; break;
79389  default: res2 = res>=0; break;
79390  }
79391 
79392  /* Undo any changes made by applyAffinity() to the input registers. */
79393  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
79394  pIn1->flags = flags1;
79395  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
79396  pIn3->flags = flags3;
79397 
79398  if( pOp->p5 & SQLITE_STOREP2 ){
79399  pOut = &aMem[pOp->p2];
79400  iCompare = res;
79401  res2 = res2!=0; /* For this path res2 must be exactly 0 or 1 */
79402  if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
79403  /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
79404  ** and prevents OP_Ne from overwriting NULL with 0. This flag
79405  ** is only used in contexts where either:
79406  ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
79407  ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
79408  ** Therefore it is not necessary to check the content of r[P2] for
79409  ** NULL. */
79410  assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
79411  assert( res2==0 || res2==1 );
79412  testcase( res2==0 && pOp->opcode==OP_Eq );
79413  testcase( res2==1 && pOp->opcode==OP_Eq );
79414  testcase( res2==0 && pOp->opcode==OP_Ne );
79415  testcase( res2==1 && pOp->opcode==OP_Ne );
79416  if( (pOp->opcode==OP_Eq)==res2 ) break;
79417  }
79418  memAboutToChange(p, pOut);
79419  MemSetTypeFlag(pOut, MEM_Int);
79420  pOut->u.i = res2;
79421  REGISTER_TRACE(pOp->p2, pOut);
79422  }else{
79423  VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
79424  if( res2 ){
79425  goto jump_to_p2;
79426  }
79427  }
79428  break;
79429 }
79430 
79431 /* Opcode: ElseNotEq * P2 * * *
79432 **
79433 ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
79434 ** If result of an OP_Eq comparison on the same two operands
79435 ** would have be NULL or false (0), then then jump to P2.
79436 ** If the result of an OP_Eq comparison on the two previous operands
79437 ** would have been true (1), then fall through.
79438 */
79439 case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
79440  assert( pOp>aOp );
79441  assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
79442  assert( pOp[-1].p5 & SQLITE_STOREP2 );
79443  VdbeBranchTaken(iCompare!=0, 2);
79444  if( iCompare!=0 ) goto jump_to_p2;
79445  break;
79446 }
79447 
79448 
79449 /* Opcode: Permutation * * * P4 *
79450 **
79451 ** Set the permutation used by the OP_Compare operator to be the array
79452 ** of integers in P4.
79453 **
79454 ** The permutation is only valid until the next OP_Compare that has
79455 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
79456 ** occur immediately prior to the OP_Compare.
79457 **
79458 ** The first integer in the P4 integer array is the length of the array
79459 ** and does not become part of the permutation.
79460 */
79461 case OP_Permutation: {
79462  assert( pOp->p4type==P4_INTARRAY );
79463  assert( pOp->p4.ai );
79464  aPermute = pOp->p4.ai + 1;
79465  break;
79466 }
79467 
79468 /* Opcode: Compare P1 P2 P3 P4 P5
79469 ** Synopsis: r[P1@P3] <-> r[P2@P3]
79470 **
79471 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
79472 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
79473 ** the comparison for use by the next OP_Jump instruct.
79474 **
79475 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
79476 ** determined by the most recent OP_Permutation operator. If the
79477 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
79478 ** order.
79479 **
79480 ** P4 is a KeyInfo structure that defines collating sequences and sort
79481 ** orders for the comparison. The permutation applies to registers
79482 ** only. The KeyInfo elements are used sequentially.
79483 **
79484 ** The comparison is a sort comparison, so NULLs compare equal,
79485 ** NULLs are less than numbers, numbers are less than strings,
79486 ** and strings are less than blobs.
79487 */
79488 case OP_Compare: {
79489  int n;
79490  int i;
79491  int p1;
79492  int p2;
79493  const KeyInfo *pKeyInfo;
79494  int idx;
79495  CollSeq *pColl; /* Collating sequence to use on this term */
79496  int bRev; /* True for DESCENDING sort order */
79497 
79498  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
79499  n = pOp->p3;
79500  pKeyInfo = pOp->p4.pKeyInfo;
79501  assert( n>0 );
79502  assert( pKeyInfo!=0 );
79503  p1 = pOp->p1;
79504  p2 = pOp->p2;
79505 #if SQLITE_DEBUG
79506  if( aPermute ){
79507  int k, mx = 0;
79508  for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
79509  assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
79510  assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
79511  }else{
79512  assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
79513  assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
79514  }
79515 #endif /* SQLITE_DEBUG */
79516  for(i=0; i<n; i++){
79517  idx = aPermute ? aPermute[i] : i;
79518  assert( memIsValid(&aMem[p1+idx]) );
79519  assert( memIsValid(&aMem[p2+idx]) );
79520  REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
79521  REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
79522  assert( i<pKeyInfo->nField );
79523  pColl = pKeyInfo->aColl[i];
79524  bRev = pKeyInfo->aSortOrder[i];
79525  iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
79526  if( iCompare ){
79527  if( bRev ) iCompare = -iCompare;
79528  break;
79529  }
79530  }
79531  aPermute = 0;
79532  break;
79533 }
79534 
79535 /* Opcode: Jump P1 P2 P3 * *
79536 **
79537 ** Jump to the instruction at address P1, P2, or P3 depending on whether
79538 ** in the most recent OP_Compare instruction the P1 vector was less than
79539 ** equal to, or greater than the P2 vector, respectively.
79540 */
79541 case OP_Jump: { /* jump */
79542  if( iCompare<0 ){
79543  VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
79544  }else if( iCompare==0 ){
79545  VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
79546  }else{
79547  VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
79548  }
79549  break;
79550 }
79551 
79552 /* Opcode: And P1 P2 P3 * *
79553 ** Synopsis: r[P3]=(r[P1] && r[P2])
79554 **
79555 ** Take the logical AND of the values in registers P1 and P2 and
79556 ** write the result into register P3.
79557 **
79558 ** If either P1 or P2 is 0 (false) then the result is 0 even if
79559 ** the other input is NULL. A NULL and true or two NULLs give
79560 ** a NULL output.
79561 */
79562 /* Opcode: Or P1 P2 P3 * *
79563 ** Synopsis: r[P3]=(r[P1] || r[P2])
79564 **
79565 ** Take the logical OR of the values in register P1 and P2 and
79566 ** store the answer in register P3.
79567 **
79568 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
79569 ** even if the other input is NULL. A NULL and false or two NULLs
79570 ** give a NULL output.
79571 */
79572 case OP_And: /* same as TK_AND, in1, in2, out3 */
79573 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
79574  int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79575  int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79576 
79577  pIn1 = &aMem[pOp->p1];
79578  if( pIn1->flags & MEM_Null ){
79579  v1 = 2;
79580  }else{
79581  v1 = sqlite3VdbeIntValue(pIn1)!=0;
79582  }
79583  pIn2 = &aMem[pOp->p2];
79584  if( pIn2->flags & MEM_Null ){
79585  v2 = 2;
79586  }else{
79587  v2 = sqlite3VdbeIntValue(pIn2)!=0;
79588  }
79589  if( pOp->opcode==OP_And ){
79590  static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
79591  v1 = and_logic[v1*3+v2];
79592  }else{
79593  static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
79594  v1 = or_logic[v1*3+v2];
79595  }
79596  pOut = &aMem[pOp->p3];
79597  if( v1==2 ){
79598  MemSetTypeFlag(pOut, MEM_Null);
79599  }else{
79600  pOut->u.i = v1;
79601  MemSetTypeFlag(pOut, MEM_Int);
79602  }
79603  break;
79604 }
79605 
79606 /* Opcode: Not P1 P2 * * *
79607 ** Synopsis: r[P2]= !r[P1]
79608 **
79609 ** Interpret the value in register P1 as a boolean value. Store the
79610 ** boolean complement in register P2. If the value in register P1 is
79611 ** NULL, then a NULL is stored in P2.
79612 */
79613 case OP_Not: { /* same as TK_NOT, in1, out2 */
79614  pIn1 = &aMem[pOp->p1];
79615  pOut = &aMem[pOp->p2];
79616  sqlite3VdbeMemSetNull(pOut);
79617  if( (pIn1->flags & MEM_Null)==0 ){
79618  pOut->flags = MEM_Int;
79619  pOut->u.i = !sqlite3VdbeIntValue(pIn1);
79620  }
79621  break;
79622 }
79623 
79624 /* Opcode: BitNot P1 P2 * * *
79625 ** Synopsis: r[P1]= ~r[P1]
79626 **
79627 ** Interpret the content of register P1 as an integer. Store the
79628 ** ones-complement of the P1 value into register P2. If P1 holds
79629 ** a NULL then store a NULL in P2.
79630 */
79631 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
79632  pIn1 = &aMem[pOp->p1];
79633  pOut = &aMem[pOp->p2];
79634  sqlite3VdbeMemSetNull(pOut);
79635  if( (pIn1->flags & MEM_Null)==0 ){
79636  pOut->flags = MEM_Int;
79637  pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
79638  }
79639  break;
79640 }
79641 
79642 /* Opcode: Once P1 P2 * * *
79643 **
79644 ** If the P1 value is equal to the P1 value on the OP_Init opcode at
79645 ** instruction 0, then jump to P2. If the two P1 values differ, then
79646 ** set the P1 value on this opcode to equal the P1 value on the OP_Init
79647 ** and fall through.
79648 */
79649 case OP_Once: { /* jump */
79650  assert( p->aOp[0].opcode==OP_Init );
79651  VdbeBranchTaken(p->aOp[0].p1==pOp->p1, 2);
79652  if( p->aOp[0].p1==pOp->p1 ){
79653  goto jump_to_p2;
79654  }else{
79655  pOp->p1 = p->aOp[0].p1;
79656  }
79657  break;
79658 }
79659 
79660 /* Opcode: If P1 P2 P3 * *
79661 **
79662 ** Jump to P2 if the value in register P1 is true. The value
79663 ** is considered true if it is numeric and non-zero. If the value
79664 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
79665 */
79666 /* Opcode: IfNot P1 P2 P3 * *
79667 **
79668 ** Jump to P2 if the value in register P1 is False. The value
79669 ** is considered false if it has a numeric value of zero. If the value
79670 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
79671 */
79672 case OP_If: /* jump, in1 */
79673 case OP_IfNot: { /* jump, in1 */
79674  int c;
79675  pIn1 = &aMem[pOp->p1];
79676  if( pIn1->flags & MEM_Null ){
79677  c = pOp->p3;
79678  }else{
79679 #ifdef SQLITE_OMIT_FLOATING_POINT
79680  c = sqlite3VdbeIntValue(pIn1)!=0;
79681 #else
79682  c = sqlite3VdbeRealValue(pIn1)!=0.0;
79683 #endif
79684  if( pOp->opcode==OP_IfNot ) c = !c;
79685  }
79686  VdbeBranchTaken(c!=0, 2);
79687  if( c ){
79688  goto jump_to_p2;
79689  }
79690  break;
79691 }
79692 
79693 /* Opcode: IsNull P1 P2 * * *
79694 ** Synopsis: if r[P1]==NULL goto P2
79695 **
79696 ** Jump to P2 if the value in register P1 is NULL.
79697 */
79698 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
79699  pIn1 = &aMem[pOp->p1];
79700  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
79701  if( (pIn1->flags & MEM_Null)!=0 ){
79702  goto jump_to_p2;
79703  }
79704  break;
79705 }
79706 
79707 /* Opcode: NotNull P1 P2 * * *
79708 ** Synopsis: if r[P1]!=NULL goto P2
79709 **
79710 ** Jump to P2 if the value in register P1 is not NULL.
79711 */
79712 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
79713  pIn1 = &aMem[pOp->p1];
79714  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
79715  if( (pIn1->flags & MEM_Null)==0 ){
79716  goto jump_to_p2;
79717  }
79718  break;
79719 }
79720 
79721 /* Opcode: Column P1 P2 P3 P4 P5
79722 ** Synopsis: r[P3]=PX
79723 **
79724 ** Interpret the data that cursor P1 points to as a structure built using
79725 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
79726 ** information about the format of the data.) Extract the P2-th column
79727 ** from this record. If there are less that (P2+1)
79728 ** values in the record, extract a NULL.
79729 **
79730 ** The value extracted is stored in register P3.
79731 **
79732 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
79733 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
79734 ** the result.
79735 **
79736 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
79737 ** then the cache of the cursor is reset prior to extracting the column.
79738 ** The first OP_Column against a pseudo-table after the value of the content
79739 ** register has changed should have this bit set.
79740 **
79741 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
79742 ** the result is guaranteed to only be used as the argument of a length()
79743 ** or typeof() function, respectively. The loading of large blobs can be
79744 ** skipped for length() and all content loading can be skipped for typeof().
79745 */
79746 case OP_Column: {
79747  int p2; /* column number to retrieve */
79748  VdbeCursor *pC; /* The VDBE cursor */
79749  BtCursor *pCrsr; /* The BTree cursor */
79750  u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
79751  int len; /* The length of the serialized data for the column */
79752  int i; /* Loop counter */
79753  Mem *pDest; /* Where to write the extracted value */
79754  Mem sMem; /* For storing the record being decoded */
79755  const u8 *zData; /* Part of the record being decoded */
79756  const u8 *zHdr; /* Next unparsed byte of the header */
79757  const u8 *zEndHdr; /* Pointer to first byte after the header */
79758  u32 offset; /* Offset into the data */
79759  u64 offset64; /* 64-bit offset */
79760  u32 avail; /* Number of bytes of available data */
79761  u32 t; /* A type code from the record header */
79762  Mem *pReg; /* PseudoTable input register */
79763 
79764  pC = p->apCsr[pOp->p1];
79765  p2 = pOp->p2;
79766 
79767  /* If the cursor cache is stale, bring it up-to-date */
79768  rc = sqlite3VdbeCursorMoveto(&pC, &p2);
79769  if( rc ) goto abort_due_to_error;
79770 
79771  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79772  pDest = &aMem[pOp->p3];
79773  memAboutToChange(p, pDest);
79774  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
79775  assert( pC!=0 );
79776  assert( p2<pC->nField );
79777  aOffset = pC->aOffset;
79778  assert( pC->eCurType!=CURTYPE_VTAB );
79779  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
79780  assert( pC->eCurType!=CURTYPE_SORTER );
79781  pCrsr = pC->uc.pCursor;
79782 
79783  if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
79784  if( pC->nullRow ){
79785  if( pC->eCurType==CURTYPE_PSEUDO ){
79786  assert( pC->uc.pseudoTableReg>0 );
79787  pReg = &aMem[pC->uc.pseudoTableReg];
79788  assert( pReg->flags & MEM_Blob );
79789  assert( memIsValid(pReg) );
79790  pC->payloadSize = pC->szRow = avail = pReg->n;
79791  pC->aRow = (u8*)pReg->z;
79792  }else{
79793  sqlite3VdbeMemSetNull(pDest);
79794  goto op_column_out;
79795  }
79796  }else{
79797  assert( pC->eCurType==CURTYPE_BTREE );
79798  assert( pCrsr );
79799  assert( sqlite3BtreeCursorIsValid(pCrsr) );
79800  pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
79801  pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
79802  assert( avail<=65536 ); /* Maximum page size is 64KiB */
79803  if( pC->payloadSize <= (u32)avail ){
79804  pC->szRow = pC->payloadSize;
79805  }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
79806  goto too_big;
79807  }else{
79808  pC->szRow = avail;
79809  }
79810  }
79811  pC->cacheStatus = p->cacheCtr;
79812  pC->iHdrOffset = getVarint32(pC->aRow, offset);
79813  pC->nHdrParsed = 0;
79814  aOffset[0] = offset;
79815 
79816 
79817  if( avail<offset ){ /*OPTIMIZATION-IF-FALSE*/
79818  /* pC->aRow does not have to hold the entire row, but it does at least
79819  ** need to cover the header of the record. If pC->aRow does not contain
79820  ** the complete header, then set it to zero, forcing the header to be
79821  ** dynamically allocated. */
79822  pC->aRow = 0;
79823  pC->szRow = 0;
79824 
79825  /* Make sure a corrupt database has not given us an oversize header.
79826  ** Do this now to avoid an oversize memory allocation.
79827  **
79828  ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
79829  ** types use so much data space that there can only be 4096 and 32 of
79830  ** them, respectively. So the maximum header length results from a
79831  ** 3-byte type for each of the maximum of 32768 columns plus three
79832  ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
79833  */
79834  if( offset > 98307 || offset > pC->payloadSize ){
79835  rc = SQLITE_CORRUPT_BKPT;
79836  goto abort_due_to_error;
79837  }
79838  }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
79839  /* The following goto is an optimization. It can be omitted and
79840  ** everything will still work. But OP_Column is measurably faster
79841  ** by skipping the subsequent conditional, which is always true.
79842  */
79843  zData = pC->aRow;
79844  assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
79845  goto op_column_read_header;
79846  }
79847  }
79848 
79849  /* Make sure at least the first p2+1 entries of the header have been
79850  ** parsed and valid information is in aOffset[] and pC->aType[].
79851  */
79852  if( pC->nHdrParsed<=p2 ){
79853  /* If there is more header available for parsing in the record, try
79854  ** to extract additional fields up through the p2+1-th field
79855  */
79856  if( pC->iHdrOffset<aOffset[0] ){
79857  /* Make sure zData points to enough of the record to cover the header. */
79858  if( pC->aRow==0 ){
79859  memset(&sMem, 0, sizeof(sMem));
79860  rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
79861  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79862  zData = (u8*)sMem.z;
79863  }else{
79864  zData = pC->aRow;
79865  }
79866 
79867  /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
79868  op_column_read_header:
79869  i = pC->nHdrParsed;
79870  offset64 = aOffset[i];
79871  zHdr = zData + pC->iHdrOffset;
79872  zEndHdr = zData + aOffset[0];
79873  do{
79874  if( (t = zHdr[0])<0x80 ){
79875  zHdr++;
79876  offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
79877  }else{
79878  zHdr += sqlite3GetVarint32(zHdr, &t);
79879  offset64 += sqlite3VdbeSerialTypeLen(t);
79880  }
79881  pC->aType[i++] = t;
79882  aOffset[i] = (u32)(offset64 & 0xffffffff);
79883  }while( i<=p2 && zHdr<zEndHdr );
79884 
79885  /* The record is corrupt if any of the following are true:
79886  ** (1) the bytes of the header extend past the declared header size
79887  ** (2) the entire header was used but not all data was used
79888  ** (3) the end of the data extends beyond the end of the record.
79889  */
79890  if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
79891  || (offset64 > pC->payloadSize)
79892  ){
79893  if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79894  rc = SQLITE_CORRUPT_BKPT;
79895  goto abort_due_to_error;
79896  }
79897 
79898  pC->nHdrParsed = i;
79899  pC->iHdrOffset = (u32)(zHdr - zData);
79900  if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79901  }else{
79902  t = 0;
79903  }
79904 
79905  /* If after trying to extract new entries from the header, nHdrParsed is
79906  ** still not up to p2, that means that the record has fewer than p2
79907  ** columns. So the result will be either the default value or a NULL.
79908  */
79909  if( pC->nHdrParsed<=p2 ){
79910  if( pOp->p4type==P4_MEM ){
79912  }else{
79913  sqlite3VdbeMemSetNull(pDest);
79914  }
79915  goto op_column_out;
79916  }
79917  }else{
79918  t = pC->aType[p2];
79919  }
79920 
79921  /* Extract the content for the p2+1-th column. Control can only
79922  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
79923  ** all valid.
79924  */
79925  assert( p2<pC->nHdrParsed );
79926  assert( rc==SQLITE_OK );
79927  assert( sqlite3VdbeCheckMemInvariants(pDest) );
79928  if( VdbeMemDynamic(pDest) ){
79929  sqlite3VdbeMemSetNull(pDest);
79930  }
79931  assert( t==pC->aType[p2] );
79932  if( pC->szRow>=aOffset[p2+1] ){
79933  /* This is the common case where the desired content fits on the original
79934  ** page - where the content is not on an overflow page */
79935  zData = pC->aRow + aOffset[p2];
79936  if( t<12 ){
79937  sqlite3VdbeSerialGet(zData, t, pDest);
79938  }else{
79939  /* If the column value is a string, we need a persistent value, not
79940  ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
79941  ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
79942  */
79943  static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
79944  pDest->n = len = (t-12)/2;
79945  pDest->enc = encoding;
79946  if( pDest->szMalloc < len+2 ){
79947  pDest->flags = MEM_Null;
79948  if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
79949  }else{
79950  pDest->z = pDest->zMalloc;
79951  }
79952  memcpy(pDest->z, zData, len);
79953  pDest->z[len] = 0;
79954  pDest->z[len+1] = 0;
79955  pDest->flags = aFlag[t&1];
79956  }
79957  }else{
79958  pDest->enc = encoding;
79959  /* This branch happens only when content is on overflow pages */
79960  if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
79961  && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
79962  || (len = sqlite3VdbeSerialTypeLen(t))==0
79963  ){
79964  /* Content is irrelevant for
79965  ** 1. the typeof() function,
79966  ** 2. the length(X) function if X is a blob, and
79967  ** 3. if the content length is zero.
79968  ** So we might as well use bogus content rather than reading
79969  ** content from disk. */
79970  static u8 aZero[8]; /* This is the bogus content */
79971  sqlite3VdbeSerialGet(aZero, t, pDest);
79972  }else{
79973  rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
79974  pDest);
79975  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79976  sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
79977  pDest->flags &= ~MEM_Ephem;
79978  }
79979  }
79980 
79981 op_column_out:
79982  UPDATE_MAX_BLOBSIZE(pDest);
79983  REGISTER_TRACE(pOp->p3, pDest);
79984  break;
79985 }
79986 
79987 /* Opcode: Affinity P1 P2 * P4 *
79988 ** Synopsis: affinity(r[P1@P2])
79989 **
79990 ** Apply affinities to a range of P2 registers starting with P1.
79991 **
79992 ** P4 is a string that is P2 characters long. The nth character of the
79993 ** string indicates the column affinity that should be used for the nth
79994 ** memory cell in the range.
79995 */
79996 case OP_Affinity: {
79997  const char *zAffinity; /* The affinity to be applied */
79998  char cAff; /* A single character of affinity */
79999 
80000  zAffinity = pOp->p4.z;
80001  assert( zAffinity!=0 );
80002  assert( zAffinity[pOp->p2]==0 );
80003  pIn1 = &aMem[pOp->p1];
80004  while( (cAff = *(zAffinity++))!=0 ){
80005  assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
80006  assert( memIsValid(pIn1) );
80007  applyAffinity(pIn1, cAff, encoding);
80008  pIn1++;
80009  }
80010  break;
80011 }
80012 
80013 /* Opcode: MakeRecord P1 P2 P3 P4 *
80014 ** Synopsis: r[P3]=mkrec(r[P1@P2])
80015 **
80016 ** Convert P2 registers beginning with P1 into the [record format]
80017 ** use as a data record in a database table or as a key
80018 ** in an index. The OP_Column opcode can decode the record later.
80019 **
80020 ** P4 may be a string that is P2 characters long. The nth character of the
80021 ** string indicates the column affinity that should be used for the nth
80022 ** field of the index key.
80023 **
80024 ** The mapping from character to affinity is given by the SQLITE_AFF_
80025 ** macros defined in sqliteInt.h.
80026 **
80027 ** If P4 is NULL then all index fields have the affinity BLOB.
80028 */
80029 case OP_MakeRecord: {
80030  u8 *zNewRecord; /* A buffer to hold the data for the new record */
80031  Mem *pRec; /* The new record */
80032  u64 nData; /* Number of bytes of data space */
80033  int nHdr; /* Number of bytes of header space */
80034  i64 nByte; /* Data space required for this record */
80035  i64 nZero; /* Number of zero bytes at the end of the record */
80036  int nVarint; /* Number of bytes in a varint */
80037  u32 serial_type; /* Type field */
80038  Mem *pData0; /* First field to be combined into the record */
80039  Mem *pLast; /* Last field of the record */
80040  int nField; /* Number of fields in the record */
80041  char *zAffinity; /* The affinity string for the record */
80042  int file_format; /* File format to use for encoding */
80043  int i; /* Space used in zNewRecord[] header */
80044  int j; /* Space used in zNewRecord[] content */
80045  u32 len; /* Length of a field */
80046 
80047  /* Assuming the record contains N fields, the record format looks
80048  ** like this:
80049  **
80050  ** ------------------------------------------------------------------------
80051  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
80052  ** ------------------------------------------------------------------------
80053  **
80054  ** Data(0) is taken from register P1. Data(1) comes from register P1+1
80055  ** and so forth.
80056  **
80057  ** Each type field is a varint representing the serial type of the
80058  ** corresponding data element (see sqlite3VdbeSerialType()). The
80059  ** hdr-size field is also a varint which is the offset from the beginning
80060  ** of the record to data0.
80061  */
80062  nData = 0; /* Number of bytes of data space */
80063  nHdr = 0; /* Number of bytes of header space */
80064  nZero = 0; /* Number of zero bytes at the end of the record */
80065  nField = pOp->p1;
80066  zAffinity = pOp->p4.z;
80067  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
80068  pData0 = &aMem[nField];
80069  nField = pOp->p2;
80070  pLast = &pData0[nField-1];
80071  file_format = p->minWriteFileFormat;
80072 
80073  /* Identify the output register */
80074  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
80075  pOut = &aMem[pOp->p3];
80076  memAboutToChange(p, pOut);
80077 
80078  /* Apply the requested affinity to all inputs
80079  */
80080  assert( pData0<=pLast );
80081  if( zAffinity ){
80082  pRec = pData0;
80083  do{
80084  applyAffinity(pRec++, *(zAffinity++), encoding);
80085  assert( zAffinity[0]==0 || pRec<=pLast );
80086  }while( zAffinity[0] );
80087  }
80088 
80089  /* Loop through the elements that will make up the record to figure
80090  ** out how much space is required for the new record.
80091  */
80092  pRec = pLast;
80093  do{
80094  assert( memIsValid(pRec) );
80095  pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
80096  if( pRec->flags & MEM_Zero ){
80097  if( nData ){
80098  if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
80099  }else{
80100  nZero += pRec->u.nZero;
80101  len -= pRec->u.nZero;
80102  }
80103  }
80104  nData += len;
80105  testcase( serial_type==127 );
80106  testcase( serial_type==128 );
80107  nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
80108  if( pRec==pData0 ) break;
80109  pRec--;
80110  }while(1);
80111 
80112  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
80113  ** which determines the total number of bytes in the header. The varint
80114  ** value is the size of the header in bytes including the size varint
80115  ** itself. */
80116  testcase( nHdr==126 );
80117  testcase( nHdr==127 );
80118  if( nHdr<=126 ){
80119  /* The common case */
80120  nHdr += 1;
80121  }else{
80122  /* Rare case of a really large header */
80123  nVarint = sqlite3VarintLen(nHdr);
80124  nHdr += nVarint;
80125  if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
80126  }
80127  nByte = nHdr+nData;
80128  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80129  goto too_big;
80130  }
80131 
80132  /* Make sure the output register has a buffer large enough to store
80133  ** the new record. The output register (pOp->p3) is not allowed to
80134  ** be one of the input registers (because the following call to
80135  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
80136  */
80137  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
80138  goto no_mem;
80139  }
80140  zNewRecord = (u8 *)pOut->z;
80141 
80142  /* Write the record */
80143  i = putVarint32(zNewRecord, nHdr);
80144  j = nHdr;
80145  assert( pData0<=pLast );
80146  pRec = pData0;
80147  do{
80148  serial_type = pRec->uTemp;
80149  /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
80150  ** additional varints, one per column. */
80151  i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
80152  /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
80153  ** immediately follow the header. */
80154  j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
80155  }while( (++pRec)<=pLast );
80156  assert( i==nHdr );
80157  assert( j==nByte );
80158 
80159  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
80160  pOut->n = (int)nByte;
80161  pOut->flags = MEM_Blob;
80162  if( nZero ){
80163  pOut->u.nZero = nZero;
80164  pOut->flags |= MEM_Zero;
80165  }
80166  pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
80167  REGISTER_TRACE(pOp->p3, pOut);
80168  UPDATE_MAX_BLOBSIZE(pOut);
80169  break;
80170 }
80171 
80172 /* Opcode: Count P1 P2 * * *
80173 ** Synopsis: r[P2]=count()
80174 **
80175 ** Store the number of entries (an integer value) in the table or index
80176 ** opened by cursor P1 in register P2
80177 */
80178 #ifndef SQLITE_OMIT_BTREECOUNT
80179 case OP_Count: { /* out2 */
80180  i64 nEntry;
80181  BtCursor *pCrsr;
80182 
80183  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
80184  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
80185  assert( pCrsr );
80186  nEntry = 0; /* Not needed. Only used to silence a warning. */
80187  rc = sqlite3BtreeCount(pCrsr, &nEntry);
80188  if( rc ) goto abort_due_to_error;
80189  pOut = out2Prerelease(p, pOp);
80190  pOut->u.i = nEntry;
80191  break;
80192 }
80193 #endif
80194 
80195 /* Opcode: Savepoint P1 * * P4 *
80196 **
80197 ** Open, release or rollback the savepoint named by parameter P4, depending
80198 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
80199 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
80200 */
80201 case OP_Savepoint: {
80202  int p1; /* Value of P1 operand */
80203  char *zName; /* Name of savepoint */
80204  int nName;
80205  Savepoint *pNew;
80206  Savepoint *pSavepoint;
80207  Savepoint *pTmp;
80208  int iSavepoint;
80209  int ii;
80210 
80211  p1 = pOp->p1;
80212  zName = pOp->p4.z;
80213 
80214  /* Assert that the p1 parameter is valid. Also that if there is no open
80215  ** transaction, then there cannot be any savepoints.
80216  */
80217  assert( db->pSavepoint==0 || db->autoCommit==0 );
80218  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
80219  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
80220  assert( checkSavepointCount(db) );
80221  assert( p->bIsReader );
80222 
80223  if( p1==SAVEPOINT_BEGIN ){
80224  if( db->nVdbeWrite>0 ){
80225  /* A new savepoint cannot be created if there are active write
80226  ** statements (i.e. open read/write incremental blob handles).
80227  */
80228  sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
80229  rc = SQLITE_BUSY;
80230  }else{
80231  nName = sqlite3Strlen30(zName);
80232 
80233 #ifndef SQLITE_OMIT_VIRTUALTABLE
80234  /* This call is Ok even if this savepoint is actually a transaction
80235  ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
80236  ** If this is a transaction savepoint being opened, it is guaranteed
80237  ** that the db->aVTrans[] array is empty. */
80238  assert( db->autoCommit==0 || db->nVTrans==0 );
80240  db->nStatement+db->nSavepoint);
80241  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80242 #endif
80243 
80244  /* Create a new savepoint structure. */
80245  pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
80246  if( pNew ){
80247  pNew->zName = (char *)&pNew[1];
80248  memcpy(pNew->zName, zName, nName+1);
80249 
80250  /* If there is no open transaction, then mark this as a special
80251  ** "transaction savepoint". */
80252  if( db->autoCommit ){
80253  db->autoCommit = 0;
80254  db->isTransactionSavepoint = 1;
80255  }else{
80256  db->nSavepoint++;
80257  }
80258 
80259  /* Link the new savepoint into the database handle's list. */
80260  pNew->pNext = db->pSavepoint;
80261  db->pSavepoint = pNew;
80262  pNew->nDeferredCons = db->nDeferredCons;
80263  pNew->nDeferredImmCons = db->nDeferredImmCons;
80264  }
80265  }
80266  }else{
80267  iSavepoint = 0;
80268 
80269  /* Find the named savepoint. If there is no such savepoint, then an
80270  ** an error is returned to the user. */
80271  for(
80272  pSavepoint = db->pSavepoint;
80273  pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
80274  pSavepoint = pSavepoint->pNext
80275  ){
80276  iSavepoint++;
80277  }
80278  if( !pSavepoint ){
80279  sqlite3VdbeError(p, "no such savepoint: %s", zName);
80280  rc = SQLITE_ERROR;
80281  }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
80282  /* It is not possible to release (commit) a savepoint if there are
80283  ** active write statements.
80284  */
80285  sqlite3VdbeError(p, "cannot release savepoint - "
80286  "SQL statements in progress");
80287  rc = SQLITE_BUSY;
80288  }else{
80289 
80290  /* Determine whether or not this is a transaction savepoint. If so,
80291  ** and this is a RELEASE command, then the current transaction
80292  ** is committed.
80293  */
80294  int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
80295  if( isTransaction && p1==SAVEPOINT_RELEASE ){
80296  if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80297  goto vdbe_return;
80298  }
80299  db->autoCommit = 1;
80300  if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80301  p->pc = (int)(pOp - aOp);
80302  db->autoCommit = 0;
80303  p->rc = rc = SQLITE_BUSY;
80304  goto vdbe_return;
80305  }
80306  db->isTransactionSavepoint = 0;
80307  rc = p->rc;
80308  }else{
80309  int isSchemaChange;
80310  iSavepoint = db->nSavepoint - iSavepoint - 1;
80311  if( p1==SAVEPOINT_ROLLBACK ){
80312  isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
80313  for(ii=0; ii<db->nDb; ii++){
80314  rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
80316  isSchemaChange==0);
80317  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80318  }
80319  }else{
80320  isSchemaChange = 0;
80321  }
80322  for(ii=0; ii<db->nDb; ii++){
80323  rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
80324  if( rc!=SQLITE_OK ){
80325  goto abort_due_to_error;
80326  }
80327  }
80328  if( isSchemaChange ){
80331  db->flags = (db->flags | SQLITE_InternChanges);
80332  }
80333  }
80334 
80335  /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
80336  ** savepoints nested inside of the savepoint being operated on. */
80337  while( db->pSavepoint!=pSavepoint ){
80338  pTmp = db->pSavepoint;
80339  db->pSavepoint = pTmp->pNext;
80340  sqlite3DbFree(db, pTmp);
80341  db->nSavepoint--;
80342  }
80343 
80344  /* If it is a RELEASE, then destroy the savepoint being operated on
80345  ** too. If it is a ROLLBACK TO, then set the number of deferred
80346  ** constraint violations present in the database to the value stored
80347  ** when the savepoint was created. */
80348  if( p1==SAVEPOINT_RELEASE ){
80349  assert( pSavepoint==db->pSavepoint );
80350  db->pSavepoint = pSavepoint->pNext;
80351  sqlite3DbFree(db, pSavepoint);
80352  if( !isTransaction ){
80353  db->nSavepoint--;
80354  }
80355  }else{
80356  db->nDeferredCons = pSavepoint->nDeferredCons;
80357  db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
80358  }
80359 
80360  if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
80361  rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
80362  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80363  }
80364  }
80365  }
80366  if( rc ) goto abort_due_to_error;
80367 
80368  break;
80369 }
80370 
80371 /* Opcode: AutoCommit P1 P2 * * *
80372 **
80373 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
80374 ** back any currently active btree transactions. If there are any active
80375 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
80376 ** there are active writing VMs or active VMs that use shared cache.
80377 **
80378 ** This instruction causes the VM to halt.
80379 */
80380 case OP_AutoCommit: {
80381  int desiredAutoCommit;
80382  int iRollback;
80383 
80384  desiredAutoCommit = pOp->p1;
80385  iRollback = pOp->p2;
80386  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
80387  assert( desiredAutoCommit==1 || iRollback==0 );
80388  assert( db->nVdbeActive>0 ); /* At least this one VM is active */
80389  assert( p->bIsReader );
80390 
80391  if( desiredAutoCommit!=db->autoCommit ){
80392  if( iRollback ){
80393  assert( desiredAutoCommit==1 );
80395  db->autoCommit = 1;
80396  }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
80397  /* If this instruction implements a COMMIT and other VMs are writing
80398  ** return an error indicating that the other VMs must complete first.
80399  */
80400  sqlite3VdbeError(p, "cannot commit transaction - "
80401  "SQL statements in progress");
80402  rc = SQLITE_BUSY;
80403  goto abort_due_to_error;
80404  }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80405  goto vdbe_return;
80406  }else{
80407  db->autoCommit = (u8)desiredAutoCommit;
80408  }
80409  if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80410  p->pc = (int)(pOp - aOp);
80411  db->autoCommit = (u8)(1-desiredAutoCommit);
80412  p->rc = rc = SQLITE_BUSY;
80413  goto vdbe_return;
80414  }
80415  assert( db->nStatement==0 );
80417  if( p->rc==SQLITE_OK ){
80418  rc = SQLITE_DONE;
80419  }else{
80420  rc = SQLITE_ERROR;
80421  }
80422  goto vdbe_return;
80423  }else{
80424  sqlite3VdbeError(p,
80425  (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
80426  (iRollback)?"cannot rollback - no transaction is active":
80427  "cannot commit - no transaction is active"));
80428 
80429  rc = SQLITE_ERROR;
80430  goto abort_due_to_error;
80431  }
80432  break;
80433 }
80434 
80435 /* Opcode: Transaction P1 P2 P3 P4 P5
80436 **
80437 ** Begin a transaction on database P1 if a transaction is not already
80438 ** active.
80439 ** If P2 is non-zero, then a write-transaction is started, or if a
80440 ** read-transaction is already active, it is upgraded to a write-transaction.
80441 ** If P2 is zero, then a read-transaction is started.
80442 **
80443 ** P1 is the index of the database file on which the transaction is
80444 ** started. Index 0 is the main database file and index 1 is the
80445 ** file used for temporary tables. Indices of 2 or more are used for
80446 ** attached databases.
80447 **
80448 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
80449 ** true (this flag is set if the Vdbe may modify more than one row and may
80450 ** throw an ABORT exception), a statement transaction may also be opened.
80451 ** More specifically, a statement transaction is opened iff the database
80452 ** connection is currently not in autocommit mode, or if there are other
80453 ** active statements. A statement transaction allows the changes made by this
80454 ** VDBE to be rolled back after an error without having to roll back the
80455 ** entire transaction. If no error is encountered, the statement transaction
80456 ** will automatically commit when the VDBE halts.
80457 **
80458 ** If P5!=0 then this opcode also checks the schema cookie against P3
80459 ** and the schema generation counter against P4.
80460 ** The cookie changes its value whenever the database schema changes.
80461 ** This operation is used to detect when that the cookie has changed
80462 ** and that the current process needs to reread the schema. If the schema
80463 ** cookie in P3 differs from the schema cookie in the database header or
80464 ** if the schema generation counter in P4 differs from the current
80465 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
80466 ** halts. The sqlite3_step() wrapper function might then reprepare the
80467 ** statement and rerun it from the beginning.
80468 */
80469 case OP_Transaction: {
80470  Btree *pBt;
80471  int iMeta;
80472  int iGen;
80473 
80474  assert( p->bIsReader );
80475  assert( p->readOnly==0 || pOp->p2==0 );
80476  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80477  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80478  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
80479  rc = SQLITE_READONLY;
80480  goto abort_due_to_error;
80481  }
80482  pBt = db->aDb[pOp->p1].pBt;
80483 
80484  if( pBt ){
80485  rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
80488  if( rc!=SQLITE_OK ){
80489  if( (rc&0xff)==SQLITE_BUSY ){
80490  p->pc = (int)(pOp - aOp);
80491  p->rc = rc;
80492  goto vdbe_return;
80493  }
80494  goto abort_due_to_error;
80495  }
80496 
80497  if( pOp->p2 && p->usesStmtJournal
80498  && (db->autoCommit==0 || db->nVdbeRead>1)
80499  ){
80500  assert( sqlite3BtreeIsInTrans(pBt) );
80501  if( p->iStatement==0 ){
80502  assert( db->nStatement>=0 && db->nSavepoint>=0 );
80503  db->nStatement++;
80504  p->iStatement = db->nSavepoint + db->nStatement;
80505  }
80506 
80508  if( rc==SQLITE_OK ){
80509  rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
80510  }
80511 
80512  /* Store the current value of the database handles deferred constraint
80513  ** counter. If the statement transaction needs to be rolled back,
80514  ** the value of this counter needs to be restored too. */
80515  p->nStmtDefCons = db->nDeferredCons;
80517  }
80518 
80519  /* Gather the schema version number for checking:
80520  ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
80521  ** version is checked to ensure that the schema has not changed since the
80522  ** SQL statement was prepared.
80523  */
80524  sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
80525  iGen = db->aDb[pOp->p1].pSchema->iGeneration;
80526  }else{
80527  iGen = iMeta = 0;
80528  }
80529  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
80530  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
80531  sqlite3DbFree(db, p->zErrMsg);
80532  p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
80533  /* If the schema-cookie from the database file matches the cookie
80534  ** stored with the in-memory representation of the schema, do
80535  ** not reload the schema from the database file.
80536  **
80537  ** If virtual-tables are in use, this is not just an optimization.
80538  ** Often, v-tables store their data in other SQLite tables, which
80539  ** are queried from within xNext() and other v-table methods using
80540  ** prepared queries. If such a query is out-of-date, we do not want to
80541  ** discard the database schema, as the user code implementing the
80542  ** v-table would have to be ready for the sqlite3_vtab structure itself
80543  ** to be invalidated whenever sqlite3_step() is called from within
80544  ** a v-table method.
80545  */
80546  if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
80547  sqlite3ResetOneSchema(db, pOp->p1);
80548  }
80549  p->expired = 1;
80550  rc = SQLITE_SCHEMA;
80551  }
80552  if( rc ) goto abort_due_to_error;
80553  break;
80554 }
80555 
80556 /* Opcode: ReadCookie P1 P2 P3 * *
80557 **
80558 ** Read cookie number P3 from database P1 and write it into register P2.
80559 ** P3==1 is the schema version. P3==2 is the database format.
80560 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
80561 ** the main database file and P1==1 is the database file used to store
80562 ** temporary tables.
80563 **
80564 ** There must be a read-lock on the database (either a transaction
80565 ** must be started or there must be an open cursor) before
80566 ** executing this instruction.
80567 */
80568 case OP_ReadCookie: { /* out2 */
80569  int iMeta;
80570  int iDb;
80571  int iCookie;
80572 
80573  assert( p->bIsReader );
80574  iDb = pOp->p1;
80575  iCookie = pOp->p3;
80576  assert( pOp->p3<SQLITE_N_BTREE_META );
80577  assert( iDb>=0 && iDb<db->nDb );
80578  assert( db->aDb[iDb].pBt!=0 );
80579  assert( DbMaskTest(p->btreeMask, iDb) );
80580 
80581  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
80582  pOut = out2Prerelease(p, pOp);
80583  pOut->u.i = iMeta;
80584  break;
80585 }
80586 
80587 /* Opcode: SetCookie P1 P2 P3 * *
80588 **
80589 ** Write the integer value P3 into cookie number P2 of database P1.
80590 ** P2==1 is the schema version. P2==2 is the database format.
80591 ** P2==3 is the recommended pager cache
80592 ** size, and so forth. P1==0 is the main database file and P1==1 is the
80593 ** database file used to store temporary tables.
80594 **
80595 ** A transaction must be started before executing this opcode.
80596 */
80597 case OP_SetCookie: {
80598  Db *pDb;
80599  assert( pOp->p2<SQLITE_N_BTREE_META );
80600  assert( pOp->p1>=0 && pOp->p1<db->nDb );
80601  assert( DbMaskTest(p->btreeMask, pOp->p1) );
80602  assert( p->readOnly==0 );
80603  pDb = &db->aDb[pOp->p1];
80604  assert( pDb->pBt!=0 );
80605  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
80606  /* See note about index shifting on OP_ReadCookie */
80607  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
80608  if( pOp->p2==BTREE_SCHEMA_VERSION ){
80609  /* When the schema cookie changes, record the new cookie internally */
80610  pDb->pSchema->schema_cookie = pOp->p3;
80611  db->flags |= SQLITE_InternChanges;
80612  }else if( pOp->p2==BTREE_FILE_FORMAT ){
80613  /* Record changes in the file format */
80614  pDb->pSchema->file_format = pOp->p3;
80615  }
80616  if( pOp->p1==1 ){
80617  /* Invalidate all prepared statements whenever the TEMP database
80618  ** schema is changed. Ticket #1644 */
80620  p->expired = 0;
80621  }
80622  if( rc ) goto abort_due_to_error;
80623  break;
80624 }
80625 
80626 /* Opcode: OpenRead P1 P2 P3 P4 P5
80627 ** Synopsis: root=P2 iDb=P3
80628 **
80629 ** Open a read-only cursor for the database table whose root page is
80630 ** P2 in a database file. The database file is determined by P3.
80631 ** P3==0 means the main database, P3==1 means the database used for
80632 ** temporary tables, and P3>1 means used the corresponding attached
80633 ** database. Give the new cursor an identifier of P1. The P1
80634 ** values need not be contiguous but all P1 values should be small integers.
80635 ** It is an error for P1 to be negative.
80636 **
80637 ** If P5!=0 then use the content of register P2 as the root page, not
80638 ** the value of P2 itself.
80639 **
80640 ** There will be a read lock on the database whenever there is an
80641 ** open cursor. If the database was unlocked prior to this instruction
80642 ** then a read lock is acquired as part of this instruction. A read
80643 ** lock allows other processes to read the database but prohibits
80644 ** any other process from modifying the database. The read lock is
80645 ** released when all cursors are closed. If this instruction attempts
80646 ** to get a read lock but fails, the script terminates with an
80647 ** SQLITE_BUSY error code.
80648 **
80649 ** The P4 value may be either an integer (P4_INT32) or a pointer to
80650 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80651 ** structure, then said structure defines the content and collating
80652 ** sequence of the index being opened. Otherwise, if P4 is an integer
80653 ** value, it is set to the number of columns in the table.
80654 **
80655 ** See also: OpenWrite, ReopenIdx
80656 */
80657 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
80658 ** Synopsis: root=P2 iDb=P3
80659 **
80660 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
80661 ** checks to see if the cursor on P1 is already open with a root page
80662 ** number of P2 and if it is this opcode becomes a no-op. In other words,
80663 ** if the cursor is already open, do not reopen it.
80664 **
80665 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
80666 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
80667 ** every other ReopenIdx or OpenRead for the same cursor number.
80668 **
80669 ** See the OpenRead opcode documentation for additional information.
80670 */
80671 /* Opcode: OpenWrite P1 P2 P3 P4 P5
80672 ** Synopsis: root=P2 iDb=P3
80673 **
80674 ** Open a read/write cursor named P1 on the table or index whose root
80675 ** page is P2. Or if P5!=0 use the content of register P2 to find the
80676 ** root page.
80677 **
80678 ** The P4 value may be either an integer (P4_INT32) or a pointer to
80679 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
80680 ** structure, then said structure defines the content and collating
80681 ** sequence of the index being opened. Otherwise, if P4 is an integer
80682 ** value, it is set to the number of columns in the table, or to the
80683 ** largest index of any column of the table that is actually used.
80684 **
80685 ** This instruction works just like OpenRead except that it opens the cursor
80686 ** in read/write mode. For a given table, there can be one or more read-only
80687 ** cursors or a single read/write cursor but not both.
80688 **
80689 ** See also OpenRead.
80690 */
80691 case OP_ReopenIdx: {
80692  int nField;
80693  KeyInfo *pKeyInfo;
80694  int p2;
80695  int iDb;
80696  int wrFlag;
80697  Btree *pX;
80698  VdbeCursor *pCur;
80699  Db *pDb;
80700 
80701  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80702  assert( pOp->p4type==P4_KEYINFO );
80703  pCur = p->apCsr[pOp->p1];
80704  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
80705  assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
80706  goto open_cursor_set_hints;
80707  }
80708  /* If the cursor is not currently open or is open on a different
80709  ** index, then fall through into OP_OpenRead to force a reopen */
80710 case OP_OpenRead:
80711 case OP_OpenWrite:
80712 
80713  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80714  assert( p->bIsReader );
80715  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
80716  || p->readOnly==0 );
80717 
80718  if( p->expired ){
80719  rc = SQLITE_ABORT_ROLLBACK;
80720  goto abort_due_to_error;
80721  }
80722 
80723  nField = 0;
80724  pKeyInfo = 0;
80725  p2 = pOp->p2;
80726  iDb = pOp->p3;
80727  assert( iDb>=0 && iDb<db->nDb );
80728  assert( DbMaskTest(p->btreeMask, iDb) );
80729  pDb = &db->aDb[iDb];
80730  pX = pDb->pBt;
80731  assert( pX!=0 );
80732  if( pOp->opcode==OP_OpenWrite ){
80733  assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
80734  wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
80735  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80736  if( pDb->pSchema->file_format < p->minWriteFileFormat ){
80738  }
80739  }else{
80740  wrFlag = 0;
80741  }
80742  if( pOp->p5 & OPFLAG_P2ISREG ){
80743  assert( p2>0 );
80744  assert( p2<=(p->nMem+1 - p->nCursor) );
80745  pIn2 = &aMem[p2];
80746  assert( memIsValid(pIn2) );
80747  assert( (pIn2->flags & MEM_Int)!=0 );
80749  p2 = (int)pIn2->u.i;
80750  /* The p2 value always comes from a prior OP_CreateTable opcode and
80751  ** that opcode will always set the p2 value to 2 or more or else fail.
80752  ** If there were a failure, the prepared statement would have halted
80753  ** before reaching this instruction. */
80754  assert( p2>=2 );
80755  }
80756  if( pOp->p4type==P4_KEYINFO ){
80757  pKeyInfo = pOp->p4.pKeyInfo;
80758  assert( pKeyInfo->enc==ENC(db) );
80759  assert( pKeyInfo->db==db );
80760  nField = pKeyInfo->nField+pKeyInfo->nXField;
80761  }else if( pOp->p4type==P4_INT32 ){
80762  nField = pOp->p4.i;
80763  }
80764  assert( pOp->p1>=0 );
80765  assert( nField>=0 );
80766  testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
80767  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
80768  if( pCur==0 ) goto no_mem;
80769  pCur->nullRow = 1;
80770  pCur->isOrdered = 1;
80771  pCur->pgnoRoot = p2;
80772 #ifdef SQLITE_DEBUG
80773  pCur->wrFlag = wrFlag;
80774 #endif
80775  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
80776  pCur->pKeyInfo = pKeyInfo;
80777  /* Set the VdbeCursor.isTable variable. Previous versions of
80778  ** SQLite used to check if the root-page flags were sane at this point
80779  ** and report database corruption if they were not, but this check has
80780  ** since moved into the btree layer. */
80781  pCur->isTable = pOp->p4type!=P4_KEYINFO;
80782 
80783 open_cursor_set_hints:
80784  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
80785  assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
80786  testcase( pOp->p5 & OPFLAG_BULKCSR );
80787 #ifdef SQLITE_ENABLE_CURSOR_HINTS
80788  testcase( pOp->p2 & OPFLAG_SEEKEQ );
80789 #endif
80791  (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
80792  if( rc ) goto abort_due_to_error;
80793  break;
80794 }
80795 
80796 /* Opcode: OpenEphemeral P1 P2 * P4 P5
80797 ** Synopsis: nColumn=P2
80798 **
80799 ** Open a new cursor P1 to a transient table.
80800 ** The cursor is always opened read/write even if
80801 ** the main database is read-only. The ephemeral
80802 ** table is deleted automatically when the cursor is closed.
80803 **
80804 ** P2 is the number of columns in the ephemeral table.
80805 ** The cursor points to a BTree table if P4==0 and to a BTree index
80806 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
80807 ** that defines the format of keys in the index.
80808 **
80809 ** The P5 parameter can be a mask of the BTREE_* flags defined
80810 ** in btree.h. These flags control aspects of the operation of
80811 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
80812 ** added automatically.
80813 */
80814 /* Opcode: OpenAutoindex P1 P2 * P4 *
80815 ** Synopsis: nColumn=P2
80816 **
80817 ** This opcode works the same as OP_OpenEphemeral. It has a
80818 ** different name to distinguish its use. Tables created using
80819 ** by this opcode will be used for automatically created transient
80820 ** indices in joins.
80821 */
80822 case OP_OpenAutoindex:
80823 case OP_OpenEphemeral: {
80824  VdbeCursor *pCx;
80825  KeyInfo *pKeyInfo;
80826 
80827  static const int vfsFlags =
80833  assert( pOp->p1>=0 );
80834  assert( pOp->p2>=0 );
80835  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
80836  if( pCx==0 ) goto no_mem;
80837  pCx->nullRow = 1;
80838  pCx->isEphemeral = 1;
80839  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
80840  BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
80841  if( rc==SQLITE_OK ){
80842  rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
80843  }
80844  if( rc==SQLITE_OK ){
80845  /* If a transient index is required, create it by calling
80846  ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
80847  ** opening it. If a transient table is required, just use the
80848  ** automatically created table with root-page 1 (an BLOB_INTKEY table).
80849  */
80850  if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
80851  int pgno;
80852  assert( pOp->p4type==P4_KEYINFO );
80853  rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
80854  if( rc==SQLITE_OK ){
80855  assert( pgno==MASTER_ROOT+1 );
80856  assert( pKeyInfo->db==db );
80857  assert( pKeyInfo->enc==ENC(db) );
80858  pCx->pKeyInfo = pKeyInfo;
80859  rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
80860  pKeyInfo, pCx->uc.pCursor);
80861  }
80862  pCx->isTable = 0;
80863  }else{
80865  0, pCx->uc.pCursor);
80866  pCx->isTable = 1;
80867  }
80868  }
80869  if( rc ) goto abort_due_to_error;
80870  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
80871  break;
80872 }
80873 
80874 /* Opcode: SorterOpen P1 P2 P3 P4 *
80875 **
80876 ** This opcode works like OP_OpenEphemeral except that it opens
80877 ** a transient index that is specifically designed to sort large
80878 ** tables using an external merge-sort algorithm.
80879 **
80880 ** If argument P3 is non-zero, then it indicates that the sorter may
80881 ** assume that a stable sort considering the first P3 fields of each
80882 ** key is sufficient to produce the required results.
80883 */
80884 case OP_SorterOpen: {
80885  VdbeCursor *pCx;
80886 
80887  assert( pOp->p1>=0 );
80888  assert( pOp->p2>=0 );
80889  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
80890  if( pCx==0 ) goto no_mem;
80891  pCx->pKeyInfo = pOp->p4.pKeyInfo;
80892  assert( pCx->pKeyInfo->db==db );
80893  assert( pCx->pKeyInfo->enc==ENC(db) );
80894  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
80895  if( rc ) goto abort_due_to_error;
80896  break;
80897 }
80898 
80899 /* Opcode: SequenceTest P1 P2 * * *
80900 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
80901 **
80902 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
80903 ** to P2. Regardless of whether or not the jump is taken, increment the
80904 ** the sequence value.
80905 */
80906 case OP_SequenceTest: {
80907  VdbeCursor *pC;
80908  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80909  pC = p->apCsr[pOp->p1];
80910  assert( isSorter(pC) );
80911  if( (pC->seqCount++)==0 ){
80912  goto jump_to_p2;
80913  }
80914  break;
80915 }
80916 
80917 /* Opcode: OpenPseudo P1 P2 P3 * *
80918 ** Synopsis: P3 columns in r[P2]
80919 **
80920 ** Open a new cursor that points to a fake table that contains a single
80921 ** row of data. The content of that one row is the content of memory
80922 ** register P2. In other words, cursor P1 becomes an alias for the
80923 ** MEM_Blob content contained in register P2.
80924 **
80925 ** A pseudo-table created by this opcode is used to hold a single
80926 ** row output from the sorter so that the row can be decomposed into
80927 ** individual columns using the OP_Column opcode. The OP_Column opcode
80928 ** is the only cursor opcode that works with a pseudo-table.
80929 **
80930 ** P3 is the number of fields in the records that will be stored by
80931 ** the pseudo-table.
80932 */
80933 case OP_OpenPseudo: {
80934  VdbeCursor *pCx;
80935 
80936  assert( pOp->p1>=0 );
80937  assert( pOp->p3>=0 );
80938  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
80939  if( pCx==0 ) goto no_mem;
80940  pCx->nullRow = 1;
80941  pCx->uc.pseudoTableReg = pOp->p2;
80942  pCx->isTable = 1;
80943  assert( pOp->p5==0 );
80944  break;
80945 }
80946 
80947 /* Opcode: Close P1 * * * *
80948 **
80949 ** Close a cursor previously opened as P1. If P1 is not
80950 ** currently open, this instruction is a no-op.
80951 */
80952 case OP_Close: {
80953  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80954  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
80955  p->apCsr[pOp->p1] = 0;
80956  break;
80957 }
80958 
80959 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
80960 /* Opcode: ColumnsUsed P1 * * P4 *
80961 **
80962 ** This opcode (which only exists if SQLite was compiled with
80963 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
80964 ** table or index for cursor P1 are used. P4 is a 64-bit integer
80965 ** (P4_INT64) in which the first 63 bits are one for each of the
80966 ** first 63 columns of the table or index that are actually used
80967 ** by the cursor. The high-order bit is set if any column after
80968 ** the 64th is used.
80969 */
80970 case OP_ColumnsUsed: {
80971  VdbeCursor *pC;
80972  pC = p->apCsr[pOp->p1];
80973  assert( pC->eCurType==CURTYPE_BTREE );
80974  pC->maskUsed = *(u64*)pOp->p4.pI64;
80975  break;
80976 }
80977 #endif
80978 
80979 /* Opcode: SeekGE P1 P2 P3 P4 *
80980 ** Synopsis: key=r[P3@P4]
80981 **
80982 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80983 ** use the value in register P3 as the key. If cursor P1 refers
80984 ** to an SQL index, then P3 is the first in an array of P4 registers
80985 ** that are used as an unpacked index key.
80986 **
80987 ** Reposition cursor P1 so that it points to the smallest entry that
80988 ** is greater than or equal to the key value. If there are no records
80989 ** greater than or equal to the key and P2 is not zero, then jump to P2.
80990 **
80991 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80992 ** opcode will always land on a record that equally equals the key, or
80993 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
80994 ** opcode must be followed by an IdxLE opcode with the same arguments.
80995 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
80996 ** IdxLE opcode will be used on subsequent loop iterations.
80997 **
80998 ** This opcode leaves the cursor configured to move in forward order,
80999 ** from the beginning toward the end. In other words, the cursor is
81000 ** configured to use Next, not Prev.
81001 **
81002 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
81003 */
81004 /* Opcode: SeekGT P1 P2 P3 P4 *
81005 ** Synopsis: key=r[P3@P4]
81006 **
81007 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81008 ** use the value in register P3 as a key. If cursor P1 refers
81009 ** to an SQL index, then P3 is the first in an array of P4 registers
81010 ** that are used as an unpacked index key.
81011 **
81012 ** Reposition cursor P1 so that it points to the smallest entry that
81013 ** is greater than the key value. If there are no records greater than
81014 ** the key and P2 is not zero, then jump to P2.
81015 **
81016 ** This opcode leaves the cursor configured to move in forward order,
81017 ** from the beginning toward the end. In other words, the cursor is
81018 ** configured to use Next, not Prev.
81019 **
81020 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
81021 */
81022 /* Opcode: SeekLT P1 P2 P3 P4 *
81023 ** Synopsis: key=r[P3@P4]
81024 **
81025 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81026 ** use the value in register P3 as a key. If cursor P1 refers
81027 ** to an SQL index, then P3 is the first in an array of P4 registers
81028 ** that are used as an unpacked index key.
81029 **
81030 ** Reposition cursor P1 so that it points to the largest entry that
81031 ** is less than the key value. If there are no records less than
81032 ** the key and P2 is not zero, then jump to P2.
81033 **
81034 ** This opcode leaves the cursor configured to move in reverse order,
81035 ** from the end toward the beginning. In other words, the cursor is
81036 ** configured to use Prev, not Next.
81037 **
81038 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
81039 */
81040 /* Opcode: SeekLE P1 P2 P3 P4 *
81041 ** Synopsis: key=r[P3@P4]
81042 **
81043 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
81044 ** use the value in register P3 as a key. If cursor P1 refers
81045 ** to an SQL index, then P3 is the first in an array of P4 registers
81046 ** that are used as an unpacked index key.
81047 **
81048 ** Reposition cursor P1 so that it points to the largest entry that
81049 ** is less than or equal to the key value. If there are no records
81050 ** less than or equal to the key and P2 is not zero, then jump to P2.
81051 **
81052 ** This opcode leaves the cursor configured to move in reverse order,
81053 ** from the end toward the beginning. In other words, the cursor is
81054 ** configured to use Prev, not Next.
81055 **
81056 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
81057 ** opcode will always land on a record that equally equals the key, or
81058 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
81059 ** opcode must be followed by an IdxGE opcode with the same arguments.
81060 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
81061 ** IdxGE opcode will be used on subsequent loop iterations.
81062 **
81063 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
81064 */
81065 case OP_SeekLT: /* jump, in3 */
81066 case OP_SeekLE: /* jump, in3 */
81067 case OP_SeekGE: /* jump, in3 */
81068 case OP_SeekGT: { /* jump, in3 */
81069  int res; /* Comparison result */
81070  int oc; /* Opcode */
81071  VdbeCursor *pC; /* The cursor to seek */
81072  UnpackedRecord r; /* The key to seek for */
81073  int nField; /* Number of columns or fields in the key */
81074  i64 iKey; /* The rowid we are to seek to */
81075  int eqOnly; /* Only interested in == results */
81076 
81077  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81078  assert( pOp->p2!=0 );
81079  pC = p->apCsr[pOp->p1];
81080  assert( pC!=0 );
81081  assert( pC->eCurType==CURTYPE_BTREE );
81082  assert( OP_SeekLE == OP_SeekLT+1 );
81083  assert( OP_SeekGE == OP_SeekLT+2 );
81084  assert( OP_SeekGT == OP_SeekLT+3 );
81085  assert( pC->isOrdered );
81086  assert( pC->uc.pCursor!=0 );
81087  oc = pOp->opcode;
81088  eqOnly = 0;
81089  pC->nullRow = 0;
81090 #ifdef SQLITE_DEBUG
81091  pC->seekOp = pOp->opcode;
81092 #endif
81093 
81094  if( pC->isTable ){
81095  /* The BTREE_SEEK_EQ flag is only set on index cursors */
81097 
81098  /* The input value in P3 might be of any type: integer, real, string,
81099  ** blob, or NULL. But it needs to be an integer before we can do
81100  ** the seek, so convert it. */
81101  pIn3 = &aMem[pOp->p3];
81102  if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
81103  applyNumericAffinity(pIn3, 0);
81104  }
81105  iKey = sqlite3VdbeIntValue(pIn3);
81106 
81107  /* If the P3 value could not be converted into an integer without
81108  ** loss of information, then special processing is required... */
81109  if( (pIn3->flags & MEM_Int)==0 ){
81110  if( (pIn3->flags & MEM_Real)==0 ){
81111  /* If the P3 value cannot be converted into any kind of a number,
81112  ** then the seek is not possible, so jump to P2 */
81113  VdbeBranchTaken(1,2); goto jump_to_p2;
81114  break;
81115  }
81116 
81117  /* If the approximation iKey is larger than the actual real search
81118  ** term, substitute >= for > and < for <=. e.g. if the search term
81119  ** is 4.9 and the integer approximation 5:
81120  **
81121  ** (x > 4.9) -> (x >= 5)
81122  ** (x <= 4.9) -> (x < 5)
81123  */
81124  if( pIn3->u.r<(double)iKey ){
81125  assert( OP_SeekGE==(OP_SeekGT-1) );
81126  assert( OP_SeekLT==(OP_SeekLE-1) );
81127  assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
81128  if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
81129  }
81130 
81131  /* If the approximation iKey is smaller than the actual real search
81132  ** term, substitute <= for < and > for >=. */
81133  else if( pIn3->u.r>(double)iKey ){
81134  assert( OP_SeekLE==(OP_SeekLT+1) );
81135  assert( OP_SeekGT==(OP_SeekGE+1) );
81136  assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
81137  if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
81138  }
81139  }
81140  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
81141  pC->movetoTarget = iKey; /* Used by OP_Delete */
81142  if( rc!=SQLITE_OK ){
81143  goto abort_due_to_error;
81144  }
81145  }else{
81146  /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
81147  ** OP_SeekLE opcodes are allowed, and these must be immediately followed
81148  ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
81149  */
81151  eqOnly = 1;
81152  assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
81153  assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
81154  assert( pOp[1].p1==pOp[0].p1 );
81155  assert( pOp[1].p2==pOp[0].p2 );
81156  assert( pOp[1].p3==pOp[0].p3 );
81157  assert( pOp[1].p4.i==pOp[0].p4.i );
81158  }
81159 
81160  nField = pOp->p4.i;
81161  assert( pOp->p4type==P4_INT32 );
81162  assert( nField>0 );
81163  r.pKeyInfo = pC->pKeyInfo;
81164  r.nField = (u16)nField;
81165 
81166  /* The next line of code computes as follows, only faster:
81167  ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
81168  ** r.default_rc = -1;
81169  ** }else{
81170  ** r.default_rc = +1;
81171  ** }
81172  */
81173  r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
81174  assert( oc!=OP_SeekGT || r.default_rc==-1 );
81175  assert( oc!=OP_SeekLE || r.default_rc==-1 );
81176  assert( oc!=OP_SeekGE || r.default_rc==+1 );
81177  assert( oc!=OP_SeekLT || r.default_rc==+1 );
81178 
81179  r.aMem = &aMem[pOp->p3];
81180 #ifdef SQLITE_DEBUG
81181  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
81182 #endif
81183  r.eqSeen = 0;
81184  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
81185  if( rc!=SQLITE_OK ){
81186  goto abort_due_to_error;
81187  }
81188  if( eqOnly && r.eqSeen==0 ){
81189  assert( res!=0 );
81190  goto seek_not_found;
81191  }
81192  }
81193  pC->deferredMoveto = 0;
81194  pC->cacheStatus = CACHE_STALE;
81195 #ifdef SQLITE_TEST
81196  sqlite3_search_count++;
81197 #endif
81198  if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
81199  if( res<0 || (res==0 && oc==OP_SeekGT) ){
81200  res = 0;
81201  rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
81202  if( rc!=SQLITE_OK ) goto abort_due_to_error;
81203  }else{
81204  res = 0;
81205  }
81206  }else{
81207  assert( oc==OP_SeekLT || oc==OP_SeekLE );
81208  if( res>0 || (res==0 && oc==OP_SeekLT) ){
81209  res = 0;
81210  rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
81211  if( rc!=SQLITE_OK ) goto abort_due_to_error;
81212  }else{
81213  /* res might be negative because the table is empty. Check to
81214  ** see if this is the case.
81215  */
81216  res = sqlite3BtreeEof(pC->uc.pCursor);
81217  }
81218  }
81219 seek_not_found:
81220  assert( pOp->p2>0 );
81221  VdbeBranchTaken(res!=0,2);
81222  if( res ){
81223  goto jump_to_p2;
81224  }else if( eqOnly ){
81225  assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
81226  pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
81227  }
81228  break;
81229 }
81230 
81231 /* Opcode: Found P1 P2 P3 P4 *
81232 ** Synopsis: key=r[P3@P4]
81233 **
81234 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
81235 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81236 ** record.
81237 **
81238 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
81239 ** is a prefix of any entry in P1 then a jump is made to P2 and
81240 ** P1 is left pointing at the matching entry.
81241 **
81242 ** This operation leaves the cursor in a state where it can be
81243 ** advanced in the forward direction. The Next instruction will work,
81244 ** but not the Prev instruction.
81245 **
81246 ** See also: NotFound, NoConflict, NotExists. SeekGe
81247 */
81248 /* Opcode: NotFound P1 P2 P3 P4 *
81249 ** Synopsis: key=r[P3@P4]
81250 **
81251 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
81252 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81253 ** record.
81254 **
81255 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
81256 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
81257 ** does contain an entry whose prefix matches the P3/P4 record then control
81258 ** falls through to the next instruction and P1 is left pointing at the
81259 ** matching entry.
81260 **
81261 ** This operation leaves the cursor in a state where it cannot be
81262 ** advanced in either direction. In other words, the Next and Prev
81263 ** opcodes do not work after this operation.
81264 **
81265 ** See also: Found, NotExists, NoConflict
81266 */
81267 /* Opcode: NoConflict 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 ** contains any NULL value, jump immediately to P2. If all terms of the
81276 ** record are not-NULL then a check is done to determine if any row in the
81277 ** P1 index btree has a matching key prefix. If there are no matches, jump
81278 ** immediately to P2. If there is a match, fall through and leave the P1
81279 ** cursor pointing to the matching row.
81280 **
81281 ** This opcode is similar to OP_NotFound with the exceptions that the
81282 ** branch is always taken if any part of the search key input is NULL.
81283 **
81284 ** This operation leaves the cursor in a state where it cannot be
81285 ** advanced in either direction. In other words, the Next and Prev
81286 ** opcodes do not work after this operation.
81287 **
81288 ** See also: NotFound, Found, NotExists
81289 */
81290 case OP_NoConflict: /* jump, in3 */
81291 case OP_NotFound: /* jump, in3 */
81292 case OP_Found: { /* jump, in3 */
81293  int alreadyExists;
81294  int takeJump;
81295  int ii;
81296  VdbeCursor *pC;
81297  int res;
81298  char *pFree;
81299  UnpackedRecord *pIdxKey;
81300  UnpackedRecord r;
81301  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
81302 
81303 #ifdef SQLITE_TEST
81304  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
81305 #endif
81306 
81307  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81308  assert( pOp->p4type==P4_INT32 );
81309  pC = p->apCsr[pOp->p1];
81310  assert( pC!=0 );
81311 #ifdef SQLITE_DEBUG
81312  pC->seekOp = pOp->opcode;
81313 #endif
81314  pIn3 = &aMem[pOp->p3];
81315  assert( pC->eCurType==CURTYPE_BTREE );
81316  assert( pC->uc.pCursor!=0 );
81317  assert( pC->isTable==0 );
81318  pFree = 0;
81319  if( pOp->p4.i>0 ){
81320  r.pKeyInfo = pC->pKeyInfo;
81321  r.nField = (u16)pOp->p4.i;
81322  r.aMem = pIn3;
81323 #ifdef SQLITE_DEBUG
81324  for(ii=0; ii<r.nField; ii++){
81325  assert( memIsValid(&r.aMem[ii]) );
81326  assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
81327  if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
81328  }
81329 #endif
81330  pIdxKey = &r;
81331  }else{
81333  pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
81334  );
81335  if( pIdxKey==0 ) goto no_mem;
81336  assert( pIn3->flags & MEM_Blob );
81337  (void)ExpandBlob(pIn3);
81338  sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
81339  }
81340  pIdxKey->default_rc = 0;
81341  takeJump = 0;
81342  if( pOp->opcode==OP_NoConflict ){
81343  /* For the OP_NoConflict opcode, take the jump if any of the
81344  ** input fields are NULL, since any key with a NULL will not
81345  ** conflict */
81346  for(ii=0; ii<pIdxKey->nField; ii++){
81347  if( pIdxKey->aMem[ii].flags & MEM_Null ){
81348  takeJump = 1;
81349  break;
81350  }
81351  }
81352  }
81353  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
81354  sqlite3DbFree(db, pFree);
81355  if( rc!=SQLITE_OK ){
81356  goto abort_due_to_error;
81357  }
81358  pC->seekResult = res;
81359  alreadyExists = (res==0);
81360  pC->nullRow = 1-alreadyExists;
81361  pC->deferredMoveto = 0;
81362  pC->cacheStatus = CACHE_STALE;
81363  if( pOp->opcode==OP_Found ){
81364  VdbeBranchTaken(alreadyExists!=0,2);
81365  if( alreadyExists ) goto jump_to_p2;
81366  }else{
81367  VdbeBranchTaken(takeJump||alreadyExists==0,2);
81368  if( takeJump || !alreadyExists ) goto jump_to_p2;
81369  }
81370  break;
81371 }
81372 
81373 /* Opcode: SeekRowid P1 P2 P3 * *
81374 ** Synopsis: intkey=r[P3]
81375 **
81376 ** P1 is the index of a cursor open on an SQL table btree (with integer
81377 ** keys). If register P3 does not contain an integer or if P1 does not
81378 ** contain a record with rowid P3 then jump immediately to P2.
81379 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
81380 ** a record with rowid P3 then
81381 ** leave the cursor pointing at that record and fall through to the next
81382 ** instruction.
81383 **
81384 ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
81385 ** the P3 register must be guaranteed to contain an integer value. With this
81386 ** opcode, register P3 might not contain an integer.
81387 **
81388 ** The OP_NotFound opcode performs the same operation on index btrees
81389 ** (with arbitrary multi-value keys).
81390 **
81391 ** This opcode leaves the cursor in a state where it cannot be advanced
81392 ** in either direction. In other words, the Next and Prev opcodes will
81393 ** not work following this opcode.
81394 **
81395 ** See also: Found, NotFound, NoConflict, SeekRowid
81396 */
81397 /* Opcode: NotExists P1 P2 P3 * *
81398 ** Synopsis: intkey=r[P3]
81399 **
81400 ** P1 is the index of a cursor open on an SQL table btree (with integer
81401 ** keys). P3 is an integer rowid. If P1 does not contain a record with
81402 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
81403 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
81404 ** leave the cursor pointing at that record and fall through to the next
81405 ** instruction.
81406 **
81407 ** The OP_SeekRowid opcode performs the same operation but also allows the
81408 ** P3 register to contain a non-integer value, in which case the jump is
81409 ** always taken. This opcode requires that P3 always contain an integer.
81410 **
81411 ** The OP_NotFound opcode performs the same operation on index btrees
81412 ** (with arbitrary multi-value keys).
81413 **
81414 ** This opcode leaves the cursor in a state where it cannot be advanced
81415 ** in either direction. In other words, the Next and Prev opcodes will
81416 ** not work following this opcode.
81417 **
81418 ** See also: Found, NotFound, NoConflict, SeekRowid
81419 */
81420 case OP_SeekRowid: { /* jump, in3 */
81421  VdbeCursor *pC;
81422  BtCursor *pCrsr;
81423  int res;
81424  u64 iKey;
81425 
81426  pIn3 = &aMem[pOp->p3];
81427  if( (pIn3->flags & MEM_Int)==0 ){
81428  applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
81429  if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
81430  }
81431  /* Fall through into OP_NotExists */
81432 case OP_NotExists: /* jump, in3 */
81433  pIn3 = &aMem[pOp->p3];
81434  assert( pIn3->flags & MEM_Int );
81435  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81436  pC = p->apCsr[pOp->p1];
81437  assert( pC!=0 );
81438 #ifdef SQLITE_DEBUG
81439  pC->seekOp = 0;
81440 #endif
81441  assert( pC->isTable );
81442  assert( pC->eCurType==CURTYPE_BTREE );
81443  pCrsr = pC->uc.pCursor;
81444  assert( pCrsr!=0 );
81445  res = 0;
81446  iKey = pIn3->u.i;
81447  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
81448  assert( rc==SQLITE_OK || res==0 );
81449  pC->movetoTarget = iKey; /* Used by OP_Delete */
81450  pC->nullRow = 0;
81451  pC->cacheStatus = CACHE_STALE;
81452  pC->deferredMoveto = 0;
81453  VdbeBranchTaken(res!=0,2);
81454  pC->seekResult = res;
81455  if( res!=0 ){
81456  assert( rc==SQLITE_OK );
81457  if( pOp->p2==0 ){
81458  rc = SQLITE_CORRUPT_BKPT;
81459  }else{
81460  goto jump_to_p2;
81461  }
81462  }
81463  if( rc ) goto abort_due_to_error;
81464  break;
81465 }
81466 
81467 /* Opcode: Sequence P1 P2 * * *
81468 ** Synopsis: r[P2]=cursor[P1].ctr++
81469 **
81470 ** Find the next available sequence number for cursor P1.
81471 ** Write the sequence number into register P2.
81472 ** The sequence number on the cursor is incremented after this
81473 ** instruction.
81474 */
81475 case OP_Sequence: { /* out2 */
81476  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81477  assert( p->apCsr[pOp->p1]!=0 );
81478  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
81479  pOut = out2Prerelease(p, pOp);
81480  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
81481  break;
81482 }
81483 
81484 
81485 /* Opcode: NewRowid P1 P2 P3 * *
81486 ** Synopsis: r[P2]=rowid
81487 **
81488 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
81489 ** The record number is not previously used as a key in the database
81490 ** table that cursor P1 points to. The new record number is written
81491 ** written to register P2.
81492 **
81493 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
81494 ** the largest previously generated record number. No new record numbers are
81495 ** allowed to be less than this value. When this value reaches its maximum,
81496 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
81497 ** generated record number. This P3 mechanism is used to help implement the
81498 ** AUTOINCREMENT feature.
81499 */
81500 case OP_NewRowid: { /* out2 */
81501  i64 v; /* The new rowid */
81502  VdbeCursor *pC; /* Cursor of table to get the new rowid */
81503  int res; /* Result of an sqlite3BtreeLast() */
81504  int cnt; /* Counter to limit the number of searches */
81505  Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
81506  VdbeFrame *pFrame; /* Root frame of VDBE */
81507 
81508  v = 0;
81509  res = 0;
81510  pOut = out2Prerelease(p, pOp);
81511  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81512  pC = p->apCsr[pOp->p1];
81513  assert( pC!=0 );
81514  assert( pC->eCurType==CURTYPE_BTREE );
81515  assert( pC->uc.pCursor!=0 );
81516  {
81517  /* The next rowid or record number (different terms for the same
81518  ** thing) is obtained in a two-step algorithm.
81519  **
81520  ** First we attempt to find the largest existing rowid and add one
81521  ** to that. But if the largest existing rowid is already the maximum
81522  ** positive integer, we have to fall through to the second
81523  ** probabilistic algorithm
81524  **
81525  ** The second algorithm is to select a rowid at random and see if
81526  ** it already exists in the table. If it does not exist, we have
81527  ** succeeded. If the random rowid does exist, we select a new one
81528  ** and try again, up to 100 times.
81529  */
81530  assert( pC->isTable );
81531 
81532 #ifdef SQLITE_32BIT_ROWID
81533 # define MAX_ROWID 0x7fffffff
81534 #else
81535  /* Some compilers complain about constants of the form 0x7fffffffffffffff.
81536  ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
81537  ** to provide the constant while making all compilers happy.
81538  */
81539 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
81540 #endif
81541 
81542  if( !pC->useRandomRowid ){
81543  rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
81544  if( rc!=SQLITE_OK ){
81545  goto abort_due_to_error;
81546  }
81547  if( res ){
81548  v = 1; /* IMP: R-61914-48074 */
81549  }else{
81550  assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
81552  if( v>=MAX_ROWID ){
81553  pC->useRandomRowid = 1;
81554  }else{
81555  v++; /* IMP: R-29538-34987 */
81556  }
81557  }
81558  }
81559 
81560 #ifndef SQLITE_OMIT_AUTOINCREMENT
81561  if( pOp->p3 ){
81562  /* Assert that P3 is a valid memory cell. */
81563  assert( pOp->p3>0 );
81564  if( p->pFrame ){
81565  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
81566  /* Assert that P3 is a valid memory cell. */
81567  assert( pOp->p3<=pFrame->nMem );
81568  pMem = &pFrame->aMem[pOp->p3];
81569  }else{
81570  /* Assert that P3 is a valid memory cell. */
81571  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
81572  pMem = &aMem[pOp->p3];
81573  memAboutToChange(p, pMem);
81574  }
81575  assert( memIsValid(pMem) );
81576 
81577  REGISTER_TRACE(pOp->p3, pMem);
81579  assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
81580  if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
81581  rc = SQLITE_FULL; /* IMP: R-12275-61338 */
81582  goto abort_due_to_error;
81583  }
81584  if( v<pMem->u.i+1 ){
81585  v = pMem->u.i + 1;
81586  }
81587  pMem->u.i = v;
81588  }
81589 #endif
81590  if( pC->useRandomRowid ){
81591  /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
81592  ** largest possible integer (9223372036854775807) then the database
81593  ** engine starts picking positive candidate ROWIDs at random until
81594  ** it finds one that is not previously used. */
81595  assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
81596  ** an AUTOINCREMENT table. */
81597  cnt = 0;
81598  do{
81599  sqlite3_randomness(sizeof(v), &v);
81600  v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
81601  }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
81602  0, &res))==SQLITE_OK)
81603  && (res==0)
81604  && (++cnt<100));
81605  if( rc ) goto abort_due_to_error;
81606  if( res==0 ){
81607  rc = SQLITE_FULL; /* IMP: R-38219-53002 */
81608  goto abort_due_to_error;
81609  }
81610  assert( v>0 ); /* EV: R-40812-03570 */
81611  }
81612  pC->deferredMoveto = 0;
81613  pC->cacheStatus = CACHE_STALE;
81614  }
81615  pOut->u.i = v;
81616  break;
81617 }
81618 
81619 /* Opcode: Insert P1 P2 P3 P4 P5
81620 ** Synopsis: intkey=r[P3] data=r[P2]
81621 **
81622 ** Write an entry into the table of cursor P1. A new entry is
81623 ** created if it doesn't already exist or the data for an existing
81624 ** entry is overwritten. The data is the value MEM_Blob stored in register
81625 ** number P2. The key is stored in register P3. The key must
81626 ** be a MEM_Int.
81627 **
81628 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
81629 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
81630 ** then rowid is stored for subsequent return by the
81631 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
81632 **
81633 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
81634 ** the last seek operation (OP_NotExists or OP_SeekRowid) was a success,
81635 ** then this
81636 ** operation will not attempt to find the appropriate row before doing
81637 ** the insert but will instead overwrite the row that the cursor is
81638 ** currently pointing to. Presumably, the prior OP_NotExists or
81639 ** OP_SeekRowid opcode
81640 ** has already positioned the cursor correctly. This is an optimization
81641 ** that boosts performance by avoiding redundant seeks.
81642 **
81643 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
81644 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
81645 ** is part of an INSERT operation. The difference is only important to
81646 ** the update hook.
81647 **
81648 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
81649 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
81650 ** following a successful insert.
81651 **
81652 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
81653 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
81654 ** and register P2 becomes ephemeral. If the cursor is changed, the
81655 ** value of register P2 will then change. Make sure this does not
81656 ** cause any problems.)
81657 **
81658 ** This instruction only works on tables. The equivalent instruction
81659 ** for indices is OP_IdxInsert.
81660 */
81661 /* Opcode: InsertInt P1 P2 P3 P4 P5
81662 ** Synopsis: intkey=P3 data=r[P2]
81663 **
81664 ** This works exactly like OP_Insert except that the key is the
81665 ** integer value P3, not the value of the integer stored in register P3.
81666 */
81667 case OP_Insert:
81668 case OP_InsertInt: {
81669  Mem *pData; /* MEM cell holding data for the record to be inserted */
81670  Mem *pKey; /* MEM cell holding key for the record */
81671  VdbeCursor *pC; /* Cursor to table into which insert is written */
81672  int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
81673  const char *zDb; /* database name - used by the update hook */
81674  Table *pTab; /* Table structure - used by update and pre-update hooks */
81675  int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
81676  BtreePayload x; /* Payload to be inserted */
81677 
81678  op = 0;
81679  pData = &aMem[pOp->p2];
81680  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81681  assert( memIsValid(pData) );
81682  pC = p->apCsr[pOp->p1];
81683  assert( pC!=0 );
81684  assert( pC->eCurType==CURTYPE_BTREE );
81685  assert( pC->uc.pCursor!=0 );
81686  assert( pC->isTable );
81687  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
81688  REGISTER_TRACE(pOp->p2, pData);
81689 
81690  if( pOp->opcode==OP_Insert ){
81691  pKey = &aMem[pOp->p3];
81692  assert( pKey->flags & MEM_Int );
81693  assert( memIsValid(pKey) );
81694  REGISTER_TRACE(pOp->p3, pKey);
81695  x.nKey = pKey->u.i;
81696  }else{
81697  assert( pOp->opcode==OP_InsertInt );
81698  x.nKey = pOp->p3;
81699  }
81700 
81701  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81702  assert( pC->isTable );
81703  assert( pC->iDb>=0 );
81704  zDb = db->aDb[pC->iDb].zDbSName;
81705  pTab = pOp->p4.pTab;
81706  assert( HasRowid(pTab) );
81707  op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
81708  }else{
81709  pTab = 0; /* Not needed. Silence a comiler warning. */
81710  zDb = 0; /* Not needed. Silence a compiler warning. */
81711  }
81712 
81713 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81714  /* Invoke the pre-update hook, if any */
81715  if( db->xPreUpdateCallback
81716  && pOp->p4type==P4_TABLE
81717  && !(pOp->p5 & OPFLAG_ISUPDATE)
81718  ){
81719  sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
81720  }
81721 #endif
81722 
81723  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
81724  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = x.nKey;
81725  if( pData->flags & MEM_Null ){
81726  x.pData = 0;
81727  x.nData = 0;
81728  }else{
81729  assert( pData->flags & (MEM_Blob|MEM_Str) );
81730  x.pData = pData->z;
81731  x.nData = pData->n;
81732  }
81733  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
81734  if( pData->flags & MEM_Zero ){
81735  x.nZero = pData->u.nZero;
81736  }else{
81737  x.nZero = 0;
81738  }
81739  x.pKey = 0;
81740  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
81741  (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
81742  );
81743  pC->deferredMoveto = 0;
81744  pC->cacheStatus = CACHE_STALE;
81745 
81746  /* Invoke the update-hook if required. */
81747  if( rc ) goto abort_due_to_error;
81748  if( db->xUpdateCallback && op ){
81749  db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
81750  }
81751  break;
81752 }
81753 
81754 /* Opcode: Delete P1 P2 P3 P4 P5
81755 **
81756 ** Delete the record at which the P1 cursor is currently pointing.
81757 **
81758 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
81759 ** the cursor will be left pointing at either the next or the previous
81760 ** record in the table. If it is left pointing at the next record, then
81761 ** the next Next instruction will be a no-op. As a result, in this case
81762 ** it is ok to delete a record from within a Next loop. If
81763 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
81764 ** left in an undefined state.
81765 **
81766 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
81767 ** delete one of several associated with deleting a table row and all its
81768 ** associated index entries. Exactly one of those deletes is the "primary"
81769 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
81770 ** marked with the AUXDELETE flag.
81771 **
81772 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
81773 ** change count is incremented (otherwise not).
81774 **
81775 ** P1 must not be pseudo-table. It has to be a real table with
81776 ** multiple rows.
81777 **
81778 ** If P4 is not NULL then it points to a Table object. In this case either
81779 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81780 ** have been positioned using OP_NotFound prior to invoking this opcode in
81781 ** this case. Specifically, if one is configured, the pre-update hook is
81782 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
81783 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81784 **
81785 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81786 ** of the memory cell that contains the value that the rowid of the row will
81787 ** be set to by the update.
81788 */
81789 case OP_Delete: {
81790  VdbeCursor *pC;
81791  const char *zDb;
81792  Table *pTab;
81793  int opflags;
81794 
81795  opflags = pOp->p2;
81796  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81797  pC = p->apCsr[pOp->p1];
81798  assert( pC!=0 );
81799  assert( pC->eCurType==CURTYPE_BTREE );
81800  assert( pC->uc.pCursor!=0 );
81801  assert( pC->deferredMoveto==0 );
81802 
81803 #ifdef SQLITE_DEBUG
81804  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81805  /* If p5 is zero, the seek operation that positioned the cursor prior to
81806  ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81807  ** the row that is being deleted */
81808  i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81809  assert( pC->movetoTarget==iKey );
81810  }
81811 #endif
81812 
81813  /* If the update-hook or pre-update-hook will be invoked, set zDb to
81814  ** the name of the db to pass as to it. Also set local pTab to a copy
81815  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81816  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
81817  ** VdbeCursor.movetoTarget to the current rowid. */
81818  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81819  assert( pC->iDb>=0 );
81820  assert( pOp->p4.pTab!=0 );
81821  zDb = db->aDb[pC->iDb].zDbSName;
81822  pTab = pOp->p4.pTab;
81823  if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81825  }
81826  }else{
81827  zDb = 0; /* Not needed. Silence a compiler warning. */
81828  pTab = 0; /* Not needed. Silence a compiler warning. */
81829  }
81830 
81831 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81832  /* Invoke the pre-update-hook if required. */
81833  if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81834  assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81835  sqlite3VdbePreUpdateHook(p, pC,
81836  (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
81837  zDb, pTab, pC->movetoTarget,
81838  pOp->p3
81839  );
81840  }
81841  if( opflags & OPFLAG_ISNOOP ) break;
81842 #endif
81843 
81844  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
81845  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
81847  assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
81848 
81849 #ifdef SQLITE_DEBUG
81850  if( p->pFrame==0 ){
81851  if( pC->isEphemeral==0
81852  && (pOp->p5 & OPFLAG_AUXDELETE)==0
81853  && (pC->wrFlag & OPFLAG_FORDELETE)==0
81854  ){
81855  nExtraDelete++;
81856  }
81857  if( pOp->p2 & OPFLAG_NCHANGE ){
81858  nExtraDelete--;
81859  }
81860  }
81861 #endif
81862 
81863  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
81864  pC->cacheStatus = CACHE_STALE;
81865  if( rc ) goto abort_due_to_error;
81866 
81867  /* Invoke the update-hook if required. */
81868  if( opflags & OPFLAG_NCHANGE ){
81869  p->nChange++;
81870  if( db->xUpdateCallback && HasRowid(pTab) ){
81871  db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81872  pC->movetoTarget);
81873  assert( pC->iDb>=0 );
81874  }
81875  }
81876 
81877  break;
81878 }
81879 /* Opcode: ResetCount * * * * *
81880 **
81881 ** The value of the change counter is copied to the database handle
81882 ** change counter (returned by subsequent calls to sqlite3_changes()).
81883 ** Then the VMs internal change counter resets to 0.
81884 ** This is used by trigger programs.
81885 */
81886 case OP_ResetCount: {
81888  p->nChange = 0;
81889  break;
81890 }
81891 
81892 /* Opcode: SorterCompare P1 P2 P3 P4
81893 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
81894 **
81895 ** P1 is a sorter cursor. This instruction compares a prefix of the
81896 ** record blob in register P3 against a prefix of the entry that
81897 ** the sorter cursor currently points to. Only the first P4 fields
81898 ** of r[P3] and the sorter record are compared.
81899 **
81900 ** If either P3 or the sorter contains a NULL in one of their significant
81901 ** fields (not counting the P4 fields at the end which are ignored) then
81902 ** the comparison is assumed to be equal.
81903 **
81904 ** Fall through to next instruction if the two records compare equal to
81905 ** each other. Jump to P2 if they are different.
81906 */
81907 case OP_SorterCompare: {
81908  VdbeCursor *pC;
81909  int res;
81910  int nKeyCol;
81911 
81912  pC = p->apCsr[pOp->p1];
81913  assert( isSorter(pC) );
81914  assert( pOp->p4type==P4_INT32 );
81915  pIn3 = &aMem[pOp->p3];
81916  nKeyCol = pOp->p4.i;
81917  res = 0;
81918  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
81919  VdbeBranchTaken(res!=0,2);
81920  if( rc ) goto abort_due_to_error;
81921  if( res ) goto jump_to_p2;
81922  break;
81923 };
81924 
81925 /* Opcode: SorterData P1 P2 P3 * *
81926 ** Synopsis: r[P2]=data
81927 **
81928 ** Write into register P2 the current sorter data for sorter cursor P1.
81929 ** Then clear the column header cache on cursor P3.
81930 **
81931 ** This opcode is normally use to move a record out of the sorter and into
81932 ** a register that is the source for a pseudo-table cursor created using
81933 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
81934 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
81935 ** us from having to issue a separate NullRow instruction to clear that cache.
81936 */
81937 case OP_SorterData: {
81938  VdbeCursor *pC;
81939 
81940  pOut = &aMem[pOp->p2];
81941  pC = p->apCsr[pOp->p1];
81942  assert( isSorter(pC) );
81943  rc = sqlite3VdbeSorterRowkey(pC, pOut);
81944  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
81945  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81946  if( rc ) goto abort_due_to_error;
81947  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
81948  break;
81949 }
81950 
81951 /* Opcode: RowData P1 P2 * * *
81952 ** Synopsis: r[P2]=data
81953 **
81954 ** Write into register P2 the complete row data for cursor P1.
81955 ** There is no interpretation of the data.
81956 ** It is just copied onto the P2 register exactly as
81957 ** it is found in the database file.
81958 **
81959 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81960 ** of a real table, not a pseudo-table.
81961 */
81962 /* Opcode: RowKey P1 P2 * * *
81963 ** Synopsis: r[P2]=key
81964 **
81965 ** Write into register P2 the complete row key for cursor P1.
81966 ** There is no interpretation of the data.
81967 ** The key is copied onto the P2 register exactly as
81968 ** it is found in the database file.
81969 **
81970 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81971 ** of a real table, not a pseudo-table.
81972 */
81973 case OP_RowKey:
81974 case OP_RowData: {
81975  VdbeCursor *pC;
81976  BtCursor *pCrsr;
81977  u32 n;
81978 
81979  pOut = &aMem[pOp->p2];
81980  memAboutToChange(p, pOut);
81981 
81982  /* Note that RowKey and RowData are really exactly the same instruction */
81983  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81984  pC = p->apCsr[pOp->p1];
81985  assert( pC!=0 );
81986  assert( pC->eCurType==CURTYPE_BTREE );
81987  assert( isSorter(pC)==0 );
81988  assert( pC->isTable || pOp->opcode!=OP_RowData );
81989  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
81990  assert( pC->nullRow==0 );
81991  assert( pC->uc.pCursor!=0 );
81992  pCrsr = pC->uc.pCursor;
81993 
81994  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
81995  ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
81996  ** that might invalidate the cursor.
81997  ** If this where not the case, on of the following assert()s
81998  ** would fail. Should this ever change (because of changes in the code
81999  ** generator) then the fix would be to insert a call to
82000  ** sqlite3VdbeCursorMoveto().
82001  */
82002  assert( pC->deferredMoveto==0 );
82003  assert( sqlite3BtreeCursorIsValid(pCrsr) );
82004 #if 0 /* Not required due to the previous to assert() statements */
82005  rc = sqlite3VdbeCursorMoveto(pC);
82006  if( rc!=SQLITE_OK ) goto abort_due_to_error;
82007 #endif
82008 
82009  n = sqlite3BtreePayloadSize(pCrsr);
82010  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
82011  goto too_big;
82012  }
82013  testcase( n==0 );
82014  if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
82015  goto no_mem;
82016  }
82017  pOut->n = n;
82018  MemSetTypeFlag(pOut, MEM_Blob);
82019  if( pC->isTable==0 ){
82020  rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
82021  }else{
82022  rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
82023  }
82024  if( rc ) goto abort_due_to_error;
82025  pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
82026  UPDATE_MAX_BLOBSIZE(pOut);
82027  REGISTER_TRACE(pOp->p2, pOut);
82028  break;
82029 }
82030 
82031 /* Opcode: Rowid P1 P2 * * *
82032 ** Synopsis: r[P2]=rowid
82033 **
82034 ** Store in register P2 an integer which is the key of the table entry that
82035 ** P1 is currently point to.
82036 **
82037 ** P1 can be either an ordinary table or a virtual table. There used to
82038 ** be a separate OP_VRowid opcode for use with virtual tables, but this
82039 ** one opcode now works for both table types.
82040 */
82041 case OP_Rowid: { /* out2 */
82042  VdbeCursor *pC;
82043  i64 v;
82044  sqlite3_vtab *pVtab;
82045  const sqlite3_module *pModule;
82046 
82047  pOut = out2Prerelease(p, pOp);
82048  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82049  pC = p->apCsr[pOp->p1];
82050  assert( pC!=0 );
82051  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
82052  if( pC->nullRow ){
82053  pOut->flags = MEM_Null;
82054  break;
82055  }else if( pC->deferredMoveto ){
82056  v = pC->movetoTarget;
82057 #ifndef SQLITE_OMIT_VIRTUALTABLE
82058  }else if( pC->eCurType==CURTYPE_VTAB ){
82059  assert( pC->uc.pVCur!=0 );
82060  pVtab = pC->uc.pVCur->pVtab;
82061  pModule = pVtab->pModule;
82062  assert( pModule->xRowid );
82063  rc = pModule->xRowid(pC->uc.pVCur, &v);
82064  sqlite3VtabImportErrmsg(p, pVtab);
82065  if( rc ) goto abort_due_to_error;
82066 #endif /* SQLITE_OMIT_VIRTUALTABLE */
82067  }else{
82068  assert( pC->eCurType==CURTYPE_BTREE );
82069  assert( pC->uc.pCursor!=0 );
82070  rc = sqlite3VdbeCursorRestore(pC);
82071  if( rc ) goto abort_due_to_error;
82072  if( pC->nullRow ){
82073  pOut->flags = MEM_Null;
82074  break;
82075  }
82077  }
82078  pOut->u.i = v;
82079  break;
82080 }
82081 
82082 /* Opcode: NullRow P1 * * * *
82083 **
82084 ** Move the cursor P1 to a null row. Any OP_Column operations
82085 ** that occur while the cursor is on the null row will always
82086 ** write a NULL.
82087 */
82088 case OP_NullRow: {
82089  VdbeCursor *pC;
82090 
82091  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82092  pC = p->apCsr[pOp->p1];
82093  assert( pC!=0 );
82094  pC->nullRow = 1;
82095  pC->cacheStatus = CACHE_STALE;
82096  if( pC->eCurType==CURTYPE_BTREE ){
82097  assert( pC->uc.pCursor!=0 );
82099  }
82100  break;
82101 }
82102 
82103 /* Opcode: Last P1 P2 P3 * *
82104 **
82105 ** The next use of the Rowid or Column or Prev instruction for P1
82106 ** will refer to the last entry in the database table or index.
82107 ** If the table or index is empty and P2>0, then jump immediately to P2.
82108 ** If P2 is 0 or if the table or index is not empty, fall through
82109 ** to the following instruction.
82110 **
82111 ** This opcode leaves the cursor configured to move in reverse order,
82112 ** from the end toward the beginning. In other words, the cursor is
82113 ** configured to use Prev, not Next.
82114 */
82115 case OP_Last: { /* jump */
82116  VdbeCursor *pC;
82117  BtCursor *pCrsr;
82118  int res;
82119 
82120  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82121  pC = p->apCsr[pOp->p1];
82122  assert( pC!=0 );
82123  assert( pC->eCurType==CURTYPE_BTREE );
82124  pCrsr = pC->uc.pCursor;
82125  res = 0;
82126  assert( pCrsr!=0 );
82127  rc = sqlite3BtreeLast(pCrsr, &res);
82128  pC->nullRow = (u8)res;
82129  pC->deferredMoveto = 0;
82130  pC->cacheStatus = CACHE_STALE;
82131  pC->seekResult = pOp->p3;
82132 #ifdef SQLITE_DEBUG
82133  pC->seekOp = OP_Last;
82134 #endif
82135  if( rc ) goto abort_due_to_error;
82136  if( pOp->p2>0 ){
82137  VdbeBranchTaken(res!=0,2);
82138  if( res ) goto jump_to_p2;
82139  }
82140  break;
82141 }
82142 
82143 
82144 /* Opcode: Sort P1 P2 * * *
82145 **
82146 ** This opcode does exactly the same thing as OP_Rewind except that
82147 ** it increments an undocumented global variable used for testing.
82148 **
82149 ** Sorting is accomplished by writing records into a sorting index,
82150 ** then rewinding that index and playing it back from beginning to
82151 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
82152 ** rewinding so that the global variable will be incremented and
82153 ** regression tests can determine whether or not the optimizer is
82154 ** correctly optimizing out sorts.
82155 */
82156 case OP_SorterSort: /* jump */
82157 case OP_Sort: { /* jump */
82158 #ifdef SQLITE_TEST
82159  sqlite3_sort_count++;
82160  sqlite3_search_count--;
82161 #endif
82163  /* Fall through into OP_Rewind */
82164 }
82165 /* Opcode: Rewind P1 P2 * * *
82166 **
82167 ** The next use of the Rowid or Column or Next instruction for P1
82168 ** will refer to the first entry in the database table or index.
82169 ** If the table or index is empty, jump immediately to P2.
82170 ** If the table or index is not empty, fall through to the following
82171 ** instruction.
82172 **
82173 ** This opcode leaves the cursor configured to move in forward order,
82174 ** from the beginning toward the end. In other words, the cursor is
82175 ** configured to use Next, not Prev.
82176 */
82177 case OP_Rewind: { /* jump */
82178  VdbeCursor *pC;
82179  BtCursor *pCrsr;
82180  int res;
82181 
82182  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82183  pC = p->apCsr[pOp->p1];
82184  assert( pC!=0 );
82185  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
82186  res = 1;
82187 #ifdef SQLITE_DEBUG
82188  pC->seekOp = OP_Rewind;
82189 #endif
82190  if( isSorter(pC) ){
82191  rc = sqlite3VdbeSorterRewind(pC, &res);
82192  }else{
82193  assert( pC->eCurType==CURTYPE_BTREE );
82194  pCrsr = pC->uc.pCursor;
82195  assert( pCrsr );
82196  rc = sqlite3BtreeFirst(pCrsr, &res);
82197  pC->deferredMoveto = 0;
82198  pC->cacheStatus = CACHE_STALE;
82199  }
82200  if( rc ) goto abort_due_to_error;
82201  pC->nullRow = (u8)res;
82202  assert( pOp->p2>0 && pOp->p2<p->nOp );
82203  VdbeBranchTaken(res!=0,2);
82204  if( res ) goto jump_to_p2;
82205  break;
82206 }
82207 
82208 /* Opcode: Next P1 P2 P3 P4 P5
82209 **
82210 ** Advance cursor P1 so that it points to the next key/data pair in its
82211 ** table or index. If there are no more key/value pairs then fall through
82212 ** to the following instruction. But if the cursor advance was successful,
82213 ** jump immediately to P2.
82214 **
82215 ** The Next opcode is only valid following an SeekGT, SeekGE, or
82216 ** OP_Rewind opcode used to position the cursor. Next is not allowed
82217 ** to follow SeekLT, SeekLE, or OP_Last.
82218 **
82219 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
82220 ** been opened prior to this opcode or the program will segfault.
82221 **
82222 ** The P3 value is a hint to the btree implementation. If P3==1, that
82223 ** means P1 is an SQL index and that this instruction could have been
82224 ** omitted if that index had been unique. P3 is usually 0. P3 is
82225 ** always either 0 or 1.
82226 **
82227 ** P4 is always of type P4_ADVANCE. The function pointer points to
82228 ** sqlite3BtreeNext().
82229 **
82230 ** If P5 is positive and the jump is taken, then event counter
82231 ** number P5-1 in the prepared statement is incremented.
82232 **
82233 ** See also: Prev, NextIfOpen
82234 */
82235 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
82236 **
82237 ** This opcode works just like Next except that if cursor P1 is not
82238 ** open it behaves a no-op.
82239 */
82240 /* Opcode: Prev P1 P2 P3 P4 P5
82241 **
82242 ** Back up cursor P1 so that it points to the previous key/data pair in its
82243 ** table or index. If there is no previous key/value pairs then fall through
82244 ** to the following instruction. But if the cursor backup was successful,
82245 ** jump immediately to P2.
82246 **
82247 **
82248 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
82249 ** OP_Last opcode used to position the cursor. Prev is not allowed
82250 ** to follow SeekGT, SeekGE, or OP_Rewind.
82251 **
82252 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
82253 ** not open then the behavior is undefined.
82254 **
82255 ** The P3 value is a hint to the btree implementation. If P3==1, that
82256 ** means P1 is an SQL index and that this instruction could have been
82257 ** omitted if that index had been unique. P3 is usually 0. P3 is
82258 ** always either 0 or 1.
82259 **
82260 ** P4 is always of type P4_ADVANCE. The function pointer points to
82261 ** sqlite3BtreePrevious().
82262 **
82263 ** If P5 is positive and the jump is taken, then event counter
82264 ** number P5-1 in the prepared statement is incremented.
82265 */
82266 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
82267 **
82268 ** This opcode works just like Prev except that if cursor P1 is not
82269 ** open it behaves a no-op.
82270 */
82271 case OP_SorterNext: { /* jump */
82272  VdbeCursor *pC;
82273  int res;
82274 
82275  pC = p->apCsr[pOp->p1];
82276  assert( isSorter(pC) );
82277  res = 0;
82278  rc = sqlite3VdbeSorterNext(db, pC, &res);
82279  goto next_tail;
82280 case OP_PrevIfOpen: /* jump */
82281 case OP_NextIfOpen: /* jump */
82282  if( p->apCsr[pOp->p1]==0 ) break;
82283  /* Fall through */
82284 case OP_Prev: /* jump */
82285 case OP_Next: /* jump */
82286  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82287  assert( pOp->p5<ArraySize(p->aCounter) );
82288  pC = p->apCsr[pOp->p1];
82289  res = pOp->p3;
82290  assert( pC!=0 );
82291  assert( pC->deferredMoveto==0 );
82292  assert( pC->eCurType==CURTYPE_BTREE );
82293  assert( res==0 || (res==1 && pC->isTable==0) );
82294  testcase( res==1 );
82295  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
82296  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
82297  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
82298  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
82299 
82300  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
82301  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
82302  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
82303  || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
82304  || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
82305  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
82306  || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
82307  || pC->seekOp==OP_Last );
82308 
82309  rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
82310 next_tail:
82311  pC->cacheStatus = CACHE_STALE;
82312  VdbeBranchTaken(res==0,2);
82313  if( rc ) goto abort_due_to_error;
82314  if( res==0 ){
82315  pC->nullRow = 0;
82316  p->aCounter[pOp->p5]++;
82317 #ifdef SQLITE_TEST
82318  sqlite3_search_count++;
82319 #endif
82320  goto jump_to_p2_and_check_for_interrupt;
82321  }else{
82322  pC->nullRow = 1;
82323  }
82324  goto check_for_interrupt;
82325 }
82326 
82327 /* Opcode: IdxInsert P1 P2 P3 * P5
82328 ** Synopsis: key=r[P2]
82329 **
82330 ** Register P2 holds an SQL index key made using the
82331 ** MakeRecord instructions. This opcode writes that key
82332 ** into the index P1. Data for the entry is nil.
82333 **
82334 ** P3 is a flag that provides a hint to the b-tree layer that this
82335 ** insert is likely to be an append.
82336 **
82337 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
82338 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
82339 ** then the change counter is unchanged.
82340 **
82341 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
82342 ** just done a seek to the spot where the new entry is to be inserted.
82343 ** This flag avoids doing an extra seek.
82344 **
82345 ** This instruction only works for indices. The equivalent instruction
82346 ** for tables is OP_Insert.
82347 */
82348 case OP_SorterInsert: /* in2 */
82349 case OP_IdxInsert: { /* in2 */
82350  VdbeCursor *pC;
82351  BtreePayload x;
82352 
82353  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82354  pC = p->apCsr[pOp->p1];
82355  assert( pC!=0 );
82356  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
82357  pIn2 = &aMem[pOp->p2];
82358  assert( pIn2->flags & MEM_Blob );
82359  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
82360  assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
82361  assert( pC->isTable==0 );
82362  rc = ExpandBlob(pIn2);
82363  if( rc ) goto abort_due_to_error;
82364  if( pOp->opcode==OP_SorterInsert ){
82365  rc = sqlite3VdbeSorterWrite(pC, pIn2);
82366  }else{
82367  x.nKey = pIn2->n;
82368  x.pKey = pIn2->z;
82369  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, pOp->p3,
82370  ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
82371  );
82372  assert( pC->deferredMoveto==0 );
82373  pC->cacheStatus = CACHE_STALE;
82374  }
82375  if( rc) goto abort_due_to_error;
82376  break;
82377 }
82378 
82379 /* Opcode: IdxDelete P1 P2 P3 * *
82380 ** Synopsis: key=r[P2@P3]
82381 **
82382 ** The content of P3 registers starting at register P2 form
82383 ** an unpacked index key. This opcode removes that entry from the
82384 ** index opened by cursor P1.
82385 */
82386 case OP_IdxDelete: {
82387  VdbeCursor *pC;
82388  BtCursor *pCrsr;
82389  int res;
82390  UnpackedRecord r;
82391 
82392  assert( pOp->p3>0 );
82393  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
82394  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82395  pC = p->apCsr[pOp->p1];
82396  assert( pC!=0 );
82397  assert( pC->eCurType==CURTYPE_BTREE );
82398  pCrsr = pC->uc.pCursor;
82399  assert( pCrsr!=0 );
82400  assert( pOp->p5==0 );
82401  r.pKeyInfo = pC->pKeyInfo;
82402  r.nField = (u16)pOp->p3;
82403  r.default_rc = 0;
82404  r.aMem = &aMem[pOp->p2];
82405  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
82406  if( rc ) goto abort_due_to_error;
82407  if( res==0 ){
82408  rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
82409  if( rc ) goto abort_due_to_error;
82410  }
82411  assert( pC->deferredMoveto==0 );
82412  pC->cacheStatus = CACHE_STALE;
82413  break;
82414 }
82415 
82416 /* Opcode: Seek P1 * P3 P4 *
82417 ** Synopsis: Move P3 to P1.rowid
82418 **
82419 ** P1 is an open index cursor and P3 is a cursor on the corresponding
82420 ** table. This opcode does a deferred seek of the P3 table cursor
82421 ** to the row that corresponds to the current row of P1.
82422 **
82423 ** This is a deferred seek. Nothing actually happens until
82424 ** the cursor is used to read a record. That way, if no reads
82425 ** occur, no unnecessary I/O happens.
82426 **
82427 ** P4 may be an array of integers (type P4_INTARRAY) containing
82428 ** one entry for each column in the P3 table. If array entry a(i)
82429 ** is non-zero, then reading column a(i)-1 from cursor P3 is
82430 ** equivalent to performing the deferred seek and then reading column i
82431 ** from P1. This information is stored in P3 and used to redirect
82432 ** reads against P3 over to P1, thus possibly avoiding the need to
82433 ** seek and read cursor P3.
82434 */
82435 /* Opcode: IdxRowid P1 P2 * * *
82436 ** Synopsis: r[P2]=rowid
82437 **
82438 ** Write into register P2 an integer which is the last entry in the record at
82439 ** the end of the index key pointed to by cursor P1. This integer should be
82440 ** the rowid of the table entry to which this index entry points.
82441 **
82442 ** See also: Rowid, MakeRecord.
82443 */
82444 case OP_Seek:
82445 case OP_IdxRowid: { /* out2 */
82446  VdbeCursor *pC; /* The P1 index cursor */
82447  VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */
82448  i64 rowid; /* Rowid that P1 current points to */
82449 
82450  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82451  pC = p->apCsr[pOp->p1];
82452  assert( pC!=0 );
82453  assert( pC->eCurType==CURTYPE_BTREE );
82454  assert( pC->uc.pCursor!=0 );
82455  assert( pC->isTable==0 );
82456  assert( pC->deferredMoveto==0 );
82457  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
82458 
82459  /* The IdxRowid and Seek opcodes are combined because of the commonality
82460  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
82461  rc = sqlite3VdbeCursorRestore(pC);
82462 
82463  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
82464  ** out from under the cursor. That will never happens for an IdxRowid
82465  ** or Seek opcode */
82466  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
82467 
82468  if( !pC->nullRow ){
82469  rowid = 0; /* Not needed. Only used to silence a warning. */
82470  rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
82471  if( rc!=SQLITE_OK ){
82472  goto abort_due_to_error;
82473  }
82474  if( pOp->opcode==OP_Seek ){
82475  assert( pOp->p3>=0 && pOp->p3<p->nCursor );
82476  pTabCur = p->apCsr[pOp->p3];
82477  assert( pTabCur!=0 );
82478  assert( pTabCur->eCurType==CURTYPE_BTREE );
82479  assert( pTabCur->uc.pCursor!=0 );
82480  assert( pTabCur->isTable );
82481  pTabCur->nullRow = 0;
82482  pTabCur->movetoTarget = rowid;
82483  pTabCur->deferredMoveto = 1;
82484  assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
82485  pTabCur->aAltMap = pOp->p4.ai;
82486  pTabCur->pAltCursor = pC;
82487  }else{
82488  pOut = out2Prerelease(p, pOp);
82489  pOut->u.i = rowid;
82490  pOut->flags = MEM_Int;
82491  }
82492  }else{
82493  assert( pOp->opcode==OP_IdxRowid );
82494  sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
82495  }
82496  break;
82497 }
82498 
82499 /* Opcode: IdxGE P1 P2 P3 P4 P5
82500 ** Synopsis: key=r[P3@P4]
82501 **
82502 ** The P4 register values beginning with P3 form an unpacked index
82503 ** key that omits the PRIMARY KEY. Compare this key value against the index
82504 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82505 ** fields at the end.
82506 **
82507 ** If the P1 index entry is greater than or equal to the key value
82508 ** then jump to P2. Otherwise fall through to the next instruction.
82509 */
82510 /* Opcode: IdxGT P1 P2 P3 P4 P5
82511 ** Synopsis: key=r[P3@P4]
82512 **
82513 ** The P4 register values beginning with P3 form an unpacked index
82514 ** key that omits the PRIMARY KEY. Compare this key value against the index
82515 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
82516 ** fields at the end.
82517 **
82518 ** If the P1 index entry is greater than the key value
82519 ** then jump to P2. Otherwise fall through to the next instruction.
82520 */
82521 /* Opcode: IdxLT P1 P2 P3 P4 P5
82522 ** Synopsis: key=r[P3@P4]
82523 **
82524 ** The P4 register values beginning with P3 form an unpacked index
82525 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
82526 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82527 ** ROWID on the P1 index.
82528 **
82529 ** If the P1 index entry is less than the key value then jump to P2.
82530 ** Otherwise fall through to the next instruction.
82531 */
82532 /* Opcode: IdxLE P1 P2 P3 P4 P5
82533 ** Synopsis: key=r[P3@P4]
82534 **
82535 ** The P4 register values beginning with P3 form an unpacked index
82536 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
82537 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82538 ** ROWID on the P1 index.
82539 **
82540 ** If the P1 index entry is less than or equal to the key value then jump
82541 ** to P2. Otherwise fall through to the next instruction.
82542 */
82543 case OP_IdxLE: /* jump */
82544 case OP_IdxGT: /* jump */
82545 case OP_IdxLT: /* jump */
82546 case OP_IdxGE: { /* jump */
82547  VdbeCursor *pC;
82548  int res;
82549  UnpackedRecord r;
82550 
82551  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82552  pC = p->apCsr[pOp->p1];
82553  assert( pC!=0 );
82554  assert( pC->isOrdered );
82555  assert( pC->eCurType==CURTYPE_BTREE );
82556  assert( pC->uc.pCursor!=0);
82557  assert( pC->deferredMoveto==0 );
82558  assert( pOp->p5==0 || pOp->p5==1 );
82559  assert( pOp->p4type==P4_INT32 );
82560  r.pKeyInfo = pC->pKeyInfo;
82561  r.nField = (u16)pOp->p4.i;
82562  if( pOp->opcode<OP_IdxLT ){
82563  assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
82564  r.default_rc = -1;
82565  }else{
82566  assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
82567  r.default_rc = 0;
82568  }
82569  r.aMem = &aMem[pOp->p3];
82570 #ifdef SQLITE_DEBUG
82571  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
82572 #endif
82573  res = 0; /* Not needed. Only used to silence a warning. */
82574  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
82575  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
82576  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
82577  assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
82578  res = -res;
82579  }else{
82580  assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
82581  res++;
82582  }
82583  VdbeBranchTaken(res>0,2);
82584  if( rc ) goto abort_due_to_error;
82585  if( res>0 ) goto jump_to_p2;
82586  break;
82587 }
82588 
82589 /* Opcode: Destroy P1 P2 P3 * *
82590 **
82591 ** Delete an entire database table or index whose root page in the database
82592 ** file is given by P1.
82593 **
82594 ** The table being destroyed is in the main database file if P3==0. If
82595 ** P3==1 then the table to be clear is in the auxiliary database file
82596 ** that is used to store tables create using CREATE TEMPORARY TABLE.
82597 **
82598 ** If AUTOVACUUM is enabled then it is possible that another root page
82599 ** might be moved into the newly deleted root page in order to keep all
82600 ** root pages contiguous at the beginning of the database. The former
82601 ** value of the root page that moved - its value before the move occurred -
82602 ** is stored in register P2. If no page
82603 ** movement was required (because the table being dropped was already
82604 ** the last one in the database) then a zero is stored in register P2.
82605 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
82606 **
82607 ** See also: Clear
82608 */
82609 case OP_Destroy: { /* out2 */
82610  int iMoved;
82611  int iDb;
82612 
82613  assert( p->readOnly==0 );
82614  assert( pOp->p1>1 );
82615  pOut = out2Prerelease(p, pOp);
82616  pOut->flags = MEM_Null;
82617  if( db->nVdbeRead > db->nVDestroy+1 ){
82618  rc = SQLITE_LOCKED;
82619  p->errorAction = OE_Abort;
82620  goto abort_due_to_error;
82621  }else{
82622  iDb = pOp->p3;
82623  assert( DbMaskTest(p->btreeMask, iDb) );
82624  iMoved = 0; /* Not needed. Only to silence a warning. */
82625  rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
82626  pOut->flags = MEM_Int;
82627  pOut->u.i = iMoved;
82628  if( rc ) goto abort_due_to_error;
82629 #ifndef SQLITE_OMIT_AUTOVACUUM
82630  if( iMoved!=0 ){
82631  sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
82632  /* All OP_Destroy operations occur on the same btree */
82633  assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
82634  resetSchemaOnFault = iDb+1;
82635  }
82636 #endif
82637  }
82638  break;
82639 }
82640 
82641 /* Opcode: Clear P1 P2 P3
82642 **
82643 ** Delete all contents of the database table or index whose root page
82644 ** in the database file is given by P1. But, unlike Destroy, do not
82645 ** remove the table or index from the database file.
82646 **
82647 ** The table being clear is in the main database file if P2==0. If
82648 ** P2==1 then the table to be clear is in the auxiliary database file
82649 ** that is used to store tables create using CREATE TEMPORARY TABLE.
82650 **
82651 ** If the P3 value is non-zero, then the table referred to must be an
82652 ** intkey table (an SQL table, not an index). In this case the row change
82653 ** count is incremented by the number of rows in the table being cleared.
82654 ** If P3 is greater than zero, then the value stored in register P3 is
82655 ** also incremented by the number of rows in the table being cleared.
82656 **
82657 ** See also: Destroy
82658 */
82659 case OP_Clear: {
82660  int nChange;
82661 
82662  nChange = 0;
82663  assert( p->readOnly==0 );
82664  assert( DbMaskTest(p->btreeMask, pOp->p2) );
82666  db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
82667  );
82668  if( pOp->p3 ){
82669  p->nChange += nChange;
82670  if( pOp->p3>0 ){
82671  assert( memIsValid(&aMem[pOp->p3]) );
82672  memAboutToChange(p, &aMem[pOp->p3]);
82673  aMem[pOp->p3].u.i += nChange;
82674  }
82675  }
82676  if( rc ) goto abort_due_to_error;
82677  break;
82678 }
82679 
82680 /* Opcode: ResetSorter P1 * * * *
82681 **
82682 ** Delete all contents from the ephemeral table or sorter
82683 ** that is open on cursor P1.
82684 **
82685 ** This opcode only works for cursors used for sorting and
82686 ** opened with OP_OpenEphemeral or OP_SorterOpen.
82687 */
82688 case OP_ResetSorter: {
82689  VdbeCursor *pC;
82690 
82691  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82692  pC = p->apCsr[pOp->p1];
82693  assert( pC!=0 );
82694  if( isSorter(pC) ){
82696  }else{
82697  assert( pC->eCurType==CURTYPE_BTREE );
82698  assert( pC->isEphemeral );
82700  if( rc ) goto abort_due_to_error;
82701  }
82702  break;
82703 }
82704 
82705 /* Opcode: CreateTable P1 P2 * * *
82706 ** Synopsis: r[P2]=root iDb=P1
82707 **
82708 ** Allocate a new table in the main database file if P1==0 or in the
82709 ** auxiliary database file if P1==1 or in an attached database if
82710 ** P1>1. Write the root page number of the new table into
82711 ** register P2
82712 **
82713 ** The difference between a table and an index is this: A table must
82714 ** have a 4-byte integer key and can have arbitrary data. An index
82715 ** has an arbitrary key but no data.
82716 **
82717 ** See also: CreateIndex
82718 */
82719 /* Opcode: CreateIndex P1 P2 * * *
82720 ** Synopsis: r[P2]=root iDb=P1
82721 **
82722 ** Allocate a new index in the main database file if P1==0 or in the
82723 ** auxiliary database file if P1==1 or in an attached database if
82724 ** P1>1. Write the root page number of the new table into
82725 ** register P2.
82726 **
82727 ** See documentation on OP_CreateTable for additional information.
82728 */
82729 case OP_CreateIndex: /* out2 */
82730 case OP_CreateTable: { /* out2 */
82731  int pgno;
82732  int flags;
82733  Db *pDb;
82734 
82735  pOut = out2Prerelease(p, pOp);
82736  pgno = 0;
82737  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82738  assert( DbMaskTest(p->btreeMask, pOp->p1) );
82739  assert( p->readOnly==0 );
82740  pDb = &db->aDb[pOp->p1];
82741  assert( pDb->pBt!=0 );
82742  if( pOp->opcode==OP_CreateTable ){
82743  /* flags = BTREE_INTKEY; */
82744  flags = BTREE_INTKEY;
82745  }else{
82746  flags = BTREE_BLOBKEY;
82747  }
82748  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
82749  if( rc ) goto abort_due_to_error;
82750  pOut->u.i = pgno;
82751  break;
82752 }
82753 
82754 /* Opcode: ParseSchema P1 * * P4 *
82755 **
82756 ** Read and parse all entries from the SQLITE_MASTER table of database P1
82757 ** that match the WHERE clause P4.
82758 **
82759 ** This opcode invokes the parser to create a new virtual machine,
82760 ** then runs the new virtual machine. It is thus a re-entrant opcode.
82761 */
82762 case OP_ParseSchema: {
82763  int iDb;
82764  const char *zMaster;
82765  char *zSql;
82766  InitData initData;
82767 
82768  /* Any prepared statement that invokes this opcode will hold mutexes
82769  ** on every btree. This is a prerequisite for invoking
82770  ** sqlite3InitCallback().
82771  */
82772 #ifdef SQLITE_DEBUG
82773  for(iDb=0; iDb<db->nDb; iDb++){
82774  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
82775  }
82776 #endif
82777 
82778  iDb = pOp->p1;
82779  assert( iDb>=0 && iDb<db->nDb );
82780  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
82781  /* Used to be a conditional */ {
82782  zMaster = SCHEMA_TABLE(iDb);
82783  initData.db = db;
82784  initData.iDb = pOp->p1;
82785  initData.pzErrMsg = &p->zErrMsg;
82786  zSql = sqlite3MPrintf(db,
82787  "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
82788  db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
82789  if( zSql==0 ){
82790  rc = SQLITE_NOMEM_BKPT;
82791  }else{
82792  assert( db->init.busy==0 );
82793  db->init.busy = 1;
82794  initData.rc = SQLITE_OK;
82795  assert( !db->mallocFailed );
82796  rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
82797  if( rc==SQLITE_OK ) rc = initData.rc;
82798  sqlite3DbFree(db, zSql);
82799  db->init.busy = 0;
82800  }
82801  }
82802  if( rc ){
82804  if( rc==SQLITE_NOMEM ){
82805  goto no_mem;
82806  }
82807  goto abort_due_to_error;
82808  }
82809  break;
82810 }
82811 
82812 #if !defined(SQLITE_OMIT_ANALYZE)
82813 /* Opcode: LoadAnalysis P1 * * * *
82814 **
82815 ** Read the sqlite_stat1 table for database P1 and load the content
82816 ** of that table into the internal index hash table. This will cause
82817 ** the analysis to be used when preparing all subsequent queries.
82818 */
82819 case OP_LoadAnalysis: {
82820  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82821  rc = sqlite3AnalysisLoad(db, pOp->p1);
82822  if( rc ) goto abort_due_to_error;
82823  break;
82824 }
82825 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
82826 
82827 /* Opcode: DropTable P1 * * P4 *
82828 **
82829 ** Remove the internal (in-memory) data structures that describe
82830 ** the table named P4 in database P1. This is called after a table
82831 ** is dropped from disk (using the Destroy opcode) in order to keep
82832 ** the internal representation of the
82833 ** schema consistent with what is on disk.
82834 */
82835 case OP_DropTable: {
82836  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
82837  break;
82838 }
82839 
82840 /* Opcode: DropIndex P1 * * P4 *
82841 **
82842 ** Remove the internal (in-memory) data structures that describe
82843 ** the index named P4 in database P1. This is called after an index
82844 ** is dropped from disk (using the Destroy opcode)
82845 ** in order to keep the internal representation of the
82846 ** schema consistent with what is on disk.
82847 */
82848 case OP_DropIndex: {
82849  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
82850  break;
82851 }
82852 
82853 /* Opcode: DropTrigger P1 * * P4 *
82854 **
82855 ** Remove the internal (in-memory) data structures that describe
82856 ** the trigger named P4 in database P1. This is called after a trigger
82857 ** is dropped from disk (using the Destroy opcode) in order to keep
82858 ** the internal representation of the
82859 ** schema consistent with what is on disk.
82860 */
82861 case OP_DropTrigger: {
82862  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
82863  break;
82864 }
82865 
82866 
82867 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
82868 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
82869 **
82870 ** Do an analysis of the currently open database. Store in
82871 ** register P1 the text of an error message describing any problems.
82872 ** If no problems are found, store a NULL in register P1.
82873 **
82874 ** The register P3 contains the maximum number of allowed errors.
82875 ** At most reg(P3) errors will be reported.
82876 ** In other words, the analysis stops as soon as reg(P1) errors are
82877 ** seen. Reg(P1) is updated with the number of errors remaining.
82878 **
82879 ** The root page numbers of all tables in the database are integers
82880 ** stored in P4_INTARRAY argument.
82881 **
82882 ** If P5 is not zero, the check is done on the auxiliary database
82883 ** file, not the main database file.
82884 **
82885 ** This opcode is used to implement the integrity_check pragma.
82886 */
82887 case OP_IntegrityCk: {
82888  int nRoot; /* Number of tables to check. (Number of root pages.) */
82889  int *aRoot; /* Array of rootpage numbers for tables to be checked */
82890  int nErr; /* Number of errors reported */
82891  char *z; /* Text of the error report */
82892  Mem *pnErr; /* Register keeping track of errors remaining */
82893 
82894  assert( p->bIsReader );
82895  nRoot = pOp->p2;
82896  aRoot = pOp->p4.ai;
82897  assert( nRoot>0 );
82898  assert( aRoot[nRoot]==0 );
82899  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
82900  pnErr = &aMem[pOp->p3];
82901  assert( (pnErr->flags & MEM_Int)!=0 );
82902  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
82903  pIn1 = &aMem[pOp->p1];
82904  assert( pOp->p5<db->nDb );
82905  assert( DbMaskTest(p->btreeMask, pOp->p5) );
82906  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
82907  (int)pnErr->u.i, &nErr);
82908  pnErr->u.i -= nErr;
82909  sqlite3VdbeMemSetNull(pIn1);
82910  if( nErr==0 ){
82911  assert( z==0 );
82912  }else if( z==0 ){
82913  goto no_mem;
82914  }else{
82916  }
82917  UPDATE_MAX_BLOBSIZE(pIn1);
82918  sqlite3VdbeChangeEncoding(pIn1, encoding);
82919  break;
82920 }
82921 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
82922 
82923 /* Opcode: RowSetAdd P1 P2 * * *
82924 ** Synopsis: rowset(P1)=r[P2]
82925 **
82926 ** Insert the integer value held by register P2 into a boolean index
82927 ** held in register P1.
82928 **
82929 ** An assertion fails if P2 is not an integer.
82930 */
82931 case OP_RowSetAdd: { /* in1, in2 */
82932  pIn1 = &aMem[pOp->p1];
82933  pIn2 = &aMem[pOp->p2];
82934  assert( (pIn2->flags & MEM_Int)!=0 );
82935  if( (pIn1->flags & MEM_RowSet)==0 ){
82937  if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82938  }
82939  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
82940  break;
82941 }
82942 
82943 /* Opcode: RowSetRead P1 P2 P3 * *
82944 ** Synopsis: r[P3]=rowset(P1)
82945 **
82946 ** Extract the smallest value from boolean index P1 and put that value into
82947 ** register P3. Or, if boolean index P1 is initially empty, leave P3
82948 ** unchanged and jump to instruction P2.
82949 */
82950 case OP_RowSetRead: { /* jump, in1, out3 */
82951  i64 val;
82952 
82953  pIn1 = &aMem[pOp->p1];
82954  if( (pIn1->flags & MEM_RowSet)==0
82955  || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
82956  ){
82957  /* The boolean index is empty */
82958  sqlite3VdbeMemSetNull(pIn1);
82959  VdbeBranchTaken(1,2);
82960  goto jump_to_p2_and_check_for_interrupt;
82961  }else{
82962  /* A value was pulled from the index */
82963  VdbeBranchTaken(0,2);
82964  sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
82965  }
82966  goto check_for_interrupt;
82967 }
82968 
82969 /* Opcode: RowSetTest P1 P2 P3 P4
82970 ** Synopsis: if r[P3] in rowset(P1) goto P2
82971 **
82972 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
82973 ** contains a RowSet object and that RowSet object contains
82974 ** the value held in P3, jump to register P2. Otherwise, insert the
82975 ** integer in P3 into the RowSet and continue on to the
82976 ** next opcode.
82977 **
82978 ** The RowSet object is optimized for the case where successive sets
82979 ** of integers, where each set contains no duplicates. Each set
82980 ** of values is identified by a unique P4 value. The first set
82981 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
82982 ** non-negative. For non-negative values of P4 only the lower 4
82983 ** bits are significant.
82984 **
82985 ** This allows optimizations: (a) when P4==0 there is no need to test
82986 ** the rowset object for P3, as it is guaranteed not to contain it,
82987 ** (b) when P4==-1 there is no need to insert the value, as it will
82988 ** never be tested for, and (c) when a value that is part of set X is
82989 ** inserted, there is no need to search to see if the same value was
82990 ** previously inserted as part of set X (only if it was previously
82991 ** inserted as part of some other set).
82992 */
82993 case OP_RowSetTest: { /* jump, in1, in3 */
82994  int iSet;
82995  int exists;
82996 
82997  pIn1 = &aMem[pOp->p1];
82998  pIn3 = &aMem[pOp->p3];
82999  iSet = pOp->p4.i;
83000  assert( pIn3->flags&MEM_Int );
83001 
83002  /* If there is anything other than a rowset object in memory cell P1,
83003  ** delete it now and initialize P1 with an empty rowset
83004  */
83005  if( (pIn1->flags & MEM_RowSet)==0 ){
83007  if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
83008  }
83009 
83010  assert( pOp->p4type==P4_INT32 );
83011  assert( iSet==-1 || iSet>=0 );
83012  if( iSet ){
83013  exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
83014  VdbeBranchTaken(exists!=0,2);
83015  if( exists ) goto jump_to_p2;
83016  }
83017  if( iSet>=0 ){
83018  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
83019  }
83020  break;
83021 }
83022 
83023 
83024 #ifndef SQLITE_OMIT_TRIGGER
83025 
83026 /* Opcode: Program P1 P2 P3 P4 P5
83027 **
83028 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
83029 **
83030 ** P1 contains the address of the memory cell that contains the first memory
83031 ** cell in an array of values used as arguments to the sub-program. P2
83032 ** contains the address to jump to if the sub-program throws an IGNORE
83033 ** exception using the RAISE() function. Register P3 contains the address
83034 ** of a memory cell in this (the parent) VM that is used to allocate the
83035 ** memory required by the sub-vdbe at runtime.
83036 **
83037 ** P4 is a pointer to the VM containing the trigger program.
83038 **
83039 ** If P5 is non-zero, then recursive program invocation is enabled.
83040 */
83041 case OP_Program: { /* jump */
83042  int nMem; /* Number of memory registers for sub-program */
83043  int nByte; /* Bytes of runtime space required for sub-program */
83044  Mem *pRt; /* Register to allocate runtime space */
83045  Mem *pMem; /* Used to iterate through memory cells */
83046  Mem *pEnd; /* Last memory cell in new array */
83047  VdbeFrame *pFrame; /* New vdbe frame to execute in */
83048  SubProgram *pProgram; /* Sub-program to execute */
83049  void *t; /* Token identifying trigger */
83050 
83051  pProgram = pOp->p4.pProgram;
83052  pRt = &aMem[pOp->p3];
83053  assert( pProgram->nOp>0 );
83054 
83055  /* If the p5 flag is clear, then recursive invocation of triggers is
83056  ** disabled for backwards compatibility (p5 is set if this sub-program
83057  ** is really a trigger, not a foreign key action, and the flag set
83058  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
83059  **
83060  ** It is recursive invocation of triggers, at the SQL level, that is
83061  ** disabled. In some cases a single trigger may generate more than one
83062  ** SubProgram (if the trigger may be executed with more than one different
83063  ** ON CONFLICT algorithm). SubProgram structures associated with a
83064  ** single trigger all have the same value for the SubProgram.token
83065  ** variable. */
83066  if( pOp->p5 ){
83067  t = pProgram->token;
83068  for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
83069  if( pFrame ) break;
83070  }
83071 
83072  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
83073  rc = SQLITE_ERROR;
83074  sqlite3VdbeError(p, "too many levels of trigger recursion");
83075  goto abort_due_to_error;
83076  }
83077 
83078  /* Register pRt is used to store the memory required to save the state
83079  ** of the current program, and the memory required at runtime to execute
83080  ** the trigger program. If this trigger has been fired before, then pRt
83081  ** is already allocated. Otherwise, it must be initialized. */
83082  if( (pRt->flags&MEM_Frame)==0 ){
83083  /* SubProgram.nMem is set to the number of memory cells used by the
83084  ** program stored in SubProgram.aOp. As well as these, one memory
83085  ** cell is required for each cursor used by the program. Set local
83086  ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
83087  */
83088  nMem = pProgram->nMem + pProgram->nCsr;
83089  assert( nMem>0 );
83090  if( pProgram->nCsr==0 ) nMem++;
83091  nByte = ROUND8(sizeof(VdbeFrame))
83092  + nMem * sizeof(Mem)
83093  + pProgram->nCsr * sizeof(VdbeCursor *);
83094  pFrame = sqlite3DbMallocZero(db, nByte);
83095  if( !pFrame ){
83096  goto no_mem;
83097  }
83098  sqlite3VdbeMemRelease(pRt);
83099  pRt->flags = MEM_Frame;
83100  pRt->u.pFrame = pFrame;
83101 
83102  pFrame->v = p;
83103  pFrame->nChildMem = nMem;
83104  pFrame->nChildCsr = pProgram->nCsr;
83105  pFrame->pc = (int)(pOp - aOp);
83106  pFrame->aMem = p->aMem;
83107  pFrame->nMem = p->nMem;
83108  pFrame->apCsr = p->apCsr;
83109  pFrame->nCursor = p->nCursor;
83110  pFrame->aOp = p->aOp;
83111  pFrame->nOp = p->nOp;
83112  pFrame->token = pProgram->token;
83113 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
83114  pFrame->anExec = p->anExec;
83115 #endif
83116 
83117  pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
83118  for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
83119  pMem->flags = MEM_Undefined;
83120  pMem->db = db;
83121  }
83122  }else{
83123  pFrame = pRt->u.pFrame;
83124  assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
83125  || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
83126  assert( pProgram->nCsr==pFrame->nChildCsr );
83127  assert( (int)(pOp - aOp)==pFrame->pc );
83128  }
83129 
83130  p->nFrame++;
83131  pFrame->pParent = p->pFrame;
83132  pFrame->lastRowid = lastRowid;
83133  pFrame->nChange = p->nChange;
83134  pFrame->nDbChange = p->db->nChange;
83135  assert( pFrame->pAuxData==0 );
83136  pFrame->pAuxData = p->pAuxData;
83137  p->pAuxData = 0;
83138  p->nChange = 0;
83139  p->pFrame = pFrame;
83140  p->aMem = aMem = VdbeFrameMem(pFrame);
83141  p->nMem = pFrame->nChildMem;
83142  p->nCursor = (u16)pFrame->nChildCsr;
83143  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
83144  p->aOp = aOp = pProgram->aOp;
83145  p->nOp = pProgram->nOp;
83146 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
83147  p->anExec = 0;
83148 #endif
83149  pOp = &aOp[-1];
83150 
83151  break;
83152 }
83153 
83154 /* Opcode: Param P1 P2 * * *
83155 **
83156 ** This opcode is only ever present in sub-programs called via the
83157 ** OP_Program instruction. Copy a value currently stored in a memory
83158 ** cell of the calling (parent) frame to cell P2 in the current frames
83159 ** address space. This is used by trigger programs to access the new.*
83160 ** and old.* values.
83161 **
83162 ** The address of the cell in the parent frame is determined by adding
83163 ** the value of the P1 argument to the value of the P1 argument to the
83164 ** calling OP_Program instruction.
83165 */
83166 case OP_Param: { /* out2 */
83167  VdbeFrame *pFrame;
83168  Mem *pIn;
83169  pOut = out2Prerelease(p, pOp);
83170  pFrame = p->pFrame;
83171  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
83173  break;
83174 }
83175 
83176 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
83177 
83178 #ifndef SQLITE_OMIT_FOREIGN_KEY
83179 /* Opcode: FkCounter P1 P2 * * *
83180 ** Synopsis: fkctr[P1]+=P2
83181 **
83182 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
83183 ** If P1 is non-zero, the database constraint counter is incremented
83184 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
83185 ** statement counter is incremented (immediate foreign key constraints).
83186 */
83187 case OP_FkCounter: {
83188  if( db->flags & SQLITE_DeferFKs ){
83189  db->nDeferredImmCons += pOp->p2;
83190  }else if( pOp->p1 ){
83191  db->nDeferredCons += pOp->p2;
83192  }else{
83193  p->nFkConstraint += pOp->p2;
83194  }
83195  break;
83196 }
83197 
83198 /* Opcode: FkIfZero P1 P2 * * *
83199 ** Synopsis: if fkctr[P1]==0 goto P2
83200 **
83201 ** This opcode tests if a foreign key constraint-counter is currently zero.
83202 ** If so, jump to instruction P2. Otherwise, fall through to the next
83203 ** instruction.
83204 **
83205 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
83206 ** is zero (the one that counts deferred constraint violations). If P1 is
83207 ** zero, the jump is taken if the statement constraint-counter is zero
83208 ** (immediate foreign key constraint violations).
83209 */
83210 case OP_FkIfZero: { /* jump */
83211  if( pOp->p1 ){
83212  VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
83213  if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
83214  }else{
83215  VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
83216  if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
83217  }
83218  break;
83219 }
83220 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
83221 
83222 #ifndef SQLITE_OMIT_AUTOINCREMENT
83223 /* Opcode: MemMax P1 P2 * * *
83224 ** Synopsis: r[P1]=max(r[P1],r[P2])
83225 **
83226 ** P1 is a register in the root frame of this VM (the root frame is
83227 ** different from the current frame if this instruction is being executed
83228 ** within a sub-program). Set the value of register P1 to the maximum of
83229 ** its current value and the value in register P2.
83230 **
83231 ** This instruction throws an error if the memory cell is not initially
83232 ** an integer.
83233 */
83234 case OP_MemMax: { /* in2 */
83235  VdbeFrame *pFrame;
83236  if( p->pFrame ){
83237  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
83238  pIn1 = &pFrame->aMem[pOp->p1];
83239  }else{
83240  pIn1 = &aMem[pOp->p1];
83241  }
83242  assert( memIsValid(pIn1) );
83244  pIn2 = &aMem[pOp->p2];
83246  if( pIn1->u.i<pIn2->u.i){
83247  pIn1->u.i = pIn2->u.i;
83248  }
83249  break;
83250 }
83251 #endif /* SQLITE_OMIT_AUTOINCREMENT */
83252 
83253 /* Opcode: IfPos P1 P2 P3 * *
83254 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
83255 **
83256 ** Register P1 must contain an integer.
83257 ** If the value of register P1 is 1 or greater, subtract P3 from the
83258 ** value in P1 and jump to P2.
83259 **
83260 ** If the initial value of register P1 is less than 1, then the
83261 ** value is unchanged and control passes through to the next instruction.
83262 */
83263 case OP_IfPos: { /* jump, in1 */
83264  pIn1 = &aMem[pOp->p1];
83265  assert( pIn1->flags&MEM_Int );
83266  VdbeBranchTaken( pIn1->u.i>0, 2);
83267  if( pIn1->u.i>0 ){
83268  pIn1->u.i -= pOp->p3;
83269  goto jump_to_p2;
83270  }
83271  break;
83272 }
83273 
83274 /* Opcode: OffsetLimit P1 P2 P3 * *
83275 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
83276 **
83277 ** This opcode performs a commonly used computation associated with
83278 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
83279 ** holds the offset counter. The opcode computes the combined value
83280 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
83281 ** value computed is the total number of rows that will need to be
83282 ** visited in order to complete the query.
83283 **
83284 ** If r[P3] is zero or negative, that means there is no OFFSET
83285 ** and r[P2] is set to be the value of the LIMIT, r[P1].
83286 **
83287 ** if r[P1] is zero or negative, that means there is no LIMIT
83288 ** and r[P2] is set to -1.
83289 **
83290 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
83291 */
83292 case OP_OffsetLimit: { /* in1, out2, in3 */
83293  pIn1 = &aMem[pOp->p1];
83294  pIn3 = &aMem[pOp->p3];
83295  pOut = out2Prerelease(p, pOp);
83296  assert( pIn1->flags & MEM_Int );
83297  assert( pIn3->flags & MEM_Int );
83298  pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0);
83299  break;
83300 }
83301 
83302 /* Opcode: IfNotZero P1 P2 P3 * *
83303 ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
83304 **
83305 ** Register P1 must contain an integer. If the content of register P1 is
83306 ** initially nonzero, then subtract P3 from the value in register P1 and
83307 ** jump to P2. If register P1 is initially zero, leave it unchanged
83308 ** and fall through.
83309 */
83310 case OP_IfNotZero: { /* jump, in1 */
83311  pIn1 = &aMem[pOp->p1];
83312  assert( pIn1->flags&MEM_Int );
83313  VdbeBranchTaken(pIn1->u.i<0, 2);
83314  if( pIn1->u.i ){
83315  pIn1->u.i -= pOp->p3;
83316  goto jump_to_p2;
83317  }
83318  break;
83319 }
83320 
83321 /* Opcode: DecrJumpZero P1 P2 * * *
83322 ** Synopsis: if (--r[P1])==0 goto P2
83323 **
83324 ** Register P1 must hold an integer. Decrement the value in register P1
83325 ** then jump to P2 if the new value is exactly zero.
83326 */
83327 case OP_DecrJumpZero: { /* jump, in1 */
83328  pIn1 = &aMem[pOp->p1];
83329  assert( pIn1->flags&MEM_Int );
83330  pIn1->u.i--;
83331  VdbeBranchTaken(pIn1->u.i==0, 2);
83332  if( pIn1->u.i==0 ) goto jump_to_p2;
83333  break;
83334 }
83335 
83336 
83337 /* Opcode: AggStep0 * P2 P3 P4 P5
83338 ** Synopsis: accum=r[P3] step(r[P2@P5])
83339 **
83340 ** Execute the step function for an aggregate. The
83341 ** function has P5 arguments. P4 is a pointer to the FuncDef
83342 ** structure that specifies the function. Register P3 is the
83343 ** accumulator.
83344 **
83345 ** The P5 arguments are taken from register P2 and its
83346 ** successors.
83347 */
83348 /* Opcode: AggStep * P2 P3 P4 P5
83349 ** Synopsis: accum=r[P3] step(r[P2@P5])
83350 **
83351 ** Execute the step function for an aggregate. The
83352 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
83353 ** object that is used to run the function. Register P3 is
83354 ** as the accumulator.
83355 **
83356 ** The P5 arguments are taken from register P2 and its
83357 ** successors.
83358 **
83359 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
83360 ** the FuncDef stored in P4 is converted into an sqlite3_context and
83361 ** the opcode is changed. In this way, the initialization of the
83362 ** sqlite3_context only happens once, instead of on each call to the
83363 ** step function.
83364 */
83365 case OP_AggStep0: {
83366  int n;
83367  sqlite3_context *pCtx;
83368 
83369  assert( pOp->p4type==P4_FUNCDEF );
83370  n = pOp->p5;
83371  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83372  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
83373  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
83374  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
83375  if( pCtx==0 ) goto no_mem;
83376  pCtx->pMem = 0;
83377  pCtx->pFunc = pOp->p4.pFunc;
83378  pCtx->iOp = (int)(pOp - aOp);
83379  pCtx->pVdbe = p;
83380  pCtx->argc = n;
83381  pOp->p4type = P4_FUNCCTX;
83382  pOp->p4.pCtx = pCtx;
83383  pOp->opcode = OP_AggStep;
83384  /* Fall through into OP_AggStep */
83385 }
83386 case OP_AggStep: {
83387  int i;
83388  sqlite3_context *pCtx;
83389  Mem *pMem;
83390  Mem t;
83391 
83392  assert( pOp->p4type==P4_FUNCCTX );
83393  pCtx = pOp->p4.pCtx;
83394  pMem = &aMem[pOp->p3];
83395 
83396  /* If this function is inside of a trigger, the register array in aMem[]
83397  ** might change from one evaluation to the next. The next block of code
83398  ** checks to see if the register array has changed, and if so it
83399  ** reinitializes the relavant parts of the sqlite3_context object */
83400  if( pCtx->pMem != pMem ){
83401  pCtx->pMem = pMem;
83402  for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
83403  }
83404 
83405 #ifdef SQLITE_DEBUG
83406  for(i=0; i<pCtx->argc; i++){
83407  assert( memIsValid(pCtx->argv[i]) );
83408  REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
83409  }
83410 #endif
83411 
83412  pMem->n++;
83413  sqlite3VdbeMemInit(&t, db, MEM_Null);
83414  pCtx->pOut = &t;
83415  pCtx->fErrorOrAux = 0;
83416  pCtx->skipFlag = 0;
83417  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
83418  if( pCtx->fErrorOrAux ){
83419  if( pCtx->isError ){
83420  sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
83421  rc = pCtx->isError;
83422  }
83424  if( rc ) goto abort_due_to_error;
83425  }else{
83426  assert( t.flags==MEM_Null );
83427  }
83428  if( pCtx->skipFlag ){
83429  assert( pOp[-1].opcode==OP_CollSeq );
83430  i = pOp[-1].p1;
83431  if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
83432  }
83433  break;
83434 }
83435 
83436 /* Opcode: AggFinal P1 P2 * P4 *
83437 ** Synopsis: accum=r[P1] N=P2
83438 **
83439 ** Execute the finalizer function for an aggregate. P1 is
83440 ** the memory location that is the accumulator for the aggregate.
83441 **
83442 ** P2 is the number of arguments that the step function takes and
83443 ** P4 is a pointer to the FuncDef for this function. The P2
83444 ** argument is not used by this opcode. It is only there to disambiguate
83445 ** functions that can take varying numbers of arguments. The
83446 ** P4 argument is only needed for the degenerate case where
83447 ** the step function was not previously called.
83448 */
83449 case OP_AggFinal: {
83450  Mem *pMem;
83451  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
83452  pMem = &aMem[pOp->p1];
83453  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
83454  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
83455  if( rc ){
83456  sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
83457  goto abort_due_to_error;
83458  }
83459  sqlite3VdbeChangeEncoding(pMem, encoding);
83460  UPDATE_MAX_BLOBSIZE(pMem);
83461  if( sqlite3VdbeMemTooBig(pMem) ){
83462  goto too_big;
83463  }
83464  break;
83465 }
83466 
83467 #ifndef SQLITE_OMIT_WAL
83468 /* Opcode: Checkpoint P1 P2 P3 * *
83469 **
83470 ** Checkpoint database P1. This is a no-op if P1 is not currently in
83471 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
83472 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
83473 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
83474 ** WAL after the checkpoint into mem[P3+1] and the number of pages
83475 ** in the WAL that have been checkpointed after the checkpoint
83476 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
83477 ** mem[P3+2] are initialized to -1.
83478 */
83479 case OP_Checkpoint: {
83480  int i; /* Loop counter */
83481  int aRes[3]; /* Results */
83482  Mem *pMem; /* Write results here */
83483 
83484  assert( p->readOnly==0 );
83485  aRes[0] = 0;
83486  aRes[1] = aRes[2] = -1;
83487  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
83488  || pOp->p2==SQLITE_CHECKPOINT_FULL
83489  || pOp->p2==SQLITE_CHECKPOINT_RESTART
83491  );
83492  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
83493  if( rc ){
83494  if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
83495  rc = SQLITE_OK;
83496  aRes[0] = 1;
83497  }
83498  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
83499  sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
83500  }
83501  break;
83502 };
83503 #endif
83504 
83505 #ifndef SQLITE_OMIT_PRAGMA
83506 /* Opcode: JournalMode P1 P2 P3 * *
83507 **
83508 ** Change the journal mode of database P1 to P3. P3 must be one of the
83509 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
83510 ** modes (delete, truncate, persist, off and memory), this is a simple
83511 ** operation. No IO is required.
83512 **
83513 ** If changing into or out of WAL mode the procedure is more complicated.
83514 **
83515 ** Write a string containing the final journal-mode to register P2.
83516 */
83517 case OP_JournalMode: { /* out2 */
83518  Btree *pBt; /* Btree to change journal mode of */
83519  Pager *pPager; /* Pager associated with pBt */
83520  int eNew; /* New journal mode */
83521  int eOld; /* The old journal mode */
83522 #ifndef SQLITE_OMIT_WAL
83523  const char *zFilename; /* Name of database file for pPager */
83524 #endif
83525 
83526  pOut = out2Prerelease(p, pOp);
83527  eNew = pOp->p3;
83528  assert( eNew==PAGER_JOURNALMODE_DELETE
83529  || eNew==PAGER_JOURNALMODE_TRUNCATE
83530  || eNew==PAGER_JOURNALMODE_PERSIST
83531  || eNew==PAGER_JOURNALMODE_OFF
83532  || eNew==PAGER_JOURNALMODE_MEMORY
83533  || eNew==PAGER_JOURNALMODE_WAL
83534  || eNew==PAGER_JOURNALMODE_QUERY
83535  );
83536  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83537  assert( p->readOnly==0 );
83538 
83539  pBt = db->aDb[pOp->p1].pBt;
83540  pPager = sqlite3BtreePager(pBt);
83541  eOld = sqlite3PagerGetJournalMode(pPager);
83542  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
83543  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
83544 
83545 #ifndef SQLITE_OMIT_WAL
83546  zFilename = sqlite3PagerFilename(pPager, 1);
83547 
83548  /* Do not allow a transition to journal_mode=WAL for a database
83549  ** in temporary storage or if the VFS does not support shared memory
83550  */
83551  if( eNew==PAGER_JOURNALMODE_WAL
83552  && (sqlite3Strlen30(zFilename)==0 /* Temp file */
83553  || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
83554  ){
83555  eNew = eOld;
83556  }
83557 
83558  if( (eNew!=eOld)
83559  && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
83560  ){
83561  if( !db->autoCommit || db->nVdbeRead>1 ){
83562  rc = SQLITE_ERROR;
83563  sqlite3VdbeError(p,
83564  "cannot change %s wal mode from within a transaction",
83565  (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
83566  );
83567  goto abort_due_to_error;
83568  }else{
83569 
83570  if( eOld==PAGER_JOURNALMODE_WAL ){
83571  /* If leaving WAL mode, close the log file. If successful, the call
83572  ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
83573  ** file. An EXCLUSIVE lock may still be held on the database file
83574  ** after a successful return.
83575  */
83576  rc = sqlite3PagerCloseWal(pPager);
83577  if( rc==SQLITE_OK ){
83578  sqlite3PagerSetJournalMode(pPager, eNew);
83579  }
83580  }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
83581  /* Cannot transition directly from MEMORY to WAL. Use mode OFF
83582  ** as an intermediate */
83584  }
83585 
83586  /* Open a transaction on the database file. Regardless of the journal
83587  ** mode, this transaction always uses a rollback journal.
83588  */
83589  assert( sqlite3BtreeIsInTrans(pBt)==0 );
83590  if( rc==SQLITE_OK ){
83591  rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
83592  }
83593  }
83594  }
83595 #endif /* ifndef SQLITE_OMIT_WAL */
83596 
83597  if( rc ) eNew = eOld;
83598  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
83599 
83600  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
83601  pOut->z = (char *)sqlite3JournalModename(eNew);
83602  pOut->n = sqlite3Strlen30(pOut->z);
83603  pOut->enc = SQLITE_UTF8;
83604  sqlite3VdbeChangeEncoding(pOut, encoding);
83605  if( rc ) goto abort_due_to_error;
83606  break;
83607 };
83608 #endif /* SQLITE_OMIT_PRAGMA */
83609 
83610 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
83611 /* Opcode: Vacuum P1 * * * *
83612 **
83613 ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
83614 ** for an attached database. The "temp" database may not be vacuumed.
83615 */
83616 case OP_Vacuum: {
83617  assert( p->readOnly==0 );
83618  rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
83619  if( rc ) goto abort_due_to_error;
83620  break;
83621 }
83622 #endif
83623 
83624 #if !defined(SQLITE_OMIT_AUTOVACUUM)
83625 /* Opcode: IncrVacuum P1 P2 * * *
83626 **
83627 ** Perform a single step of the incremental vacuum procedure on
83628 ** the P1 database. If the vacuum has finished, jump to instruction
83629 ** P2. Otherwise, fall through to the next instruction.
83630 */
83631 case OP_IncrVacuum: { /* jump */
83632  Btree *pBt;
83633 
83634  assert( pOp->p1>=0 && pOp->p1<db->nDb );
83635  assert( DbMaskTest(p->btreeMask, pOp->p1) );
83636  assert( p->readOnly==0 );
83637  pBt = db->aDb[pOp->p1].pBt;
83638  rc = sqlite3BtreeIncrVacuum(pBt);
83640  if( rc ){
83641  if( rc!=SQLITE_DONE ) goto abort_due_to_error;
83642  rc = SQLITE_OK;
83643  goto jump_to_p2;
83644  }
83645  break;
83646 }
83647 #endif
83648 
83649 /* Opcode: Expire P1 * * * *
83650 **
83651 ** Cause precompiled statements to expire. When an expired statement
83652 ** is executed using sqlite3_step() it will either automatically
83653 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
83654 ** or it will fail with SQLITE_SCHEMA.
83655 **
83656 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
83657 ** then only the currently executing statement is expired.
83658 */
83659 case OP_Expire: {
83660  if( !pOp->p1 ){
83662  }else{
83663  p->expired = 1;
83664  }
83665  break;
83666 }
83667 
83668 #ifndef SQLITE_OMIT_SHARED_CACHE
83669 /* Opcode: TableLock P1 P2 P3 P4 *
83670 ** Synopsis: iDb=P1 root=P2 write=P3
83671 **
83672 ** Obtain a lock on a particular table. This instruction is only used when
83673 ** the shared-cache feature is enabled.
83674 **
83675 ** P1 is the index of the database in sqlite3.aDb[] of the database
83676 ** on which the lock is acquired. A readlock is obtained if P3==0 or
83677 ** a write lock if P3==1.
83678 **
83679 ** P2 contains the root-page of the table to lock.
83680 **
83681 ** P4 contains a pointer to the name of the table being locked. This is only
83682 ** used to generate an error message if the lock cannot be obtained.
83683 */
83684 case OP_TableLock: {
83685  u8 isWriteLock = (u8)pOp->p3;
83686  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
83687  int p1 = pOp->p1;
83688  assert( p1>=0 && p1<db->nDb );
83689  assert( DbMaskTest(p->btreeMask, p1) );
83690  assert( isWriteLock==0 || isWriteLock==1 );
83691  rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
83692  if( rc ){
83693  if( (rc&0xFF)==SQLITE_LOCKED ){
83694  const char *z = pOp->p4.z;
83695  sqlite3VdbeError(p, "database table is locked: %s", z);
83696  }
83697  goto abort_due_to_error;
83698  }
83699  }
83700  break;
83701 }
83702 #endif /* SQLITE_OMIT_SHARED_CACHE */
83703 
83704 #ifndef SQLITE_OMIT_VIRTUALTABLE
83705 /* Opcode: VBegin * * * P4 *
83706 **
83707 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
83708 ** xBegin method for that table.
83709 **
83710 ** Also, whether or not P4 is set, check that this is not being called from
83711 ** within a callback to a virtual table xSync() method. If it is, the error
83712 ** code will be set to SQLITE_LOCKED.
83713 */
83714 case OP_VBegin: {
83715  VTable *pVTab;
83716  pVTab = pOp->p4.pVtab;
83717  rc = sqlite3VtabBegin(db, pVTab);
83718  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
83719  if( rc ) goto abort_due_to_error;
83720  break;
83721 }
83722 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83723 
83724 #ifndef SQLITE_OMIT_VIRTUALTABLE
83725 /* Opcode: VCreate P1 P2 * * *
83726 **
83727 ** P2 is a register that holds the name of a virtual table in database
83728 ** P1. Call the xCreate method for that table.
83729 */
83730 case OP_VCreate: {
83731  Mem sMem; /* For storing the record being decoded */
83732  const char *zTab; /* Name of the virtual table */
83733 
83734  memset(&sMem, 0, sizeof(sMem));
83735  sMem.db = db;
83736  /* Because P2 is always a static string, it is impossible for the
83737  ** sqlite3VdbeMemCopy() to fail */
83738  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
83739  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
83740  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
83741  assert( rc==SQLITE_OK );
83742  zTab = (const char*)sqlite3_value_text(&sMem);
83743  assert( zTab || db->mallocFailed );
83744  if( zTab ){
83745  rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
83746  }
83747  sqlite3VdbeMemRelease(&sMem);
83748  if( rc ) goto abort_due_to_error;
83749  break;
83750 }
83751 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83752 
83753 #ifndef SQLITE_OMIT_VIRTUALTABLE
83754 /* Opcode: VDestroy P1 * * P4 *
83755 **
83756 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
83757 ** of that table.
83758 */
83759 case OP_VDestroy: {
83760  db->nVDestroy++;
83761  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
83762  db->nVDestroy--;
83763  if( rc ) goto abort_due_to_error;
83764  break;
83765 }
83766 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83767 
83768 #ifndef SQLITE_OMIT_VIRTUALTABLE
83769 /* Opcode: VOpen P1 * * P4 *
83770 **
83771 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83772 ** P1 is a cursor number. This opcode opens a cursor to the virtual
83773 ** table and stores that cursor in P1.
83774 */
83775 case OP_VOpen: {
83776  VdbeCursor *pCur;
83777  sqlite3_vtab_cursor *pVCur;
83778  sqlite3_vtab *pVtab;
83779  const sqlite3_module *pModule;
83780 
83781  assert( p->bIsReader );
83782  pCur = 0;
83783  pVCur = 0;
83784  pVtab = pOp->p4.pVtab->pVtab;
83785  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83786  rc = SQLITE_LOCKED;
83787  goto abort_due_to_error;
83788  }
83789  pModule = pVtab->pModule;
83790  rc = pModule->xOpen(pVtab, &pVCur);
83791  sqlite3VtabImportErrmsg(p, pVtab);
83792  if( rc ) goto abort_due_to_error;
83793 
83794  /* Initialize sqlite3_vtab_cursor base class */
83795  pVCur->pVtab = pVtab;
83796 
83797  /* Initialize vdbe cursor object */
83798  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
83799  if( pCur ){
83800  pCur->uc.pVCur = pVCur;
83801  pVtab->nRef++;
83802  }else{
83803  assert( db->mallocFailed );
83804  pModule->xClose(pVCur);
83805  goto no_mem;
83806  }
83807  break;
83808 }
83809 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83810 
83811 #ifndef SQLITE_OMIT_VIRTUALTABLE
83812 /* Opcode: VFilter P1 P2 P3 P4 *
83813 ** Synopsis: iplan=r[P3] zplan='P4'
83814 **
83815 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
83816 ** the filtered result set is empty.
83817 **
83818 ** P4 is either NULL or a string that was generated by the xBestIndex
83819 ** method of the module. The interpretation of the P4 string is left
83820 ** to the module implementation.
83821 **
83822 ** This opcode invokes the xFilter method on the virtual table specified
83823 ** by P1. The integer query plan parameter to xFilter is stored in register
83824 ** P3. Register P3+1 stores the argc parameter to be passed to the
83825 ** xFilter method. Registers P3+2..P3+1+argc are the argc
83826 ** additional parameters which are passed to
83827 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
83828 **
83829 ** A jump is made to P2 if the result set after filtering would be empty.
83830 */
83831 case OP_VFilter: { /* jump */
83832  int nArg;
83833  int iQuery;
83834  const sqlite3_module *pModule;
83835  Mem *pQuery;
83836  Mem *pArgc;
83837  sqlite3_vtab_cursor *pVCur;
83838  sqlite3_vtab *pVtab;
83839  VdbeCursor *pCur;
83840  int res;
83841  int i;
83842  Mem **apArg;
83843 
83844  pQuery = &aMem[pOp->p3];
83845  pArgc = &pQuery[1];
83846  pCur = p->apCsr[pOp->p1];
83847  assert( memIsValid(pQuery) );
83848  REGISTER_TRACE(pOp->p3, pQuery);
83849  assert( pCur->eCurType==CURTYPE_VTAB );
83850  pVCur = pCur->uc.pVCur;
83851  pVtab = pVCur->pVtab;
83852  pModule = pVtab->pModule;
83853 
83854  /* Grab the index number and argc parameters */
83855  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
83856  nArg = (int)pArgc->u.i;
83857  iQuery = (int)pQuery->u.i;
83858 
83859  /* Invoke the xFilter method */
83860  res = 0;
83861  apArg = p->apArg;
83862  for(i = 0; i<nArg; i++){
83863  apArg[i] = &pArgc[i+1];
83864  }
83865  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
83866  sqlite3VtabImportErrmsg(p, pVtab);
83867  if( rc ) goto abort_due_to_error;
83868  res = pModule->xEof(pVCur);
83869  pCur->nullRow = 0;
83870  VdbeBranchTaken(res!=0,2);
83871  if( res ) goto jump_to_p2;
83872  break;
83873 }
83874 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83875 
83876 #ifndef SQLITE_OMIT_VIRTUALTABLE
83877 /* Opcode: VColumn P1 P2 P3 * *
83878 ** Synopsis: r[P3]=vcolumn(P2)
83879 **
83880 ** Store the value of the P2-th column of
83881 ** the row of the virtual-table that the
83882 ** P1 cursor is pointing to into register P3.
83883 */
83884 case OP_VColumn: {
83885  sqlite3_vtab *pVtab;
83886  const sqlite3_module *pModule;
83887  Mem *pDest;
83888  sqlite3_context sContext;
83889 
83890  VdbeCursor *pCur = p->apCsr[pOp->p1];
83891  assert( pCur->eCurType==CURTYPE_VTAB );
83892  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83893  pDest = &aMem[pOp->p3];
83894  memAboutToChange(p, pDest);
83895  if( pCur->nullRow ){
83896  sqlite3VdbeMemSetNull(pDest);
83897  break;
83898  }
83899  pVtab = pCur->uc.pVCur->pVtab;
83900  pModule = pVtab->pModule;
83901  assert( pModule->xColumn );
83902  memset(&sContext, 0, sizeof(sContext));
83903  sContext.pOut = pDest;
83904  MemSetTypeFlag(pDest, MEM_Null);
83905  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
83906  sqlite3VtabImportErrmsg(p, pVtab);
83907  if( sContext.isError ){
83908  rc = sContext.isError;
83909  }
83910  sqlite3VdbeChangeEncoding(pDest, encoding);
83911  REGISTER_TRACE(pOp->p3, pDest);
83912  UPDATE_MAX_BLOBSIZE(pDest);
83913 
83914  if( sqlite3VdbeMemTooBig(pDest) ){
83915  goto too_big;
83916  }
83917  if( rc ) goto abort_due_to_error;
83918  break;
83919 }
83920 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83921 
83922 #ifndef SQLITE_OMIT_VIRTUALTABLE
83923 /* Opcode: VNext P1 P2 * * *
83924 **
83925 ** Advance virtual table P1 to the next row in its result set and
83926 ** jump to instruction P2. Or, if the virtual table has reached
83927 ** the end of its result set, then fall through to the next instruction.
83928 */
83929 case OP_VNext: { /* jump */
83930  sqlite3_vtab *pVtab;
83931  const sqlite3_module *pModule;
83932  int res;
83933  VdbeCursor *pCur;
83934 
83935  res = 0;
83936  pCur = p->apCsr[pOp->p1];
83937  assert( pCur->eCurType==CURTYPE_VTAB );
83938  if( pCur->nullRow ){
83939  break;
83940  }
83941  pVtab = pCur->uc.pVCur->pVtab;
83942  pModule = pVtab->pModule;
83943  assert( pModule->xNext );
83944 
83945  /* Invoke the xNext() method of the module. There is no way for the
83946  ** underlying implementation to return an error if one occurs during
83947  ** xNext(). Instead, if an error occurs, true is returned (indicating that
83948  ** data is available) and the error code returned when xColumn or
83949  ** some other method is next invoked on the save virtual table cursor.
83950  */
83951  rc = pModule->xNext(pCur->uc.pVCur);
83952  sqlite3VtabImportErrmsg(p, pVtab);
83953  if( rc ) goto abort_due_to_error;
83954  res = pModule->xEof(pCur->uc.pVCur);
83955  VdbeBranchTaken(!res,2);
83956  if( !res ){
83957  /* If there is data, jump to P2 */
83958  goto jump_to_p2_and_check_for_interrupt;
83959  }
83960  goto check_for_interrupt;
83961 }
83962 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83963 
83964 #ifndef SQLITE_OMIT_VIRTUALTABLE
83965 /* Opcode: VRename P1 * * P4 *
83966 **
83967 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83968 ** This opcode invokes the corresponding xRename method. The value
83969 ** in register P1 is passed as the zName argument to the xRename method.
83970 */
83971 case OP_VRename: {
83972  sqlite3_vtab *pVtab;
83973  Mem *pName;
83974 
83975  pVtab = pOp->p4.pVtab->pVtab;
83976  pName = &aMem[pOp->p1];
83977  assert( pVtab->pModule->xRename );
83978  assert( memIsValid(pName) );
83979  assert( p->readOnly==0 );
83980  REGISTER_TRACE(pOp->p1, pName);
83981  assert( pName->flags & MEM_Str );
83982  testcase( pName->enc==SQLITE_UTF8 );
83983  testcase( pName->enc==SQLITE_UTF16BE );
83984  testcase( pName->enc==SQLITE_UTF16LE );
83986  if( rc ) goto abort_due_to_error;
83987  rc = pVtab->pModule->xRename(pVtab, pName->z);
83988  sqlite3VtabImportErrmsg(p, pVtab);
83989  p->expired = 0;
83990  if( rc ) goto abort_due_to_error;
83991  break;
83992 }
83993 #endif
83994 
83995 #ifndef SQLITE_OMIT_VIRTUALTABLE
83996 /* Opcode: VUpdate P1 P2 P3 P4 P5
83997 ** Synopsis: data=r[P3@P2]
83998 **
83999 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
84000 ** This opcode invokes the corresponding xUpdate method. P2 values
84001 ** are contiguous memory cells starting at P3 to pass to the xUpdate
84002 ** invocation. The value in register (P3+P2-1) corresponds to the
84003 ** p2th element of the argv array passed to xUpdate.
84004 **
84005 ** The xUpdate method will do a DELETE or an INSERT or both.
84006 ** The argv[0] element (which corresponds to memory cell P3)
84007 ** is the rowid of a row to delete. If argv[0] is NULL then no
84008 ** deletion occurs. The argv[1] element is the rowid of the new
84009 ** row. This can be NULL to have the virtual table select the new
84010 ** rowid for itself. The subsequent elements in the array are
84011 ** the values of columns in the new row.
84012 **
84013 ** If P2==1 then no insert is performed. argv[0] is the rowid of
84014 ** a row to delete.
84015 **
84016 ** P1 is a boolean flag. If it is set to true and the xUpdate call
84017 ** is successful, then the value returned by sqlite3_last_insert_rowid()
84018 ** is set to the value of the rowid for the row just inserted.
84019 **
84020 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
84021 ** apply in the case of a constraint failure on an insert or update.
84022 */
84023 case OP_VUpdate: {
84024  sqlite3_vtab *pVtab;
84025  const sqlite3_module *pModule;
84026  int nArg;
84027  int i;
84028  sqlite_int64 rowid;
84029  Mem **apArg;
84030  Mem *pX;
84031 
84032  assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
84033  || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
84034  );
84035  assert( p->readOnly==0 );
84036  pVtab = pOp->p4.pVtab->pVtab;
84037  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
84038  rc = SQLITE_LOCKED;
84039  goto abort_due_to_error;
84040  }
84041  pModule = pVtab->pModule;
84042  nArg = pOp->p2;
84043  assert( pOp->p4type==P4_VTAB );
84044  if( ALWAYS(pModule->xUpdate) ){
84045  u8 vtabOnConflict = db->vtabOnConflict;
84046  apArg = p->apArg;
84047  pX = &aMem[pOp->p3];
84048  for(i=0; i<nArg; i++){
84049  assert( memIsValid(pX) );
84050  memAboutToChange(p, pX);
84051  apArg[i] = pX;
84052  pX++;
84053  }
84054  db->vtabOnConflict = pOp->p5;
84055  rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
84056  db->vtabOnConflict = vtabOnConflict;
84057  sqlite3VtabImportErrmsg(p, pVtab);
84058  if( rc==SQLITE_OK && pOp->p1 ){
84059  assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
84060  db->lastRowid = lastRowid = rowid;
84061  }
84062  if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
84063  if( pOp->p5==OE_Ignore ){
84064  rc = SQLITE_OK;
84065  }else{
84066  p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
84067  }
84068  }else{
84069  p->nChange++;
84070  }
84071  if( rc ) goto abort_due_to_error;
84072  }
84073  break;
84074 }
84075 #endif /* SQLITE_OMIT_VIRTUALTABLE */
84076 
84077 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84078 /* Opcode: Pagecount P1 P2 * * *
84079 **
84080 ** Write the current number of pages in database P1 to memory cell P2.
84081 */
84082 case OP_Pagecount: { /* out2 */
84083  pOut = out2Prerelease(p, pOp);
84084  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
84085  break;
84086 }
84087 #endif
84088 
84089 
84090 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
84091 /* Opcode: MaxPgcnt P1 P2 P3 * *
84092 **
84093 ** Try to set the maximum page count for database P1 to the value in P3.
84094 ** Do not let the maximum page count fall below the current page count and
84095 ** do not change the maximum page count value if P3==0.
84096 **
84097 ** Store the maximum page count after the change in register P2.
84098 */
84099 case OP_MaxPgcnt: { /* out2 */
84100  unsigned int newMax;
84101  Btree *pBt;
84102 
84103  pOut = out2Prerelease(p, pOp);
84104  pBt = db->aDb[pOp->p1].pBt;
84105  newMax = 0;
84106  if( pOp->p3 ){
84107  newMax = sqlite3BtreeLastPage(pBt);
84108  if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
84109  }
84110  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
84111  break;
84112 }
84113 #endif
84114 
84115 
84116 /* Opcode: Init P1 P2 * P4 *
84117 ** Synopsis: Start at P2
84118 **
84119 ** Programs contain a single instance of this opcode as the very first
84120 ** opcode.
84121 **
84122 ** If tracing is enabled (by the sqlite3_trace()) interface, then
84123 ** the UTF-8 string contained in P4 is emitted on the trace callback.
84124 ** Or if P4 is blank, use the string returned by sqlite3_sql().
84125 **
84126 ** If P2 is not zero, jump to instruction P2.
84127 **
84128 ** Increment the value of P1 so that OP_Once opcodes will jump the
84129 ** first time they are evaluated for this run.
84130 */
84131 case OP_Init: { /* jump */
84132  char *zTrace;
84133  int i;
84134 
84135  /* If the P4 argument is not NULL, then it must be an SQL comment string.
84136  ** The "--" string is broken up to prevent false-positives with srcck1.c.
84137  **
84138  ** This assert() provides evidence for:
84139  ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
84140  ** would have been returned by the legacy sqlite3_trace() interface by
84141  ** using the X argument when X begins with "--" and invoking
84142  ** sqlite3_expanded_sql(P) otherwise.
84143  */
84144  assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
84145  assert( pOp==p->aOp ); /* Always instruction 0 */
84146 
84147 #ifndef SQLITE_OMIT_TRACE
84149  && !p->doingRerun
84150  && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
84151  ){
84152 #ifndef SQLITE_OMIT_DEPRECATED
84153  if( db->mTrace & SQLITE_TRACE_LEGACY ){
84154  void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
84155  char *z = sqlite3VdbeExpandSql(p, zTrace);
84156  x(db->pTraceArg, z);
84157  sqlite3_free(z);
84158  }else
84159 #endif
84160  {
84161  (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
84162  }
84163  }
84164 #ifdef SQLITE_USE_FCNTL_TRACE
84165  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
84166  if( zTrace ){
84167  int j;
84168  for(j=0; j<db->nDb; j++){
84169  if( DbMaskTest(p->btreeMask, j)==0 ) continue;
84170  sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
84171  }
84172  }
84173 #endif /* SQLITE_USE_FCNTL_TRACE */
84174 #ifdef SQLITE_DEBUG
84175  if( (db->flags & SQLITE_SqlTrace)!=0
84176  && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
84177  ){
84178  sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
84179  }
84180 #endif /* SQLITE_DEBUG */
84181 #endif /* SQLITE_OMIT_TRACE */
84182  assert( pOp->p2>0 );
84183  if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
84184  for(i=1; i<p->nOp; i++){
84185  if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
84186  }
84187  pOp->p1 = 0;
84188  }
84189  pOp->p1++;
84190  goto jump_to_p2;
84191 }
84192 
84193 #ifdef SQLITE_ENABLE_CURSOR_HINTS
84194 /* Opcode: CursorHint P1 * * P4 *
84195 **
84196 ** Provide a hint to cursor P1 that it only needs to return rows that
84197 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
84198 ** to values currently held in registers. TK_COLUMN terms in the P4
84199 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
84200 */
84201 case OP_CursorHint: {
84202  VdbeCursor *pC;
84203 
84204  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
84205  assert( pOp->p4type==P4_EXPR );
84206  pC = p->apCsr[pOp->p1];
84207  if( pC ){
84208  assert( pC->eCurType==CURTYPE_BTREE );
84209  sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
84210  pOp->p4.pExpr, aMem);
84211  }
84212  break;
84213 }
84214 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
84215 
84216 /* Opcode: Noop * * * * *
84217 **
84218 ** Do nothing. This instruction is often useful as a jump
84219 ** destination.
84220 */
84221 /*
84222 ** The magic Explain opcode are only inserted when explain==2 (which
84223 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
84224 ** This opcode records information from the optimizer. It is the
84225 ** the same as a no-op. This opcodesnever appears in a real VM program.
84226 */
84227 default: { /* This is really OP_Noop and OP_Explain */
84228  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
84229  break;
84230 }
84231 
84232 /*****************************************************************************
84233 ** The cases of the switch statement above this line should all be indented
84234 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
84235 ** readability. From this point on down, the normal indentation rules are
84236 ** restored.
84237 *****************************************************************************/
84238  }
84239 
84240 #ifdef VDBE_PROFILE
84241  {
84242  u64 endTime = sqlite3Hwtime();
84243  if( endTime>start ) pOrigOp->cycles += endTime - start;
84244  pOrigOp->cnt++;
84245  }
84246 #endif
84247 
84248  /* The following code adds nothing to the actual functionality
84249  ** of the program. It is only here for testing and debugging.
84250  ** On the other hand, it does burn CPU cycles every time through
84251  ** the evaluator loop. So we can leave it out when NDEBUG is defined.
84252  */
84253 #ifndef NDEBUG
84254  assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
84255 
84256 #ifdef SQLITE_DEBUG
84257  if( db->flags & SQLITE_VdbeTrace ){
84258  u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
84259  if( rc!=0 ) printf("rc=%d\n",rc);
84260  if( opProperty & (OPFLG_OUT2) ){
84261  registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
84262  }
84263  if( opProperty & OPFLG_OUT3 ){
84264  registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
84265  }
84266  }
84267 #endif /* SQLITE_DEBUG */
84268 #endif /* NDEBUG */
84269  } /* The end of the for(;;) loop the loops through opcodes */
84270 
84271  /* If we reach this point, it means that execution is finished with
84272  ** an error of some kind.
84273  */
84274 abort_due_to_error:
84275  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
84276  assert( rc );
84277  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
84278  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84279  }
84280  p->rc = rc;
84281  sqlite3SystemError(db, rc);
84282  testcase( sqlite3GlobalConfig.xLog!=0 );
84283  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
84284  (int)(pOp - aOp), p->zSql, p->zErrMsg);
84285  sqlite3VdbeHalt(p);
84286  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
84287  rc = SQLITE_ERROR;
84288  if( resetSchemaOnFault>0 ){
84289  sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
84290  }
84291 
84292  /* This is the only way out of this procedure. We have to
84293  ** release the mutexes on btrees that were acquired at the
84294  ** top. */
84295 vdbe_return:
84296  db->lastRowid = lastRowid;
84297  testcase( nVmStep>0 );
84298  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
84299  sqlite3VdbeLeave(p);
84300  assert( rc!=SQLITE_OK || nExtraDelete==0
84301  || sqlite3_strlike("DELETE%",p->zSql,0)!=0
84302  );
84303  return rc;
84304 
84305  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
84306  ** is encountered.
84307  */
84308 too_big:
84309  sqlite3VdbeError(p, "string or blob too big");
84310  rc = SQLITE_TOOBIG;
84311  goto abort_due_to_error;
84312 
84313  /* Jump to here if a malloc() fails.
84314  */
84315 no_mem:
84316  sqlite3OomFault(db);
84317  sqlite3VdbeError(p, "out of memory");
84318  rc = SQLITE_NOMEM_BKPT;
84319  goto abort_due_to_error;
84320 
84321  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
84322  ** flag.
84323  */
84324 abort_due_to_interrupt:
84325  assert( db->u1.isInterrupted );
84327  p->rc = rc;
84328  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84329  goto abort_due_to_error;
84330 }
84331 
84332 
84333 /************** End of vdbe.c ************************************************/
84334 /************** Begin file vdbeblob.c ****************************************/
84335 /*
84336 ** 2007 May 1
84337 **
84338 ** The author disclaims copyright to this source code. In place of
84339 ** a legal notice, here is a blessing:
84340 **
84341 ** May you do good and not evil.
84342 ** May you find forgiveness for yourself and forgive others.
84343 ** May you share freely, never taking more than you give.
84344 **
84345 *************************************************************************
84346 **
84347 ** This file contains code used to implement incremental BLOB I/O.
84348 */
84349 
84350 /* #include "sqliteInt.h" */
84351 /* #include "vdbeInt.h" */
84352 
84353 #ifndef SQLITE_OMIT_INCRBLOB
84354 
84355 /*
84356 ** Valid sqlite3_blob* handles point to Incrblob structures.
84357 */
84358 typedef struct Incrblob Incrblob;
84359 struct Incrblob {
84360  int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
84361  int nByte; /* Size of open blob, in bytes */
84362  int iOffset; /* Byte offset of blob in cursor data */
84363  int iCol; /* Table column this handle is open on */
84364  BtCursor *pCsr; /* Cursor pointing at blob row */
84365  sqlite3_stmt *pStmt; /* Statement holding cursor open */
84366  sqlite3 *db; /* The associated database */
84367  char *zDb; /* Database name */
84368  Table *pTab; /* Table object */
84369 };
84370 
84371 
84372 /*
84373 ** This function is used by both blob_open() and blob_reopen(). It seeks
84374 ** the b-tree cursor associated with blob handle p to point to row iRow.
84375 ** If successful, SQLITE_OK is returned and subsequent calls to
84376 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
84377 **
84378 ** If an error occurs, or if the specified row does not exist or does not
84379 ** contain a value of type TEXT or BLOB in the column nominated when the
84380 ** blob handle was opened, then an error code is returned and *pzErr may
84381 ** be set to point to a buffer containing an error message. It is the
84382 ** responsibility of the caller to free the error message buffer using
84383 ** sqlite3DbFree().
84384 **
84385 ** If an error does occur, then the b-tree cursor is closed. All subsequent
84386 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
84387 ** immediately return SQLITE_ABORT.
84388 */
84389 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
84390  int rc; /* Error code */
84391  char *zErr = 0; /* Error message */
84392  Vdbe *v = (Vdbe *)p->pStmt;
84393 
84394  /* Set the value of the SQL statements only variable to integer iRow.
84395  ** This is done directly instead of using sqlite3_bind_int64() to avoid
84396  ** triggering asserts related to mutexes.
84397  */
84398  assert( v->aVar[0].flags&MEM_Int );
84399  v->aVar[0].u.i = iRow;
84400 
84401  rc = sqlite3_step(p->pStmt);
84402  if( rc==SQLITE_ROW ){
84403  VdbeCursor *pC = v->apCsr[0];
84404  u32 type = pC->aType[p->iCol];
84405  if( type<12 ){
84406  zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
84407  type==0?"null": type==7?"real": "integer"
84408  );
84409  rc = SQLITE_ERROR;
84410  sqlite3_finalize(p->pStmt);
84411  p->pStmt = 0;
84412  }else{
84413  p->iOffset = pC->aType[p->iCol + pC->nField];
84414  p->nByte = sqlite3VdbeSerialTypeLen(type);
84415  p->pCsr = pC->uc.pCursor;
84417  }
84418  }
84419 
84420  if( rc==SQLITE_ROW ){
84421  rc = SQLITE_OK;
84422  }else if( p->pStmt ){
84423  rc = sqlite3_finalize(p->pStmt);
84424  p->pStmt = 0;
84425  if( rc==SQLITE_OK ){
84426  zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
84427  rc = SQLITE_ERROR;
84428  }else{
84429  zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
84430  }
84431  }
84432 
84433  assert( rc!=SQLITE_OK || zErr==0 );
84434  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
84435 
84436  *pzErr = zErr;
84437  return rc;
84438 }
84439 
84440 /*
84441 ** Open a blob handle.
84442 */
84444  sqlite3* db, /* The database connection */
84445  const char *zDb, /* The attached database containing the blob */
84446  const char *zTable, /* The table containing the blob */
84447  const char *zColumn, /* The column containing the blob */
84448  sqlite_int64 iRow, /* The row containing the glob */
84449  int flags, /* True -> read/write access, false -> read-only */
84450  sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
84451 ){
84452  int nAttempt = 0;
84453  int iCol; /* Index of zColumn in row-record */
84454  int rc = SQLITE_OK;
84455  char *zErr = 0;
84456  Table *pTab;
84457  Parse *pParse = 0;
84458  Incrblob *pBlob = 0;
84459 
84460 #ifdef SQLITE_ENABLE_API_ARMOR
84461  if( ppBlob==0 ){
84462  return SQLITE_MISUSE_BKPT;
84463  }
84464 #endif
84465  *ppBlob = 0;
84466 #ifdef SQLITE_ENABLE_API_ARMOR
84467  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
84468  return SQLITE_MISUSE_BKPT;
84469  }
84470 #endif
84471  flags = !!flags; /* flags = (flags ? 1 : 0); */
84472 
84474 
84475  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
84476  if( !pBlob ) goto blob_open_out;
84477  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
84478  if( !pParse ) goto blob_open_out;
84479 
84480  do {
84481  memset(pParse, 0, sizeof(Parse));
84482  pParse->db = db;
84483  sqlite3DbFree(db, zErr);
84484  zErr = 0;
84485 
84487  pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
84488  if( pTab && IsVirtual(pTab) ){
84489  pTab = 0;
84490  sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
84491  }
84492  if( pTab && !HasRowid(pTab) ){
84493  pTab = 0;
84494  sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
84495  }
84496 #ifndef SQLITE_OMIT_VIEW
84497  if( pTab && pTab->pSelect ){
84498  pTab = 0;
84499  sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
84500  }
84501 #endif
84502  if( !pTab ){
84503  if( pParse->zErrMsg ){
84504  sqlite3DbFree(db, zErr);
84505  zErr = pParse->zErrMsg;
84506  pParse->zErrMsg = 0;
84507  }
84508  rc = SQLITE_ERROR;
84510  goto blob_open_out;
84511  }
84512  pBlob->pTab = pTab;
84513  pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
84514 
84515  /* Now search pTab for the exact column. */
84516  for(iCol=0; iCol<pTab->nCol; iCol++) {
84517  if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
84518  break;
84519  }
84520  }
84521  if( iCol==pTab->nCol ){
84522  sqlite3DbFree(db, zErr);
84523  zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
84524  rc = SQLITE_ERROR;
84526  goto blob_open_out;
84527  }
84528 
84529  /* If the value is being opened for writing, check that the
84530  ** column is not indexed, and that it is not part of a foreign key.
84531  ** It is against the rules to open a column to which either of these
84532  ** descriptions applies for writing. */
84533  if( flags ){
84534  const char *zFault = 0;
84535  Index *pIdx;
84536 #ifndef SQLITE_OMIT_FOREIGN_KEY
84537  if( db->flags&SQLITE_ForeignKeys ){
84538  /* Check that the column is not part of an FK child key definition. It
84539  ** is not necessary to check if it is part of a parent key, as parent
84540  ** key columns must be indexed. The check below will pick up this
84541  ** case. */
84542  FKey *pFKey;
84543  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84544  int j;
84545  for(j=0; j<pFKey->nCol; j++){
84546  if( pFKey->aCol[j].iFrom==iCol ){
84547  zFault = "foreign key";
84548  }
84549  }
84550  }
84551  }
84552 #endif
84553  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84554  int j;
84555  for(j=0; j<pIdx->nKeyCol; j++){
84556  /* FIXME: Be smarter about indexes that use expressions */
84557  if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
84558  zFault = "indexed";
84559  }
84560  }
84561  }
84562  if( zFault ){
84563  sqlite3DbFree(db, zErr);
84564  zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
84565  rc = SQLITE_ERROR;
84567  goto blob_open_out;
84568  }
84569  }
84570 
84571  pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
84572  assert( pBlob->pStmt || db->mallocFailed );
84573  if( pBlob->pStmt ){
84574 
84575  /* This VDBE program seeks a btree cursor to the identified
84576  ** db/table/row entry. The reason for using a vdbe program instead
84577  ** of writing code to use the b-tree layer directly is that the
84578  ** vdbe program will take advantage of the various transaction,
84579  ** locking and error handling infrastructure built into the vdbe.
84580  **
84581  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
84582  ** Code external to the Vdbe then "borrows" the b-tree cursor and
84583  ** uses it to implement the blob_read(), blob_write() and
84584  ** blob_bytes() functions.
84585  **
84586  ** The sqlite3_blob_close() function finalizes the vdbe program,
84587  ** which closes the b-tree cursor and (possibly) commits the
84588  ** transaction.
84589  */
84590  static const int iLn = VDBE_OFFSET_LINENO(2);
84591  static const VdbeOpList openBlob[] = {
84592  {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
84593  {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
84594  {OP_Variable, 1, 1, 0}, /* 2: Move ?1 into reg[1] */
84595  {OP_NotExists, 0, 7, 1}, /* 3: Seek the cursor */
84596  {OP_Column, 0, 0, 1}, /* 4 */
84597  {OP_ResultRow, 1, 0, 0}, /* 5 */
84598  {OP_Goto, 0, 2, 0}, /* 6 */
84599  {OP_Close, 0, 0, 0}, /* 7 */
84600  {OP_Halt, 0, 0, 0}, /* 8 */
84601  };
84602  Vdbe *v = (Vdbe *)pBlob->pStmt;
84603  int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84604  VdbeOp *aOp;
84605 
84606  sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
84607  pTab->pSchema->schema_cookie,
84608  pTab->pSchema->iGeneration);
84609  sqlite3VdbeChangeP5(v, 1);
84610  aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
84611 
84612  /* Make sure a mutex is held on the table to be accessed */
84613  sqlite3VdbeUsesBtree(v, iDb);
84614 
84615  if( db->mallocFailed==0 ){
84616  assert( aOp!=0 );
84617  /* Configure the OP_TableLock instruction */
84618 #ifdef SQLITE_OMIT_SHARED_CACHE
84619  aOp[0].opcode = OP_Noop;
84620 #else
84621  aOp[0].p1 = iDb;
84622  aOp[0].p2 = pTab->tnum;
84623  aOp[0].p3 = flags;
84624  sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
84625  }
84626  if( db->mallocFailed==0 ){
84627 #endif
84628 
84629  /* Remove either the OP_OpenWrite or OpenRead. Set the P2
84630  ** parameter of the other to pTab->tnum. */
84631  if( flags ) aOp[1].opcode = OP_OpenWrite;
84632  aOp[1].p2 = pTab->tnum;
84633  aOp[1].p3 = iDb;
84634 
84635  /* Configure the number of columns. Configure the cursor to
84636  ** think that the table has one more column than it really
84637  ** does. An OP_Column to retrieve this imaginary column will
84638  ** always return an SQL NULL. This is useful because it means
84639  ** we can invoke OP_Column to fill in the vdbe cursors type
84640  ** and offset cache without causing any IO.
84641  */
84642  aOp[1].p4type = P4_INT32;
84643  aOp[1].p4.i = pTab->nCol+1;
84644  aOp[4].p2 = pTab->nCol;
84645 
84646  pParse->nVar = 1;
84647  pParse->nMem = 1;
84648  pParse->nTab = 1;
84649  sqlite3VdbeMakeReady(v, pParse);
84650  }
84651  }
84652 
84653  pBlob->flags = flags;
84654  pBlob->iCol = iCol;
84655  pBlob->db = db;
84657  if( db->mallocFailed ){
84658  goto blob_open_out;
84659  }
84660  sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
84661  rc = blobSeekToRow(pBlob, iRow, &zErr);
84662  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
84663 
84664 blob_open_out:
84665  if( rc==SQLITE_OK && db->mallocFailed==0 ){
84666  *ppBlob = (sqlite3_blob *)pBlob;
84667  }else{
84668  if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
84669  sqlite3DbFree(db, pBlob);
84670  }
84671  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84672  sqlite3DbFree(db, zErr);
84673  sqlite3ParserReset(pParse);
84674  sqlite3StackFree(db, pParse);
84675  rc = sqlite3ApiExit(db, rc);
84677  return rc;
84678 }
84679 
84680 /*
84681 ** Close a blob handle that was previously created using
84682 ** sqlite3_blob_open().
84683 */
84685  Incrblob *p = (Incrblob *)pBlob;
84686  int rc;
84687  sqlite3 *db;
84688 
84689  if( p ){
84690  db = p->db;
84692  rc = sqlite3_finalize(p->pStmt);
84693  sqlite3DbFree(db, p);
84695  }else{
84696  rc = SQLITE_OK;
84697  }
84698  return rc;
84699 }
84700 
84701 /*
84702 ** Perform a read or write operation on a blob
84703 */
84704 static int blobReadWrite(
84705  sqlite3_blob *pBlob,
84706  void *z,
84707  int n,
84708  int iOffset,
84709  int (*xCall)(BtCursor*, u32, u32, void*)
84710 ){
84711  int rc;
84712  Incrblob *p = (Incrblob *)pBlob;
84713  Vdbe *v;
84714  sqlite3 *db;
84715 
84716  if( p==0 ) return SQLITE_MISUSE_BKPT;
84717  db = p->db;
84719  v = (Vdbe*)p->pStmt;
84720 
84721  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
84722  /* Request is out of range. Return a transient error. */
84723  rc = SQLITE_ERROR;
84724  }else if( v==0 ){
84725  /* If there is no statement handle, then the blob-handle has
84726  ** already been invalidated. Return SQLITE_ABORT in this case.
84727  */
84728  rc = SQLITE_ABORT;
84729  }else{
84730  /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
84731  ** returned, clean-up the statement handle.
84732  */
84733  assert( db == v->db );
84735 
84736 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
84737  if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
84738  /* If a pre-update hook is registered and this is a write cursor,
84739  ** invoke it here.
84740  **
84741  ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
84742  ** operation should really be an SQLITE_UPDATE. This is probably
84743  ** incorrect, but is convenient because at this point the new.* values
84744  ** are not easily obtainable. And for the sessions module, an
84745  ** SQLITE_UPDATE where the PK columns do not change is handled in the
84746  ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
84747  ** slightly more efficient). Since you cannot write to a PK column
84748  ** using the incremental-blob API, this works. For the sessions module
84749  ** anyhow.
84750  */
84751  sqlite3_int64 iKey;
84752  iKey = sqlite3BtreeIntegerKey(p->pCsr);
84753  sqlite3VdbePreUpdateHook(
84754  v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
84755  );
84756  }
84757 #endif
84758 
84759  rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
84761  if( rc==SQLITE_ABORT ){
84763  p->pStmt = 0;
84764  }else{
84765  v->rc = rc;
84766  }
84767  }
84768  sqlite3Error(db, rc);
84769  rc = sqlite3ApiExit(db, rc);
84771  return rc;
84772 }
84773 
84774 /*
84775 ** Read data from a blob handle.
84776 */
84777 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
84778  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
84779 }
84780 
84781 /*
84782 ** Write data to a blob handle.
84783 */
84784 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
84785  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
84786 }
84787 
84788 /*
84789 ** Query a blob handle for the size of the data.
84790 **
84791 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
84792 ** so no mutex is required for access.
84793 */
84795  Incrblob *p = (Incrblob *)pBlob;
84796  return (p && p->pStmt) ? p->nByte : 0;
84797 }
84798 
84799 /*
84800 ** Move an existing blob handle to point to a different row of the same
84801 ** database table.
84802 **
84803 ** If an error occurs, or if the specified row does not exist or does not
84804 ** contain a blob or text value, then an error code is returned and the
84805 ** database handle error code and message set. If this happens, then all
84806 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
84807 ** immediately return SQLITE_ABORT.
84808 */
84809 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
84810  int rc;
84811  Incrblob *p = (Incrblob *)pBlob;
84812  sqlite3 *db;
84813 
84814  if( p==0 ) return SQLITE_MISUSE_BKPT;
84815  db = p->db;
84817 
84818  if( p->pStmt==0 ){
84819  /* If there is no statement handle, then the blob-handle has
84820  ** already been invalidated. Return SQLITE_ABORT in this case.
84821  */
84822  rc = SQLITE_ABORT;
84823  }else{
84824  char *zErr;
84825  rc = blobSeekToRow(p, iRow, &zErr);
84826  if( rc!=SQLITE_OK ){
84827  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84828  sqlite3DbFree(db, zErr);
84829  }
84830  assert( rc!=SQLITE_SCHEMA );
84831  }
84832 
84833  rc = sqlite3ApiExit(db, rc);
84834  assert( rc==SQLITE_OK || p->pStmt==0 );
84836  return rc;
84837 }
84838 
84839 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
84840 
84841 /************** End of vdbeblob.c ********************************************/
84842 /************** Begin file vdbesort.c ****************************************/
84843 /*
84844 ** 2011-07-09
84845 **
84846 ** The author disclaims copyright to this source code. In place of
84847 ** a legal notice, here is a blessing:
84848 **
84849 ** May you do good and not evil.
84850 ** May you find forgiveness for yourself and forgive others.
84851 ** May you share freely, never taking more than you give.
84852 **
84853 *************************************************************************
84854 ** This file contains code for the VdbeSorter object, used in concert with
84855 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
84856 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
84857 ** using indexes and without LIMIT clauses.
84858 **
84859 ** The VdbeSorter object implements a multi-threaded external merge sort
84860 ** algorithm that is efficient even if the number of elements being sorted
84861 ** exceeds the available memory.
84862 **
84863 ** Here is the (internal, non-API) interface between this module and the
84864 ** rest of the SQLite system:
84865 **
84866 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
84867 **
84868 ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
84869 ** object. The row is a binary blob in the
84870 ** OP_MakeRecord format that contains both
84871 ** the ORDER BY key columns and result columns
84872 ** in the case of a SELECT w/ ORDER BY, or
84873 ** the complete record for an index entry
84874 ** in the case of a CREATE INDEX.
84875 **
84876 ** sqlite3VdbeSorterRewind() Sort all content previously added.
84877 ** Position the read cursor on the
84878 ** first sorted element.
84879 **
84880 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
84881 ** element.
84882 **
84883 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
84884 ** row currently under the read cursor.
84885 **
84886 ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
84887 ** currently under the read cursor against
84888 ** another binary blob X and report if
84889 ** X is strictly less than the read cursor.
84890 ** Used to enforce uniqueness in a
84891 ** CREATE UNIQUE INDEX statement.
84892 **
84893 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
84894 ** all resources.
84895 **
84896 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
84897 ** is like Close() followed by Init() only
84898 ** much faster.
84899 **
84900 ** The interfaces above must be called in a particular order. Write() can
84901 ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
84902 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
84903 **
84904 ** Init()
84905 ** for each record: Write()
84906 ** Rewind()
84907 ** Rowkey()/Compare()
84908 ** Next()
84909 ** Close()
84910 **
84911 ** Algorithm:
84912 **
84913 ** Records passed to the sorter via calls to Write() are initially held
84914 ** unsorted in main memory. Assuming the amount of memory used never exceeds
84915 ** a threshold, when Rewind() is called the set of records is sorted using
84916 ** an in-memory merge sort. In this case, no temporary files are required
84917 ** and subsequent calls to Rowkey(), Next() and Compare() read records
84918 ** directly from main memory.
84919 **
84920 ** If the amount of space used to store records in main memory exceeds the
84921 ** threshold, then the set of records currently in memory are sorted and
84922 ** written to a temporary file in "Packed Memory Array" (PMA) format.
84923 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
84924 ** of PMAs may be created by merging existing PMAs together - for example
84925 ** merging two or more level-0 PMAs together creates a level-1 PMA.
84926 **
84927 ** The threshold for the amount of main memory to use before flushing
84928 ** records to a PMA is roughly the same as the limit configured for the
84929 ** page-cache of the main database. Specifically, the threshold is set to
84930 ** the value returned by "PRAGMA main.page_size" multipled by
84931 ** that returned by "PRAGMA main.cache_size", in bytes.
84932 **
84933 ** If the sorter is running in single-threaded mode, then all PMAs generated
84934 ** are appended to a single temporary file. Or, if the sorter is running in
84935 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
84936 ** N is the configured number of worker threads. In this case, instead of
84937 ** sorting the records and writing the PMA to a temporary file itself, the
84938 ** calling thread usually launches a worker thread to do so. Except, if
84939 ** there are already N worker threads running, the main thread does the work
84940 ** itself.
84941 **
84942 ** The sorter is running in multi-threaded mode if (a) the library was built
84943 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
84944 ** than zero, and (b) worker threads have been enabled at runtime by calling
84945 ** "PRAGMA threads=N" with some value of N greater than 0.
84946 **
84947 ** When Rewind() is called, any data remaining in memory is flushed to a
84948 ** final PMA. So at this point the data is stored in some number of sorted
84949 ** PMAs within temporary files on disk.
84950 **
84951 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
84952 ** sorter is running in single-threaded mode, then these PMAs are merged
84953 ** incrementally as keys are retreived from the sorter by the VDBE. The
84954 ** MergeEngine object, described in further detail below, performs this
84955 ** merge.
84956 **
84957 ** Or, if running in multi-threaded mode, then a background thread is
84958 ** launched to merge the existing PMAs. Once the background thread has
84959 ** merged T bytes of data into a single sorted PMA, the main thread
84960 ** begins reading keys from that PMA while the background thread proceeds
84961 ** with merging the next T bytes of data. And so on.
84962 **
84963 ** Parameter T is set to half the value of the memory threshold used
84964 ** by Write() above to determine when to create a new PMA.
84965 **
84966 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
84967 ** Rewind() is called, then a hierarchy of incremental-merges is used.
84968 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
84969 ** disk are merged together. Then T bytes of data from the second set, and
84970 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
84971 ** PMAs at a time. This done is to improve locality.
84972 **
84973 ** If running in multi-threaded mode and there are more than
84974 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
84975 ** than one background thread may be created. Specifically, there may be
84976 ** one background thread for each temporary file on disk, and one background
84977 ** thread to merge the output of each of the others to a single PMA for
84978 ** the main thread to read from.
84979 */
84980 /* #include "sqliteInt.h" */
84981 /* #include "vdbeInt.h" */
84982 
84983 /*
84984 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
84985 ** messages to stderr that may be helpful in understanding the performance
84986 ** characteristics of the sorter in multi-threaded mode.
84987 */
84988 #if 0
84989 # define SQLITE_DEBUG_SORTER_THREADS 1
84990 #endif
84991 
84992 /*
84993 ** Hard-coded maximum amount of data to accumulate in memory before flushing
84994 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
84995 ** overflows. 512MiB.
84996 */
84997 #define SQLITE_MAX_PMASZ (1<<29)
84998 
84999 /*
85000 ** Private objects used by the sorter
85001 */
85002 typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
85003 typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
85004 typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
85005 typedef struct SorterRecord SorterRecord; /* A record being sorted */
85006 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
85007 typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
85008 typedef struct SorterList SorterList; /* In-memory list of records */
85009 typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
85010 
85011 /*
85012 ** A container for a temp file handle and the current amount of data
85013 ** stored in the file.
85014 */
85015 struct SorterFile {
85016  sqlite3_file *pFd; /* File handle */
85017  i64 iEof; /* Bytes of data stored in pFd */
85018 };
85019 
85020 /*
85021 ** An in-memory list of objects to be sorted.
85022 **
85023 ** If aMemory==0 then each object is allocated separately and the objects
85024 ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
85025 ** are stored in the aMemory[] bulk memory, one right after the other, and
85026 ** are connected using SorterRecord.u.iNext.
85027 */
85028 struct SorterList {
85029  SorterRecord *pList; /* Linked list of records */
85030  u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
85031  int szPMA; /* Size of pList as PMA in bytes */
85032 };
85033 
85034 /*
85035 ** The MergeEngine object is used to combine two or more smaller PMAs into
85036 ** one big PMA using a merge operation. Separate PMAs all need to be
85037 ** combined into one big PMA in order to be able to step through the sorted
85038 ** records in order.
85039 **
85040 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
85041 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
85042 ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
85043 ** For the purposes of the paragraphs below, we assume that the array is
85044 ** actually N elements in size, where N is the smallest power of 2 greater
85045 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
85046 ** are treated as if they are empty (always at EOF).
85047 **
85048 ** The aTree[] array is also N elements in size. The value of N is stored in
85049 ** the MergeEngine.nTree variable.
85050 **
85051 ** The final (N/2) elements of aTree[] contain the results of comparing
85052 ** pairs of PMA keys together. Element i contains the result of
85053 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
85054 ** aTree element is set to the index of it.
85055 **
85056 ** For the purposes of this comparison, EOF is considered greater than any
85057 ** other key value. If the keys are equal (only possible with two EOF
85058 ** values), it doesn't matter which index is stored.
85059 **
85060 ** The (N/4) elements of aTree[] that precede the final (N/2) described
85061 ** above contains the index of the smallest of each block of 4 PmaReaders
85062 ** And so on. So that aTree[1] contains the index of the PmaReader that
85063 ** currently points to the smallest key value. aTree[0] is unused.
85064 **
85065 ** Example:
85066 **
85067 ** aReadr[0] -> Banana
85068 ** aReadr[1] -> Feijoa
85069 ** aReadr[2] -> Elderberry
85070 ** aReadr[3] -> Currant
85071 ** aReadr[4] -> Grapefruit
85072 ** aReadr[5] -> Apple
85073 ** aReadr[6] -> Durian
85074 ** aReadr[7] -> EOF
85075 **
85076 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
85077 **
85078 ** The current element is "Apple" (the value of the key indicated by
85079 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
85080 ** be advanced to the next key in its segment. Say the next key is
85081 ** "Eggplant":
85082 **
85083 ** aReadr[5] -> Eggplant
85084 **
85085 ** The contents of aTree[] are updated first by comparing the new PmaReader
85086 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
85087 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
85088 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
85089 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
85090 ** so the value written into element 1 of the array is 0. As follows:
85091 **
85092 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
85093 **
85094 ** In other words, each time we advance to the next sorter element, log2(N)
85095 ** key comparison operations are required, where N is the number of segments
85096 ** being merged (rounded up to the next power of 2).
85097 */
85098 struct MergeEngine {
85099  int nTree; /* Used size of aTree/aReadr (power of 2) */
85100  SortSubtask *pTask; /* Used by this thread only */
85101  int *aTree; /* Current state of incremental merge */
85102  PmaReader *aReadr; /* Array of PmaReaders to merge data from */
85103 };
85104 
85105 /*
85106 ** This object represents a single thread of control in a sort operation.
85107 ** Exactly VdbeSorter.nTask instances of this object are allocated
85108 ** as part of each VdbeSorter object. Instances are never allocated any
85109 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
85110 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
85111 ** single-threaded operation, there is exactly one instance of this object
85112 ** and for multi-threaded operation there are two or more instances.
85113 **
85114 ** Essentially, this structure contains all those fields of the VdbeSorter
85115 ** structure for which each thread requires a separate instance. For example,
85116 ** each thread requries its own UnpackedRecord object to unpack records in
85117 ** as part of comparison operations.
85118 **
85119 ** Before a background thread is launched, variable bDone is set to 0. Then,
85120 ** right before it exits, the thread itself sets bDone to 1. This is used for
85121 ** two purposes:
85122 **
85123 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
85124 ** attempt to select a SortSubtask for which there is not already an
85125 ** active background thread (since doing so causes the main thread
85126 ** to block until it finishes).
85127 **
85128 ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
85129 ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
85130 ** block provoke debugging output.
85131 **
85132 ** In both cases, the effects of the main thread seeing (bDone==0) even
85133 ** after the thread has finished are not dire. So we don't worry about
85134 ** memory barriers and such here.
85135 */
85136 typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
85137 struct SortSubtask {
85138  SQLiteThread *pThread; /* Background thread, if any */
85139  int bDone; /* Set if thread is finished but not joined */
85140  VdbeSorter *pSorter; /* Sorter that owns this sub-task */
85141  UnpackedRecord *pUnpacked; /* Space to unpack a record */
85142  SorterList list; /* List for thread to write to a PMA */
85143  int nPMA; /* Number of PMAs currently in file */
85144  SorterCompare xCompare; /* Compare function to use */
85145  SorterFile file; /* Temp file for level-0 PMAs */
85146  SorterFile file2; /* Space for other PMAs */
85147 };
85148 
85149 
85150 /*
85151 ** Main sorter structure. A single instance of this is allocated for each
85152 ** sorter cursor created by the VDBE.
85153 **
85154 ** mxKeysize:
85155 ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
85156 ** this variable is updated so as to be set to the size on disk of the
85157 ** largest record in the sorter.
85158 */
85159 struct VdbeSorter {
85160  int mnPmaSize; /* Minimum PMA size, in bytes */
85161  int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
85162  int mxKeysize; /* Largest serialized key seen so far */
85163  int pgsz; /* Main database page size */
85164  PmaReader *pReader; /* Readr data from here after Rewind() */
85165  MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
85166  sqlite3 *db; /* Database connection */
85167  KeyInfo *pKeyInfo; /* How to compare records */
85168  UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
85169  SorterList list; /* List of in-memory records */
85170  int iMemory; /* Offset of free space in list.aMemory */
85171  int nMemory; /* Size of list.aMemory allocation in bytes */
85172  u8 bUsePMA; /* True if one or more PMAs created */
85173  u8 bUseThreads; /* True to use background threads */
85174  u8 iPrev; /* Previous thread used to flush PMA */
85175  u8 nTask; /* Size of aTask[] array */
85177  SortSubtask aTask[1]; /* One or more subtasks */
85178 };
85179 
85180 #define SORTER_TYPE_INTEGER 0x01
85181 #define SORTER_TYPE_TEXT 0x02
85182 
85183 /*
85184 ** An instance of the following object is used to read records out of a
85185 ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
85186 ** aKey might point into aMap or into aBuffer. If neither of those locations
85187 ** contain a contiguous representation of the key, then aAlloc is allocated
85188 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
85189 **
85190 ** pFd==0 at EOF.
85191 */
85192 struct PmaReader {
85193  i64 iReadOff; /* Current read offset */
85194  i64 iEof; /* 1 byte past EOF for this PmaReader */
85195  int nAlloc; /* Bytes of space at aAlloc */
85196  int nKey; /* Number of bytes in key */
85197  sqlite3_file *pFd; /* File handle we are reading from */
85198  u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
85199  u8 *aKey; /* Pointer to current key */
85200  u8 *aBuffer; /* Current read buffer */
85201  int nBuffer; /* Size of read buffer in bytes */
85202  u8 *aMap; /* Pointer to mapping of entire file */
85203  IncrMerger *pIncr; /* Incremental merger */
85204 };
85205 
85206 /*
85207 ** Normally, a PmaReader object iterates through an existing PMA stored
85208 ** within a temp file. However, if the PmaReader.pIncr variable points to
85209 ** an object of the following type, it may be used to iterate/merge through
85210 ** multiple PMAs simultaneously.
85211 **
85212 ** There are two types of IncrMerger object - single (bUseThread==0) and
85213 ** multi-threaded (bUseThread==1).
85214 **
85215 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
85216 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
85217 ** size. When the IncrMerger is initialized, it reads enough data from
85218 ** pMerger to populate aFile[0]. It then sets variables within the
85219 ** corresponding PmaReader object to read from that file and kicks off
85220 ** a background thread to populate aFile[1] with the next mxSz bytes of
85221 ** sorted record data from pMerger.
85222 **
85223 ** When the PmaReader reaches the end of aFile[0], it blocks until the
85224 ** background thread has finished populating aFile[1]. It then exchanges
85225 ** the contents of the aFile[0] and aFile[1] variables within this structure,
85226 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
85227 ** another background thread to populate the new aFile[1]. And so on, until
85228 ** the contents of pMerger are exhausted.
85229 **
85230 ** A single-threaded IncrMerger does not open any temporary files of its
85231 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
85232 ** at offset iStartOff of file pTask->file2. And instead of using a
85233 ** background thread to prepare data for the PmaReader, with a single
85234 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
85235 ** keys from pMerger by the calling thread whenever the PmaReader runs out
85236 ** of data.
85237 */
85238 struct IncrMerger {
85239  SortSubtask *pTask; /* Task that owns this merger */
85240  MergeEngine *pMerger; /* Merge engine thread reads data from */
85241  i64 iStartOff; /* Offset to start writing file at */
85242  int mxSz; /* Maximum bytes of data to store */
85243  int bEof; /* Set to true when merge is finished */
85244  int bUseThread; /* True to use a bg thread for this object */
85245  SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
85246 };
85247 
85248 /*
85249 ** An instance of this object is used for writing a PMA.
85250 **
85251 ** The PMA is written one record at a time. Each record is of an arbitrary
85252 ** size. But I/O is more efficient if it occurs in page-sized blocks where
85253 ** each block is aligned on a page boundary. This object caches writes to
85254 ** the PMA so that aligned, page-size blocks are written.
85255 */
85256 struct PmaWriter {
85257  int eFWErr; /* Non-zero if in an error state */
85258  u8 *aBuffer; /* Pointer to write buffer */
85259  int nBuffer; /* Size of write buffer in bytes */
85260  int iBufStart; /* First byte of buffer to write */
85261  int iBufEnd; /* Last byte of buffer to write */
85262  i64 iWriteOff; /* Offset of start of buffer in file */
85263  sqlite3_file *pFd; /* File handle to write to */
85264 };
85265 
85266 /*
85267 ** This object is the header on a single record while that record is being
85268 ** held in memory and prior to being written out as part of a PMA.
85269 **
85270 ** How the linked list is connected depends on how memory is being managed
85271 ** by this module. If using a separate allocation for each in-memory record
85272 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
85273 ** SorterRecord.u.pNext pointers.
85274 **
85275 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
85276 ** then while records are being accumulated the list is linked using the
85277 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
85278 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
85279 ** has finished passing records to the sorter, or when the in-memory buffer
85280 ** is full, the list is sorted. As part of the sorting process, it is
85281 ** converted to use the SorterRecord.u.pNext pointers. See function
85282 ** vdbeSorterSort() for details.
85283 */
85285  int nVal; /* Size of the record in bytes */
85286  union {
85287  SorterRecord *pNext; /* Pointer to next record in list */
85288  int iNext; /* Offset within aMemory of next record */
85289  } u;
85290  /* The data for the record immediately follows this header */
85291 };
85292 
85293 /* Return a pointer to the buffer containing the record data for SorterRecord
85294 ** object p. Should be used as if:
85295 **
85296 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
85297 */
85298 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
85299 
85300 
85301 /* Maximum number of PMAs that a single MergeEngine can merge */
85302 #define SORTER_MAX_MERGE_COUNT 16
85303 
85304 static int vdbeIncrSwap(IncrMerger*);
85305 static void vdbeIncrFree(IncrMerger *);
85306 
85307 /*
85308 ** Free all memory belonging to the PmaReader object passed as the
85309 ** argument. All structure fields are set to zero before returning.
85310 */
85311 static void vdbePmaReaderClear(PmaReader *pReadr){
85312  sqlite3_free(pReadr->aAlloc);
85313  sqlite3_free(pReadr->aBuffer);
85314  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85315  vdbeIncrFree(pReadr->pIncr);
85316  memset(pReadr, 0, sizeof(PmaReader));
85317 }
85318 
85319 /*
85320 ** Read the next nByte bytes of data from the PMA p.
85321 ** If successful, set *ppOut to point to a buffer containing the data
85322 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
85323 ** error code.
85324 **
85325 ** The buffer returned in *ppOut is only valid until the
85326 ** next call to this function.
85327 */
85328 static int vdbePmaReadBlob(
85329  PmaReader *p, /* PmaReader from which to take the blob */
85330  int nByte, /* Bytes of data to read */
85331  u8 **ppOut /* OUT: Pointer to buffer containing data */
85332 ){
85333  int iBuf; /* Offset within buffer to read from */
85334  int nAvail; /* Bytes of data available in buffer */
85335 
85336  if( p->aMap ){
85337  *ppOut = &p->aMap[p->iReadOff];
85338  p->iReadOff += nByte;
85339  return SQLITE_OK;
85340  }
85341 
85342  assert( p->aBuffer );
85343 
85344  /* If there is no more data to be read from the buffer, read the next
85345  ** p->nBuffer bytes of data from the file into it. Or, if there are less
85346  ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
85347  iBuf = p->iReadOff % p->nBuffer;
85348  if( iBuf==0 ){
85349  int nRead; /* Bytes to read from disk */
85350  int rc; /* sqlite3OsRead() return code */
85351 
85352  /* Determine how many bytes of data to read. */
85353  if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
85354  nRead = p->nBuffer;
85355  }else{
85356  nRead = (int)(p->iEof - p->iReadOff);
85357  }
85358  assert( nRead>0 );
85359 
85360  /* Readr data from the file. Return early if an error occurs. */
85361  rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
85362  assert( rc!=SQLITE_IOERR_SHORT_READ );
85363  if( rc!=SQLITE_OK ) return rc;
85364  }
85365  nAvail = p->nBuffer - iBuf;
85366 
85367  if( nByte<=nAvail ){
85368  /* The requested data is available in the in-memory buffer. In this
85369  ** case there is no need to make a copy of the data, just return a
85370  ** pointer into the buffer to the caller. */
85371  *ppOut = &p->aBuffer[iBuf];
85372  p->iReadOff += nByte;
85373  }else{
85374  /* The requested data is not all available in the in-memory buffer.
85375  ** In this case, allocate space at p->aAlloc[] to copy the requested
85376  ** range into. Then return a copy of pointer p->aAlloc to the caller. */
85377  int nRem; /* Bytes remaining to copy */
85378 
85379  /* Extend the p->aAlloc[] allocation if required. */
85380  if( p->nAlloc<nByte ){
85381  u8 *aNew;
85382  int nNew = MAX(128, p->nAlloc*2);
85383  while( nByte>nNew ) nNew = nNew*2;
85384  aNew = sqlite3Realloc(p->aAlloc, nNew);
85385  if( !aNew ) return SQLITE_NOMEM_BKPT;
85386  p->nAlloc = nNew;
85387  p->aAlloc = aNew;
85388  }
85389 
85390  /* Copy as much data as is available in the buffer into the start of
85391  ** p->aAlloc[]. */
85392  memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
85393  p->iReadOff += nAvail;
85394  nRem = nByte - nAvail;
85395 
85396  /* The following loop copies up to p->nBuffer bytes per iteration into
85397  ** the p->aAlloc[] buffer. */
85398  while( nRem>0 ){
85399  int rc; /* vdbePmaReadBlob() return code */
85400  int nCopy; /* Number of bytes to copy */
85401  u8 *aNext; /* Pointer to buffer to copy data from */
85402 
85403  nCopy = nRem;
85404  if( nRem>p->nBuffer ) nCopy = p->nBuffer;
85405  rc = vdbePmaReadBlob(p, nCopy, &aNext);
85406  if( rc!=SQLITE_OK ) return rc;
85407  assert( aNext!=p->aAlloc );
85408  memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
85409  nRem -= nCopy;
85410  }
85411 
85412  *ppOut = p->aAlloc;
85413  }
85414 
85415  return SQLITE_OK;
85416 }
85417 
85418 /*
85419 ** Read a varint from the stream of data accessed by p. Set *pnOut to
85420 ** the value read.
85421 */
85422 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
85423  int iBuf;
85424 
85425  if( p->aMap ){
85426  p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
85427  }else{
85428  iBuf = p->iReadOff % p->nBuffer;
85429  if( iBuf && (p->nBuffer-iBuf)>=9 ){
85430  p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
85431  }else{
85432  u8 aVarint[16], *a;
85433  int i = 0, rc;
85434  do{
85435  rc = vdbePmaReadBlob(p, 1, &a);
85436  if( rc ) return rc;
85437  aVarint[(i++)&0xf] = a[0];
85438  }while( (a[0]&0x80)!=0 );
85439  sqlite3GetVarint(aVarint, pnOut);
85440  }
85441  }
85442 
85443  return SQLITE_OK;
85444 }
85445 
85446 /*
85447 ** Attempt to memory map file pFile. If successful, set *pp to point to the
85448 ** new mapping and return SQLITE_OK. If the mapping is not attempted
85449 ** (because the file is too large or the VFS layer is configured not to use
85450 ** mmap), return SQLITE_OK and set *pp to NULL.
85451 **
85452 ** Or, if an error occurs, return an SQLite error code. The final value of
85453 ** *pp is undefined in this case.
85454 */
85455 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
85456  int rc = SQLITE_OK;
85457  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
85458  sqlite3_file *pFd = pFile->pFd;
85459  if( pFd->pMethods->iVersion>=3 ){
85460  rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
85461  testcase( rc!=SQLITE_OK );
85462  }
85463  }
85464  return rc;
85465 }
85466 
85467 /*
85468 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
85469 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
85470 ** if successful, or an SQLite error code if an error occurs.
85471 */
85473  SortSubtask *pTask, /* Task context */
85474  PmaReader *pReadr, /* Reader whose cursor is to be moved */
85475  SorterFile *pFile, /* Sorter file to read from */
85476  i64 iOff /* Offset in pFile */
85477 ){
85478  int rc = SQLITE_OK;
85479 
85480  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
85481 
85482  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
85483  if( pReadr->aMap ){
85484  sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85485  pReadr->aMap = 0;
85486  }
85487  pReadr->iReadOff = iOff;
85488  pReadr->iEof = pFile->iEof;
85489  pReadr->pFd = pFile->pFd;
85490 
85491  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
85492  if( rc==SQLITE_OK && pReadr->aMap==0 ){
85493  int pgsz = pTask->pSorter->pgsz;
85494  int iBuf = pReadr->iReadOff % pgsz;
85495  if( pReadr->aBuffer==0 ){
85496  pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
85497  if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
85498  pReadr->nBuffer = pgsz;
85499  }
85500  if( rc==SQLITE_OK && iBuf ){
85501  int nRead = pgsz - iBuf;
85502  if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
85503  nRead = (int)(pReadr->iEof - pReadr->iReadOff);
85504  }
85505  rc = sqlite3OsRead(
85506  pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
85507  );
85508  testcase( rc!=SQLITE_OK );
85509  }
85510  }
85511 
85512  return rc;
85513 }
85514 
85515 /*
85516 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
85517 ** no error occurs, or an SQLite error code if one does.
85518 */
85519 static int vdbePmaReaderNext(PmaReader *pReadr){
85520  int rc = SQLITE_OK; /* Return Code */
85521  u64 nRec = 0; /* Size of record in bytes */
85522 
85523 
85524  if( pReadr->iReadOff>=pReadr->iEof ){
85525  IncrMerger *pIncr = pReadr->pIncr;
85526  int bEof = 1;
85527  if( pIncr ){
85528  rc = vdbeIncrSwap(pIncr);
85529  if( rc==SQLITE_OK && pIncr->bEof==0 ){
85530  rc = vdbePmaReaderSeek(
85531  pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
85532  );
85533  bEof = 0;
85534  }
85535  }
85536 
85537  if( bEof ){
85538  /* This is an EOF condition */
85539  vdbePmaReaderClear(pReadr);
85540  testcase( rc!=SQLITE_OK );
85541  return rc;
85542  }
85543  }
85544 
85545  if( rc==SQLITE_OK ){
85546  rc = vdbePmaReadVarint(pReadr, &nRec);
85547  }
85548  if( rc==SQLITE_OK ){
85549  pReadr->nKey = (int)nRec;
85550  rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
85551  testcase( rc!=SQLITE_OK );
85552  }
85553 
85554  return rc;
85555 }
85556 
85557 /*
85558 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
85559 ** starting at offset iStart and ending at offset iEof-1. This function
85560 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
85561 ** PMA is empty).
85562 **
85563 ** If the pnByte parameter is NULL, then it is assumed that the file
85564 ** contains a single PMA, and that that PMA omits the initial length varint.
85565 */
85567  SortSubtask *pTask, /* Task context */
85568  SorterFile *pFile, /* Sorter file to read from */
85569  i64 iStart, /* Start offset in pFile */
85570  PmaReader *pReadr, /* PmaReader to populate */
85571  i64 *pnByte /* IN/OUT: Increment this value by PMA size */
85572 ){
85573  int rc;
85574 
85575  assert( pFile->iEof>iStart );
85576  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
85577  assert( pReadr->aBuffer==0 );
85578  assert( pReadr->aMap==0 );
85579 
85580  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
85581  if( rc==SQLITE_OK ){
85582  u64 nByte = 0; /* Size of PMA in bytes */
85583  rc = vdbePmaReadVarint(pReadr, &nByte);
85584  pReadr->iEof = pReadr->iReadOff + nByte;
85585  *pnByte += nByte;
85586  }
85587 
85588  if( rc==SQLITE_OK ){
85589  rc = vdbePmaReaderNext(pReadr);
85590  }
85591  return rc;
85592 }
85593 
85594 /*
85595 ** A version of vdbeSorterCompare() that assumes that it has already been
85596 ** determined that the first field of key1 is equal to the first field of
85597 ** key2.
85598 */
85600  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
85601  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
85602  const void *pKey1, int nKey1, /* Left side of comparison */
85603  const void *pKey2, int nKey2 /* Right side of comparison */
85604 ){
85605  UnpackedRecord *r2 = pTask->pUnpacked;
85606  if( *pbKey2Cached==0 ){
85607  sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85608  *pbKey2Cached = 1;
85609  }
85610  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
85611 }
85612 
85613 /*
85614 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
85615 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
85616 ** used by the comparison. Return the result of the comparison.
85617 **
85618 ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
85619 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
85620 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
85621 ** version of key2 and *pbKey2Cached set to true before returning.
85622 **
85623 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
85624 ** to SQLITE_NOMEM.
85625 */
85627  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
85628  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
85629  const void *pKey1, int nKey1, /* Left side of comparison */
85630  const void *pKey2, int nKey2 /* Right side of comparison */
85631 ){
85632  UnpackedRecord *r2 = pTask->pUnpacked;
85633  if( !*pbKey2Cached ){
85634  sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85635  *pbKey2Cached = 1;
85636  }
85637  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
85638 }
85639 
85640 /*
85641 ** A specially optimized version of vdbeSorterCompare() that assumes that
85642 ** the first field of each key is a TEXT value and that the collation
85643 ** sequence to compare them with is BINARY.
85644 */
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  const u8 * const p1 = (const u8 * const)pKey1;
85652  const u8 * const p2 = (const u8 * const)pKey2;
85653  const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
85654  const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
85655 
85656  int n1;
85657  int n2;
85658  int res;
85659 
85660  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
85661  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
85662  res = memcmp(v1, v2, MIN(n1, n2));
85663  if( res==0 ){
85664  res = n1 - n2;
85665  }
85666 
85667  if( res==0 ){
85668  if( pTask->pSorter->pKeyInfo->nField>1 ){
85669  res = vdbeSorterCompareTail(
85670  pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85671  );
85672  }
85673  }else{
85674  if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85675  res = res * -1;
85676  }
85677  }
85678 
85679  return res;
85680 }
85681 
85682 /*
85683 ** A specially optimized version of vdbeSorterCompare() that assumes that
85684 ** the first field of each key is an INTEGER value.
85685 */
85687  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
85688  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
85689  const void *pKey1, int nKey1, /* Left side of comparison */
85690  const void *pKey2, int nKey2 /* Right side of comparison */
85691 ){
85692  const u8 * const p1 = (const u8 * const)pKey1;
85693  const u8 * const p2 = (const u8 * const)pKey2;
85694  const int s1 = p1[1]; /* Left hand serial type */
85695  const int s2 = p2[1]; /* Right hand serial type */
85696  const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
85697  const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
85698  int res; /* Return value */
85699 
85700  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
85701  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
85702 
85703  if( s1>7 && s2>7 ){
85704  res = s1 - s2;
85705  }else{
85706  if( s1==s2 ){
85707  if( (*v1 ^ *v2) & 0x80 ){
85708  /* The two values have different signs */
85709  res = (*v1 & 0x80) ? -1 : +1;
85710  }else{
85711  /* The two values have the same sign. Compare using memcmp(). */
85712  static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
85713  int i;
85714  res = 0;
85715  for(i=0; i<aLen[s1]; i++){
85716  if( (res = v1[i] - v2[i]) ) break;
85717  }
85718  }
85719  }else{
85720  if( s2>7 ){
85721  res = +1;
85722  }else if( s1>7 ){
85723  res = -1;
85724  }else{
85725  res = s1 - s2;
85726  }
85727  assert( res!=0 );
85728 
85729  if( res>0 ){
85730  if( *v1 & 0x80 ) res = -1;
85731  }else{
85732  if( *v2 & 0x80 ) res = +1;
85733  }
85734  }
85735  }
85736 
85737  if( res==0 ){
85738  if( pTask->pSorter->pKeyInfo->nField>1 ){
85739  res = vdbeSorterCompareTail(
85740  pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85741  );
85742  }
85743  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85744  res = res * -1;
85745  }
85746 
85747  return res;
85748 }
85749 
85750 /*
85751 ** Initialize the temporary index cursor just opened as a sorter cursor.
85752 **
85753 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
85754 ** to determine the number of fields that should be compared from the
85755 ** records being sorted. However, if the value passed as argument nField
85756 ** is non-zero and the sorter is able to guarantee a stable sort, nField
85757 ** is used instead. This is used when sorting records for a CREATE INDEX
85758 ** statement. In this case, keys are always delivered to the sorter in
85759 ** order of the primary key, which happens to be make up the final part
85760 ** of the records being sorted. So if the sort is stable, there is never
85761 ** any reason to compare PK fields and they can be ignored for a small
85762 ** performance boost.
85763 **
85764 ** The sorter can guarantee a stable sort when running in single-threaded
85765 ** mode, but not in multi-threaded mode.
85766 **
85767 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
85768 */
85770  sqlite3 *db, /* Database connection (for malloc()) */
85771  int nField, /* Number of key fields in each record */
85772  VdbeCursor *pCsr /* Cursor that holds the new sorter */
85773 ){
85774  int pgsz; /* Page size of main database */
85775  int i; /* Used to iterate through aTask[] */
85776  VdbeSorter *pSorter; /* The new sorter */
85777  KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
85778  int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
85779  int sz; /* Size of pSorter in bytes */
85780  int rc = SQLITE_OK;
85781 #if SQLITE_MAX_WORKER_THREADS==0
85782 # define nWorker 0
85783 #else
85784  int nWorker;
85785 #endif
85786 
85787  /* Initialize the upper limit on the number of worker threads */
85788 #if SQLITE_MAX_WORKER_THREADS>0
85789  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
85790  nWorker = 0;
85791  }else{
85792  nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
85793  }
85794 #endif
85795 
85796  /* Do not allow the total number of threads (main thread + all workers)
85797  ** to exceed the maximum merge count */
85798 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
85799  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
85800  nWorker = SORTER_MAX_MERGE_COUNT-1;
85801  }
85802 #endif
85803 
85804  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
85805  assert( pCsr->eCurType==CURTYPE_SORTER );
85806  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
85807  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
85808 
85809  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
85810  pCsr->uc.pSorter = pSorter;
85811  if( pSorter==0 ){
85812  rc = SQLITE_NOMEM_BKPT;
85813  }else{
85814  pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
85815  memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
85816  pKeyInfo->db = 0;
85817  if( nField && nWorker==0 ){
85818  pKeyInfo->nXField += (pKeyInfo->nField - nField);
85819  pKeyInfo->nField = nField;
85820  }
85821  pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
85822  pSorter->nTask = nWorker + 1;
85823  pSorter->iPrev = (u8)(nWorker - 1);
85824  pSorter->bUseThreads = (pSorter->nTask>1);
85825  pSorter->db = db;
85826  for(i=0; i<pSorter->nTask; i++){
85827  SortSubtask *pTask = &pSorter->aTask[i];
85828  pTask->pSorter = pSorter;
85829  }
85830 
85831  if( !sqlite3TempInMemory(db) ){
85832  i64 mxCache; /* Cache size in bytes*/
85833  u32 szPma = sqlite3GlobalConfig.szPma;
85834  pSorter->mnPmaSize = szPma * pgsz;
85835 
85836  mxCache = db->aDb[0].pSchema->cache_size;
85837  if( mxCache<0 ){
85838  /* A negative cache-size value C indicates that the cache is abs(C)
85839  ** KiB in size. */
85840  mxCache = mxCache * -1024;
85841  }else{
85842  mxCache = mxCache * pgsz;
85843  }
85844  mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85845  pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
85846 
85847  /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
85848  ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
85849  ** large heap allocations.
85850  */
85851  if( sqlite3GlobalConfig.pScratch==0 ){
85852  assert( pSorter->iMemory==0 );
85853  pSorter->nMemory = pgsz;
85854  pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
85855  if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
85856  }
85857  }
85858 
85859  if( (pKeyInfo->nField+pKeyInfo->nXField)<13
85860  && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
85861  ){
85863  }
85864  }
85865 
85866  return rc;
85867 }
85868 #undef nWorker /* Defined at the top of this function */
85869 
85870 /*
85871 ** Free the list of sorted records starting at pRecord.
85872 */
85873 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
85874  SorterRecord *p;
85875  SorterRecord *pNext;
85876  for(p=pRecord; p; p=pNext){
85877  pNext = p->u.pNext;
85878  sqlite3DbFree(db, p);
85879  }
85880 }
85881 
85882 /*
85883 ** Free all resources owned by the object indicated by argument pTask. All
85884 ** fields of *pTask are zeroed before returning.
85885 */
85886 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
85887  sqlite3DbFree(db, pTask->pUnpacked);
85888 #if SQLITE_MAX_WORKER_THREADS>0
85889  /* pTask->list.aMemory can only be non-zero if it was handed memory
85890  ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
85891  if( pTask->list.aMemory ){
85892  sqlite3_free(pTask->list.aMemory);
85893  }else
85894 #endif
85895  {
85896  assert( pTask->list.aMemory==0 );
85897  vdbeSorterRecordFree(0, pTask->list.pList);
85898  }
85899  if( pTask->file.pFd ){
85900  sqlite3OsCloseFree(pTask->file.pFd);
85901  }
85902  if( pTask->file2.pFd ){
85903  sqlite3OsCloseFree(pTask->file2.pFd);
85904  }
85905  memset(pTask, 0, sizeof(SortSubtask));
85906 }
85907 
85908 #ifdef SQLITE_DEBUG_SORTER_THREADS
85909 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
85910  i64 t;
85911  int iTask = (pTask - pTask->pSorter->aTask);
85912  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85913  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
85914 }
85915 static void vdbeSorterRewindDebug(const char *zEvent){
85916  i64 t;
85918  fprintf(stderr, "%lld:X %s\n", t, zEvent);
85919 }
85920 static void vdbeSorterPopulateDebug(
85921  SortSubtask *pTask,
85922  const char *zEvent
85923 ){
85924  i64 t;
85925  int iTask = (pTask - pTask->pSorter->aTask);
85926  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85927  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
85928 }
85929 static void vdbeSorterBlockDebug(
85930  SortSubtask *pTask,
85931  int bBlocked,
85932  const char *zEvent
85933 ){
85934  if( bBlocked ){
85935  i64 t;
85936  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85937  fprintf(stderr, "%lld:main %s\n", t, zEvent);
85938  }
85939 }
85940 #else
85941 # define vdbeSorterWorkDebug(x,y)
85942 # define vdbeSorterRewindDebug(y)
85943 # define vdbeSorterPopulateDebug(x,y)
85944 # define vdbeSorterBlockDebug(x,y,z)
85945 #endif
85946 
85947 #if SQLITE_MAX_WORKER_THREADS>0
85948 /*
85949 ** Join thread pTask->thread.
85950 */
85951 static int vdbeSorterJoinThread(SortSubtask *pTask){
85952  int rc = SQLITE_OK;
85953  if( pTask->pThread ){
85954 #ifdef SQLITE_DEBUG_SORTER_THREADS
85955  int bDone = pTask->bDone;
85956 #endif
85957  void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
85958  vdbeSorterBlockDebug(pTask, !bDone, "enter");
85959  (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
85960  vdbeSorterBlockDebug(pTask, !bDone, "exit");
85961  rc = SQLITE_PTR_TO_INT(pRet);
85962  assert( pTask->bDone==1 );
85963  pTask->bDone = 0;
85964  pTask->pThread = 0;
85965  }
85966  return rc;
85967 }
85968 
85969 /*
85970 ** Launch a background thread to run xTask(pIn).
85971 */
85973  SortSubtask *pTask, /* Thread will use this task object */
85974  void *(*xTask)(void*), /* Routine to run in a separate thread */
85975  void *pIn /* Argument passed into xTask() */
85976 ){
85977  assert( pTask->pThread==0 && pTask->bDone==0 );
85978  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
85979 }
85980 
85981 /*
85982 ** Join all outstanding threads launched by SorterWrite() to create
85983 ** level-0 PMAs.
85984 */
85985 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
85986  int rc = rcin;
85987  int i;
85988 
85989  /* This function is always called by the main user thread.
85990  **
85991  ** If this function is being called after SorterRewind() has been called,
85992  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
85993  ** is currently attempt to join one of the other threads. To avoid a race
85994  ** condition where this thread also attempts to join the same object, join
85995  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
85996  for(i=pSorter->nTask-1; i>=0; i--){
85997  SortSubtask *pTask = &pSorter->aTask[i];
85998  int rc2 = vdbeSorterJoinThread(pTask);
85999  if( rc==SQLITE_OK ) rc = rc2;
86000  }
86001  return rc;
86002 }
86003 #else
86004 # define vdbeSorterJoinAll(x,rcin) (rcin)
86005 # define vdbeSorterJoinThread(pTask) SQLITE_OK
86006 #endif
86007 
86008 /*
86009 ** Allocate a new MergeEngine object capable of handling up to
86010 ** nReader PmaReader inputs.
86011 **
86012 ** nReader is automatically rounded up to the next power of two.
86013 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
86014 */
86015 static MergeEngine *vdbeMergeEngineNew(int nReader){
86016  int N = 2; /* Smallest power of two >= nReader */
86017  int nByte; /* Total bytes of space to allocate */
86018  MergeEngine *pNew; /* Pointer to allocated object to return */
86019 
86020  assert( nReader<=SORTER_MAX_MERGE_COUNT );
86021 
86022  while( N<nReader ) N += N;
86023  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
86024 
86025  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
86026  if( pNew ){
86027  pNew->nTree = N;
86028  pNew->pTask = 0;
86029  pNew->aReadr = (PmaReader*)&pNew[1];
86030  pNew->aTree = (int*)&pNew->aReadr[N];
86031  }
86032  return pNew;
86033 }
86034 
86035 /*
86036 ** Free the MergeEngine object passed as the only argument.
86037 */
86038 static void vdbeMergeEngineFree(MergeEngine *pMerger){
86039  int i;
86040  if( pMerger ){
86041  for(i=0; i<pMerger->nTree; i++){
86042  vdbePmaReaderClear(&pMerger->aReadr[i]);
86043  }
86044  }
86045  sqlite3_free(pMerger);
86046 }
86047 
86048 /*
86049 ** Free all resources associated with the IncrMerger object indicated by
86050 ** the first argument.
86051 */
86052 static void vdbeIncrFree(IncrMerger *pIncr){
86053  if( pIncr ){
86054 #if SQLITE_MAX_WORKER_THREADS>0
86055  if( pIncr->bUseThread ){
86056  vdbeSorterJoinThread(pIncr->pTask);
86057  if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
86058  if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
86059  }
86060 #endif
86061  vdbeMergeEngineFree(pIncr->pMerger);
86062  sqlite3_free(pIncr);
86063  }
86064 }
86065 
86066 /*
86067 ** Reset a sorting cursor back to its original empty state.
86068 */
86070  int i;
86071  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
86072  assert( pSorter->bUseThreads || pSorter->pReader==0 );
86073 #if SQLITE_MAX_WORKER_THREADS>0
86074  if( pSorter->pReader ){
86075  vdbePmaReaderClear(pSorter->pReader);
86076  sqlite3DbFree(db, pSorter->pReader);
86077  pSorter->pReader = 0;
86078  }
86079 #endif
86080  vdbeMergeEngineFree(pSorter->pMerger);
86081  pSorter->pMerger = 0;
86082  for(i=0; i<pSorter->nTask; i++){
86083  SortSubtask *pTask = &pSorter->aTask[i];
86084  vdbeSortSubtaskCleanup(db, pTask);
86085  pTask->pSorter = pSorter;
86086  }
86087  if( pSorter->list.aMemory==0 ){
86088  vdbeSorterRecordFree(0, pSorter->list.pList);
86089  }
86090  pSorter->list.pList = 0;
86091  pSorter->list.szPMA = 0;
86092  pSorter->bUsePMA = 0;
86093  pSorter->iMemory = 0;
86094  pSorter->mxKeysize = 0;
86095  sqlite3DbFree(db, pSorter->pUnpacked);
86096  pSorter->pUnpacked = 0;
86097 }
86098 
86099 /*
86100 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
86101 */
86103  VdbeSorter *pSorter;
86104  assert( pCsr->eCurType==CURTYPE_SORTER );
86105  pSorter = pCsr->uc.pSorter;
86106  if( pSorter ){
86107  sqlite3VdbeSorterReset(db, pSorter);
86108  sqlite3_free(pSorter->list.aMemory);
86109  sqlite3DbFree(db, pSorter);
86110  pCsr->uc.pSorter = 0;
86111  }
86112 }
86113 
86114 #if SQLITE_MAX_MMAP_SIZE>0
86115 /*
86116 ** The first argument is a file-handle open on a temporary file. The file
86117 ** is guaranteed to be nByte bytes or smaller in size. This function
86118 ** attempts to extend the file to nByte bytes in size and to ensure that
86119 ** the VFS has memory mapped it.
86120 **
86121 ** Whether or not the file does end up memory mapped of course depends on
86122 ** the specific VFS implementation.
86123 */
86124 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
86125  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
86126  void *p = 0;
86127  int chunksize = 4*1024;
86130  sqlite3OsFetch(pFd, 0, (int)nByte, &p);
86131  sqlite3OsUnfetch(pFd, 0, p);
86132  }
86133 }
86134 #else
86135 # define vdbeSorterExtendFile(x,y,z)
86136 #endif
86137 
86138 /*
86139 ** Allocate space for a file-handle and open a temporary file. If successful,
86140 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
86141 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
86142 */
86144  sqlite3 *db, /* Database handle doing sort */
86145  i64 nExtend, /* Attempt to extend file to this size */
86146  sqlite3_file **ppFd
86147 ){
86148  int rc;
86149  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
86150  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
86154  );
86155  if( rc==SQLITE_OK ){
86156  i64 max = SQLITE_MAX_MMAP_SIZE;
86157  sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
86158  if( nExtend>0 ){
86159  vdbeSorterExtendFile(db, *ppFd, nExtend);
86160  }
86161  }
86162  return rc;
86163 }
86164 
86165 /*
86166 ** If it has not already been allocated, allocate the UnpackedRecord
86167 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
86168 ** if no allocation was required), or SQLITE_NOMEM otherwise.
86169 */
86170 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
86171  if( pTask->pUnpacked==0 ){
86172  char *pFree;
86174  pTask->pSorter->pKeyInfo, 0, 0, &pFree
86175  );
86176  assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
86177  if( pFree==0 ) return SQLITE_NOMEM_BKPT;
86178  pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
86179  pTask->pUnpacked->errCode = 0;
86180  }
86181  return SQLITE_OK;
86182 }
86183 
86184 
86185 /*
86186 ** Merge the two sorted lists p1 and p2 into a single list.
86187 */
86189  SortSubtask *pTask, /* Calling thread context */
86190  SorterRecord *p1, /* First list to merge */
86191  SorterRecord *p2 /* Second list to merge */
86192 ){
86193  SorterRecord *pFinal = 0;
86194  SorterRecord **pp = &pFinal;
86195  int bCached = 0;
86196 
86197  assert( p1!=0 && p2!=0 );
86198  for(;;){
86199  int res;
86200  res = pTask->xCompare(
86201  pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
86202  );
86203 
86204  if( res<=0 ){
86205  *pp = p1;
86206  pp = &p1->u.pNext;
86207  p1 = p1->u.pNext;
86208  if( p1==0 ){
86209  *pp = p2;
86210  break;
86211  }
86212  }else{
86213  *pp = p2;
86214  pp = &p2->u.pNext;
86215  p2 = p2->u.pNext;
86216  bCached = 0;
86217  if( p2==0 ){
86218  *pp = p1;
86219  break;
86220  }
86221  }
86222  }
86223  return pFinal;
86224 }
86225 
86226 /*
86227 ** Return the SorterCompare function to compare values collected by the
86228 ** sorter object passed as the only argument.
86229 */
86231  if( p->typeMask==SORTER_TYPE_INTEGER ){
86232  return vdbeSorterCompareInt;
86233  }else if( p->typeMask==SORTER_TYPE_TEXT ){
86234  return vdbeSorterCompareText;
86235  }
86236  return vdbeSorterCompare;
86237 }
86238 
86239 /*
86240 ** Sort the linked list of records headed at pTask->pList. Return
86241 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
86242 ** an error occurs.
86243 */
86244 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
86245  int i;
86246  SorterRecord **aSlot;
86247  SorterRecord *p;
86248  int rc;
86249 
86250  rc = vdbeSortAllocUnpacked(pTask);
86251  if( rc!=SQLITE_OK ) return rc;
86252 
86253  p = pList->pList;
86254  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
86255 
86256  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
86257  if( !aSlot ){
86258  return SQLITE_NOMEM_BKPT;
86259  }
86260 
86261  while( p ){
86262  SorterRecord *pNext;
86263  if( pList->aMemory ){
86264  if( (u8*)p==pList->aMemory ){
86265  pNext = 0;
86266  }else{
86267  assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
86268  pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
86269  }
86270  }else{
86271  pNext = p->u.pNext;
86272  }
86273 
86274  p->u.pNext = 0;
86275  for(i=0; aSlot[i]; i++){
86276  p = vdbeSorterMerge(pTask, p, aSlot[i]);
86277  aSlot[i] = 0;
86278  }
86279  aSlot[i] = p;
86280  p = pNext;
86281  }
86282 
86283  p = 0;
86284  for(i=0; i<64; i++){
86285  if( aSlot[i]==0 ) continue;
86286  p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
86287  }
86288  pList->pList = p;
86289 
86290  sqlite3_free(aSlot);
86291  assert( pTask->pUnpacked->errCode==SQLITE_OK
86292  || pTask->pUnpacked->errCode==SQLITE_NOMEM
86293  );
86294  return pTask->pUnpacked->errCode;
86295 }
86296 
86297 /*
86298 ** Initialize a PMA-writer object.
86299 */
86300 static void vdbePmaWriterInit(
86301  sqlite3_file *pFd, /* File handle to write to */
86302  PmaWriter *p, /* Object to populate */
86303  int nBuf, /* Buffer size */
86304  i64 iStart /* Offset of pFd to begin writing at */
86305 ){
86306  memset(p, 0, sizeof(PmaWriter));
86307  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
86308  if( !p->aBuffer ){
86310  }else{
86311  p->iBufEnd = p->iBufStart = (iStart % nBuf);
86312  p->iWriteOff = iStart - p->iBufStart;
86313  p->nBuffer = nBuf;
86314  p->pFd = pFd;
86315  }
86316 }
86317 
86318 /*
86319 ** Write nData bytes of data to the PMA. Return SQLITE_OK
86320 ** if successful, or an SQLite error code if an error occurs.
86321 */
86322 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
86323  int nRem = nData;
86324  while( nRem>0 && p->eFWErr==0 ){
86325  int nCopy = nRem;
86326  if( nCopy>(p->nBuffer - p->iBufEnd) ){
86327  nCopy = p->nBuffer - p->iBufEnd;
86328  }
86329 
86330  memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
86331  p->iBufEnd += nCopy;
86332  if( p->iBufEnd==p->nBuffer ){
86333  p->eFWErr = sqlite3OsWrite(p->pFd,
86334  &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86335  p->iWriteOff + p->iBufStart
86336  );
86337  p->iBufStart = p->iBufEnd = 0;
86338  p->iWriteOff += p->nBuffer;
86339  }
86340  assert( p->iBufEnd<p->nBuffer );
86341 
86342  nRem -= nCopy;
86343  }
86344 }
86345 
86346 /*
86347 ** Flush any buffered data to disk and clean up the PMA-writer object.
86348 ** The results of using the PMA-writer after this call are undefined.
86349 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
86350 ** required. Otherwise, return an SQLite error code.
86351 **
86352 ** Before returning, set *piEof to the offset immediately following the
86353 ** last byte written to the file.
86354 */
86355 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
86356  int rc;
86357  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
86358  p->eFWErr = sqlite3OsWrite(p->pFd,
86359  &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
86360  p->iWriteOff + p->iBufStart
86361  );
86362  }
86363  *piEof = (p->iWriteOff + p->iBufEnd);
86364  sqlite3_free(p->aBuffer);
86365  rc = p->eFWErr;
86366  memset(p, 0, sizeof(PmaWriter));
86367  return rc;
86368 }
86369 
86370 /*
86371 ** Write value iVal encoded as a varint to the PMA. Return
86372 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
86373 */
86374 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
86375  int nByte;
86376  u8 aByte[10];
86377  nByte = sqlite3PutVarint(aByte, iVal);
86378  vdbePmaWriteBlob(p, aByte, nByte);
86379 }
86380 
86381 /*
86382 ** Write the current contents of in-memory linked-list pList to a level-0
86383 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
86384 ** successful, or an SQLite error code otherwise.
86385 **
86386 ** The format of a PMA is:
86387 **
86388 ** * A varint. This varint contains the total number of bytes of content
86389 ** in the PMA (not including the varint itself).
86390 **
86391 ** * One or more records packed end-to-end in order of ascending keys.
86392 ** Each record consists of a varint followed by a blob of data (the
86393 ** key). The varint is the number of bytes in the blob of data.
86394 */
86395 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
86396  sqlite3 *db = pTask->pSorter->db;
86397  int rc = SQLITE_OK; /* Return code */
86398  PmaWriter writer; /* Object used to write to the file */
86399 
86400 #ifdef SQLITE_DEBUG
86401  /* Set iSz to the expected size of file pTask->file after writing the PMA.
86402  ** This is used by an assert() statement at the end of this function. */
86403  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
86404 #endif
86405 
86406  vdbeSorterWorkDebug(pTask, "enter");
86407  memset(&writer, 0, sizeof(PmaWriter));
86408  assert( pList->szPMA>0 );
86409 
86410  /* If the first temporary PMA file has not been opened, open it now. */
86411  if( pTask->file.pFd==0 ){
86412  rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
86413  assert( rc!=SQLITE_OK || pTask->file.pFd );
86414  assert( pTask->file.iEof==0 );
86415  assert( pTask->nPMA==0 );
86416  }
86417 
86418  /* Try to get the file to memory map */
86419  if( rc==SQLITE_OK ){
86420  vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
86421  }
86422 
86423  /* Sort the list */
86424  if( rc==SQLITE_OK ){
86425  rc = vdbeSorterSort(pTask, pList);
86426  }
86427 
86428  if( rc==SQLITE_OK ){
86429  SorterRecord *p;
86430  SorterRecord *pNext = 0;
86431 
86432  vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
86433  pTask->file.iEof);
86434  pTask->nPMA++;
86435  vdbePmaWriteVarint(&writer, pList->szPMA);
86436  for(p=pList->pList; p; p=pNext){
86437  pNext = p->u.pNext;
86438  vdbePmaWriteVarint(&writer, p->nVal);
86439  vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
86440  if( pList->aMemory==0 ) sqlite3_free(p);
86441  }
86442  pList->pList = p;
86443  rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
86444  }
86445 
86446  vdbeSorterWorkDebug(pTask, "exit");
86447  assert( rc!=SQLITE_OK || pList->pList==0 );
86448  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
86449  return rc;
86450 }
86451 
86452 /*
86453 ** Advance the MergeEngine to its next entry.
86454 ** Set *pbEof to true there is no next entry because
86455 ** the MergeEngine has reached the end of all its inputs.
86456 **
86457 ** Return SQLITE_OK if successful or an error code if an error occurs.
86458 */
86460  MergeEngine *pMerger, /* The merge engine to advance to the next row */
86461  int *pbEof /* Set TRUE at EOF. Set false for more content */
86462 ){
86463  int rc;
86464  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
86465  SortSubtask *pTask = pMerger->pTask;
86466 
86467  /* Advance the current PmaReader */
86468  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
86469 
86470  /* Update contents of aTree[] */
86471  if( rc==SQLITE_OK ){
86472  int i; /* Index of aTree[] to recalculate */
86473  PmaReader *pReadr1; /* First PmaReader to compare */
86474  PmaReader *pReadr2; /* Second PmaReader to compare */
86475  int bCached = 0;
86476 
86477  /* Find the first two PmaReaders to compare. The one that was just
86478  ** advanced (iPrev) and the one next to it in the array. */
86479  pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
86480  pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
86481 
86482  for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
86483  /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
86484  int iRes;
86485  if( pReadr1->pFd==0 ){
86486  iRes = +1;
86487  }else if( pReadr2->pFd==0 ){
86488  iRes = -1;
86489  }else{
86490  iRes = pTask->xCompare(pTask, &bCached,
86491  pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
86492  );
86493  }
86494 
86495  /* If pReadr1 contained the smaller value, set aTree[i] to its index.
86496  ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
86497  ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
86498  ** pKey2 to point to the record belonging to pReadr2.
86499  **
86500  ** Alternatively, if pReadr2 contains the smaller of the two values,
86501  ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
86502  ** was actually called above, then pTask->pUnpacked now contains
86503  ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
86504  ** vdbeSorterCompare() from decoding pReadr2 again.
86505  **
86506  ** If the two values were equal, then the value from the oldest
86507  ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
86508  ** is sorted from oldest to newest, so pReadr1 contains older values
86509  ** than pReadr2 iff (pReadr1<pReadr2). */
86510  if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
86511  pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
86512  pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86513  bCached = 0;
86514  }else{
86515  if( pReadr1->pFd ) bCached = 0;
86516  pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
86517  pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86518  }
86519  }
86520  *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
86521  }
86522 
86523  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
86524 }
86525 
86526 #if SQLITE_MAX_WORKER_THREADS>0
86527 /*
86528 ** The main routine for background threads that write level-0 PMAs.
86529 */
86530 static void *vdbeSorterFlushThread(void *pCtx){
86531  SortSubtask *pTask = (SortSubtask*)pCtx;
86532  int rc; /* Return code */
86533  assert( pTask->bDone==0 );
86534  rc = vdbeSorterListToPMA(pTask, &pTask->list);
86535  pTask->bDone = 1;
86536  return SQLITE_INT_TO_PTR(rc);
86537 }
86538 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
86539 
86540 /*
86541 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
86542 ** using a background thread.
86543 */
86544 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
86545 #if SQLITE_MAX_WORKER_THREADS==0
86546  pSorter->bUsePMA = 1;
86547  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
86548 #else
86549  int rc = SQLITE_OK;
86550  int i;
86551  SortSubtask *pTask = 0; /* Thread context used to create new PMA */
86552  int nWorker = (pSorter->nTask-1);
86553 
86554  /* Set the flag to indicate that at least one PMA has been written.
86555  ** Or will be, anyhow. */
86556  pSorter->bUsePMA = 1;
86557 
86558  /* Select a sub-task to sort and flush the current list of in-memory
86559  ** records to disk. If the sorter is running in multi-threaded mode,
86560  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
86561  ** the background thread from a sub-tasks previous turn is still running,
86562  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
86563  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
86564  ** sub-tasks are prefered as they use background threads - the final
86565  ** sub-task uses the main thread. */
86566  for(i=0; i<nWorker; i++){
86567  int iTest = (pSorter->iPrev + i + 1) % nWorker;
86568  pTask = &pSorter->aTask[iTest];
86569  if( pTask->bDone ){
86570  rc = vdbeSorterJoinThread(pTask);
86571  }
86572  if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
86573  }
86574 
86575  if( rc==SQLITE_OK ){
86576  if( i==nWorker ){
86577  /* Use the foreground thread for this operation */
86578  rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
86579  }else{
86580  /* Launch a background thread for this operation */
86581  u8 *aMem = pTask->list.aMemory;
86582  void *pCtx = (void*)pTask;
86583 
86584  assert( pTask->pThread==0 && pTask->bDone==0 );
86585  assert( pTask->list.pList==0 );
86586  assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
86587 
86588  pSorter->iPrev = (u8)(pTask - pSorter->aTask);
86589  pTask->list = pSorter->list;
86590  pSorter->list.pList = 0;
86591  pSorter->list.szPMA = 0;
86592  if( aMem ){
86593  pSorter->list.aMemory = aMem;
86594  pSorter->nMemory = sqlite3MallocSize(aMem);
86595  }else if( pSorter->list.aMemory ){
86596  pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
86597  if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
86598  }
86599 
86600  rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
86601  }
86602  }
86603 
86604  return rc;
86605 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
86606 }
86607 
86608 /*
86609 ** Add a record to the sorter.
86610 */
86612  const VdbeCursor *pCsr, /* Sorter cursor */
86613  Mem *pVal /* Memory cell containing record */
86614 ){
86615  VdbeSorter *pSorter;
86616  int rc = SQLITE_OK; /* Return Code */
86617  SorterRecord *pNew; /* New list element */
86618  int bFlush; /* True to flush contents of memory to PMA */
86619  int nReq; /* Bytes of memory required */
86620  int nPMA; /* Bytes of PMA space required */
86621  int t; /* serial type of first record field */
86622 
86623  assert( pCsr->eCurType==CURTYPE_SORTER );
86624  pSorter = pCsr->uc.pSorter;
86625  getVarint32((const u8*)&pVal->z[1], t);
86626  if( t>0 && t<10 && t!=7 ){
86627  pSorter->typeMask &= SORTER_TYPE_INTEGER;
86628  }else if( t>10 && (t & 0x01) ){
86629  pSorter->typeMask &= SORTER_TYPE_TEXT;
86630  }else{
86631  pSorter->typeMask = 0;
86632  }
86633 
86634  assert( pSorter );
86635 
86636  /* Figure out whether or not the current contents of memory should be
86637  ** flushed to a PMA before continuing. If so, do so.
86638  **
86639  ** If using the single large allocation mode (pSorter->aMemory!=0), then
86640  ** flush the contents of memory to a new PMA if (a) at least one value is
86641  ** already in memory and (b) the new value will not fit in memory.
86642  **
86643  ** Or, if using separate allocations for each record, flush the contents
86644  ** of memory to a PMA if either of the following are true:
86645  **
86646  ** * The total memory allocated for the in-memory list is greater
86647  ** than (page-size * cache-size), or
86648  **
86649  ** * The total memory allocated for the in-memory list is greater
86650  ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
86651  */
86652  nReq = pVal->n + sizeof(SorterRecord);
86653  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
86654  if( pSorter->mxPmaSize ){
86655  if( pSorter->list.aMemory ){
86656  bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
86657  }else{
86658  bFlush = (
86659  (pSorter->list.szPMA > pSorter->mxPmaSize)
86660  || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
86661  );
86662  }
86663  if( bFlush ){
86664  rc = vdbeSorterFlushPMA(pSorter);
86665  pSorter->list.szPMA = 0;
86666  pSorter->iMemory = 0;
86667  assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
86668  }
86669  }
86670 
86671  pSorter->list.szPMA += nPMA;
86672  if( nPMA>pSorter->mxKeysize ){
86673  pSorter->mxKeysize = nPMA;
86674  }
86675 
86676  if( pSorter->list.aMemory ){
86677  int nMin = pSorter->iMemory + nReq;
86678 
86679  if( nMin>pSorter->nMemory ){
86680  u8 *aNew;
86681  int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
86682  int nNew = pSorter->nMemory * 2;
86683  while( nNew < nMin ) nNew = nNew*2;
86684  if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
86685  if( nNew < nMin ) nNew = nMin;
86686 
86687  aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
86688  if( !aNew ) return SQLITE_NOMEM_BKPT;
86689  pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
86690  pSorter->list.aMemory = aNew;
86691  pSorter->nMemory = nNew;
86692  }
86693 
86694  pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
86695  pSorter->iMemory += ROUND8(nReq);
86696  if( pSorter->list.pList ){
86697  pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
86698  }
86699  }else{
86700  pNew = (SorterRecord *)sqlite3Malloc(nReq);
86701  if( pNew==0 ){
86702  return SQLITE_NOMEM_BKPT;
86703  }
86704  pNew->u.pNext = pSorter->list.pList;
86705  }
86706 
86707  memcpy(SRVAL(pNew), pVal->z, pVal->n);
86708  pNew->nVal = pVal->n;
86709  pSorter->list.pList = pNew;
86710 
86711  return rc;
86712 }
86713 
86714 /*
86715 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
86716 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
86717 ** except that the number-of-bytes varint is omitted from the start.
86718 */
86719 static int vdbeIncrPopulate(IncrMerger *pIncr){
86720  int rc = SQLITE_OK;
86721  int rc2;
86722  i64 iStart = pIncr->iStartOff;
86723  SorterFile *pOut = &pIncr->aFile[1];
86724  SortSubtask *pTask = pIncr->pTask;
86725  MergeEngine *pMerger = pIncr->pMerger;
86726  PmaWriter writer;
86727  assert( pIncr->bEof==0 );
86728 
86729  vdbeSorterPopulateDebug(pTask, "enter");
86730 
86731  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
86732  while( rc==SQLITE_OK ){
86733  int dummy;
86734  PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
86735  int nKey = pReader->nKey;
86736  i64 iEof = writer.iWriteOff + writer.iBufEnd;
86737 
86738  /* Check if the output file is full or if the input has been exhausted.
86739  ** In either case exit the loop. */
86740  if( pReader->pFd==0 ) break;
86741  if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
86742 
86743  /* Write the next key to the output. */
86744  vdbePmaWriteVarint(&writer, nKey);
86745  vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
86746  assert( pIncr->pMerger->pTask==pTask );
86747  rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
86748  }
86749 
86750  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
86751  if( rc==SQLITE_OK ) rc = rc2;
86752  vdbeSorterPopulateDebug(pTask, "exit");
86753  return rc;
86754 }
86755 
86756 #if SQLITE_MAX_WORKER_THREADS>0
86757 /*
86758 ** The main routine for background threads that populate aFile[1] of
86759 ** multi-threaded IncrMerger objects.
86760 */
86761 static void *vdbeIncrPopulateThread(void *pCtx){
86762  IncrMerger *pIncr = (IncrMerger*)pCtx;
86763  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
86764  pIncr->pTask->bDone = 1;
86765  return pRet;
86766 }
86767 
86768 /*
86769 ** Launch a background thread to populate aFile[1] of pIncr.
86770 */
86771 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
86772  void *p = (void*)pIncr;
86773  assert( pIncr->bUseThread );
86775 }
86776 #endif
86777 
86778 /*
86779 ** This function is called when the PmaReader corresponding to pIncr has
86780 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
86781 ** aFile[0] such that the PmaReader should start rereading it from the
86782 ** beginning.
86783 **
86784 ** For single-threaded objects, this is accomplished by literally reading
86785 ** keys from pIncr->pMerger and repopulating aFile[0].
86786 **
86787 ** For multi-threaded objects, all that is required is to wait until the
86788 ** background thread is finished (if it is not already) and then swap
86789 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
86790 ** been exhausted, this function also launches a new background thread
86791 ** to populate the new aFile[1].
86792 **
86793 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
86794 */
86795 static int vdbeIncrSwap(IncrMerger *pIncr){
86796  int rc = SQLITE_OK;
86797 
86798 #if SQLITE_MAX_WORKER_THREADS>0
86799  if( pIncr->bUseThread ){
86800  rc = vdbeSorterJoinThread(pIncr->pTask);
86801 
86802  if( rc==SQLITE_OK ){
86803  SorterFile f0 = pIncr->aFile[0];
86804  pIncr->aFile[0] = pIncr->aFile[1];
86805  pIncr->aFile[1] = f0;
86806  }
86807 
86808  if( rc==SQLITE_OK ){
86809  if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86810  pIncr->bEof = 1;
86811  }else{
86812  rc = vdbeIncrBgPopulate(pIncr);
86813  }
86814  }
86815  }else
86816 #endif
86817  {
86818  rc = vdbeIncrPopulate(pIncr);
86819  pIncr->aFile[0] = pIncr->aFile[1];
86820  if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86821  pIncr->bEof = 1;
86822  }
86823  }
86824 
86825  return rc;
86826 }
86827 
86828 /*
86829 ** Allocate and return a new IncrMerger object to read data from pMerger.
86830 **
86831 ** If an OOM condition is encountered, return NULL. In this case free the
86832 ** pMerger argument before returning.
86833 */
86835  SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
86836  MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
86837  IncrMerger **ppOut /* Write the new IncrMerger here */
86838 ){
86839  int rc = SQLITE_OK;
86840  IncrMerger *pIncr = *ppOut = (IncrMerger*)
86841  (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
86842  if( pIncr ){
86843  pIncr->pMerger = pMerger;
86844  pIncr->pTask = pTask;
86845  pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
86846  pTask->file2.iEof += pIncr->mxSz;
86847  }else{
86848  vdbeMergeEngineFree(pMerger);
86849  rc = SQLITE_NOMEM_BKPT;
86850  }
86851  return rc;
86852 }
86853 
86854 #if SQLITE_MAX_WORKER_THREADS>0
86855 /*
86856 ** Set the "use-threads" flag on object pIncr.
86857 */
86859  pIncr->bUseThread = 1;
86860  pIncr->pTask->file2.iEof -= pIncr->mxSz;
86861 }
86862 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
86863 
86864 
86865 
86866 /*
86867 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
86868 ** two PmaReaders that feed that entry. Neither of the PmaReaders
86869 ** are advanced. This routine merely does the comparison.
86870 */
86872  MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
86873  int iOut /* Store the result in pMerger->aTree[iOut] */
86874 ){
86875  int i1;
86876  int i2;
86877  int iRes;
86878  PmaReader *p1;
86879  PmaReader *p2;
86880 
86881  assert( iOut<pMerger->nTree && iOut>0 );
86882 
86883  if( iOut>=(pMerger->nTree/2) ){
86884  i1 = (iOut - pMerger->nTree/2) * 2;
86885  i2 = i1 + 1;
86886  }else{
86887  i1 = pMerger->aTree[iOut*2];
86888  i2 = pMerger->aTree[iOut*2+1];
86889  }
86890 
86891  p1 = &pMerger->aReadr[i1];
86892  p2 = &pMerger->aReadr[i2];
86893 
86894  if( p1->pFd==0 ){
86895  iRes = i2;
86896  }else if( p2->pFd==0 ){
86897  iRes = i1;
86898  }else{
86899  SortSubtask *pTask = pMerger->pTask;
86900  int bCached = 0;
86901  int res;
86902  assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
86903  res = pTask->xCompare(
86904  pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
86905  );
86906  if( res<=0 ){
86907  iRes = i1;
86908  }else{
86909  iRes = i2;
86910  }
86911  }
86912 
86913  pMerger->aTree[iOut] = iRes;
86914 }
86915 
86916 /*
86917 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
86918 ** and vdbePmaReaderIncrMergeInit().
86919 **
86920 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
86921 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
86922 ** when there exists one or more separate worker threads.
86923 */
86924 #define INCRINIT_NORMAL 0
86925 #define INCRINIT_TASK 1
86926 #define INCRINIT_ROOT 2
86927 
86928 /*
86929 ** Forward reference required as the vdbeIncrMergeInit() and
86930 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
86931 ** building a merge tree.
86932 */
86933 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
86934 
86935 /*
86936 ** Initialize the MergeEngine object passed as the second argument. Once this
86937 ** function returns, the first key of merged data may be read from the
86938 ** MergeEngine object in the usual fashion.
86939 **
86940 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
86941 ** objects attached to the PmaReader objects that the merger reads from have
86942 ** already been populated, but that they have not yet populated aFile[0] and
86943 ** set the PmaReader objects up to read from it. In this case all that is
86944 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
86945 ** its first key.
86946 **
86947 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
86948 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
86949 ** to pMerger.
86950 **
86951 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86952 */
86954  SortSubtask *pTask, /* Thread that will run pMerger */
86955  MergeEngine *pMerger, /* MergeEngine to initialize */
86956  int eMode /* One of the INCRINIT_XXX constants */
86957 ){
86958  int rc = SQLITE_OK; /* Return code */
86959  int i; /* For looping over PmaReader objects */
86960  int nTree = pMerger->nTree;
86961 
86962  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86963  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86964 
86965  /* Verify that the MergeEngine is assigned to a single thread */
86966  assert( pMerger->pTask==0 );
86967  pMerger->pTask = pTask;
86968 
86969  for(i=0; i<nTree; i++){
86970  if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
86971  /* PmaReaders should be normally initialized in order, as if they are
86972  ** reading from the same temp file this makes for more linear file IO.
86973  ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
86974  ** in use it will block the vdbePmaReaderNext() call while it uses
86975  ** the main thread to fill its buffer. So calling PmaReaderNext()
86976  ** on this PmaReader before any of the multi-threaded PmaReaders takes
86977  ** better advantage of multi-processor hardware. */
86978  rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
86979  }else{
86980  rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
86981  }
86982  if( rc!=SQLITE_OK ) return rc;
86983  }
86984 
86985  for(i=pMerger->nTree-1; i>0; i--){
86986  vdbeMergeEngineCompare(pMerger, i);
86987  }
86988  return pTask->pUnpacked->errCode;
86989 }
86990 
86991 /*
86992 ** The PmaReader passed as the first argument is guaranteed to be an
86993 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
86994 ** and/or initialize the temp file related fields of the IncrMerge
86995 ** object at (pReadr->pIncr).
86996 **
86997 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
86998 ** in the sub-tree headed by pReadr are also initialized. Data is then
86999 ** loaded into the buffers belonging to pReadr and it is set to point to
87000 ** the first key in its range.
87001 **
87002 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
87003 ** to be a multi-threaded PmaReader and this function is being called in a
87004 ** background thread. In this case all PmaReaders in the sub-tree are
87005 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
87006 ** pReadr is populated. However, pReadr itself is not set up to point
87007 ** to its first key. A call to vdbePmaReaderNext() is still required to do
87008 ** that.
87009 **
87010 ** The reason this function does not call vdbePmaReaderNext() immediately
87011 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
87012 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
87013 ** this entire function is being run by thread (pTask->thread), that will
87014 ** lead to the current background thread attempting to join itself.
87015 **
87016 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
87017 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
87018 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
87019 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
87020 ** the current PmaReader set to point to the first key in its range.
87021 **
87022 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87023 */
87024 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
87025  int rc = SQLITE_OK;
87026  IncrMerger *pIncr = pReadr->pIncr;
87027  SortSubtask *pTask = pIncr->pTask;
87028  sqlite3 *db = pTask->pSorter->db;
87029 
87030  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
87031  assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
87032 
87033  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
87034 
87035  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
87036  ** requires two temp files to itself, whereas a single-threaded object
87037  ** only requires a region of pTask->file2. */
87038  if( rc==SQLITE_OK ){
87039  int mxSz = pIncr->mxSz;
87040 #if SQLITE_MAX_WORKER_THREADS>0
87041  if( pIncr->bUseThread ){
87042  rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
87043  if( rc==SQLITE_OK ){
87044  rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
87045  }
87046  }else
87047 #endif
87048  /*if( !pIncr->bUseThread )*/{
87049  if( pTask->file2.pFd==0 ){
87050  assert( pTask->file2.iEof>0 );
87051  rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
87052  pTask->file2.iEof = 0;
87053  }
87054  if( rc==SQLITE_OK ){
87055  pIncr->aFile[1].pFd = pTask->file2.pFd;
87056  pIncr->iStartOff = pTask->file2.iEof;
87057  pTask->file2.iEof += mxSz;
87058  }
87059  }
87060  }
87061 
87062 #if SQLITE_MAX_WORKER_THREADS>0
87063  if( rc==SQLITE_OK && pIncr->bUseThread ){
87064  /* Use the current thread to populate aFile[1], even though this
87065  ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
87066  ** then this function is already running in background thread
87067  ** pIncr->pTask->thread.
87068  **
87069  ** If this is the INCRINIT_ROOT object, then it is running in the
87070  ** main VDBE thread. But that is Ok, as that thread cannot return
87071  ** control to the VDBE or proceed with anything useful until the
87072  ** first results are ready from this merger object anyway.
87073  */
87074  assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
87075  rc = vdbeIncrPopulate(pIncr);
87076  }
87077 #endif
87078 
87079  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
87080  rc = vdbePmaReaderNext(pReadr);
87081  }
87082 
87083  return rc;
87084 }
87085 
87086 #if SQLITE_MAX_WORKER_THREADS>0
87087 /*
87088 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
87089 ** background threads.
87090 */
87091 static void *vdbePmaReaderBgIncrInit(void *pCtx){
87092  PmaReader *pReader = (PmaReader*)pCtx;
87093  void *pRet = SQLITE_INT_TO_PTR(
87095  );
87096  pReader->pIncr->pTask->bDone = 1;
87097  return pRet;
87098 }
87099 #endif
87100 
87101 /*
87102 ** If the PmaReader passed as the first argument is not an incremental-reader
87103 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
87104 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
87105 ** this routine to initialize the incremental merge.
87106 **
87107 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
87108 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
87109 ** Or, if the IncrMerger is single threaded, the same function is called
87110 ** using the current thread.
87111 */
87112 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
87113  IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
87114  int rc = SQLITE_OK; /* Return code */
87115  if( pIncr ){
87116 #if SQLITE_MAX_WORKER_THREADS>0
87117  assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
87118  if( pIncr->bUseThread ){
87119  void *pCtx = (void*)pReadr;
87121  }else
87122 #endif
87123  {
87124  rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
87125  }
87126  }
87127  return rc;
87128 }
87129 
87130 /*
87131 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
87132 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
87133 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
87134 ** to NULL and return an SQLite error code.
87135 **
87136 ** When this function is called, *piOffset is set to the offset of the
87137 ** first PMA to read from pTask->file. Assuming no error occurs, it is
87138 ** set to the offset immediately following the last byte of the last
87139 ** PMA before returning. If an error does occur, then the final value of
87140 ** *piOffset is undefined.
87141 */
87143  SortSubtask *pTask, /* Sorter task to read from */
87144  int nPMA, /* Number of PMAs to read */
87145  i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
87146  MergeEngine **ppOut /* OUT: New merge-engine */
87147 ){
87148  MergeEngine *pNew; /* Merge engine to return */
87149  i64 iOff = *piOffset;
87150  int i;
87151  int rc = SQLITE_OK;
87152 
87153  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
87154  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
87155 
87156  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
87157  i64 nDummy = 0;
87158  PmaReader *pReadr = &pNew->aReadr[i];
87159  rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
87160  iOff = pReadr->iEof;
87161  }
87162 
87163  if( rc!=SQLITE_OK ){
87164  vdbeMergeEngineFree(pNew);
87165  *ppOut = 0;
87166  }
87167  *piOffset = iOff;
87168  return rc;
87169 }
87170 
87171 /*
87172 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
87173 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
87174 **
87175 ** i.e.
87176 **
87177 ** nPMA<=16 -> TreeDepth() == 0
87178 ** nPMA<=256 -> TreeDepth() == 1
87179 ** nPMA<=65536 -> TreeDepth() == 2
87180 */
87181 static int vdbeSorterTreeDepth(int nPMA){
87182  int nDepth = 0;
87183  i64 nDiv = SORTER_MAX_MERGE_COUNT;
87184  while( nDiv < (i64)nPMA ){
87185  nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
87186  nDepth++;
87187  }
87188  return nDepth;
87189 }
87190 
87191 /*
87192 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
87193 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
87194 ** tree, counting from zero. This function adds pLeaf to the tree.
87195 **
87196 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
87197 ** code is returned and pLeaf is freed.
87198 */
87200  SortSubtask *pTask, /* Task context */
87201  int nDepth, /* Depth of tree according to TreeDepth() */
87202  int iSeq, /* Sequence number of leaf within tree */
87203  MergeEngine *pRoot, /* Root of tree */
87204  MergeEngine *pLeaf /* Leaf to add to tree */
87205 ){
87206  int rc = SQLITE_OK;
87207  int nDiv = 1;
87208  int i;
87209  MergeEngine *p = pRoot;
87210  IncrMerger *pIncr;
87211 
87212  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
87213 
87214  for(i=1; i<nDepth; i++){
87215  nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
87216  }
87217 
87218  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
87219  int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
87220  PmaReader *pReadr = &p->aReadr[iIter];
87221 
87222  if( pReadr->pIncr==0 ){
87224  if( pNew==0 ){
87225  rc = SQLITE_NOMEM_BKPT;
87226  }else{
87227  rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
87228  }
87229  }
87230  if( rc==SQLITE_OK ){
87231  p = pReadr->pIncr->pMerger;
87232  nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
87233  }
87234  }
87235 
87236  if( rc==SQLITE_OK ){
87237  p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
87238  }else{
87239  vdbeIncrFree(pIncr);
87240  }
87241  return rc;
87242 }
87243 
87244 /*
87245 ** This function is called as part of a SorterRewind() operation on a sorter
87246 ** that has already written two or more level-0 PMAs to one or more temp
87247 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
87248 ** can be used to incrementally merge all PMAs on disk.
87249 **
87250 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
87251 ** MergeEngine object at the root of the tree before returning. Or, if an
87252 ** error occurs, an SQLite error code is returned and the final value
87253 ** of *ppOut is undefined.
87254 */
87256  VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
87257  MergeEngine **ppOut /* Write the MergeEngine here */
87258 ){
87259  MergeEngine *pMain = 0;
87260  int rc = SQLITE_OK;
87261  int iTask;
87262 
87263 #if SQLITE_MAX_WORKER_THREADS>0
87264  /* If the sorter uses more than one task, then create the top-level
87265  ** MergeEngine here. This MergeEngine will read data from exactly
87266  ** one PmaReader per sub-task. */
87267  assert( pSorter->bUseThreads || pSorter->nTask==1 );
87268  if( pSorter->nTask>1 ){
87269  pMain = vdbeMergeEngineNew(pSorter->nTask);
87270  if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
87271  }
87272 #endif
87273 
87274  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87275  SortSubtask *pTask = &pSorter->aTask[iTask];
87276  assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
87277  if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
87278  MergeEngine *pRoot = 0; /* Root node of tree for this task */
87279  int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
87280  i64 iReadOff = 0;
87281 
87282  if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
87283  rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
87284  }else{
87285  int i;
87286  int iSeq = 0;
87288  if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
87289  for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
87290  MergeEngine *pMerger = 0; /* New level-0 PMA merger */
87291  int nReader; /* Number of level-0 PMAs to merge */
87292 
87293  nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
87294  rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
87295  if( rc==SQLITE_OK ){
87296  rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
87297  }
87298  }
87299  }
87300 
87301  if( rc==SQLITE_OK ){
87302 #if SQLITE_MAX_WORKER_THREADS>0
87303  if( pMain!=0 ){
87304  rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
87305  }else
87306 #endif
87307  {
87308  assert( pMain==0 );
87309  pMain = pRoot;
87310  }
87311  }else{
87312  vdbeMergeEngineFree(pRoot);
87313  }
87314  }
87315  }
87316 
87317  if( rc!=SQLITE_OK ){
87318  vdbeMergeEngineFree(pMain);
87319  pMain = 0;
87320  }
87321  *ppOut = pMain;
87322  return rc;
87323 }
87324 
87325 /*
87326 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
87327 ** on a sorter that has written two or more PMAs to temporary files. It sets
87328 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
87329 ** (for multi-threaded sorters) so that it can be used to iterate through
87330 ** all records stored in the sorter.
87331 **
87332 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87333 */
87334 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
87335  int rc; /* Return code */
87336  SortSubtask *pTask0 = &pSorter->aTask[0];
87337  MergeEngine *pMain = 0;
87338 #if SQLITE_MAX_WORKER_THREADS
87339  sqlite3 *db = pTask0->pSorter->db;
87340  int i;
87341  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
87342  for(i=0; i<pSorter->nTask; i++){
87343  pSorter->aTask[i].xCompare = xCompare;
87344  }
87345 #endif
87346 
87347  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
87348  if( rc==SQLITE_OK ){
87349 #if SQLITE_MAX_WORKER_THREADS
87350  assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
87351  if( pSorter->bUseThreads ){
87352  int iTask;
87353  PmaReader *pReadr = 0;
87354  SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
87355  rc = vdbeSortAllocUnpacked(pLast);
87356  if( rc==SQLITE_OK ){
87357  pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
87358  pSorter->pReader = pReadr;
87359  if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
87360  }
87361  if( rc==SQLITE_OK ){
87362  rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
87363  if( rc==SQLITE_OK ){
87365  for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
87366  IncrMerger *pIncr;
87367  if( (pIncr = pMain->aReadr[iTask].pIncr) ){
87368  vdbeIncrMergerSetThreads(pIncr);
87369  assert( pIncr->pTask!=pLast );
87370  }
87371  }
87372  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87373  /* Check that:
87374  **
87375  ** a) The incremental merge object is configured to use the
87376  ** right task, and
87377  ** b) If it is using task (nTask-1), it is configured to run
87378  ** in single-threaded mode. This is important, as the
87379  ** root merge (INCRINIT_ROOT) will be using the same task
87380  ** object.
87381  */
87382  PmaReader *p = &pMain->aReadr[iTask];
87383  assert( p->pIncr==0 || (
87384  (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
87385  && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
87386  ));
87388  }
87389  }
87390  pMain = 0;
87391  }
87392  if( rc==SQLITE_OK ){
87394  }
87395  }else
87396 #endif
87397  {
87398  rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
87399  pSorter->pMerger = pMain;
87400  pMain = 0;
87401  }
87402  }
87403 
87404  if( rc!=SQLITE_OK ){
87405  vdbeMergeEngineFree(pMain);
87406  }
87407  return rc;
87408 }
87409 
87410 
87411 /*
87412 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
87413 ** this function is called to prepare for iterating through the records
87414 ** in sorted order.
87415 */
87417  VdbeSorter *pSorter;
87418  int rc = SQLITE_OK; /* Return code */
87419 
87420  assert( pCsr->eCurType==CURTYPE_SORTER );
87421  pSorter = pCsr->uc.pSorter;
87422  assert( pSorter );
87423 
87424  /* If no data has been written to disk, then do not do so now. Instead,
87425  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
87426  ** from the in-memory list. */
87427  if( pSorter->bUsePMA==0 ){
87428  if( pSorter->list.pList ){
87429  *pbEof = 0;
87430  rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
87431  }else{
87432  *pbEof = 1;
87433  }
87434  return rc;
87435  }
87436 
87437  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
87438  ** function flushes the contents of memory to disk, it immediately always
87439  ** creates a new list consisting of a single key immediately afterwards.
87440  ** So the list is never empty at this point. */
87441  assert( pSorter->list.pList );
87442  rc = vdbeSorterFlushPMA(pSorter);
87443 
87444  /* Join all threads */
87445  rc = vdbeSorterJoinAll(pSorter, rc);
87446 
87447  vdbeSorterRewindDebug("rewind");
87448 
87449  /* Assuming no errors have occurred, set up a merger structure to
87450  ** incrementally read and merge all remaining PMAs. */
87451  assert( pSorter->pReader==0 );
87452  if( rc==SQLITE_OK ){
87453  rc = vdbeSorterSetupMerge(pSorter);
87454  *pbEof = 0;
87455  }
87456 
87457  vdbeSorterRewindDebug("rewinddone");
87458  return rc;
87459 }
87460 
87461 /*
87462 ** Advance to the next element in the sorter.
87463 */
87464 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
87465  VdbeSorter *pSorter;
87466  int rc; /* Return code */
87467 
87468  assert( pCsr->eCurType==CURTYPE_SORTER );
87469  pSorter = pCsr->uc.pSorter;
87470  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
87471  if( pSorter->bUsePMA ){
87472  assert( pSorter->pReader==0 || pSorter->pMerger==0 );
87473  assert( pSorter->bUseThreads==0 || pSorter->pReader );
87474  assert( pSorter->bUseThreads==1 || pSorter->pMerger );
87475 #if SQLITE_MAX_WORKER_THREADS>0
87476  if( pSorter->bUseThreads ){
87477  rc = vdbePmaReaderNext(pSorter->pReader);
87478  *pbEof = (pSorter->pReader->pFd==0);
87479  }else
87480 #endif
87481  /*if( !pSorter->bUseThreads )*/ {
87482  assert( pSorter->pMerger!=0 );
87483  assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
87484  rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
87485  }
87486  }else{
87487  SorterRecord *pFree = pSorter->list.pList;
87488  pSorter->list.pList = pFree->u.pNext;
87489  pFree->u.pNext = 0;
87490  if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
87491  *pbEof = !pSorter->list.pList;
87492  rc = SQLITE_OK;
87493  }
87494  return rc;
87495 }
87496 
87497 /*
87498 ** Return a pointer to a buffer owned by the sorter that contains the
87499 ** current key.
87500 */
87501 static void *vdbeSorterRowkey(
87502  const VdbeSorter *pSorter, /* Sorter object */
87503  int *pnKey /* OUT: Size of current key in bytes */
87504 ){
87505  void *pKey;
87506  if( pSorter->bUsePMA ){
87507  PmaReader *pReader;
87508 #if SQLITE_MAX_WORKER_THREADS>0
87509  if( pSorter->bUseThreads ){
87510  pReader = pSorter->pReader;
87511  }else
87512 #endif
87513  /*if( !pSorter->bUseThreads )*/{
87514  pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
87515  }
87516  *pnKey = pReader->nKey;
87517  pKey = pReader->aKey;
87518  }else{
87519  *pnKey = pSorter->list.pList->nVal;
87520  pKey = SRVAL(pSorter->list.pList);
87521  }
87522  return pKey;
87523 }
87524 
87525 /*
87526 ** Copy the current sorter key into the memory cell pOut.
87527 */
87529  VdbeSorter *pSorter;
87530  void *pKey; int nKey; /* Sorter key to copy into pOut */
87531 
87532  assert( pCsr->eCurType==CURTYPE_SORTER );
87533  pSorter = pCsr->uc.pSorter;
87534  pKey = vdbeSorterRowkey(pSorter, &nKey);
87535  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
87536  return SQLITE_NOMEM_BKPT;
87537  }
87538  pOut->n = nKey;
87539  MemSetTypeFlag(pOut, MEM_Blob);
87540  memcpy(pOut->z, pKey, nKey);
87541 
87542  return SQLITE_OK;
87543 }
87544 
87545 /*
87546 ** Compare the key in memory cell pVal with the key that the sorter cursor
87547 ** passed as the first argument currently points to. For the purposes of
87548 ** the comparison, ignore the rowid field at the end of each record.
87549 **
87550 ** If the sorter cursor key contains any NULL values, consider it to be
87551 ** less than pVal. Even if pVal also contains NULL values.
87552 **
87553 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
87554 ** Otherwise, set *pRes to a negative, zero or positive value if the
87555 ** key in pVal is smaller than, equal to or larger than the current sorter
87556 ** key.
87557 **
87558 ** This routine forms the core of the OP_SorterCompare opcode, which in
87559 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
87560 */
87562  const VdbeCursor *pCsr, /* Sorter cursor */
87563  Mem *pVal, /* Value to compare to current sorter key */
87564  int nKeyCol, /* Compare this many columns */
87565  int *pRes /* OUT: Result of comparison */
87566 ){
87567  VdbeSorter *pSorter;
87568  UnpackedRecord *r2;
87569  KeyInfo *pKeyInfo;
87570  int i;
87571  void *pKey; int nKey; /* Sorter key to compare pVal with */
87572 
87573  assert( pCsr->eCurType==CURTYPE_SORTER );
87574  pSorter = pCsr->uc.pSorter;
87575  r2 = pSorter->pUnpacked;
87576  pKeyInfo = pCsr->pKeyInfo;
87577  if( r2==0 ){
87578  char *p;
87579  r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
87580  assert( pSorter->pUnpacked==(UnpackedRecord*)p );
87581  if( r2==0 ) return SQLITE_NOMEM_BKPT;
87582  r2->nField = nKeyCol;
87583  }
87584  assert( r2->nField==nKeyCol );
87585 
87586  pKey = vdbeSorterRowkey(pSorter, &nKey);
87587  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
87588  for(i=0; i<nKeyCol; i++){
87589  if( r2->aMem[i].flags & MEM_Null ){
87590  *pRes = -1;
87591  return SQLITE_OK;
87592  }
87593  }
87594 
87595  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
87596  return SQLITE_OK;
87597 }
87598 
87599 /************** End of vdbesort.c ********************************************/
87600 /************** Begin file memjournal.c **************************************/
87601 /*
87602 ** 2008 October 7
87603 **
87604 ** The author disclaims copyright to this source code. In place of
87605 ** a legal notice, here is a blessing:
87606 **
87607 ** May you do good and not evil.
87608 ** May you find forgiveness for yourself and forgive others.
87609 ** May you share freely, never taking more than you give.
87610 **
87611 *************************************************************************
87612 **
87613 ** This file contains code use to implement an in-memory rollback journal.
87614 ** The in-memory rollback journal is used to journal transactions for
87615 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
87616 **
87617 ** Update: The in-memory journal is also used to temporarily cache
87618 ** smaller journals that are not critical for power-loss recovery.
87619 ** For example, statement journals that are not too big will be held
87620 ** entirely in memory, thus reducing the number of file I/O calls, and
87621 ** more importantly, reducing temporary file creation events. If these
87622 ** journals become too large for memory, they are spilled to disk. But
87623 ** in the common case, they are usually small and no file I/O needs to
87624 ** occur.
87625 */
87626 /* #include "sqliteInt.h" */
87627 
87628 /* Forward references to internal structures */
87629 typedef struct MemJournal MemJournal;
87630 typedef struct FilePoint FilePoint;
87631 typedef struct FileChunk FileChunk;
87632 
87633 /*
87634 ** The rollback journal is composed of a linked list of these structures.
87635 **
87636 ** The zChunk array is always at least 8 bytes in size - usually much more.
87637 ** Its actual size is stored in the MemJournal.nChunkSize variable.
87638 */
87639 struct FileChunk {
87640  FileChunk *pNext; /* Next chunk in the journal */
87641  u8 zChunk[8]; /* Content of this chunk */
87642 };
87643 
87644 /*
87645 ** By default, allocate this many bytes of memory for each FileChunk object.
87646 */
87647 #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
87648 
87649 /*
87650 ** For chunk size nChunkSize, return the number of bytes that should
87651 ** be allocated for each FileChunk structure.
87652 */
87653 #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
87654 
87655 /*
87656 ** An instance of this object serves as a cursor into the rollback journal.
87657 ** The cursor can be either for reading or writing.
87658 */
87659 struct FilePoint {
87660  sqlite3_int64 iOffset; /* Offset from the beginning of the file */
87661  FileChunk *pChunk; /* Specific chunk into which cursor points */
87662 };
87663 
87664 /*
87665 ** This structure is a subclass of sqlite3_file. Each open memory-journal
87666 ** is an instance of this class.
87667 */
87668 struct MemJournal {
87669  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
87670  int nChunkSize; /* In-memory chunk-size */
87671 
87672  int nSpill; /* Bytes of data before flushing */
87673  int nSize; /* Bytes of data currently in memory */
87674  FileChunk *pFirst; /* Head of in-memory chunk-list */
87675  FilePoint endpoint; /* Pointer to the end of the file */
87676  FilePoint readpoint; /* Pointer to the end of the last xRead() */
87677 
87678  int flags; /* xOpen flags */
87679  sqlite3_vfs *pVfs; /* The "real" underlying VFS */
87680  const char *zJournal; /* Name of the journal file */
87681 };
87682 
87683 /*
87684 ** Read data from the in-memory journal file. This is the implementation
87685 ** of the sqlite3_vfs.xRead method.
87686 */
87687 static int memjrnlRead(
87688  sqlite3_file *pJfd, /* The journal file from which to read */
87689  void *zBuf, /* Put the results here */
87690  int iAmt, /* Number of bytes to read */
87691  sqlite_int64 iOfst /* Begin reading at this offset */
87692 ){
87693  MemJournal *p = (MemJournal *)pJfd;
87694  u8 *zOut = zBuf;
87695  int nRead = iAmt;
87696  int iChunkOffset;
87697  FileChunk *pChunk;
87698 
87699 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87700  if( (iAmt+iOfst)>p->endpoint.iOffset ){
87701  return SQLITE_IOERR_SHORT_READ;
87702  }
87703 #endif
87704 
87705  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
87706  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
87707  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
87708  sqlite3_int64 iOff = 0;
87709  for(pChunk=p->pFirst;
87710  ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
87711  pChunk=pChunk->pNext
87712  ){
87713  iOff += p->nChunkSize;
87714  }
87715  }else{
87716  pChunk = p->readpoint.pChunk;
87717  assert( pChunk!=0 );
87718  }
87719 
87720  iChunkOffset = (int)(iOfst%p->nChunkSize);
87721  do {
87722  int iSpace = p->nChunkSize - iChunkOffset;
87723  int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
87724  memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
87725  zOut += nCopy;
87726  nRead -= iSpace;
87727  iChunkOffset = 0;
87728  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
87729  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
87730  p->readpoint.pChunk = pChunk;
87731 
87732  return SQLITE_OK;
87733 }
87734 
87735 /*
87736 ** Free the list of FileChunk structures headed at MemJournal.pFirst.
87737 */
87739  FileChunk *pIter;
87740  FileChunk *pNext;
87741  for(pIter=p->pFirst; pIter; pIter=pNext){
87742  pNext = pIter->pNext;
87743  sqlite3_free(pIter);
87744  }
87745  p->pFirst = 0;
87746 }
87747 
87748 /*
87749 ** Flush the contents of memory to a real file on disk.
87750 */
87752  int rc;
87753  sqlite3_file *pReal = (sqlite3_file*)p;
87754  MemJournal copy = *p;
87755 
87756  memset(p, 0, sizeof(MemJournal));
87757  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
87758  if( rc==SQLITE_OK ){
87759  int nChunk = copy.nChunkSize;
87760  i64 iOff = 0;
87761  FileChunk *pIter;
87762  for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
87763  if( iOff + nChunk > copy.endpoint.iOffset ){
87764  nChunk = copy.endpoint.iOffset - iOff;
87765  }
87766  rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
87767  if( rc ) break;
87768  iOff += nChunk;
87769  }
87770  if( rc==SQLITE_OK ){
87771  /* No error has occurred. Free the in-memory buffers. */
87772  memjrnlFreeChunks(&copy);
87773  }
87774  }
87775  if( rc!=SQLITE_OK ){
87776  /* If an error occurred while creating or writing to the file, restore
87777  ** the original before returning. This way, SQLite uses the in-memory
87778  ** journal data to roll back changes made to the internal page-cache
87779  ** before this function was called. */
87780  sqlite3OsClose(pReal);
87781  *p = copy;
87782  }
87783  return rc;
87784 }
87785 
87786 
87787 /*
87788 ** Write data to the file.
87789 */
87790 static int memjrnlWrite(
87791  sqlite3_file *pJfd, /* The journal file into which to write */
87792  const void *zBuf, /* Take data to be written from here */
87793  int iAmt, /* Number of bytes to write */
87794  sqlite_int64 iOfst /* Begin writing at this offset into the file */
87795 ){
87796  MemJournal *p = (MemJournal *)pJfd;
87797  int nWrite = iAmt;
87798  u8 *zWrite = (u8 *)zBuf;
87799 
87800  /* If the file should be created now, create it and write the new data
87801  ** into the file on disk. */
87802  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
87803  int rc = memjrnlCreateFile(p);
87804  if( rc==SQLITE_OK ){
87805  rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
87806  }
87807  return rc;
87808  }
87809 
87810  /* If the contents of this write should be stored in memory */
87811  else{
87812  /* An in-memory journal file should only ever be appended to. Random
87813  ** access writes are not required. The only exception to this is when
87814  ** the in-memory journal is being used by a connection using the
87815  ** atomic-write optimization. In this case the first 28 bytes of the
87816  ** journal file may be written as part of committing the transaction. */
87817  assert( iOfst==p->endpoint.iOffset || iOfst==0 );
87818 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87819  if( iOfst==0 && p->pFirst ){
87820  assert( p->nChunkSize>iAmt );
87821  memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
87822  }else
87823 #else
87824  assert( iOfst>0 || p->pFirst==0 );
87825 #endif
87826  {
87827  while( nWrite>0 ){
87828  FileChunk *pChunk = p->endpoint.pChunk;
87829  int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
87830  int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
87831 
87832  if( iChunkOffset==0 ){
87833  /* New chunk is required to extend the file. */
87835  if( !pNew ){
87836  return SQLITE_IOERR_NOMEM_BKPT;
87837  }
87838  pNew->pNext = 0;
87839  if( pChunk ){
87840  assert( p->pFirst );
87841  pChunk->pNext = pNew;
87842  }else{
87843  assert( !p->pFirst );
87844  p->pFirst = pNew;
87845  }
87846  p->endpoint.pChunk = pNew;
87847  }
87848 
87849  memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
87850  zWrite += iSpace;
87851  nWrite -= iSpace;
87852  p->endpoint.iOffset += iSpace;
87853  }
87854  p->nSize = iAmt + iOfst;
87855  }
87856  }
87857 
87858  return SQLITE_OK;
87859 }
87860 
87861 /*
87862 ** Truncate the file.
87863 **
87864 ** If the journal file is already on disk, truncate it there. Or, if it
87865 ** is still in main memory but is being truncated to zero bytes in size,
87866 ** ignore
87867 */
87868 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
87869  MemJournal *p = (MemJournal *)pJfd;
87870  if( ALWAYS(size==0) ){
87871  memjrnlFreeChunks(p);
87872  p->nSize = 0;
87873  p->endpoint.pChunk = 0;
87874  p->endpoint.iOffset = 0;
87875  p->readpoint.pChunk = 0;
87876  p->readpoint.iOffset = 0;
87877  }
87878  return SQLITE_OK;
87879 }
87880 
87881 /*
87882 ** Close the file.
87883 */
87884 static int memjrnlClose(sqlite3_file *pJfd){
87885  MemJournal *p = (MemJournal *)pJfd;
87886  memjrnlFreeChunks(p);
87887  return SQLITE_OK;
87888 }
87889 
87890 /*
87891 ** Sync the file.
87892 **
87893 ** If the real file has been created, call its xSync method. Otherwise,
87894 ** syncing an in-memory journal is a no-op.
87895 */
87896 static int memjrnlSync(sqlite3_file *pJfd, int flags){
87897  UNUSED_PARAMETER2(pJfd, flags);
87898  return SQLITE_OK;
87899 }
87900 
87901 /*
87902 ** Query the size of the file in bytes.
87903 */
87904 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
87905  MemJournal *p = (MemJournal *)pJfd;
87906  *pSize = (sqlite_int64) p->endpoint.iOffset;
87907  return SQLITE_OK;
87908 }
87909 
87910 /*
87911 ** Table of methods for MemJournal sqlite3_file object.
87912 */
87913 static const struct sqlite3_io_methods MemJournalMethods = {
87914  1, /* iVersion */
87915  memjrnlClose, /* xClose */
87916  memjrnlRead, /* xRead */
87917  memjrnlWrite, /* xWrite */
87918  memjrnlTruncate, /* xTruncate */
87919  memjrnlSync, /* xSync */
87920  memjrnlFileSize, /* xFileSize */
87921  0, /* xLock */
87922  0, /* xUnlock */
87923  0, /* xCheckReservedLock */
87924  0, /* xFileControl */
87925  0, /* xSectorSize */
87926  0, /* xDeviceCharacteristics */
87927  0, /* xShmMap */
87928  0, /* xShmLock */
87929  0, /* xShmBarrier */
87930  0, /* xShmUnmap */
87931  0, /* xFetch */
87932  0 /* xUnfetch */
87933 };
87934 
87935 /*
87936 ** Open a journal file.
87937 **
87938 ** The behaviour of the journal file depends on the value of parameter
87939 ** nSpill. If nSpill is 0, then the journal file is always create and
87940 ** accessed using the underlying VFS. If nSpill is less than zero, then
87941 ** all content is always stored in main-memory. Finally, if nSpill is a
87942 ** positive value, then the journal file is initially created in-memory
87943 ** but may be flushed to disk later on. In this case the journal file is
87944 ** flushed to disk either when it grows larger than nSpill bytes in size,
87945 ** or when sqlite3JournalCreate() is called.
87946 */
87948  sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
87949  const char *zName, /* Name of the journal file */
87950  sqlite3_file *pJfd, /* Preallocated, blank file handle */
87951  int flags, /* Opening flags */
87952  int nSpill /* Bytes buffered before opening the file */
87953 ){
87954  MemJournal *p = (MemJournal*)pJfd;
87955 
87956  /* Zero the file-handle object. If nSpill was passed zero, initialize
87957  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
87958  ** case none of the code in this module is executed as a result of calls
87959  ** made on the journal file-handle. */
87960  memset(p, 0, sizeof(MemJournal));
87961  if( nSpill==0 ){
87962  return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
87963  }
87964 
87965  if( nSpill>0 ){
87966  p->nChunkSize = nSpill;
87967  }else{
87970  }
87971 
87972  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
87973  p->nSpill = nSpill;
87974  p->flags = flags;
87975  p->zJournal = zName;
87976  p->pVfs = pVfs;
87977  return SQLITE_OK;
87978 }
87979 
87980 /*
87981 ** Open an in-memory journal file.
87982 */
87983 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
87984  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
87985 }
87986 
87987 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87988 /*
87989 ** If the argument p points to a MemJournal structure that is not an
87990 ** in-memory-only journal file (i.e. is one that was opened with a +ve
87991 ** nSpill parameter), and the underlying file has not yet been created,
87992 ** create it now.
87993 */
87994 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
87995  int rc = SQLITE_OK;
87996  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
87997  rc = memjrnlCreateFile((MemJournal*)p);
87998  }
87999  return rc;
88000 }
88001 #endif
88002 
88003 /*
88004 ** The file-handle passed as the only argument is open on a journal file.
88005 ** Return true if this "journal file" is currently stored in heap memory,
88006 ** or false otherwise.
88007 */
88009  return p->pMethods==&MemJournalMethods;
88010 }
88011 
88012 /*
88013 ** Return the number of bytes required to store a JournalFile that uses vfs
88014 ** pVfs to create the underlying on-disk files.
88015 */
88016 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
88017  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
88018 }
88019 
88020 /************** End of memjournal.c ******************************************/
88021 /************** Begin file walker.c ******************************************/
88022 /*
88023 ** 2008 August 16
88024 **
88025 ** The author disclaims copyright to this source code. In place of
88026 ** a legal notice, here is a blessing:
88027 **
88028 ** May you do good and not evil.
88029 ** May you find forgiveness for yourself and forgive others.
88030 ** May you share freely, never taking more than you give.
88031 **
88032 *************************************************************************
88033 ** This file contains routines used for walking the parser tree for
88034 ** an SQL statement.
88035 */
88036 /* #include "sqliteInt.h" */
88037 /* #include <stdlib.h> */
88038 /* #include <string.h> */
88039 
88040 
88041 /*
88042 ** Walk an expression tree. Invoke the callback once for each node
88043 ** of the expression, while descending. (In other words, the callback
88044 ** is invoked before visiting children.)
88045 **
88046 ** The return value from the callback should be one of the WRC_*
88047 ** constants to specify how to proceed with the walk.
88048 **
88049 ** WRC_Continue Continue descending down the tree.
88050 **
88051 ** WRC_Prune Do not descend into child nodes. But allow
88052 ** the walk to continue with sibling nodes.
88053 **
88054 ** WRC_Abort Do no more callbacks. Unwind the stack and
88055 ** return the top-level walk call.
88056 **
88057 ** The return value from this routine is WRC_Abort to abandon the tree walk
88058 ** and WRC_Continue to continue.
88059 */
88060 static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
88061  int rc;
88063  testcase( ExprHasProperty(pExpr, EP_Reduced) );
88064  rc = pWalker->xExprCallback(pWalker, pExpr);
88065  if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
88066  return rc & WRC_Abort;
88067  }
88068  if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
88069  if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
88070  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88071  if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
88072  }else if( pExpr->x.pList ){
88073  if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
88074  }
88075  return WRC_Continue;
88076 }
88078  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
88079 }
88080 
88081 /*
88082 ** Call sqlite3WalkExpr() for every expression in list p or until
88083 ** an abort request is seen.
88084 */
88086  int i;
88087  struct ExprList_item *pItem;
88088  if( p ){
88089  for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
88090  if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
88091  }
88092  }
88093  return WRC_Continue;
88094 }
88095 
88096 /*
88097 ** Walk all expressions associated with SELECT statement p. Do
88098 ** not invoke the SELECT callback on p, but do (of course) invoke
88099 ** any expr callbacks and SELECT callbacks that come from subqueries.
88100 ** Return WRC_Abort or WRC_Continue.
88101 */
88103  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
88104  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
88105  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
88106  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
88107  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
88108  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
88109  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
88110  return WRC_Continue;
88111 }
88112 
88113 /*
88114 ** Walk the parse trees associated with all subqueries in the
88115 ** FROM clause of SELECT statement p. Do not invoke the select
88116 ** callback on p, but do invoke it on each FROM clause subquery
88117 ** and on any subqueries further down in the tree. Return
88118 ** WRC_Abort or WRC_Continue;
88119 */
88121  SrcList *pSrc;
88122  int i;
88123  struct SrcList_item *pItem;
88124 
88125  pSrc = p->pSrc;
88126  if( ALWAYS(pSrc) ){
88127  for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
88128  if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
88129  return WRC_Abort;
88130  }
88131  if( pItem->fg.isTabFunc
88132  && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
88133  ){
88134  return WRC_Abort;
88135  }
88136  }
88137  }
88138  return WRC_Continue;
88139 }
88140 
88141 /*
88142 ** Call sqlite3WalkExpr() for every expression in Select statement p.
88143 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
88144 ** on the compound select chain, p->pPrior.
88145 **
88146 ** If it is not NULL, the xSelectCallback() callback is invoked before
88147 ** the walk of the expressions and FROM clause. The xSelectCallback2()
88148 ** method, if it is not NULL, is invoked following the walk of the
88149 ** expressions and FROM clause.
88150 **
88151 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
88152 ** there is an abort request.
88153 **
88154 ** If the Walker does not have an xSelectCallback() then this routine
88155 ** is a no-op returning WRC_Continue.
88156 */
88158  int rc;
88159  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
88160  return WRC_Continue;
88161  }
88162  rc = WRC_Continue;
88163  pWalker->walkerDepth++;
88164  while( p ){
88165  if( pWalker->xSelectCallback ){
88166  rc = pWalker->xSelectCallback(pWalker, p);
88167  if( rc ) break;
88168  }
88169  if( sqlite3WalkSelectExpr(pWalker, p)
88170  || sqlite3WalkSelectFrom(pWalker, p)
88171  ){
88172  pWalker->walkerDepth--;
88173  return WRC_Abort;
88174  }
88175  if( pWalker->xSelectCallback2 ){
88176  pWalker->xSelectCallback2(pWalker, p);
88177  }
88178  p = p->pPrior;
88179  }
88180  pWalker->walkerDepth--;
88181  return rc & WRC_Abort;
88182 }
88183 
88184 /************** End of walker.c **********************************************/
88185 /************** Begin file resolve.c *****************************************/
88186 /*
88187 ** 2008 August 18
88188 **
88189 ** The author disclaims copyright to this source code. In place of
88190 ** a legal notice, here is a blessing:
88191 **
88192 ** May you do good and not evil.
88193 ** May you find forgiveness for yourself and forgive others.
88194 ** May you share freely, never taking more than you give.
88195 **
88196 *************************************************************************
88197 **
88198 ** This file contains routines used for walking the parser tree and
88199 ** resolve all identifiers by associating them with a particular
88200 ** table and column.
88201 */
88202 /* #include "sqliteInt.h" */
88203 /* #include <stdlib.h> */
88204 /* #include <string.h> */
88205 
88206 /*
88207 ** Walk the expression tree pExpr and increase the aggregate function
88208 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
88209 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
88210 ** outer query into an inner subquery.
88211 **
88212 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
88213 ** is a helper function - a callback for the tree walker.
88214 */
88215 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
88216  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
88217  return WRC_Continue;
88218 }
88219 static void incrAggFunctionDepth(Expr *pExpr, int N){
88220  if( N>0 ){
88221  Walker w;
88222  memset(&w, 0, sizeof(w));
88224  w.u.n = N;
88225  sqlite3WalkExpr(&w, pExpr);
88226  }
88227 }
88228 
88229 /*
88230 ** Turn the pExpr expression into an alias for the iCol-th column of the
88231 ** result set in pEList.
88232 **
88233 ** If the reference is followed by a COLLATE operator, then make sure
88234 ** the COLLATE operator is preserved. For example:
88235 **
88236 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
88237 **
88238 ** Should be transformed into:
88239 **
88240 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
88241 **
88242 ** The nSubquery parameter specifies how many levels of subquery the
88243 ** alias is removed from the original expression. The usual value is
88244 ** zero but it might be more if the alias is contained within a subquery
88245 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
88246 ** structures must be increased by the nSubquery amount.
88247 */
88248 static void resolveAlias(
88249  Parse *pParse, /* Parsing context */
88250  ExprList *pEList, /* A result set */
88251  int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
88252  Expr *pExpr, /* Transform this into an alias to the result set */
88253  const char *zType, /* "GROUP" or "ORDER" or "" */
88254  int nSubquery /* Number of subqueries that the label is moving */
88255 ){
88256  Expr *pOrig; /* The iCol-th column of the result set */
88257  Expr *pDup; /* Copy of pOrig */
88258  sqlite3 *db; /* The database connection */
88259 
88260  assert( iCol>=0 && iCol<pEList->nExpr );
88261  pOrig = pEList->a[iCol].pExpr;
88262  assert( pOrig!=0 );
88263  db = pParse->db;
88264  pDup = sqlite3ExprDup(db, pOrig, 0);
88265  if( pDup==0 ) return;
88266  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
88267  if( pExpr->op==TK_COLLATE ){
88268  pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
88269  }
88270  ExprSetProperty(pDup, EP_Alias);
88271 
88272  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
88273  ** prevents ExprDelete() from deleting the Expr structure itself,
88274  ** allowing it to be repopulated by the memcpy() on the following line.
88275  ** The pExpr->u.zToken might point into memory that will be freed by the
88276  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
88277  ** make a copy of the token before doing the sqlite3DbFree().
88278  */
88279  ExprSetProperty(pExpr, EP_Static);
88280  sqlite3ExprDelete(db, pExpr);
88281  memcpy(pExpr, pDup, sizeof(*pExpr));
88282  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
88283  assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
88284  pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
88285  pExpr->flags |= EP_MemToken;
88286  }
88287  sqlite3DbFree(db, pDup);
88288 }
88289 
88290 
88291 /*
88292 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
88293 **
88294 ** Return FALSE if the USING clause is NULL or if it does not contain
88295 ** zCol.
88296 */
88297 static int nameInUsingClause(IdList *pUsing, const char *zCol){
88298  if( pUsing ){
88299  int k;
88300  for(k=0; k<pUsing->nId; k++){
88301  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
88302  }
88303  }
88304  return 0;
88305 }
88306 
88307 /*
88308 ** Subqueries stores the original database, table and column names for their
88309 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
88310 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
88311 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
88312 ** match anything.
88313 */
88315  const char *zSpan,
88316  const char *zCol,
88317  const char *zTab,
88318  const char *zDb
88319 ){
88320  int n;
88321  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88322  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
88323  return 0;
88324  }
88325  zSpan += n+1;
88326  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88327  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
88328  return 0;
88329  }
88330  zSpan += n+1;
88331  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
88332  return 0;
88333  }
88334  return 1;
88335 }
88336 
88337 /*
88338 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
88339 ** that name in the set of source tables in pSrcList and make the pExpr
88340 ** expression node refer back to that source column. The following changes
88341 ** are made to pExpr:
88342 **
88343 ** pExpr->iDb Set the index in db->aDb[] of the database X
88344 ** (even if X is implied).
88345 ** pExpr->iTable Set to the cursor number for the table obtained
88346 ** from pSrcList.
88347 ** pExpr->pTab Points to the Table structure of X.Y (even if
88348 ** X and/or Y are implied.)
88349 ** pExpr->iColumn Set to the column number within the table.
88350 ** pExpr->op Set to TK_COLUMN.
88351 ** pExpr->pLeft Any expression this points to is deleted
88352 ** pExpr->pRight Any expression this points to is deleted.
88353 **
88354 ** The zDb variable is the name of the database (the "X"). This value may be
88355 ** NULL meaning that name is of the form Y.Z or Z. Any available database
88356 ** can be used. The zTable variable is the name of the table (the "Y"). This
88357 ** value can be NULL if zDb is also NULL. If zTable is NULL it
88358 ** means that the form of the name is Z and that columns from any table
88359 ** can be used.
88360 **
88361 ** If the name cannot be resolved unambiguously, leave an error message
88362 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
88363 */
88364 static int lookupName(
88365  Parse *pParse, /* The parsing context */
88366  const char *zDb, /* Name of the database containing table, or NULL */
88367  const char *zTab, /* Name of table containing column, or NULL */
88368  const char *zCol, /* Name of the column. */
88369  NameContext *pNC, /* The name context used to resolve the name */
88370  Expr *pExpr /* Make this EXPR node point to the selected column */
88371 ){
88372  int i, j; /* Loop counters */
88373  int cnt = 0; /* Number of matching column names */
88374  int cntTab = 0; /* Number of matching table names */
88375  int nSubquery = 0; /* How many levels of subquery */
88376  sqlite3 *db = pParse->db; /* The database connection */
88377  struct SrcList_item *pItem; /* Use for looping over pSrcList items */
88378  struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
88379  NameContext *pTopNC = pNC; /* First namecontext in the list */
88380  Schema *pSchema = 0; /* Schema of the expression */
88381  int isTrigger = 0; /* True if resolved to a trigger column */
88382  Table *pTab = 0; /* Table hold the row */
88383  Column *pCol; /* A column of pTab */
88384 
88385  assert( pNC ); /* the name context cannot be NULL. */
88386  assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
88387  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
88388 
88389  /* Initialize the node to no-match */
88390  pExpr->iTable = -1;
88391  pExpr->pTab = 0;
88393 
88394  /* Translate the schema name in zDb into a pointer to the corresponding
88395  ** schema. If not found, pSchema will remain NULL and nothing will match
88396  ** resulting in an appropriate error message toward the end of this routine
88397  */
88398  if( zDb ){
88399  testcase( pNC->ncFlags & NC_PartIdx );
88400  testcase( pNC->ncFlags & NC_IsCheck );
88401  if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
88402  /* Silently ignore database qualifiers inside CHECK constraints and
88403  ** partial indices. Do not raise errors because that might break
88404  ** legacy and because it does not hurt anything to just ignore the
88405  ** database name. */
88406  zDb = 0;
88407  }else{
88408  for(i=0; i<db->nDb; i++){
88409  assert( db->aDb[i].zDbSName );
88410  if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
88411  pSchema = db->aDb[i].pSchema;
88412  break;
88413  }
88414  }
88415  }
88416  }
88417 
88418  /* Start at the inner-most context and move outward until a match is found */
88419  while( pNC && cnt==0 ){
88420  ExprList *pEList;
88421  SrcList *pSrcList = pNC->pSrcList;
88422 
88423  if( pSrcList ){
88424  for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
88425  pTab = pItem->pTab;
88426  assert( pTab!=0 && pTab->zName!=0 );
88427  assert( pTab->nCol>0 );
88428  if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
88429  int hit = 0;
88430  pEList = pItem->pSelect->pEList;
88431  for(j=0; j<pEList->nExpr; j++){
88432  if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
88433  cnt++;
88434  cntTab = 2;
88435  pMatch = pItem;
88436  pExpr->iColumn = j;
88437  hit = 1;
88438  }
88439  }
88440  if( hit || zTab==0 ) continue;
88441  }
88442  if( zDb && pTab->pSchema!=pSchema ){
88443  continue;
88444  }
88445  if( zTab ){
88446  const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
88447  assert( zTabName!=0 );
88448  if( sqlite3StrICmp(zTabName, zTab)!=0 ){
88449  continue;
88450  }
88451  }
88452  if( 0==(cntTab++) ){
88453  pMatch = pItem;
88454  }
88455  for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
88456  if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88457  /* If there has been exactly one prior match and this match
88458  ** is for the right-hand table of a NATURAL JOIN or is in a
88459  ** USING clause, then skip this match.
88460  */
88461  if( cnt==1 ){
88462  if( pItem->fg.jointype & JT_NATURAL ) continue;
88463  if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
88464  }
88465  cnt++;
88466  pMatch = pItem;
88467  /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
88468  pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
88469  break;
88470  }
88471  }
88472  }
88473  if( pMatch ){
88474  pExpr->iTable = pMatch->iCursor;
88475  pExpr->pTab = pMatch->pTab;
88476  /* RIGHT JOIN not (yet) supported */
88477  assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
88478  if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
88479  ExprSetProperty(pExpr, EP_CanBeNull);
88480  }
88481  pSchema = pExpr->pTab->pSchema;
88482  }
88483  } /* if( pSrcList ) */
88484 
88485 #ifndef SQLITE_OMIT_TRIGGER
88486  /* If we have not already resolved the name, then maybe
88487  ** it is a new.* or old.* trigger argument reference
88488  */
88489  if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
88490  int op = pParse->eTriggerOp;
88491  assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
88492  if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
88493  pExpr->iTable = 1;
88494  pTab = pParse->pTriggerTab;
88495  }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
88496  pExpr->iTable = 0;
88497  pTab = pParse->pTriggerTab;
88498  }else{
88499  pTab = 0;
88500  }
88501 
88502  if( pTab ){
88503  int iCol;
88504  pSchema = pTab->pSchema;
88505  cntTab++;
88506  for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
88507  if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88508  if( iCol==pTab->iPKey ){
88509  iCol = -1;
88510  }
88511  break;
88512  }
88513  }
88514  if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
88515  /* IMP: R-51414-32910 */
88516  iCol = -1;
88517  }
88518  if( iCol<pTab->nCol ){
88519  cnt++;
88520  if( iCol<0 ){
88521  pExpr->affinity = SQLITE_AFF_INTEGER;
88522  }else if( pExpr->iTable==0 ){
88523  testcase( iCol==31 );
88524  testcase( iCol==32 );
88525  pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88526  }else{
88527  testcase( iCol==31 );
88528  testcase( iCol==32 );
88529  pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88530  }
88531  pExpr->iColumn = (i16)iCol;
88532  pExpr->pTab = pTab;
88533  isTrigger = 1;
88534  }
88535  }
88536  }
88537 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
88538 
88539  /*
88540  ** Perhaps the name is a reference to the ROWID
88541  */
88542  if( cnt==0
88543  && cntTab==1
88544  && pMatch
88545  && (pNC->ncFlags & NC_IdxExpr)==0
88546  && sqlite3IsRowid(zCol)
88547  && VisibleRowid(pMatch->pTab)
88548  ){
88549  cnt = 1;
88550  pExpr->iColumn = -1;
88551  pExpr->affinity = SQLITE_AFF_INTEGER;
88552  }
88553 
88554  /*
88555  ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
88556  ** might refer to an result-set alias. This happens, for example, when
88557  ** we are resolving names in the WHERE clause of the following command:
88558  **
88559  ** SELECT a+b AS x FROM table WHERE x<10;
88560  **
88561  ** In cases like this, replace pExpr with a copy of the expression that
88562  ** forms the result set entry ("a+b" in the example) and return immediately.
88563  ** Note that the expression in the result set should have already been
88564  ** resolved by the time the WHERE clause is resolved.
88565  **
88566  ** The ability to use an output result-set column in the WHERE, GROUP BY,
88567  ** or HAVING clauses, or as part of a larger expression in the ORDER BY
88568  ** clause is not standard SQL. This is a (goofy) SQLite extension, that
88569  ** is supported for backwards compatibility only. Hence, we issue a warning
88570  ** on sqlite3_log() whenever the capability is used.
88571  */
88572  if( (pEList = pNC->pEList)!=0
88573  && zTab==0
88574  && cnt==0
88575  ){
88576  for(j=0; j<pEList->nExpr; j++){
88577  char *zAs = pEList->a[j].zName;
88578  if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88579  Expr *pOrig;
88580  assert( pExpr->pLeft==0 && pExpr->pRight==0 );
88581  assert( pExpr->x.pList==0 );
88582  assert( pExpr->x.pSelect==0 );
88583  pOrig = pEList->a[j].pExpr;
88584  if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
88585  sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
88586  return WRC_Abort;
88587  }
88588  if( sqlite3ExprVectorSize(pOrig)!=1 ){
88589  sqlite3ErrorMsg(pParse, "row value misused");
88590  return WRC_Abort;
88591  }
88592  resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
88593  cnt = 1;
88594  pMatch = 0;
88595  assert( zTab==0 && zDb==0 );
88596  goto lookupname_end;
88597  }
88598  }
88599  }
88600 
88601  /* Advance to the next name context. The loop will exit when either
88602  ** we have a match (cnt>0) or when we run out of name contexts.
88603  */
88604  if( cnt==0 ){
88605  pNC = pNC->pNext;
88606  nSubquery++;
88607  }
88608  }
88609 
88610  /*
88611  ** If X and Y are NULL (in other words if only the column name Z is
88612  ** supplied) and the value of Z is enclosed in double-quotes, then
88613  ** Z is a string literal if it doesn't match any column names. In that
88614  ** case, we need to return right away and not make any changes to
88615  ** pExpr.
88616  **
88617  ** Because no reference was made to outer contexts, the pNC->nRef
88618  ** fields are not changed in any context.
88619  */
88620  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
88621  pExpr->op = TK_STRING;
88622  pExpr->pTab = 0;
88623  return WRC_Prune;
88624  }
88625 
88626  /*
88627  ** cnt==0 means there was not match. cnt>1 means there were two or
88628  ** more matches. Either way, we have an error.
88629  */
88630  if( cnt!=1 ){
88631  const char *zErr;
88632  zErr = cnt==0 ? "no such column" : "ambiguous column name";
88633  if( zDb ){
88634  sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
88635  }else if( zTab ){
88636  sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
88637  }else{
88638  sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
88639  }
88640  pParse->checkSchema = 1;
88641  pTopNC->nErr++;
88642  }
88643 
88644  /* If a column from a table in pSrcList is referenced, then record
88645  ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
88646  ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
88647  ** column number is greater than the number of bits in the bitmask
88648  ** then set the high-order bit of the bitmask.
88649  */
88650  if( pExpr->iColumn>=0 && pMatch!=0 ){
88651  int n = pExpr->iColumn;
88652  testcase( n==BMS-1 );
88653  if( n>=BMS ){
88654  n = BMS-1;
88655  }
88656  assert( pMatch->iCursor==pExpr->iTable );
88657  pMatch->colUsed |= ((Bitmask)1)<<n;
88658  }
88659 
88660  /* Clean up and return
88661  */
88662  sqlite3ExprDelete(db, pExpr->pLeft);
88663  pExpr->pLeft = 0;
88664  sqlite3ExprDelete(db, pExpr->pRight);
88665  pExpr->pRight = 0;
88666  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
88667 lookupname_end:
88668  if( cnt==1 ){
88669  assert( pNC!=0 );
88670  if( !ExprHasProperty(pExpr, EP_Alias) ){
88671  sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
88672  }
88673  /* Increment the nRef value on all name contexts from TopNC up to
88674  ** the point where the name matched. */
88675  for(;;){
88676  assert( pTopNC!=0 );
88677  pTopNC->nRef++;
88678  if( pTopNC==pNC ) break;
88679  pTopNC = pTopNC->pNext;
88680  }
88681  return WRC_Prune;
88682  } else {
88683  return WRC_Abort;
88684  }
88685 }
88686 
88687 /*
88688 ** Allocate and return a pointer to an expression to load the column iCol
88689 ** from datasource iSrc in SrcList pSrc.
88690 */
88691 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
88692  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
88693  if( p ){
88694  struct SrcList_item *pItem = &pSrc->a[iSrc];
88695  p->pTab = pItem->pTab;
88696  p->iTable = pItem->iCursor;
88697  if( p->pTab->iPKey==iCol ){
88698  p->iColumn = -1;
88699  }else{
88700  p->iColumn = (ynVar)iCol;
88701  testcase( iCol==BMS );
88702  testcase( iCol==BMS-1 );
88703  pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
88704  }
88706  }
88707  return p;
88708 }
88709 
88710 /*
88711 ** Report an error that an expression is not valid for some set of
88712 ** pNC->ncFlags values determined by validMask.
88713 */
88714 static void notValid(
88715  Parse *pParse, /* Leave error message here */
88716  NameContext *pNC, /* The name context */
88717  const char *zMsg, /* Type of error */
88718  int validMask /* Set of contexts for which prohibited */
88719 ){
88720  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
88721  if( (pNC->ncFlags & validMask)!=0 ){
88722  const char *zIn = "partial index WHERE clauses";
88723  if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
88724 #ifndef SQLITE_OMIT_CHECK
88725  else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
88726 #endif
88727  sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
88728  }
88729 }
88730 
88731 /*
88732 ** Expression p should encode a floating point value between 1.0 and 0.0.
88733 ** Return 1024 times this value. Or return -1 if p is not a floating point
88734 ** value between 1.0 and 0.0.
88735 */
88736 static int exprProbability(Expr *p){
88737  double r = -1.0;
88738  if( p->op!=TK_FLOAT ) return -1;
88740  assert( r>=0.0 );
88741  if( r>1.0 ) return -1;
88742  return (int)(r*134217728.0);
88743 }
88744 
88745 /*
88746 ** This routine is callback for sqlite3WalkExpr().
88747 **
88748 ** Resolve symbolic names into TK_COLUMN operators for the current
88749 ** node in the expression tree. Return 0 to continue the search down
88750 ** the tree or 2 to abort the tree walk.
88751 **
88752 ** This routine also does error checking and name resolution for
88753 ** function names. The operator for aggregate functions is changed
88754 ** to TK_AGG_FUNCTION.
88755 */
88756 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
88757  NameContext *pNC;
88758  Parse *pParse;
88759 
88760  pNC = pWalker->u.pNC;
88761  assert( pNC!=0 );
88762  pParse = pNC->pParse;
88763  assert( pParse==pWalker->pParse );
88764 
88765  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
88766  ExprSetProperty(pExpr, EP_Resolved);
88767 #ifndef NDEBUG
88768  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
88769  SrcList *pSrcList = pNC->pSrcList;
88770  int i;
88771  for(i=0; i<pNC->pSrcList->nSrc; i++){
88772  assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
88773  }
88774  }
88775 #endif
88776  switch( pExpr->op ){
88777 
88778 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
88779  /* The special operator TK_ROW means use the rowid for the first
88780  ** column in the FROM clause. This is used by the LIMIT and ORDER BY
88781  ** clause processing on UPDATE and DELETE statements.
88782  */
88783  case TK_ROW: {
88784  SrcList *pSrcList = pNC->pSrcList;
88785  struct SrcList_item *pItem;
88786  assert( pSrcList && pSrcList->nSrc==1 );
88787  pItem = pSrcList->a;
88788  pExpr->op = TK_COLUMN;
88789  pExpr->pTab = pItem->pTab;
88790  pExpr->iTable = pItem->iCursor;
88791  pExpr->iColumn = -1;
88792  pExpr->affinity = SQLITE_AFF_INTEGER;
88793  break;
88794  }
88795 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
88796  && !defined(SQLITE_OMIT_SUBQUERY) */
88797 
88798  /* A lone identifier is the name of a column.
88799  */
88800  case TK_ID: {
88801  return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
88802  }
88803 
88804  /* A table name and column name: ID.ID
88805  ** Or a database, table and column: ID.ID.ID
88806  */
88807  case TK_DOT: {
88808  const char *zColumn;
88809  const char *zTable;
88810  const char *zDb;
88811  Expr *pRight;
88812 
88813  /* if( pSrcList==0 ) break; */
88814  notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
88815  pRight = pExpr->pRight;
88816  if( pRight->op==TK_ID ){
88817  zDb = 0;
88818  zTable = pExpr->pLeft->u.zToken;
88819  zColumn = pRight->u.zToken;
88820  }else{
88821  assert( pRight->op==TK_DOT );
88822  zDb = pExpr->pLeft->u.zToken;
88823  zTable = pRight->pLeft->u.zToken;
88824  zColumn = pRight->pRight->u.zToken;
88825  }
88826  return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
88827  }
88828 
88829  /* Resolve function names
88830  */
88831  case TK_FUNCTION: {
88832  ExprList *pList = pExpr->x.pList; /* The argument list */
88833  int n = pList ? pList->nExpr : 0; /* Number of arguments */
88834  int no_such_func = 0; /* True if no such function exists */
88835  int wrong_num_args = 0; /* True if wrong number of arguments */
88836  int is_agg = 0; /* True if is an aggregate function */
88837  int nId; /* Number of characters in function name */
88838  const char *zId; /* The function name. */
88839  FuncDef *pDef; /* Information about the function */
88840  u8 enc = ENC(pParse->db); /* The database encoding */
88841 
88842  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88843  zId = pExpr->u.zToken;
88844  nId = sqlite3Strlen30(zId);
88845  pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
88846  if( pDef==0 ){
88847  pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
88848  if( pDef==0 ){
88849  no_such_func = 1;
88850  }else{
88851  wrong_num_args = 1;
88852  }
88853  }else{
88854  is_agg = pDef->xFinalize!=0;
88855  if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
88857  if( n==2 ){
88858  pExpr->iTable = exprProbability(pList->a[1].pExpr);
88859  if( pExpr->iTable<0 ){
88860  sqlite3ErrorMsg(pParse,
88861  "second argument to likelihood() must be a "
88862  "constant between 0.0 and 1.0");
88863  pNC->nErr++;
88864  }
88865  }else{
88866  /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
88867  ** equivalent to likelihood(X, 0.0625).
88868  ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
88869  ** short-hand for likelihood(X,0.0625).
88870  ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
88871  ** for likelihood(X,0.9375).
88872  ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
88873  ** to likelihood(X,0.9375). */
88874  /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
88875  pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
88876  }
88877  }
88878 #ifndef SQLITE_OMIT_AUTHORIZATION
88879  {
88880  int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
88881  if( auth!=SQLITE_OK ){
88882  if( auth==SQLITE_DENY ){
88883  sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
88884  pDef->zName);
88885  pNC->nErr++;
88886  }
88887  pExpr->op = TK_NULL;
88888  return WRC_Prune;
88889  }
88890  }
88891 #endif
88893  /* For the purposes of the EP_ConstFunc flag, date and time
88894  ** functions and other functions that change slowly are considered
88895  ** constant because they are constant for the duration of one query */
88897  }
88898  if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
88899  /* Date/time functions that use 'now', and other functions like
88900  ** sqlite_version() that might change over time cannot be used
88901  ** in an index. */
88902  notValid(pParse, pNC, "non-deterministic functions",
88904  }
88905  }
88906  if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
88907  sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
88908  pNC->nErr++;
88909  is_agg = 0;
88910  }else if( no_such_func && pParse->db->init.busy==0
88911 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
88912  && pParse->explain==0
88913 #endif
88914  ){
88915  sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
88916  pNC->nErr++;
88917  }else if( wrong_num_args ){
88918  sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
88919  nId, zId);
88920  pNC->nErr++;
88921  }
88922  if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
88923  sqlite3WalkExprList(pWalker, pList);
88924  if( is_agg ){
88925  NameContext *pNC2 = pNC;
88926  pExpr->op = TK_AGG_FUNCTION;
88927  pExpr->op2 = 0;
88928  while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
88929  pExpr->op2++;
88930  pNC2 = pNC2->pNext;
88931  }
88932  assert( pDef!=0 );
88933  if( pNC2 ){
88934  assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
88935  testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
88936  pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
88937 
88938  }
88939  pNC->ncFlags |= NC_AllowAgg;
88940  }
88941  /* FIX ME: Compute pExpr->affinity based on the expected return
88942  ** type of the function
88943  */
88944  return WRC_Prune;
88945  }
88946 #ifndef SQLITE_OMIT_SUBQUERY
88947  case TK_SELECT:
88948  case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
88949 #endif
88950  case TK_IN: {
88951  testcase( pExpr->op==TK_IN );
88952  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88953  int nRef = pNC->nRef;
88954  notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88955  sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
88956  assert( pNC->nRef>=nRef );
88957  if( nRef!=pNC->nRef ){
88958  ExprSetProperty(pExpr, EP_VarSelect);
88959  pNC->ncFlags |= NC_VarSelect;
88960  }
88961  }
88962  break;
88963  }
88964  case TK_VARIABLE: {
88965  notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88966  break;
88967  }
88968  case TK_BETWEEN:
88969  case TK_EQ:
88970  case TK_NE:
88971  case TK_LT:
88972  case TK_LE:
88973  case TK_GT:
88974  case TK_GE:
88975  case TK_IS:
88976  case TK_ISNOT: {
88977  int nLeft, nRight;
88978  if( pParse->db->mallocFailed ) break;
88979  assert( pExpr->pLeft!=0 );
88980  nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
88981  if( pExpr->op==TK_BETWEEN ){
88982  nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
88983  if( nRight==nLeft ){
88984  nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
88985  }
88986  }else{
88987  assert( pExpr->pRight!=0 );
88988  nRight = sqlite3ExprVectorSize(pExpr->pRight);
88989  }
88990  if( nLeft!=nRight ){
88991  testcase( pExpr->op==TK_EQ );
88992  testcase( pExpr->op==TK_NE );
88993  testcase( pExpr->op==TK_LT );
88994  testcase( pExpr->op==TK_LE );
88995  testcase( pExpr->op==TK_GT );
88996  testcase( pExpr->op==TK_GE );
88997  testcase( pExpr->op==TK_IS );
88998  testcase( pExpr->op==TK_ISNOT );
88999  testcase( pExpr->op==TK_BETWEEN );
89000  sqlite3ErrorMsg(pParse, "row value misused");
89001  }
89002  break;
89003  }
89004  }
89005  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
89006 }
89007 
89008 /*
89009 ** pEList is a list of expressions which are really the result set of the
89010 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
89011 ** This routine checks to see if pE is a simple identifier which corresponds
89012 ** to the AS-name of one of the terms of the expression list. If it is,
89013 ** this routine return an integer between 1 and N where N is the number of
89014 ** elements in pEList, corresponding to the matching entry. If there is
89015 ** no match, or if pE is not a simple identifier, then this routine
89016 ** return 0.
89017 **
89018 ** pEList has been resolved. pE has not.
89019 */
89020 static int resolveAsName(
89021  Parse *pParse, /* Parsing context for error messages */
89022  ExprList *pEList, /* List of expressions to scan */
89023  Expr *pE /* Expression we are trying to match */
89024 ){
89025  int i; /* Loop counter */
89026 
89027  UNUSED_PARAMETER(pParse);
89028 
89029  if( pE->op==TK_ID ){
89030  char *zCol = pE->u.zToken;
89031  for(i=0; i<pEList->nExpr; i++){
89032  char *zAs = pEList->a[i].zName;
89033  if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
89034  return i+1;
89035  }
89036  }
89037  }
89038  return 0;
89039 }
89040 
89041 /*
89042 ** pE is a pointer to an expression which is a single term in the
89043 ** ORDER BY of a compound SELECT. The expression has not been
89044 ** name resolved.
89045 **
89046 ** At the point this routine is called, we already know that the
89047 ** ORDER BY term is not an integer index into the result set. That
89048 ** case is handled by the calling routine.
89049 **
89050 ** Attempt to match pE against result set columns in the left-most
89051 ** SELECT statement. Return the index i of the matching column,
89052 ** as an indication to the caller that it should sort by the i-th column.
89053 ** The left-most column is 1. In other words, the value returned is the
89054 ** same integer value that would be used in the SQL statement to indicate
89055 ** the column.
89056 **
89057 ** If there is no match, return 0. Return -1 if an error occurs.
89058 */
89060  Parse *pParse, /* Parsing context for error messages */
89061  Select *pSelect, /* The SELECT statement with the ORDER BY clause */
89062  Expr *pE /* The specific ORDER BY term */
89063 ){
89064  int i; /* Loop counter */
89065  ExprList *pEList; /* The columns of the result set */
89066  NameContext nc; /* Name context for resolving pE */
89067  sqlite3 *db; /* Database connection */
89068  int rc; /* Return code from subprocedures */
89069  u8 savedSuppErr; /* Saved value of db->suppressErr */
89070 
89071  assert( sqlite3ExprIsInteger(pE, &i)==0 );
89072  pEList = pSelect->pEList;
89073 
89074  /* Resolve all names in the ORDER BY term expression
89075  */
89076  memset(&nc, 0, sizeof(nc));
89077  nc.pParse = pParse;
89078  nc.pSrcList = pSelect->pSrc;
89079  nc.pEList = pEList;
89080  nc.ncFlags = NC_AllowAgg;
89081  nc.nErr = 0;
89082  db = pParse->db;
89083  savedSuppErr = db->suppressErr;
89084  db->suppressErr = 1;
89085  rc = sqlite3ResolveExprNames(&nc, pE);
89086  db->suppressErr = savedSuppErr;
89087  if( rc ) return 0;
89088 
89089  /* Try to match the ORDER BY expression against an expression
89090  ** in the result set. Return an 1-based index of the matching
89091  ** result-set entry.
89092  */
89093  for(i=0; i<pEList->nExpr; i++){
89094  if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
89095  return i+1;
89096  }
89097  }
89098 
89099  /* If no match, return 0. */
89100  return 0;
89101 }
89102 
89103 /*
89104 ** Generate an ORDER BY or GROUP BY term out-of-range error.
89105 */
89107  Parse *pParse, /* The error context into which to write the error */
89108  const char *zType, /* "ORDER" or "GROUP" */
89109  int i, /* The index (1-based) of the term out of range */
89110  int mx /* Largest permissible value of i */
89111 ){
89112  sqlite3ErrorMsg(pParse,
89113  "%r %s BY term out of range - should be "
89114  "between 1 and %d", i, zType, mx);
89115 }
89116 
89117 /*
89118 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
89119 ** each term of the ORDER BY clause is a constant integer between 1
89120 ** and N where N is the number of columns in the compound SELECT.
89121 **
89122 ** ORDER BY terms that are already an integer between 1 and N are
89123 ** unmodified. ORDER BY terms that are integers outside the range of
89124 ** 1 through N generate an error. ORDER BY terms that are expressions
89125 ** are matched against result set expressions of compound SELECT
89126 ** beginning with the left-most SELECT and working toward the right.
89127 ** At the first match, the ORDER BY expression is transformed into
89128 ** the integer column number.
89129 **
89130 ** Return the number of errors seen.
89131 */
89133  Parse *pParse, /* Parsing context. Leave error messages here */
89134  Select *pSelect /* The SELECT statement containing the ORDER BY */
89135 ){
89136  int i;
89137  ExprList *pOrderBy;
89138  ExprList *pEList;
89139  sqlite3 *db;
89140  int moreToDo = 1;
89141 
89142  pOrderBy = pSelect->pOrderBy;
89143  if( pOrderBy==0 ) return 0;
89144  db = pParse->db;
89145 #if SQLITE_MAX_COLUMN
89146  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89147  sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
89148  return 1;
89149  }
89150 #endif
89151  for(i=0; i<pOrderBy->nExpr; i++){
89152  pOrderBy->a[i].done = 0;
89153  }
89154  pSelect->pNext = 0;
89155  while( pSelect->pPrior ){
89156  pSelect->pPrior->pNext = pSelect;
89157  pSelect = pSelect->pPrior;
89158  }
89159  while( pSelect && moreToDo ){
89160  struct ExprList_item *pItem;
89161  moreToDo = 0;
89162  pEList = pSelect->pEList;
89163  assert( pEList!=0 );
89164  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89165  int iCol = -1;
89166  Expr *pE, *pDup;
89167  if( pItem->done ) continue;
89168  pE = sqlite3ExprSkipCollate(pItem->pExpr);
89169  if( sqlite3ExprIsInteger(pE, &iCol) ){
89170  if( iCol<=0 || iCol>pEList->nExpr ){
89171  resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
89172  return 1;
89173  }
89174  }else{
89175  iCol = resolveAsName(pParse, pEList, pE);
89176  if( iCol==0 ){
89177  pDup = sqlite3ExprDup(db, pE, 0);
89178  if( !db->mallocFailed ){
89179  assert(pDup);
89180  iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
89181  }
89182  sqlite3ExprDelete(db, pDup);
89183  }
89184  }
89185  if( iCol>0 ){
89186  /* Convert the ORDER BY term into an integer column number iCol,
89187  ** taking care to preserve the COLLATE clause if it exists */
89188  Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
89189  if( pNew==0 ) return 1;
89190  pNew->flags |= EP_IntValue;
89191  pNew->u.iValue = iCol;
89192  if( pItem->pExpr==pE ){
89193  pItem->pExpr = pNew;
89194  }else{
89195  Expr *pParent = pItem->pExpr;
89196  assert( pParent->op==TK_COLLATE );
89197  while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
89198  assert( pParent->pLeft==pE );
89199  pParent->pLeft = pNew;
89200  }
89201  sqlite3ExprDelete(db, pE);
89202  pItem->u.x.iOrderByCol = (u16)iCol;
89203  pItem->done = 1;
89204  }else{
89205  moreToDo = 1;
89206  }
89207  }
89208  pSelect = pSelect->pNext;
89209  }
89210  for(i=0; i<pOrderBy->nExpr; i++){
89211  if( pOrderBy->a[i].done==0 ){
89212  sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
89213  "column in the result set", i+1);
89214  return 1;
89215  }
89216  }
89217  return 0;
89218 }
89219 
89220 /*
89221 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
89222 ** the SELECT statement pSelect. If any term is reference to a
89223 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
89224 ** field) then convert that term into a copy of the corresponding result set
89225 ** column.
89226 **
89227 ** If any errors are detected, add an error message to pParse and
89228 ** return non-zero. Return zero if no errors are seen.
89229 */
89231  Parse *pParse, /* Parsing context. Leave error messages here */
89232  Select *pSelect, /* The SELECT statement containing the clause */
89233  ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
89234  const char *zType /* "ORDER" or "GROUP" */
89235 ){
89236  int i;
89237  sqlite3 *db = pParse->db;
89238  ExprList *pEList;
89239  struct ExprList_item *pItem;
89240 
89241  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
89242 #if SQLITE_MAX_COLUMN
89243  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
89244  sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
89245  return 1;
89246  }
89247 #endif
89248  pEList = pSelect->pEList;
89249  assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
89250  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89251  if( pItem->u.x.iOrderByCol ){
89252  if( pItem->u.x.iOrderByCol>pEList->nExpr ){
89253  resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
89254  return 1;
89255  }
89256  resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
89257  zType,0);
89258  }
89259  }
89260  return 0;
89261 }
89262 
89263 /*
89264 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
89265 ** The Name context of the SELECT statement is pNC. zType is either
89266 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
89267 **
89268 ** This routine resolves each term of the clause into an expression.
89269 ** If the order-by term is an integer I between 1 and N (where N is the
89270 ** number of columns in the result set of the SELECT) then the expression
89271 ** in the resolution is a copy of the I-th result-set expression. If
89272 ** the order-by term is an identifier that corresponds to the AS-name of
89273 ** a result-set expression, then the term resolves to a copy of the
89274 ** result-set expression. Otherwise, the expression is resolved in
89275 ** the usual way - using sqlite3ResolveExprNames().
89276 **
89277 ** This routine returns the number of errors. If errors occur, then
89278 ** an appropriate error message might be left in pParse. (OOM errors
89279 ** excepted.)
89280 */
89282  NameContext *pNC, /* The name context of the SELECT statement */
89283  Select *pSelect, /* The SELECT statement holding pOrderBy */
89284  ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
89285  const char *zType /* Either "ORDER" or "GROUP", as appropriate */
89286 ){
89287  int i, j; /* Loop counters */
89288  int iCol; /* Column number */
89289  struct ExprList_item *pItem; /* A term of the ORDER BY clause */
89290  Parse *pParse; /* Parsing context */
89291  int nResult; /* Number of terms in the result set */
89292 
89293  if( pOrderBy==0 ) return 0;
89294  nResult = pSelect->pEList->nExpr;
89295  pParse = pNC->pParse;
89296  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89297  Expr *pE = pItem->pExpr;
89298  Expr *pE2 = sqlite3ExprSkipCollate(pE);
89299  if( zType[0]!='G' ){
89300  iCol = resolveAsName(pParse, pSelect->pEList, pE2);
89301  if( iCol>0 ){
89302  /* If an AS-name match is found, mark this ORDER BY column as being
89303  ** a copy of the iCol-th result-set column. The subsequent call to
89304  ** sqlite3ResolveOrderGroupBy() will convert the expression to a
89305  ** copy of the iCol-th result-set expression. */
89306  pItem->u.x.iOrderByCol = (u16)iCol;
89307  continue;
89308  }
89309  }
89310  if( sqlite3ExprIsInteger(pE2, &iCol) ){
89311  /* The ORDER BY term is an integer constant. Again, set the column
89312  ** number so that sqlite3ResolveOrderGroupBy() will convert the
89313  ** order-by term to a copy of the result-set expression */
89314  if( iCol<1 || iCol>0xffff ){
89315  resolveOutOfRangeError(pParse, zType, i+1, nResult);
89316  return 1;
89317  }
89318  pItem->u.x.iOrderByCol = (u16)iCol;
89319  continue;
89320  }
89321 
89322  /* Otherwise, treat the ORDER BY term as an ordinary expression */
89323  pItem->u.x.iOrderByCol = 0;
89324  if( sqlite3ResolveExprNames(pNC, pE) ){
89325  return 1;
89326  }
89327  for(j=0; j<pSelect->pEList->nExpr; j++){
89328  if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
89329  pItem->u.x.iOrderByCol = j+1;
89330  }
89331  }
89332  }
89333  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
89334 }
89335 
89336 /*
89337 ** Resolve names in the SELECT statement p and all of its descendants.
89338 */
89339 static int resolveSelectStep(Walker *pWalker, Select *p){
89340  NameContext *pOuterNC; /* Context that contains this SELECT */
89341  NameContext sNC; /* Name context of this SELECT */
89342  int isCompound; /* True if p is a compound select */
89343  int nCompound; /* Number of compound terms processed so far */
89344  Parse *pParse; /* Parsing context */
89345  int i; /* Loop counter */
89346  ExprList *pGroupBy; /* The GROUP BY clause */
89347  Select *pLeftmost; /* Left-most of SELECT of a compound */
89348  sqlite3 *db; /* Database connection */
89349 
89350 
89351  assert( p!=0 );
89352  if( p->selFlags & SF_Resolved ){
89353  return WRC_Prune;
89354  }
89355  pOuterNC = pWalker->u.pNC;
89356  pParse = pWalker->pParse;
89357  db = pParse->db;
89358 
89359  /* Normally sqlite3SelectExpand() will be called first and will have
89360  ** already expanded this SELECT. However, if this is a subquery within
89361  ** an expression, sqlite3ResolveExprNames() will be called without a
89362  ** prior call to sqlite3SelectExpand(). When that happens, let
89363  ** sqlite3SelectPrep() do all of the processing for this SELECT.
89364  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
89365  ** this routine in the correct order.
89366  */
89367  if( (p->selFlags & SF_Expanded)==0 ){
89368  sqlite3SelectPrep(pParse, p, pOuterNC);
89369  return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
89370  }
89371 
89372  isCompound = p->pPrior!=0;
89373  nCompound = 0;
89374  pLeftmost = p;
89375  while( p ){
89376  assert( (p->selFlags & SF_Expanded)!=0 );
89377  assert( (p->selFlags & SF_Resolved)==0 );
89378  p->selFlags |= SF_Resolved;
89379 
89380  /* Resolve the expressions in the LIMIT and OFFSET clauses. These
89381  ** are not allowed to refer to any names, so pass an empty NameContext.
89382  */
89383  memset(&sNC, 0, sizeof(sNC));
89384  sNC.pParse = pParse;
89385  if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
89386  sqlite3ResolveExprNames(&sNC, p->pOffset) ){
89387  return WRC_Abort;
89388  }
89389 
89390  /* If the SF_Converted flags is set, then this Select object was
89391  ** was created by the convertCompoundSelectToSubquery() function.
89392  ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
89393  ** as if it were part of the sub-query, not the parent. This block
89394  ** moves the pOrderBy down to the sub-query. It will be moved back
89395  ** after the names have been resolved. */
89396  if( p->selFlags & SF_Converted ){
89397  Select *pSub = p->pSrc->a[0].pSelect;
89398  assert( p->pSrc->nSrc==1 && p->pOrderBy );
89399  assert( pSub->pPrior && pSub->pOrderBy==0 );
89400  pSub->pOrderBy = p->pOrderBy;
89401  p->pOrderBy = 0;
89402  }
89403 
89404  /* Recursively resolve names in all subqueries
89405  */
89406  for(i=0; i<p->pSrc->nSrc; i++){
89407  struct SrcList_item *pItem = &p->pSrc->a[i];
89408  if( pItem->pSelect ){
89409  NameContext *pNC; /* Used to iterate name contexts */
89410  int nRef = 0; /* Refcount for pOuterNC and outer contexts */
89411  const char *zSavedContext = pParse->zAuthContext;
89412 
89413  /* Count the total number of references to pOuterNC and all of its
89414  ** parent contexts. After resolving references to expressions in
89415  ** pItem->pSelect, check if this value has changed. If so, then
89416  ** SELECT statement pItem->pSelect must be correlated. Set the
89417  ** pItem->fg.isCorrelated flag if this is the case. */
89418  for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
89419 
89420  if( pItem->zName ) pParse->zAuthContext = pItem->zName;
89421  sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
89422  pParse->zAuthContext = zSavedContext;
89423  if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
89424 
89425  for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
89426  assert( pItem->fg.isCorrelated==0 && nRef<=0 );
89427  pItem->fg.isCorrelated = (nRef!=0);
89428  }
89429  }
89430 
89431  /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
89432  ** resolve the result-set expression list.
89433  */
89434  sNC.ncFlags = NC_AllowAgg;
89435  sNC.pSrcList = p->pSrc;
89436  sNC.pNext = pOuterNC;
89437 
89438  /* Resolve names in the result set. */
89439  if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
89440 
89441  /* If there are no aggregate functions in the result-set, and no GROUP BY
89442  ** expression, do not allow aggregates in any of the other expressions.
89443  */
89444  assert( (p->selFlags & SF_Aggregate)==0 );
89445  pGroupBy = p->pGroupBy;
89446  if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
89447  assert( NC_MinMaxAgg==SF_MinMaxAgg );
89448  p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
89449  }else{
89450  sNC.ncFlags &= ~NC_AllowAgg;
89451  }
89452 
89453  /* If a HAVING clause is present, then there must be a GROUP BY clause.
89454  */
89455  if( p->pHaving && !pGroupBy ){
89456  sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
89457  return WRC_Abort;
89458  }
89459 
89460  /* Add the output column list to the name-context before parsing the
89461  ** other expressions in the SELECT statement. This is so that
89462  ** expressions in the WHERE clause (etc.) can refer to expressions by
89463  ** aliases in the result set.
89464  **
89465  ** Minor point: If this is the case, then the expression will be
89466  ** re-evaluated for each reference to it.
89467  */
89468  sNC.pEList = p->pEList;
89469  if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
89470  if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
89471 
89472  /* Resolve names in table-valued-function arguments */
89473  for(i=0; i<p->pSrc->nSrc; i++){
89474  struct SrcList_item *pItem = &p->pSrc->a[i];
89475  if( pItem->fg.isTabFunc
89476  && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
89477  ){
89478  return WRC_Abort;
89479  }
89480  }
89481 
89482  /* The ORDER BY and GROUP BY clauses may not refer to terms in
89483  ** outer queries
89484  */
89485  sNC.pNext = 0;
89486  sNC.ncFlags |= NC_AllowAgg;
89487 
89488  /* If this is a converted compound query, move the ORDER BY clause from
89489  ** the sub-query back to the parent query. At this point each term
89490  ** within the ORDER BY clause has been transformed to an integer value.
89491  ** These integers will be replaced by copies of the corresponding result
89492  ** set expressions by the call to resolveOrderGroupBy() below. */
89493  if( p->selFlags & SF_Converted ){
89494  Select *pSub = p->pSrc->a[0].pSelect;
89495  p->pOrderBy = pSub->pOrderBy;
89496  pSub->pOrderBy = 0;
89497  }
89498 
89499  /* Process the ORDER BY clause for singleton SELECT statements.
89500  ** The ORDER BY clause for compounds SELECT statements is handled
89501  ** below, after all of the result-sets for all of the elements of
89502  ** the compound have been resolved.
89503  **
89504  ** If there is an ORDER BY clause on a term of a compound-select other
89505  ** than the right-most term, then that is a syntax error. But the error
89506  ** is not detected until much later, and so we need to go ahead and
89507  ** resolve those symbols on the incorrect ORDER BY for consistency.
89508  */
89509  if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
89510  && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
89511  ){
89512  return WRC_Abort;
89513  }
89514  if( db->mallocFailed ){
89515  return WRC_Abort;
89516  }
89517 
89518  /* Resolve the GROUP BY clause. At the same time, make sure
89519  ** the GROUP BY clause does not contain aggregate functions.
89520  */
89521  if( pGroupBy ){
89522  struct ExprList_item *pItem;
89523 
89524  if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
89525  return WRC_Abort;
89526  }
89527  for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
89528  if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
89529  sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
89530  "the GROUP BY clause");
89531  return WRC_Abort;
89532  }
89533  }
89534  }
89535 
89536  /* If this is part of a compound SELECT, check that it has the right
89537  ** number of expressions in the select list. */
89538  if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
89540  return WRC_Abort;
89541  }
89542 
89543  /* Advance to the next term of the compound
89544  */
89545  p = p->pPrior;
89546  nCompound++;
89547  }
89548 
89549  /* Resolve the ORDER BY on a compound SELECT after all terms of
89550  ** the compound have been resolved.
89551  */
89552  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
89553  return WRC_Abort;
89554  }
89555 
89556  return WRC_Prune;
89557 }
89558 
89559 /*
89560 ** This routine walks an expression tree and resolves references to
89561 ** table columns and result-set columns. At the same time, do error
89562 ** checking on function usage and set a flag if any aggregate functions
89563 ** are seen.
89564 **
89565 ** To resolve table columns references we look for nodes (or subtrees) of the
89566 ** form X.Y.Z or Y.Z or just Z where
89567 **
89568 ** X: The name of a database. Ex: "main" or "temp" or
89569 ** the symbolic name assigned to an ATTACH-ed database.
89570 **
89571 ** Y: The name of a table in a FROM clause. Or in a trigger
89572 ** one of the special names "old" or "new".
89573 **
89574 ** Z: The name of a column in table Y.
89575 **
89576 ** The node at the root of the subtree is modified as follows:
89577 **
89578 ** Expr.op Changed to TK_COLUMN
89579 ** Expr.pTab Points to the Table object for X.Y
89580 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
89581 ** Expr.iTable The VDBE cursor number for X.Y
89582 **
89583 **
89584 ** To resolve result-set references, look for expression nodes of the
89585 ** form Z (with no X and Y prefix) where the Z matches the right-hand
89586 ** size of an AS clause in the result-set of a SELECT. The Z expression
89587 ** is replaced by a copy of the left-hand side of the result-set expression.
89588 ** Table-name and function resolution occurs on the substituted expression
89589 ** tree. For example, in:
89590 **
89591 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
89592 **
89593 ** The "x" term of the order by is replaced by "a+b" to render:
89594 **
89595 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
89596 **
89597 ** Function calls are checked to make sure that the function is
89598 ** defined and that the correct number of arguments are specified.
89599 ** If the function is an aggregate function, then the NC_HasAgg flag is
89600 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
89601 ** If an expression contains aggregate functions then the EP_Agg
89602 ** property on the expression is set.
89603 **
89604 ** An error message is left in pParse if anything is amiss. The number
89605 ** if errors is returned.
89606 */
89608  NameContext *pNC, /* Namespace to resolve expressions in. */
89609  Expr *pExpr /* The expression to be analyzed. */
89610 ){
89611  u16 savedHasAgg;
89612  Walker w;
89613 
89614  if( pExpr==0 ) return 0;
89615 #if SQLITE_MAX_EXPR_DEPTH>0
89616  {
89617  Parse *pParse = pNC->pParse;
89618  if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
89619  return 1;
89620  }
89621  pParse->nHeight += pExpr->nHeight;
89622  }
89623 #endif
89624  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
89625  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
89626  w.pParse = pNC->pParse;
89629  w.xSelectCallback2 = 0;
89630  w.walkerDepth = 0;
89631  w.eCode = 0;
89632  w.u.pNC = pNC;
89633  sqlite3WalkExpr(&w, pExpr);
89634 #if SQLITE_MAX_EXPR_DEPTH>0
89635  pNC->pParse->nHeight -= pExpr->nHeight;
89636 #endif
89637  if( pNC->nErr>0 || w.pParse->nErr>0 ){
89638  ExprSetProperty(pExpr, EP_Error);
89639  }
89640  if( pNC->ncFlags & NC_HasAgg ){
89641  ExprSetProperty(pExpr, EP_Agg);
89642  }
89643  pNC->ncFlags |= savedHasAgg;
89644  return ExprHasProperty(pExpr, EP_Error);
89645 }
89646 
89647 /*
89648 ** Resolve all names for all expression in an expression list. This is
89649 ** just like sqlite3ResolveExprNames() except that it works for an expression
89650 ** list rather than a single expression.
89651 */
89653  NameContext *pNC, /* Namespace to resolve expressions in. */
89654  ExprList *pList /* The expression list to be analyzed. */
89655 ){
89656  int i;
89657  if( pList ){
89658  for(i=0; i<pList->nExpr; i++){
89659  if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
89660  }
89661  }
89662  return WRC_Continue;
89663 }
89664 
89665 /*
89666 ** Resolve all names in all expressions of a SELECT and in all
89667 ** decendents of the SELECT, including compounds off of p->pPrior,
89668 ** subqueries in expressions, and subqueries used as FROM clause
89669 ** terms.
89670 **
89671 ** See sqlite3ResolveExprNames() for a description of the kinds of
89672 ** transformations that occur.
89673 **
89674 ** All SELECT statements should have been expanded using
89675 ** sqlite3SelectExpand() prior to invoking this routine.
89676 */
89678  Parse *pParse, /* The parser context */
89679  Select *p, /* The SELECT statement being coded. */
89680  NameContext *pOuterNC /* Name context for parent SELECT statement */
89681 ){
89682  Walker w;
89683 
89684  assert( p!=0 );
89685  memset(&w, 0, sizeof(w));
89688  w.pParse = pParse;
89689  w.u.pNC = pOuterNC;
89690  sqlite3WalkSelect(&w, p);
89691 }
89692 
89693 /*
89694 ** Resolve names in expressions that can only reference a single table:
89695 **
89696 ** * CHECK constraints
89697 ** * WHERE clauses on partial indices
89698 **
89699 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
89700 ** is set to -1 and the Expr.iColumn value is set to the column number.
89701 **
89702 ** Any errors cause an error message to be set in pParse.
89703 */
89705  Parse *pParse, /* Parsing context */
89706  Table *pTab, /* The table being referenced */
89707  int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
89708  Expr *pExpr, /* Expression to resolve. May be NULL. */
89709  ExprList *pList /* Expression list to resolve. May be NUL. */
89710 ){
89711  SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
89712  NameContext sNC; /* Name context for pParse->pNewTable */
89713 
89714  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
89715  memset(&sNC, 0, sizeof(sNC));
89716  memset(&sSrc, 0, sizeof(sSrc));
89717  sSrc.nSrc = 1;
89718  sSrc.a[0].zName = pTab->zName;
89719  sSrc.a[0].pTab = pTab;
89720  sSrc.a[0].iCursor = -1;
89721  sNC.pParse = pParse;
89722  sNC.pSrcList = &sSrc;
89723  sNC.ncFlags = type;
89724  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
89725  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
89726 }
89727 
89728 /************** End of resolve.c *********************************************/
89729 /************** Begin file expr.c ********************************************/
89730 /*
89731 ** 2001 September 15
89732 **
89733 ** The author disclaims copyright to this source code. In place of
89734 ** a legal notice, here is a blessing:
89735 **
89736 ** May you do good and not evil.
89737 ** May you find forgiveness for yourself and forgive others.
89738 ** May you share freely, never taking more than you give.
89739 **
89740 *************************************************************************
89741 ** This file contains routines used for analyzing expressions and
89742 ** for generating VDBE code that evaluates expressions in SQLite.
89743 */
89744 /* #include "sqliteInt.h" */
89745 
89746 /* Forward declarations */
89747 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
89748 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
89749 
89750 /*
89751 ** Return the affinity character for a single column of a table.
89752 */
89754  assert( iCol<pTab->nCol );
89755  return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
89756 }
89757 
89758 /*
89759 ** Return the 'affinity' of the expression pExpr if any.
89760 **
89761 ** If pExpr is a column, a reference to a column via an 'AS' alias,
89762 ** or a sub-select with a column as the return value, then the
89763 ** affinity of that column is returned. Otherwise, 0x00 is returned,
89764 ** indicating no affinity for the expression.
89765 **
89766 ** i.e. the WHERE clause expressions in the following statements all
89767 ** have an affinity:
89768 **
89769 ** CREATE TABLE t1(a);
89770 ** SELECT * FROM t1 WHERE a;
89771 ** SELECT a AS b FROM t1 WHERE b;
89772 ** SELECT * FROM t1 WHERE (select a from t1);
89773 */
89775  int op;
89776  pExpr = sqlite3ExprSkipCollate(pExpr);
89777  if( pExpr->flags & EP_Generic ) return 0;
89778  op = pExpr->op;
89779  if( op==TK_SELECT ){
89780  assert( pExpr->flags&EP_xIsSelect );
89781  return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
89782  }
89783  if( op==TK_REGISTER ) op = pExpr->op2;
89784 #ifndef SQLITE_OMIT_CAST
89785  if( op==TK_CAST ){
89786  assert( !ExprHasProperty(pExpr, EP_IntValue) );
89787  return sqlite3AffinityType(pExpr->u.zToken, 0);
89788  }
89789 #endif
89790  if( op==TK_AGG_COLUMN || op==TK_COLUMN ){
89791  return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
89792  }
89793  if( op==TK_SELECT_COLUMN ){
89794  assert( pExpr->pLeft->flags&EP_xIsSelect );
89795  return sqlite3ExprAffinity(
89796  pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
89797  );
89798  }
89799  return pExpr->affinity;
89800 }
89801 
89802 /*
89803 ** Set the collating sequence for expression pExpr to be the collating
89804 ** sequence named by pToken. Return a pointer to a new Expr node that
89805 ** implements the COLLATE operator.
89806 **
89807 ** If a memory allocation error occurs, that fact is recorded in pParse->db
89808 ** and the pExpr parameter is returned unchanged.
89809 */
89811  Parse *pParse, /* Parsing context */
89812  Expr *pExpr, /* Add the "COLLATE" clause to this expression */
89813  const Token *pCollName, /* Name of collating sequence */
89814  int dequote /* True to dequote pCollName */
89815 ){
89816  if( pCollName->n>0 ){
89817  Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
89818  if( pNew ){
89819  pNew->pLeft = pExpr;
89820  pNew->flags |= EP_Collate|EP_Skip;
89821  pExpr = pNew;
89822  }
89823  }
89824  return pExpr;
89825 }
89826 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
89827  Token s;
89828  assert( zC!=0 );
89829  sqlite3TokenInit(&s, (char*)zC);
89830  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
89831 }
89832 
89833 /*
89834 ** Skip over any TK_COLLATE operators and any unlikely()
89835 ** or likelihood() function at the root of an expression.
89836 */
89838  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
89839  if( ExprHasProperty(pExpr, EP_Unlikely) ){
89840  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89841  assert( pExpr->x.pList->nExpr>0 );
89842  assert( pExpr->op==TK_FUNCTION );
89843  pExpr = pExpr->x.pList->a[0].pExpr;
89844  }else{
89845  assert( pExpr->op==TK_COLLATE );
89846  pExpr = pExpr->pLeft;
89847  }
89848  }
89849  return pExpr;
89850 }
89851 
89852 /*
89853 ** Return the collation sequence for the expression pExpr. If
89854 ** there is no defined collating sequence, return NULL.
89855 **
89856 ** The collating sequence might be determined by a COLLATE operator
89857 ** or by the presence of a column with a defined collating sequence.
89858 ** COLLATE operators take first precedence. Left operands take
89859 ** precedence over right operands.
89860 */
89862  sqlite3 *db = pParse->db;
89863  CollSeq *pColl = 0;
89864  Expr *p = pExpr;
89865  while( p ){
89866  int op = p->op;
89867  if( p->flags & EP_Generic ) break;
89868  if( op==TK_CAST || op==TK_UPLUS ){
89869  p = p->pLeft;
89870  continue;
89871  }
89872  if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
89873  pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
89874  break;
89875  }
89876  if( (op==TK_AGG_COLUMN || op==TK_COLUMN
89877  || op==TK_REGISTER || op==TK_TRIGGER)
89878  && p->pTab!=0
89879  ){
89880  /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
89881  ** a TK_COLUMN but was previously evaluated and cached in a register */
89882  int j = p->iColumn;
89883  if( j>=0 ){
89884  const char *zColl = p->pTab->aCol[j].zColl;
89885  pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
89886  }
89887  break;
89888  }
89889  if( p->flags & EP_Collate ){
89890  if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
89891  p = p->pLeft;
89892  }else{
89893  Expr *pNext = p->pRight;
89894  /* The Expr.x union is never used at the same time as Expr.pRight */
89895  assert( p->x.pList==0 || p->pRight==0 );
89896  /* p->flags holds EP_Collate and p->pLeft->flags does not. And
89897  ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
89898  ** least one EP_Collate. Thus the following two ALWAYS. */
89899  if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
89900  int i;
89901  for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
89902  if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
89903  pNext = p->x.pList->a[i].pExpr;
89904  break;
89905  }
89906  }
89907  }
89908  p = pNext;
89909  }
89910  }else{
89911  break;
89912  }
89913  }
89914  if( sqlite3CheckCollSeq(pParse, pColl) ){
89915  pColl = 0;
89916  }
89917  return pColl;
89918 }
89919 
89920 /*
89921 ** pExpr is an operand of a comparison operator. aff2 is the
89922 ** type affinity of the other operand. This routine returns the
89923 ** type affinity that should be used for the comparison operator.
89924 */
89926  char aff1 = sqlite3ExprAffinity(pExpr);
89927  if( aff1 && aff2 ){
89928  /* Both sides of the comparison are columns. If one has numeric
89929  ** affinity, use that. Otherwise use no affinity.
89930  */
89932  return SQLITE_AFF_NUMERIC;
89933  }else{
89934  return SQLITE_AFF_BLOB;
89935  }
89936  }else if( !aff1 && !aff2 ){
89937  /* Neither side of the comparison is a column. Compare the
89938  ** results directly.
89939  */
89940  return SQLITE_AFF_BLOB;
89941  }else{
89942  /* One side is a column, the other is not. Use the columns affinity. */
89943  assert( aff1==0 || aff2==0 );
89944  return (aff1 + aff2);
89945  }
89946 }
89947 
89948 /*
89949 ** pExpr is a comparison operator. Return the type affinity that should
89950 ** be applied to both operands prior to doing the comparison.
89951 */
89952 static char comparisonAffinity(Expr *pExpr){
89953  char aff;
89954  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
89955  pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
89956  pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
89957  assert( pExpr->pLeft );
89958  aff = sqlite3ExprAffinity(pExpr->pLeft);
89959  if( pExpr->pRight ){
89960  aff = sqlite3CompareAffinity(pExpr->pRight, aff);
89961  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89962  aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
89963  }else if( NEVER(aff==0) ){
89964  aff = SQLITE_AFF_BLOB;
89965  }
89966  return aff;
89967 }
89968 
89969 /*
89970 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
89971 ** idx_affinity is the affinity of an indexed column. Return true
89972 ** if the index with affinity idx_affinity may be used to implement
89973 ** the comparison in pExpr.
89974 */
89975 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
89976  char aff = comparisonAffinity(pExpr);
89977  switch( aff ){
89978  case SQLITE_AFF_BLOB:
89979  return 1;
89980  case SQLITE_AFF_TEXT:
89981  return idx_affinity==SQLITE_AFF_TEXT;
89982  default:
89983  return sqlite3IsNumericAffinity(idx_affinity);
89984  }
89985 }
89986 
89987 /*
89988 ** Return the P5 value that should be used for a binary comparison
89989 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
89990 */
89991 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
89992  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
89993  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
89994  return aff;
89995 }
89996 
89997 /*
89998 ** Return a pointer to the collation sequence that should be used by
89999 ** a binary comparison operator comparing pLeft and pRight.
90000 **
90001 ** If the left hand expression has a collating sequence type, then it is
90002 ** used. Otherwise the collation sequence for the right hand expression
90003 ** is used, or the default (BINARY) if neither expression has a collating
90004 ** type.
90005 **
90006 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
90007 ** it is not considered.
90008 */
90010  Parse *pParse,
90011  Expr *pLeft,
90012  Expr *pRight
90013 ){
90014  CollSeq *pColl;
90015  assert( pLeft );
90016  if( pLeft->flags & EP_Collate ){
90017  pColl = sqlite3ExprCollSeq(pParse, pLeft);
90018  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
90019  pColl = sqlite3ExprCollSeq(pParse, pRight);
90020  }else{
90021  pColl = sqlite3ExprCollSeq(pParse, pLeft);
90022  if( !pColl ){
90023  pColl = sqlite3ExprCollSeq(pParse, pRight);
90024  }
90025  }
90026  return pColl;
90027 }
90028 
90029 /*
90030 ** Generate code for a comparison operator.
90031 */
90032 static int codeCompare(
90033  Parse *pParse, /* The parsing (and code generating) context */
90034  Expr *pLeft, /* The left operand */
90035  Expr *pRight, /* The right operand */
90036  int opcode, /* The comparison opcode */
90037  int in1, int in2, /* Register holding operands */
90038  int dest, /* Jump here if true. */
90039  int jumpIfNull /* If true, jump if either operand is NULL */
90040 ){
90041  int p5;
90042  int addr;
90043  CollSeq *p4;
90044 
90045  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
90046  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
90047  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
90048  (void*)p4, P4_COLLSEQ);
90049  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
90050  return addr;
90051 }
90052 
90053 /*
90054 ** Return true if expression pExpr is a vector, or false otherwise.
90055 **
90056 ** A vector is defined as any expression that results in two or more
90057 ** columns of result. Every TK_VECTOR node is an vector because the
90058 ** parser will not generate a TK_VECTOR with fewer than two entries.
90059 ** But a TK_SELECT might be either a vector or a scalar. It is only
90060 ** considered a vector if it has two or more result columns.
90061 */
90063  return sqlite3ExprVectorSize(pExpr)>1;
90064 }
90065 
90066 /*
90067 ** If the expression passed as the only argument is of type TK_VECTOR
90068 ** return the number of expressions in the vector. Or, if the expression
90069 ** is a sub-select, return the number of columns in the sub-select. For
90070 ** any other type of expression, return 1.
90071 */
90073  u8 op = pExpr->op;
90074  if( op==TK_REGISTER ) op = pExpr->op2;
90075  if( op==TK_VECTOR ){
90076  return pExpr->x.pList->nExpr;
90077  }else if( op==TK_SELECT ){
90078  return pExpr->x.pSelect->pEList->nExpr;
90079  }else{
90080  return 1;
90081  }
90082 }
90083 
90084 #ifndef SQLITE_OMIT_SUBQUERY
90085 /*
90086 ** Return a pointer to a subexpression of pVector that is the i-th
90087 ** column of the vector (numbered starting with 0). The caller must
90088 ** ensure that i is within range.
90089 **
90090 ** If pVector is really a scalar (and "scalar" here includes subqueries
90091 ** that return a single column!) then return pVector unmodified.
90092 **
90093 ** pVector retains ownership of the returned subexpression.
90094 **
90095 ** If the vector is a (SELECT ...) then the expression returned is
90096 ** just the expression for the i-th term of the result set, and may
90097 ** not be ready for evaluation because the table cursor has not yet
90098 ** been positioned.
90099 */
90101  assert( i<sqlite3ExprVectorSize(pVector) );
90102  if( sqlite3ExprIsVector(pVector) ){
90103  assert( pVector->op2==0 || pVector->op==TK_REGISTER );
90104  if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
90105  return pVector->x.pSelect->pEList->a[i].pExpr;
90106  }else{
90107  return pVector->x.pList->a[i].pExpr;
90108  }
90109  }
90110  return pVector;
90111 }
90112 #endif /* !defined(SQLITE_OMIT_SUBQUERY) */
90113 
90114 #ifndef SQLITE_OMIT_SUBQUERY
90115 /*
90116 ** Compute and return a new Expr object which when passed to
90117 ** sqlite3ExprCode() will generate all necessary code to compute
90118 ** the iField-th column of the vector expression pVector.
90119 **
90120 ** It is ok for pVector to be a scalar (as long as iField==0).
90121 ** In that case, this routine works like sqlite3ExprDup().
90122 **
90123 ** The caller owns the returned Expr object and is responsible for
90124 ** ensuring that the returned value eventually gets freed.
90125 **
90126 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
90127 ** then the returned object will reference pVector and so pVector must remain
90128 ** valid for the life of the returned object. If pVector is a TK_VECTOR
90129 ** or a scalar expression, then it can be deleted as soon as this routine
90130 ** returns.
90131 **
90132 ** A trick to cause a TK_SELECT pVector to be deleted together with
90133 ** the returned Expr object is to attach the pVector to the pRight field
90134 ** of the returned TK_SELECT_COLUMN Expr object.
90135 */
90137  Parse *pParse, /* Parsing context */
90138  Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
90139  int iField /* Which column of the vector to return */
90140 ){
90141  Expr *pRet;
90142  if( pVector->op==TK_SELECT ){
90143  assert( pVector->flags & EP_xIsSelect );
90144  /* The TK_SELECT_COLUMN Expr node:
90145  **
90146  ** pLeft: pVector containing TK_SELECT
90147  ** pRight: not used. But recursively deleted.
90148  ** iColumn: Index of a column in pVector
90149  ** pLeft->iTable: First in an array of register holding result, or 0
90150  ** if the result is not yet computed.
90151  **
90152  ** sqlite3ExprDelete() specifically skips the recursive delete of
90153  ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
90154  ** can be attached to pRight to cause this node to take ownership of
90155  ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
90156  ** with the same pLeft pointer to the pVector, but only one of them
90157  ** will own the pVector.
90158  */
90159  pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0, 0);
90160  if( pRet ){
90161  pRet->iColumn = iField;
90162  pRet->pLeft = pVector;
90163  }
90164  assert( pRet==0 || pRet->iTable==0 );
90165  }else{
90166  if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
90167  pRet = sqlite3ExprDup(pParse->db, pVector, 0);
90168  }
90169  return pRet;
90170 }
90171 #endif /* !define(SQLITE_OMIT_SUBQUERY) */
90172 
90173 /*
90174 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
90175 ** it. Return the register in which the result is stored (or, if the
90176 ** sub-select returns more than one column, the first in an array
90177 ** of registers in which the result is stored).
90178 **
90179 ** If pExpr is not a TK_SELECT expression, return 0.
90180 */
90181 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
90182  int reg = 0;
90183 #ifndef SQLITE_OMIT_SUBQUERY
90184  if( pExpr->op==TK_SELECT ){
90185  reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
90186  }
90187 #endif
90188  return reg;
90189 }
90190 
90191 /*
90192 ** Argument pVector points to a vector expression - either a TK_VECTOR
90193 ** or TK_SELECT that returns more than one column. This function returns
90194 ** the register number of a register that contains the value of
90195 ** element iField of the vector.
90196 **
90197 ** If pVector is a TK_SELECT expression, then code for it must have
90198 ** already been generated using the exprCodeSubselect() routine. In this
90199 ** case parameter regSelect should be the first in an array of registers
90200 ** containing the results of the sub-select.
90201 **
90202 ** If pVector is of type TK_VECTOR, then code for the requested field
90203 ** is generated. In this case (*pRegFree) may be set to the number of
90204 ** a temporary register to be freed by the caller before returning.
90205 **
90206 ** Before returning, output parameter (*ppExpr) is set to point to the
90207 ** Expr object corresponding to element iElem of the vector.
90208 */
90210  Parse *pParse, /* Parse context */
90211  Expr *pVector, /* Vector to extract element from */
90212  int iField, /* Field to extract from pVector */
90213  int regSelect, /* First in array of registers */
90214  Expr **ppExpr, /* OUT: Expression element */
90215  int *pRegFree /* OUT: Temp register to free */
90216 ){
90217  u8 op = pVector->op;
90218  assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
90219  if( op==TK_REGISTER ){
90220  *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
90221  return pVector->iTable+iField;
90222  }
90223  if( op==TK_SELECT ){
90224  *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
90225  return regSelect+iField;
90226  }
90227  *ppExpr = pVector->x.pList->a[iField].pExpr;
90228  return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
90229 }
90230 
90231 /*
90232 ** Expression pExpr is a comparison between two vector values. Compute
90233 ** the result of the comparison (1, 0, or NULL) and write that
90234 ** result into register dest.
90235 **
90236 ** The caller must satisfy the following preconditions:
90237 **
90238 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
90239 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
90240 ** otherwise: op==pExpr->op and p5==0
90241 */
90242 static void codeVectorCompare(
90243  Parse *pParse, /* Code generator context */
90244  Expr *pExpr, /* The comparison operation */
90245  int dest, /* Write results into this register */
90246  u8 op, /* Comparison operator */
90247  u8 p5 /* SQLITE_NULLEQ or zero */
90248 ){
90249  Vdbe *v = pParse->pVdbe;
90250  Expr *pLeft = pExpr->pLeft;
90251  Expr *pRight = pExpr->pRight;
90252  int nLeft = sqlite3ExprVectorSize(pLeft);
90253  int i;
90254  int regLeft = 0;
90255  int regRight = 0;
90256  u8 opx = op;
90257  int addrDone = sqlite3VdbeMakeLabel(v);
90258 
90259  assert( nLeft==sqlite3ExprVectorSize(pRight) );
90260  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
90261  || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
90262  || pExpr->op==TK_LT || pExpr->op==TK_GT
90263  || pExpr->op==TK_LE || pExpr->op==TK_GE
90264  );
90265  assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
90266  || (pExpr->op==TK_ISNOT && op==TK_NE) );
90267  assert( p5==0 || pExpr->op!=op );
90268  assert( p5==SQLITE_NULLEQ || pExpr->op==op );
90269 
90270  p5 |= SQLITE_STOREP2;
90271  if( opx==TK_LE ) opx = TK_LT;
90272  if( opx==TK_GE ) opx = TK_GT;
90273 
90274  regLeft = exprCodeSubselect(pParse, pLeft);
90275  regRight = exprCodeSubselect(pParse, pRight);
90276 
90277  for(i=0; 1 /*Loop exits by "break"*/; i++){
90278  int regFree1 = 0, regFree2 = 0;
90279  Expr *pL, *pR;
90280  int r1, r2;
90281  assert( i>=0 && i<nLeft );
90282  if( i>0 ) sqlite3ExprCachePush(pParse);
90283  r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
90284  r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
90285  codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
90286  testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
90287  testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
90288  testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
90289  testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
90290  testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
90291  testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
90292  sqlite3ReleaseTempReg(pParse, regFree1);
90293  sqlite3ReleaseTempReg(pParse, regFree2);
90294  if( i>0 ) sqlite3ExprCachePop(pParse);
90295  if( i==nLeft-1 ){
90296  break;
90297  }
90298  if( opx==TK_EQ ){
90299  sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
90300  p5 |= SQLITE_KEEPNULL;
90301  }else if( opx==TK_NE ){
90302  sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
90303  p5 |= SQLITE_KEEPNULL;
90304  }else{
90305  assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
90306  sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
90307  VdbeCoverageIf(v, op==TK_LT);
90308  VdbeCoverageIf(v, op==TK_GT);
90309  VdbeCoverageIf(v, op==TK_LE);
90310  VdbeCoverageIf(v, op==TK_GE);
90311  if( i==nLeft-2 ) opx = op;
90312  }
90313  }
90314  sqlite3VdbeResolveLabel(v, addrDone);
90315 }
90316 
90317 #if SQLITE_MAX_EXPR_DEPTH>0
90318 /*
90319 ** Check that argument nHeight is less than or equal to the maximum
90320 ** expression depth allowed. If it is not, leave an error message in
90321 ** pParse.
90322 */
90323 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
90324  int rc = SQLITE_OK;
90325  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
90326  if( nHeight>mxHeight ){
90327  sqlite3ErrorMsg(pParse,
90328  "Expression tree is too large (maximum depth %d)", mxHeight
90329  );
90330  rc = SQLITE_ERROR;
90331  }
90332  return rc;
90333 }
90334 
90335 /* The following three functions, heightOfExpr(), heightOfExprList()
90336 ** and heightOfSelect(), are used to determine the maximum height
90337 ** of any expression tree referenced by the structure passed as the
90338 ** first argument.
90339 **
90340 ** If this maximum height is greater than the current value pointed
90341 ** to by pnHeight, the second parameter, then set *pnHeight to that
90342 ** value.
90343 */
90344 static void heightOfExpr(Expr *p, int *pnHeight){
90345  if( p ){
90346  if( p->nHeight>*pnHeight ){
90347  *pnHeight = p->nHeight;
90348  }
90349  }
90350 }
90351 static void heightOfExprList(ExprList *p, int *pnHeight){
90352  if( p ){
90353  int i;
90354  for(i=0; i<p->nExpr; i++){
90355  heightOfExpr(p->a[i].pExpr, pnHeight);
90356  }
90357  }
90358 }
90359 static void heightOfSelect(Select *p, int *pnHeight){
90360  if( p ){
90361  heightOfExpr(p->pWhere, pnHeight);
90362  heightOfExpr(p->pHaving, pnHeight);
90363  heightOfExpr(p->pLimit, pnHeight);
90364  heightOfExpr(p->pOffset, pnHeight);
90365  heightOfExprList(p->pEList, pnHeight);
90366  heightOfExprList(p->pGroupBy, pnHeight);
90367  heightOfExprList(p->pOrderBy, pnHeight);
90368  heightOfSelect(p->pPrior, pnHeight);
90369  }
90370 }
90371 
90372 /*
90373 ** Set the Expr.nHeight variable in the structure passed as an
90374 ** argument. An expression with no children, Expr.pList or
90375 ** Expr.pSelect member has a height of 1. Any other expression
90376 ** has a height equal to the maximum height of any other
90377 ** referenced Expr plus one.
90378 **
90379 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
90380 ** if appropriate.
90381 */
90382 static void exprSetHeight(Expr *p){
90383  int nHeight = 0;
90384  heightOfExpr(p->pLeft, &nHeight);
90385  heightOfExpr(p->pRight, &nHeight);
90386  if( ExprHasProperty(p, EP_xIsSelect) ){
90387  heightOfSelect(p->x.pSelect, &nHeight);
90388  }else if( p->x.pList ){
90389  heightOfExprList(p->x.pList, &nHeight);
90391  }
90392  p->nHeight = nHeight + 1;
90393 }
90394 
90395 /*
90396 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
90397 ** the height is greater than the maximum allowed expression depth,
90398 ** leave an error in pParse.
90399 **
90400 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
90401 ** Expr.flags.
90402 */
90404  if( pParse->nErr ) return;
90405  exprSetHeight(p);
90406  sqlite3ExprCheckHeight(pParse, p->nHeight);
90407 }
90408 
90409 /*
90410 ** Return the maximum height of any expression tree referenced
90411 ** by the select statement passed as an argument.
90412 */
90414  int nHeight = 0;
90415  heightOfSelect(p, &nHeight);
90416  return nHeight;
90417 }
90418 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
90419 /*
90420 ** Propagate all EP_Propagate flags from the Expr.x.pList into
90421 ** Expr.flags.
90422 */
90424  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
90426  }
90427 }
90428 #define exprSetHeight(y)
90429 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
90430 
90431 /*
90432 ** This routine is the core allocator for Expr nodes.
90433 **
90434 ** Construct a new expression node and return a pointer to it. Memory
90435 ** for this node and for the pToken argument is a single allocation
90436 ** obtained from sqlite3DbMalloc(). The calling function
90437 ** is responsible for making sure the node eventually gets freed.
90438 **
90439 ** If dequote is true, then the token (if it exists) is dequoted.
90440 ** If dequote is false, no dequoting is performed. The deQuote
90441 ** parameter is ignored if pToken is NULL or if the token does not
90442 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
90443 ** then the EP_DblQuoted flag is set on the expression node.
90444 **
90445 ** Special case: If op==TK_INTEGER and pToken points to a string that
90446 ** can be translated into a 32-bit integer, then the token is not
90447 ** stored in u.zToken. Instead, the integer values is written
90448 ** into u.iValue and the EP_IntValue flag is set. No extra storage
90449 ** is allocated to hold the integer text and the dequote flag is ignored.
90450 */
90452  sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
90453  int op, /* Expression opcode */
90454  const Token *pToken, /* Token argument. Might be NULL */
90455  int dequote /* True to dequote */
90456 ){
90457  Expr *pNew;
90458  int nExtra = 0;
90459  int iValue = 0;
90460 
90461  assert( db!=0 );
90462  if( pToken ){
90463  if( op!=TK_INTEGER || pToken->z==0
90464  || sqlite3GetInt32(pToken->z, &iValue)==0 ){
90465  nExtra = pToken->n+1;
90466  assert( iValue>=0 );
90467  }
90468  }
90469  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
90470  if( pNew ){
90471  memset(pNew, 0, sizeof(Expr));
90472  pNew->op = (u8)op;
90473  pNew->iAgg = -1;
90474  if( pToken ){
90475  if( nExtra==0 ){
90476  pNew->flags |= EP_IntValue;
90477  pNew->u.iValue = iValue;
90478  }else{
90479  pNew->u.zToken = (char*)&pNew[1];
90480  assert( pToken->z!=0 || pToken->n==0 );
90481  if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
90482  pNew->u.zToken[pToken->n] = 0;
90483  if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
90484  if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
90485  sqlite3Dequote(pNew->u.zToken);
90486  }
90487  }
90488  }
90489 #if SQLITE_MAX_EXPR_DEPTH>0
90490  pNew->nHeight = 1;
90491 #endif
90492  }
90493  return pNew;
90494 }
90495 
90496 /*
90497 ** Allocate a new expression node from a zero-terminated token that has
90498 ** already been dequoted.
90499 */
90501  sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
90502  int op, /* Expression opcode */
90503  const char *zToken /* Token argument. Might be NULL */
90504 ){
90505  Token x;
90506  x.z = zToken;
90507  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
90508  return sqlite3ExprAlloc(db, op, &x, 0);
90509 }
90510 
90511 /*
90512 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
90513 **
90514 ** If pRoot==NULL that means that a memory allocation error has occurred.
90515 ** In that case, delete the subtrees pLeft and pRight.
90516 */
90518  sqlite3 *db,
90519  Expr *pRoot,
90520  Expr *pLeft,
90521  Expr *pRight
90522 ){
90523  if( pRoot==0 ){
90524  assert( db->mallocFailed );
90525  sqlite3ExprDelete(db, pLeft);
90526  sqlite3ExprDelete(db, pRight);
90527  }else{
90528  if( pRight ){
90529  pRoot->pRight = pRight;
90530  pRoot->flags |= EP_Propagate & pRight->flags;
90531  }
90532  if( pLeft ){
90533  pRoot->pLeft = pLeft;
90534  pRoot->flags |= EP_Propagate & pLeft->flags;
90535  }
90536  exprSetHeight(pRoot);
90537  }
90538 }
90539 
90540 /*
90541 ** Allocate an Expr node which joins as many as two subtrees.
90542 **
90543 ** One or both of the subtrees can be NULL. Return a pointer to the new
90544 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
90545 ** free the subtrees and return NULL.
90546 */
90548  Parse *pParse, /* Parsing context */
90549  int op, /* Expression opcode */
90550  Expr *pLeft, /* Left operand */
90551  Expr *pRight, /* Right operand */
90552  const Token *pToken /* Argument token */
90553 ){
90554  Expr *p;
90555  if( op==TK_AND && pParse->nErr==0 ){
90556  /* Take advantage of short-circuit false optimization for AND */
90557  p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
90558  }else{
90559  p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
90560  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
90561  }
90562  if( p ) {
90563  sqlite3ExprCheckHeight(pParse, p->nHeight);
90564  }
90565  return p;
90566 }
90567 
90568 /*
90569 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
90570 ** do a memory allocation failure) then delete the pSelect object.
90571 */
90572 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
90573  if( pExpr ){
90574  pExpr->x.pSelect = pSelect;
90576  sqlite3ExprSetHeightAndFlags(pParse, pExpr);
90577  }else{
90578  assert( pParse->db->mallocFailed );
90579  sqlite3SelectDelete(pParse->db, pSelect);
90580  }
90581 }
90582 
90583 
90584 /*
90585 ** If the expression is always either TRUE or FALSE (respectively),
90586 ** then return 1. If one cannot determine the truth value of the
90587 ** expression at compile-time return 0.
90588 **
90589 ** This is an optimization. If is OK to return 0 here even if
90590 ** the expression really is always false or false (a false negative).
90591 ** But it is a bug to return 1 if the expression might have different
90592 ** boolean values in different circumstances (a false positive.)
90593 **
90594 ** Note that if the expression is part of conditional for a
90595 ** LEFT JOIN, then we cannot determine at compile-time whether or not
90596 ** is it true or false, so always return 0.
90597 */
90598 static int exprAlwaysTrue(Expr *p){
90599  int v = 0;
90600  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90601  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90602  return v!=0;
90603 }
90604 static int exprAlwaysFalse(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 
90611 /*
90612 ** Join two expressions using an AND operator. If either expression is
90613 ** NULL, then just return the other expression.
90614 **
90615 ** If one side or the other of the AND is known to be false, then instead
90616 ** of returning an AND expression, just return a constant expression with
90617 ** a value of false.
90618 */
90620  if( pLeft==0 ){
90621  return pRight;
90622  }else if( pRight==0 ){
90623  return pLeft;
90624  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
90625  sqlite3ExprDelete(db, pLeft);
90626  sqlite3ExprDelete(db, pRight);
90627  return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
90628  }else{
90629  Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
90630  sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
90631  return pNew;
90632  }
90633 }
90634 
90635 /*
90636 ** Construct a new expression node for a function with multiple
90637 ** arguments.
90638 */
90640  Expr *pNew;
90641  sqlite3 *db = pParse->db;
90642  assert( pToken );
90643  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
90644  if( pNew==0 ){
90645  sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
90646  return 0;
90647  }
90648  pNew->x.pList = pList;
90649  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
90650  sqlite3ExprSetHeightAndFlags(pParse, pNew);
90651  return pNew;
90652 }
90653 
90654 /*
90655 ** Assign a variable number to an expression that encodes a wildcard
90656 ** in the original SQL statement.
90657 **
90658 ** Wildcards consisting of a single "?" are assigned the next sequential
90659 ** variable number.
90660 **
90661 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
90662 ** sure "nnn" is not too be to avoid a denial of service attack when
90663 ** the SQL statement comes from an external source.
90664 **
90665 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
90666 ** as the previous instance of the same wildcard. Or if this is the first
90667 ** instance of the wildcard, the next sequential variable number is
90668 ** assigned.
90669 */
90671  sqlite3 *db = pParse->db;
90672  const char *z;
90673 
90674  if( pExpr==0 ) return;
90676  z = pExpr->u.zToken;
90677  assert( z!=0 );
90678  assert( z[0]!=0 );
90679  assert( n==sqlite3Strlen30(z) );
90680  if( z[1]==0 ){
90681  /* Wildcard of the form "?". Assign the next variable number */
90682  assert( z[0]=='?' );
90683  pExpr->iColumn = (ynVar)(++pParse->nVar);
90684  }else{
90685  ynVar x;
90686  if( z[0]=='?' ){
90687  /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
90688  ** use it as the variable number */
90689  i64 i;
90690  int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
90691  x = (ynVar)i;
90692  testcase( i==0 );
90693  testcase( i==1 );
90696  if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90697  sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
90698  db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
90699  return;
90700  }
90701  if( i>pParse->nVar ){
90702  pParse->nVar = (int)i;
90703  }
90704  }else{
90705  /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
90706  ** number as the prior appearance of the same name, or if the name
90707  ** has never appeared before, reuse the same variable number
90708  */
90709  ynVar i;
90710  for(i=x=0; i<pParse->nzVar; i++){
90711  if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
90712  x = (ynVar)i+1;
90713  break;
90714  }
90715  }
90716  if( x==0 ) x = (ynVar)(++pParse->nVar);
90717  }
90718  pExpr->iColumn = x;
90719  if( x>pParse->nzVar ){
90720  char **a;
90721  a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
90722  if( a==0 ){
90723  assert( db->mallocFailed ); /* Error reported through mallocFailed */
90724  return;
90725  }
90726  pParse->azVar = a;
90727  memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
90728  pParse->nzVar = x;
90729  }
90730  if( pParse->azVar[x-1]==0 ){
90731  pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
90732  }
90733  }
90734  if( pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90735  sqlite3ErrorMsg(pParse, "too many SQL variables");
90736  }
90737 }
90738 
90739 /*
90740 ** Recursively delete an expression tree.
90741 */
90743  assert( p!=0 );
90744  /* Sanity check: Assert that the IntValue is non-negative if it exists */
90745  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
90746 #ifdef SQLITE_DEBUG
90748  assert( p->pLeft==0 );
90749  assert( p->pRight==0 );
90750  assert( p->x.pSelect==0 );
90751  }
90752 #endif
90753  if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
90754  /* The Expr.x union is never used at the same time as Expr.pRight */
90755  assert( p->x.pList==0 || p->pRight==0 );
90756  if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
90757  sqlite3ExprDelete(db, p->pRight);
90758  if( ExprHasProperty(p, EP_xIsSelect) ){
90759  sqlite3SelectDelete(db, p->x.pSelect);
90760  }else{
90761  sqlite3ExprListDelete(db, p->x.pList);
90762  }
90763  }
90764  if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
90765  if( !ExprHasProperty(p, EP_Static) ){
90766  sqlite3DbFree(db, p);
90767  }
90768 }
90770  if( p ) sqlite3ExprDeleteNN(db, p);
90771 }
90772 
90773 /*
90774 ** Return the number of bytes allocated for the expression structure
90775 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
90776 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
90777 */
90778 static int exprStructSize(Expr *p){
90780  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
90781  return EXPR_FULLSIZE;
90782 }
90783 
90784 /*
90785 ** The dupedExpr*Size() routines each return the number of bytes required
90786 ** to store a copy of an expression or expression tree. They differ in
90787 ** how much of the tree is measured.
90788 **
90789 ** dupedExprStructSize() Size of only the Expr structure
90790 ** dupedExprNodeSize() Size of Expr + space for token
90791 ** dupedExprSize() Expr + token + subtree components
90792 **
90793 ***************************************************************************
90794 **
90795 ** The dupedExprStructSize() function returns two values OR-ed together:
90796 ** (1) the space required for a copy of the Expr structure only and
90797 ** (2) the EP_xxx flags that indicate what the structure size should be.
90798 ** The return values is always one of:
90799 **
90800 ** EXPR_FULLSIZE
90801 ** EXPR_REDUCEDSIZE | EP_Reduced
90802 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
90803 **
90804 ** The size of the structure can be found by masking the return value
90805 ** of this routine with 0xfff. The flags can be found by masking the
90806 ** return value with EP_Reduced|EP_TokenOnly.
90807 **
90808 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
90809 ** (unreduced) Expr objects as they or originally constructed by the parser.
90810 ** During expression analysis, extra information is computed and moved into
90811 ** later parts of teh Expr object and that extra information might get chopped
90812 ** off if the expression is reduced. Note also that it does not work to
90813 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
90814 ** to reduce a pristine expression tree from the parser. The implementation
90815 ** of dupedExprStructSize() contain multiple assert() statements that attempt
90816 ** to enforce this constraint.
90817 */
90818 static int dupedExprStructSize(Expr *p, int flags){
90819  int nSize;
90820  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
90821  assert( EXPR_FULLSIZE<=0xfff );
90822  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
90823  if( 0==flags ){
90824  nSize = EXPR_FULLSIZE;
90825  }else{
90826  assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
90827  assert( !ExprHasProperty(p, EP_FromJoin) );
90828  assert( !ExprHasProperty(p, EP_MemToken) );
90829  assert( !ExprHasProperty(p, EP_NoReduce) );
90830  if( p->pLeft || p->x.pList ){
90831  nSize = EXPR_REDUCEDSIZE | EP_Reduced;
90832  }else{
90833  assert( p->pRight==0 );
90834  nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
90835  }
90836  }
90837  return nSize;
90838 }
90839 
90840 /*
90841 ** This function returns the space in bytes required to store the copy
90842 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
90843 ** string is defined.)
90844 */
90845 static int dupedExprNodeSize(Expr *p, int flags){
90846  int nByte = dupedExprStructSize(p, flags) & 0xfff;
90847  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90848  nByte += sqlite3Strlen30(p->u.zToken)+1;
90849  }
90850  return ROUND8(nByte);
90851 }
90852 
90853 /*
90854 ** Return the number of bytes required to create a duplicate of the
90855 ** expression passed as the first argument. The second argument is a
90856 ** mask containing EXPRDUP_XXX flags.
90857 **
90858 ** The value returned includes space to create a copy of the Expr struct
90859 ** itself and the buffer referred to by Expr.u.zToken, if any.
90860 **
90861 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
90862 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
90863 ** and Expr.pRight variables (but not for any structures pointed to or
90864 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
90865 */
90866 static int dupedExprSize(Expr *p, int flags){
90867  int nByte = 0;
90868  if( p ){
90869  nByte = dupedExprNodeSize(p, flags);
90870  if( flags&EXPRDUP_REDUCE ){
90871  nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
90872  }
90873  }
90874  return nByte;
90875 }
90876 
90877 /*
90878 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
90879 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
90880 ** to store the copy of expression p, the copies of p->u.zToken
90881 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
90882 ** if any. Before returning, *pzBuffer is set to the first byte past the
90883 ** portion of the buffer copied into by this function.
90884 */
90885 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
90886  Expr *pNew; /* Value to return */
90887  u8 *zAlloc; /* Memory space from which to build Expr object */
90888  u32 staticFlag; /* EP_Static if space not obtained from malloc */
90889 
90890  assert( db!=0 );
90891  assert( p );
90892  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
90893  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
90894 
90895  /* Figure out where to write the new Expr structure. */
90896  if( pzBuffer ){
90897  zAlloc = *pzBuffer;
90898  staticFlag = EP_Static;
90899  }else{
90900  zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
90901  staticFlag = 0;
90902  }
90903  pNew = (Expr *)zAlloc;
90904 
90905  if( pNew ){
90906  /* Set nNewSize to the size allocated for the structure pointed to
90907  ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
90908  ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
90909  ** by the copy of the p->u.zToken string (if any).
90910  */
90911  const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
90912  const int nNewSize = nStructSize & 0xfff;
90913  int nToken;
90914  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90915  nToken = sqlite3Strlen30(p->u.zToken) + 1;
90916  }else{
90917  nToken = 0;
90918  }
90919  if( dupFlags ){
90920  assert( ExprHasProperty(p, EP_Reduced)==0 );
90921  memcpy(zAlloc, p, nNewSize);
90922  }else{
90923  u32 nSize = (u32)exprStructSize(p);
90924  memcpy(zAlloc, p, nSize);
90925  if( nSize<EXPR_FULLSIZE ){
90926  memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
90927  }
90928  }
90929 
90930  /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
90932  pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
90933  pNew->flags |= staticFlag;
90934 
90935  /* Copy the p->u.zToken string, if any. */
90936  if( nToken ){
90937  char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
90938  memcpy(zToken, p->u.zToken, nToken);
90939  }
90940 
90941  if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
90942  /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
90943  if( ExprHasProperty(p, EP_xIsSelect) ){
90944  pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
90945  }else{
90946  pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
90947  }
90948  }
90949 
90950  /* Fill in pNew->pLeft and pNew->pRight. */
90952  zAlloc += dupedExprNodeSize(p, dupFlags);
90953  if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
90954  pNew->pLeft = p->pLeft ?
90955  exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
90956  pNew->pRight = p->pRight ?
90957  exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
90958  }
90959  if( pzBuffer ){
90960  *pzBuffer = zAlloc;
90961  }
90962  }else{
90964  if( pNew->op==TK_SELECT_COLUMN ){
90965  pNew->pLeft = p->pLeft;
90966  }else{
90967  pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
90968  }
90969  pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
90970  }
90971  }
90972  }
90973  return pNew;
90974 }
90975 
90976 /*
90977 ** Create and return a deep copy of the object passed as the second
90978 ** argument. If an OOM condition is encountered, NULL is returned
90979 ** and the db->mallocFailed flag set.
90980 */
90981 #ifndef SQLITE_OMIT_CTE
90982 static With *withDup(sqlite3 *db, With *p){
90983  With *pRet = 0;
90984  if( p ){
90985  int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
90986  pRet = sqlite3DbMallocZero(db, nByte);
90987  if( pRet ){
90988  int i;
90989  pRet->nCte = p->nCte;
90990  for(i=0; i<p->nCte; i++){
90991  pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
90992  pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
90993  pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
90994  }
90995  }
90996  }
90997  return pRet;
90998 }
90999 #else
91000 # define withDup(x,y) 0
91001 #endif
91002 
91003 /*
91004 ** The following group of routines make deep copies of expressions,
91005 ** expression lists, ID lists, and select statements. The copies can
91006 ** be deleted (by being passed to their respective ...Delete() routines)
91007 ** without effecting the originals.
91008 **
91009 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
91010 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
91011 ** by subsequent calls to sqlite*ListAppend() routines.
91012 **
91013 ** Any tables that the SrcList might point to are not duplicated.
91014 **
91015 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
91016 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
91017 ** truncated version of the usual Expr structure that will be stored as
91018 ** part of the in-memory representation of the database schema.
91019 */
91021  assert( flags==0 || flags==EXPRDUP_REDUCE );
91022  return p ? exprDup(db, p, flags, 0) : 0;
91023 }
91025  ExprList *pNew;
91026  struct ExprList_item *pItem, *pOldItem;
91027  int i;
91028  assert( db!=0 );
91029  if( p==0 ) return 0;
91030  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
91031  if( pNew==0 ) return 0;
91032  pNew->nExpr = i = p->nExpr;
91033  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
91034  pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
91035  if( pItem==0 ){
91036  sqlite3DbFree(db, pNew);
91037  return 0;
91038  }
91039  pOldItem = p->a;
91040  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
91041  Expr *pOldExpr = pOldItem->pExpr;
91042  pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
91043  pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
91044  pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
91045  pItem->sortOrder = pOldItem->sortOrder;
91046  pItem->done = 0;
91047  pItem->bSpanIsTab = pOldItem->bSpanIsTab;
91048  pItem->u = pOldItem->u;
91049  }
91050  return pNew;
91051 }
91052 
91053 /*
91054 ** If cursors, triggers, views and subqueries are all omitted from
91055 ** the build, then none of the following routines, except for
91056 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
91057 ** called with a NULL argument.
91058 */
91059 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
91060  || !defined(SQLITE_OMIT_SUBQUERY)
91062  SrcList *pNew;
91063  int i;
91064  int nByte;
91065  assert( db!=0 );
91066  if( p==0 ) return 0;
91067  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
91068  pNew = sqlite3DbMallocRawNN(db, nByte );
91069  if( pNew==0 ) return 0;
91070  pNew->nSrc = pNew->nAlloc = p->nSrc;
91071  for(i=0; i<p->nSrc; i++){
91072  struct SrcList_item *pNewItem = &pNew->a[i];
91073  struct SrcList_item *pOldItem = &p->a[i];
91074  Table *pTab;
91075  pNewItem->pSchema = pOldItem->pSchema;
91076  pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
91077  pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
91078  pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
91079  pNewItem->fg = pOldItem->fg;
91080  pNewItem->iCursor = pOldItem->iCursor;
91081  pNewItem->addrFillSub = pOldItem->addrFillSub;
91082  pNewItem->regReturn = pOldItem->regReturn;
91083  if( pNewItem->fg.isIndexedBy ){
91084  pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
91085  }
91086  pNewItem->pIBIndex = pOldItem->pIBIndex;
91087  if( pNewItem->fg.isTabFunc ){
91088  pNewItem->u1.pFuncArg =
91089  sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
91090  }
91091  pTab = pNewItem->pTab = pOldItem->pTab;
91092  if( pTab ){
91093  pTab->nRef++;
91094  }
91095  pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
91096  pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
91097  pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
91098  pNewItem->colUsed = pOldItem->colUsed;
91099  }
91100  return pNew;
91101 }
91103  IdList *pNew;
91104  int i;
91105  assert( db!=0 );
91106  if( p==0 ) return 0;
91107  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
91108  if( pNew==0 ) return 0;
91109  pNew->nId = p->nId;
91110  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
91111  if( pNew->a==0 ){
91112  sqlite3DbFree(db, pNew);
91113  return 0;
91114  }
91115  /* Note that because the size of the allocation for p->a[] is not
91116  ** necessarily a power of two, sqlite3IdListAppend() may not be called
91117  ** on the duplicate created by this function. */
91118  for(i=0; i<p->nId; i++){
91119  struct IdList_item *pNewItem = &pNew->a[i];
91120  struct IdList_item *pOldItem = &p->a[i];
91121  pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
91122  pNewItem->idx = pOldItem->idx;
91123  }
91124  return pNew;
91125 }
91127  Select *pNew, *pPrior;
91128  assert( db!=0 );
91129  if( p==0 ) return 0;
91130  pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
91131  if( pNew==0 ) return 0;
91132  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
91133  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
91134  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
91135  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
91136  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
91137  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
91138  pNew->op = p->op;
91139  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
91140  if( pPrior ) pPrior->pNext = pNew;
91141  pNew->pNext = 0;
91142  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
91143  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
91144  pNew->iLimit = 0;
91145  pNew->iOffset = 0;
91146  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
91147  pNew->addrOpenEphm[0] = -1;
91148  pNew->addrOpenEphm[1] = -1;
91149  pNew->nSelectRow = p->nSelectRow;
91150  pNew->pWith = withDup(db, p->pWith);
91151  sqlite3SelectSetName(pNew, p->zSelName);
91152  return pNew;
91153 }
91154 #else
91155 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
91156  assert( p==0 );
91157  return 0;
91158 }
91159 #endif
91160 
91161 
91162 /*
91163 ** Add a new element to the end of an expression list. If pList is
91164 ** initially NULL, then create a new expression list.
91165 **
91166 ** If a memory allocation error occurs, the entire list is freed and
91167 ** NULL is returned. If non-NULL is returned, then it is guaranteed
91168 ** that the new entry was successfully appended.
91169 */
91171  Parse *pParse, /* Parsing context */
91172  ExprList *pList, /* List to which to append. Might be NULL */
91173  Expr *pExpr /* Expression to be appended. Might be NULL */
91174 ){
91175  sqlite3 *db = pParse->db;
91176  assert( db!=0 );
91177  if( pList==0 ){
91178  pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
91179  if( pList==0 ){
91180  goto no_mem;
91181  }
91182  pList->nExpr = 0;
91183  pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
91184  if( pList->a==0 ) goto no_mem;
91185  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
91186  struct ExprList_item *a;
91187  assert( pList->nExpr>0 );
91188  a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
91189  if( a==0 ){
91190  goto no_mem;
91191  }
91192  pList->a = a;
91193  }
91194  assert( pList->a!=0 );
91195  if( 1 ){
91196  struct ExprList_item *pItem = &pList->a[pList->nExpr++];
91197  memset(pItem, 0, sizeof(*pItem));
91198  pItem->pExpr = pExpr;
91199  }
91200  return pList;
91201 
91202 no_mem:
91203  /* Avoid leaking memory if malloc has failed. */
91204  sqlite3ExprDelete(db, pExpr);
91205  sqlite3ExprListDelete(db, pList);
91206  return 0;
91207 }
91208 
91209 /*
91210 ** pColumns and pExpr form a vector assignment which is part of the SET
91211 ** clause of an UPDATE statement. Like this:
91212 **
91213 ** (a,b,c) = (expr1,expr2,expr3)
91214 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
91215 **
91216 ** For each term of the vector assignment, append new entries to the
91217 ** expression list pList. In the case of a subquery on the LHS, append
91218 ** TK_SELECT_COLUMN expressions.
91219 */
91221  Parse *pParse, /* Parsing context */
91222  ExprList *pList, /* List to which to append. Might be NULL */
91223  IdList *pColumns, /* List of names of LHS of the assignment */
91224  Expr *pExpr /* Vector expression to be appended. Might be NULL */
91225 ){
91226  sqlite3 *db = pParse->db;
91227  int n;
91228  int i;
91229  int iFirst = pList ? pList->nExpr : 0;
91230  /* pColumns can only be NULL due to an OOM but an OOM will cause an
91231  ** exit prior to this routine being invoked */
91232  if( NEVER(pColumns==0) ) goto vector_append_error;
91233  if( pExpr==0 ) goto vector_append_error;
91234  n = sqlite3ExprVectorSize(pExpr);
91235  if( pColumns->nId!=n ){
91236  sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
91237  pColumns->nId, n);
91238  goto vector_append_error;
91239  }
91240  for(i=0; i<n; i++){
91241  Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
91242  pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
91243  if( pList ){
91244  assert( pList->nExpr==iFirst+i+1 );
91245  pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
91246  pColumns->a[i].zName = 0;
91247  }
91248  }
91249  if( pExpr->op==TK_SELECT ){
91250  if( pList && pList->a[iFirst].pExpr ){
91251  assert( pList->a[iFirst].pExpr->op==TK_SELECT_COLUMN );
91252  pList->a[iFirst].pExpr->pRight = pExpr;
91253  pExpr = 0;
91254  }
91255  }
91256 
91257 vector_append_error:
91258  sqlite3ExprDelete(db, pExpr);
91259  sqlite3IdListDelete(db, pColumns);
91260  return pList;
91261 }
91262 
91263 /*
91264 ** Set the sort order for the last element on the given ExprList.
91265 */
91267  if( p==0 ) return;
91268  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
91269  assert( p->nExpr>0 );
91270  if( iSortOrder<0 ){
91271  assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
91272  return;
91273  }
91274  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
91275 }
91276 
91277 /*
91278 ** Set the ExprList.a[].zName element of the most recently added item
91279 ** on the expression list.
91280 **
91281 ** pList might be NULL following an OOM error. But pName should never be
91282 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
91283 ** is set.
91284 */
91286  Parse *pParse, /* Parsing context */
91287  ExprList *pList, /* List to which to add the span. */
91288  Token *pName, /* Name to be added */
91289  int dequote /* True to cause the name to be dequoted */
91290 ){
91291  assert( pList!=0 || pParse->db->mallocFailed!=0 );
91292  if( pList ){
91293  struct ExprList_item *pItem;
91294  assert( pList->nExpr>0 );
91295  pItem = &pList->a[pList->nExpr-1];
91296  assert( pItem->zName==0 );
91297  pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
91298  if( dequote ) sqlite3Dequote(pItem->zName);
91299  }
91300 }
91301 
91302 /*
91303 ** Set the ExprList.a[].zSpan element of the most recently added item
91304 ** on the expression list.
91305 **
91306 ** pList might be NULL following an OOM error. But pSpan should never be
91307 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
91308 ** is set.
91309 */
91311  Parse *pParse, /* Parsing context */
91312  ExprList *pList, /* List to which to add the span. */
91313  ExprSpan *pSpan /* The span to be added */
91314 ){
91315  sqlite3 *db = pParse->db;
91316  assert( pList!=0 || db->mallocFailed!=0 );
91317  if( pList ){
91318  struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
91319  assert( pList->nExpr>0 );
91320  assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
91321  sqlite3DbFree(db, pItem->zSpan);
91322  pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
91323  (int)(pSpan->zEnd - pSpan->zStart));
91324  }
91325 }
91326 
91327 /*
91328 ** If the expression list pEList contains more than iLimit elements,
91329 ** leave an error message in pParse.
91330 */
91332  Parse *pParse,
91333  ExprList *pEList,
91334  const char *zObject
91335 ){
91336  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
91337  testcase( pEList && pEList->nExpr==mx );
91338  testcase( pEList && pEList->nExpr==mx+1 );
91339  if( pEList && pEList->nExpr>mx ){
91340  sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
91341  }
91342 }
91343 
91344 /*
91345 ** Delete an entire expression list.
91346 */
91348  int i;
91349  struct ExprList_item *pItem;
91350  assert( pList->a!=0 || pList->nExpr==0 );
91351  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
91352  sqlite3ExprDelete(db, pItem->pExpr);
91353  sqlite3DbFree(db, pItem->zName);
91354  sqlite3DbFree(db, pItem->zSpan);
91355  }
91356  sqlite3DbFree(db, pList->a);
91357  sqlite3DbFree(db, pList);
91358 }
91360  if( pList ) exprListDeleteNN(db, pList);
91361 }
91362 
91363 /*
91364 ** Return the bitwise-OR of all Expr.flags fields in the given
91365 ** ExprList.
91366 */
91368  int i;
91369  u32 m = 0;
91370  if( pList ){
91371  for(i=0; i<pList->nExpr; i++){
91372  Expr *pExpr = pList->a[i].pExpr;
91373  assert( pExpr!=0 );
91374  m |= pExpr->flags;
91375  }
91376  }
91377  return m;
91378 }
91379 
91380 /*
91381 ** These routines are Walker callbacks used to check expressions to
91382 ** see if they are "constant" for some definition of constant. The
91383 ** Walker.eCode value determines the type of "constant" we are looking
91384 ** for.
91385 **
91386 ** These callback routines are used to implement the following:
91387 **
91388 ** sqlite3ExprIsConstant() pWalker->eCode==1
91389 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
91390 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
91391 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
91392 **
91393 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
91394 ** is found to not be a constant.
91395 **
91396 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
91397 ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
91398 ** an existing schema and 4 when processing a new statement. A bound
91399 ** parameter raises an error for new statements, but is silently converted
91400 ** to NULL for existing schemas. This allows sqlite_master tables that
91401 ** contain a bound parameter because they were generated by older versions
91402 ** of SQLite to be parsed by newer versions of SQLite without raising a
91403 ** malformed schema error.
91404 */
91405 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
91406 
91407  /* If pWalker->eCode is 2 then any term of the expression that comes from
91408  ** the ON or USING clauses of a left join disqualifies the expression
91409  ** from being considered constant. */
91410  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
91411  pWalker->eCode = 0;
91412  return WRC_Abort;
91413  }
91414 
91415  switch( pExpr->op ){
91416  /* Consider functions to be constant if all their arguments are constant
91417  ** and either pWalker->eCode==4 or 5 or the function has the
91418  ** SQLITE_FUNC_CONST flag. */
91419  case TK_FUNCTION:
91420  if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
91421  return WRC_Continue;
91422  }else{
91423  pWalker->eCode = 0;
91424  return WRC_Abort;
91425  }
91426  case TK_ID:
91427  case TK_COLUMN:
91428  case TK_AGG_FUNCTION:
91429  case TK_AGG_COLUMN:
91430  testcase( pExpr->op==TK_ID );
91431  testcase( pExpr->op==TK_COLUMN );
91432  testcase( pExpr->op==TK_AGG_FUNCTION );
91433  testcase( pExpr->op==TK_AGG_COLUMN );
91434  if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
91435  return WRC_Continue;
91436  }else{
91437  pWalker->eCode = 0;
91438  return WRC_Abort;
91439  }
91440  case TK_VARIABLE:
91441  if( pWalker->eCode==5 ){
91442  /* Silently convert bound parameters that appear inside of CREATE
91443  ** statements into a NULL when parsing the CREATE statement text out
91444  ** of the sqlite_master table */
91445  pExpr->op = TK_NULL;
91446  }else if( pWalker->eCode==4 ){
91447  /* A bound parameter in a CREATE statement that originates from
91448  ** sqlite3_prepare() causes an error */
91449  pWalker->eCode = 0;
91450  return WRC_Abort;
91451  }
91452  /* Fall through */
91453  default:
91454  testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
91455  testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
91456  return WRC_Continue;
91457  }
91458 }
91459 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
91460  UNUSED_PARAMETER(NotUsed);
91461  pWalker->eCode = 0;
91462  return WRC_Abort;
91463 }
91464 static int exprIsConst(Expr *p, int initFlag, int iCur){
91465  Walker w;
91466  memset(&w, 0, sizeof(w));
91467  w.eCode = initFlag;
91470  w.u.iCur = iCur;
91471  sqlite3WalkExpr(&w, p);
91472  return w.eCode;
91473 }
91474 
91475 /*
91476 ** Walk an expression tree. Return non-zero if the expression is constant
91477 ** and 0 if it involves variables or function calls.
91478 **
91479 ** For the purposes of this function, a double-quoted string (ex: "abc")
91480 ** is considered a variable but a single-quoted string (ex: 'abc') is
91481 ** a constant.
91482 */
91484  return exprIsConst(p, 1, 0);
91485 }
91486 
91487 /*
91488 ** Walk an expression tree. Return non-zero if the expression is constant
91489 ** that does no originate from the ON or USING clauses of a join.
91490 ** Return 0 if it involves variables or function calls or terms from
91491 ** an ON or USING clause.
91492 */
91494  return exprIsConst(p, 2, 0);
91495 }
91496 
91497 /*
91498 ** Walk an expression tree. Return non-zero if the expression is constant
91499 ** for any single row of the table with cursor iCur. In other words, the
91500 ** expression must not refer to any non-deterministic function nor any
91501 ** table other than iCur.
91502 */
91504  return exprIsConst(p, 3, iCur);
91505 }
91506 
91507 /*
91508 ** Walk an expression tree. Return non-zero if the expression is constant
91509 ** or a function call with constant arguments. Return and 0 if there
91510 ** are any variables.
91511 **
91512 ** For the purposes of this function, a double-quoted string (ex: "abc")
91513 ** is considered a variable but a single-quoted string (ex: 'abc') is
91514 ** a constant.
91515 */
91517  assert( isInit==0 || isInit==1 );
91518  return exprIsConst(p, 4+isInit, 0);
91519 }
91520 
91521 #ifdef SQLITE_ENABLE_CURSOR_HINTS
91522 /*
91523 ** Walk an expression tree. Return 1 if the expression contains a
91524 ** subquery of some kind. Return 0 if there are no subqueries.
91525 */
91526 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
91527  Walker w;
91528  memset(&w, 0, sizeof(w));
91529  w.eCode = 1;
91532  sqlite3WalkExpr(&w, p);
91533  return w.eCode==0;
91534 }
91535 #endif
91536 
91537 /*
91538 ** If the expression p codes a constant integer that is small enough
91539 ** to fit in a 32-bit integer, return 1 and put the value of the integer
91540 ** in *pValue. If the expression is not an integer or if it is too big
91541 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
91542 */
91544  int rc = 0;
91545 
91546  /* If an expression is an integer literal that fits in a signed 32-bit
91547  ** integer, then the EP_IntValue flag will have already been set */
91548  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
91549  || sqlite3GetInt32(p->u.zToken, &rc)==0 );
91550 
91551  if( p->flags & EP_IntValue ){
91552  *pValue = p->u.iValue;
91553  return 1;
91554  }
91555  switch( p->op ){
91556  case TK_UPLUS: {
91557  rc = sqlite3ExprIsInteger(p->pLeft, pValue);
91558  break;
91559  }
91560  case TK_UMINUS: {
91561  int v;
91562  if( sqlite3ExprIsInteger(p->pLeft, &v) ){
91563  assert( v!=(-2147483647-1) );
91564  *pValue = -v;
91565  rc = 1;
91566  }
91567  break;
91568  }
91569  default: break;
91570  }
91571  return rc;
91572 }
91573 
91574 /*
91575 ** Return FALSE if there is no chance that the expression can be NULL.
91576 **
91577 ** If the expression might be NULL or if the expression is too complex
91578 ** to tell return TRUE.
91579 **
91580 ** This routine is used as an optimization, to skip OP_IsNull opcodes
91581 ** when we know that a value cannot be NULL. Hence, a false positive
91582 ** (returning TRUE when in fact the expression can never be NULL) might
91583 ** be a small performance hit but is otherwise harmless. On the other
91584 ** hand, a false negative (returning FALSE when the result could be NULL)
91585 ** will likely result in an incorrect answer. So when in doubt, return
91586 ** TRUE.
91587 */
91589  u8 op;
91590  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
91591  op = p->op;
91592  if( op==TK_REGISTER ) op = p->op2;
91593  switch( op ){
91594  case TK_INTEGER:
91595  case TK_STRING:
91596  case TK_FLOAT:
91597  case TK_BLOB:
91598  return 0;
91599  case TK_COLUMN:
91600  assert( p->pTab!=0 );
91601  return ExprHasProperty(p, EP_CanBeNull) ||
91602  (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
91603  default:
91604  return 1;
91605  }
91606 }
91607 
91608 /*
91609 ** Return TRUE if the given expression is a constant which would be
91610 ** unchanged by OP_Affinity with the affinity given in the second
91611 ** argument.
91612 **
91613 ** This routine is used to determine if the OP_Affinity operation
91614 ** can be omitted. When in doubt return FALSE. A false negative
91615 ** is harmless. A false positive, however, can result in the wrong
91616 ** answer.
91617 */
91619  u8 op;
91620  if( aff==SQLITE_AFF_BLOB ) return 1;
91621  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
91622  op = p->op;
91623  if( op==TK_REGISTER ) op = p->op2;
91624  switch( op ){
91625  case TK_INTEGER: {
91626  return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
91627  }
91628  case TK_FLOAT: {
91629  return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
91630  }
91631  case TK_STRING: {
91632  return aff==SQLITE_AFF_TEXT;
91633  }
91634  case TK_BLOB: {
91635  return 1;
91636  }
91637  case TK_COLUMN: {
91638  assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
91639  return p->iColumn<0
91640  && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
91641  }
91642  default: {
91643  return 0;
91644  }
91645  }
91646 }
91647 
91648 /*
91649 ** Return TRUE if the given string is a row-id column name.
91650 */
91651 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
91652  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
91653  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
91654  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
91655  return 0;
91656 }
91657 
91658 /*
91659 ** pX is the RHS of an IN operator. If pX is a SELECT statement
91660 ** that can be simplified to a direct table access, then return
91661 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
91662 ** or if the SELECT statement needs to be manifested into a transient
91663 ** table, then return NULL.
91664 */
91665 #ifndef SQLITE_OMIT_SUBQUERY
91667  Select *p;
91668  SrcList *pSrc;
91669  ExprList *pEList;
91670  Table *pTab;
91671  int i;
91672  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
91673  if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
91674  p = pX->x.pSelect;
91675  if( p->pPrior ) return 0; /* Not a compound SELECT */
91676  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
91679  return 0; /* No DISTINCT keyword and no aggregate functions */
91680  }
91681  assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
91682  if( p->pLimit ) return 0; /* Has no LIMIT clause */
91683  assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
91684  if( p->pWhere ) return 0; /* Has no WHERE clause */
91685  pSrc = p->pSrc;
91686  assert( pSrc!=0 );
91687  if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
91688  if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
91689  pTab = pSrc->a[0].pTab;
91690  assert( pTab!=0 );
91691  assert( pTab->pSelect==0 ); /* FROM clause is not a view */
91692  if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
91693  pEList = p->pEList;
91694  assert( pEList!=0 );
91695  /* All SELECT results must be columns. */
91696  for(i=0; i<pEList->nExpr; i++){
91697  Expr *pRes = pEList->a[i].pExpr;
91698  if( pRes->op!=TK_COLUMN ) return 0;
91699  assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
91700  }
91701  return p;
91702 }
91703 #endif /* SQLITE_OMIT_SUBQUERY */
91704 
91705 #ifndef SQLITE_OMIT_SUBQUERY
91706 /*
91707 ** Generate code that checks the left-most column of index table iCur to see if
91708 ** it contains any NULL entries. Cause the register at regHasNull to be set
91709 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
91710 ** to be set to NULL if iCur contains one or more NULL values.
91711 */
91712 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
91713  int addr1;
91714  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
91715  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
91716  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
91718  VdbeComment((v, "first_entry_in(%d)", iCur));
91719  sqlite3VdbeJumpHere(v, addr1);
91720 }
91721 #endif
91722 
91723 
91724 #ifndef SQLITE_OMIT_SUBQUERY
91725 /*
91726 ** The argument is an IN operator with a list (not a subquery) on the
91727 ** right-hand side. Return TRUE if that list is constant.
91728 */
91729 static int sqlite3InRhsIsConstant(Expr *pIn){
91730  Expr *pLHS;
91731  int res;
91732  assert( !ExprHasProperty(pIn, EP_xIsSelect) );
91733  pLHS = pIn->pLeft;
91734  pIn->pLeft = 0;
91735  res = sqlite3ExprIsConstant(pIn);
91736  pIn->pLeft = pLHS;
91737  return res;
91738 }
91739 #endif
91740 
91741 /*
91742 ** This function is used by the implementation of the IN (...) operator.
91743 ** The pX parameter is the expression on the RHS of the IN operator, which
91744 ** might be either a list of expressions or a subquery.
91745 **
91746 ** The job of this routine is to find or create a b-tree object that can
91747 ** be used either to test for membership in the RHS set or to iterate through
91748 ** all members of the RHS set, skipping duplicates.
91749 **
91750 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
91751 ** and pX->iTable is set to the index of that cursor.
91752 **
91753 ** The returned value of this function indicates the b-tree type, as follows:
91754 **
91755 ** IN_INDEX_ROWID - The cursor was opened on a database table.
91756 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
91757 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
91758 ** IN_INDEX_EPH - The cursor was opened on a specially created and
91759 ** populated epheremal table.
91760 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
91761 ** implemented as a sequence of comparisons.
91762 **
91763 ** An existing b-tree might be used if the RHS expression pX is a simple
91764 ** subquery such as:
91765 **
91766 ** SELECT <column1>, <column2>... FROM <table>
91767 **
91768 ** If the RHS of the IN operator is a list or a more complex subquery, then
91769 ** an ephemeral table might need to be generated from the RHS and then
91770 ** pX->iTable made to point to the ephemeral table instead of an
91771 ** existing table.
91772 **
91773 ** The inFlags parameter must contain exactly one of the bits
91774 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
91775 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
91776 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
91777 ** IN index will be used to loop over all values of the RHS of the
91778 ** IN operator.
91779 **
91780 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
91781 ** through the set members) then the b-tree must not contain duplicates.
91782 ** An epheremal table must be used unless the selected columns are guaranteed
91783 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
91784 ** a UNIQUE constraint or index.
91785 **
91786 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
91787 ** for fast set membership tests) then an epheremal table must
91788 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
91789 ** index can be found with the specified <columns> as its left-most.
91790 **
91791 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
91792 ** if the RHS of the IN operator is a list (not a subquery) then this
91793 ** routine might decide that creating an ephemeral b-tree for membership
91794 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
91795 ** calling routine should implement the IN operator using a sequence
91796 ** of Eq or Ne comparison operations.
91797 **
91798 ** When the b-tree is being used for membership tests, the calling function
91799 ** might need to know whether or not the RHS side of the IN operator
91800 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
91801 ** if there is any chance that the (...) might contain a NULL value at
91802 ** runtime, then a register is allocated and the register number written
91803 ** to *prRhsHasNull. If there is no chance that the (...) contains a
91804 ** NULL value, then *prRhsHasNull is left unchanged.
91805 **
91806 ** If a register is allocated and its location stored in *prRhsHasNull, then
91807 ** the value in that register will be NULL if the b-tree contains one or more
91808 ** NULL values, and it will be some non-NULL value if the b-tree contains no
91809 ** NULL values.
91810 **
91811 ** If the aiMap parameter is not NULL, it must point to an array containing
91812 ** one element for each column returned by the SELECT statement on the RHS
91813 ** of the IN(...) operator. The i'th entry of the array is populated with the
91814 ** offset of the index column that matches the i'th column returned by the
91815 ** SELECT. For example, if the expression and selected index are:
91816 **
91817 ** (?,?,?) IN (SELECT a, b, c FROM t1)
91818 ** CREATE INDEX i1 ON t1(b, c, a);
91819 **
91820 ** then aiMap[] is populated with {2, 0, 1}.
91821 */
91822 #ifndef SQLITE_OMIT_SUBQUERY
91824  Parse *pParse, /* Parsing context */
91825  Expr *pX, /* The right-hand side (RHS) of the IN operator */
91826  u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
91827  int *prRhsHasNull, /* Register holding NULL status. See notes */
91828  int *aiMap /* Mapping from Index fields to RHS fields */
91829 ){
91830  Select *p; /* SELECT to the right of IN operator */
91831  int eType = 0; /* Type of RHS table. IN_INDEX_* */
91832  int iTab = pParse->nTab++; /* Cursor of the RHS table */
91833  int mustBeUnique; /* True if RHS must be unique */
91834  Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
91835 
91836  assert( pX->op==TK_IN );
91837  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
91838 
91839  /* If the RHS of this IN(...) operator is a SELECT, and if it matters
91840  ** whether or not the SELECT result contains NULL values, check whether
91841  ** or not NULL is actually possible (it may not be, for example, due
91842  ** to NOT NULL constraints in the schema). If no NULL values are possible,
91843  ** set prRhsHasNull to 0 before continuing. */
91844  if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
91845  int i;
91846  ExprList *pEList = pX->x.pSelect->pEList;
91847  for(i=0; i<pEList->nExpr; i++){
91848  if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
91849  }
91850  if( i==pEList->nExpr ){
91851  prRhsHasNull = 0;
91852  }
91853  }
91854 
91855  /* Check to see if an existing table or index can be used to
91856  ** satisfy the query. This is preferable to generating a new
91857  ** ephemeral table. */
91858  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
91859  sqlite3 *db = pParse->db; /* Database connection */
91860  Table *pTab; /* Table <table>. */
91861  i16 iDb; /* Database idx for pTab */
91862  ExprList *pEList = p->pEList;
91863  int nExpr = pEList->nExpr;
91864 
91865  assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
91866  assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
91867  assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
91868  pTab = p->pSrc->a[0].pTab;
91869 
91870  /* Code an OP_Transaction and OP_TableLock for <table>. */
91871  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91872  sqlite3CodeVerifySchema(pParse, iDb);
91873  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91874 
91875  assert(v); /* sqlite3GetVdbe() has always been previously called */
91876  if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
91877  /* The "x IN (SELECT rowid FROM table)" case */
91878  int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
91879  VdbeCoverage(v);
91880 
91881  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91882  eType = IN_INDEX_ROWID;
91883 
91884  sqlite3VdbeJumpHere(v, iAddr);
91885  }else{
91886  Index *pIdx; /* Iterator variable */
91887  int affinity_ok = 1;
91888  int i;
91889 
91890  /* Check that the affinity that will be used to perform each
91891  ** comparison is the same as the affinity of each column in table
91892  ** on the RHS of the IN operator. If it not, it is not possible to
91893  ** use any index of the RHS table. */
91894  for(i=0; i<nExpr && affinity_ok; i++){
91895  Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
91896  int iCol = pEList->a[i].pExpr->iColumn;
91897  char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
91898  char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
91899  testcase( cmpaff==SQLITE_AFF_BLOB );
91900  testcase( cmpaff==SQLITE_AFF_TEXT );
91901  switch( cmpaff ){
91902  case SQLITE_AFF_BLOB:
91903  break;
91904  case SQLITE_AFF_TEXT:
91905  /* sqlite3CompareAffinity() only returns TEXT if one side or the
91906  ** other has no affinity and the other side is TEXT. Hence,
91907  ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
91908  ** and for the term on the LHS of the IN to have no affinity. */
91909  assert( idxaff==SQLITE_AFF_TEXT );
91910  break;
91911  default:
91912  affinity_ok = sqlite3IsNumericAffinity(idxaff);
91913  }
91914  }
91915 
91916  if( affinity_ok ){
91917  /* Search for an existing index that will work for this IN operator */
91918  for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
91919  Bitmask colUsed; /* Columns of the index used */
91920  Bitmask mCol; /* Mask for the current column */
91921  if( pIdx->nColumn<nExpr ) continue;
91922  /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
91923  ** BITMASK(nExpr) without overflowing */
91924  testcase( pIdx->nColumn==BMS-2 );
91925  testcase( pIdx->nColumn==BMS-1 );
91926  if( pIdx->nColumn>=BMS-1 ) continue;
91927  if( mustBeUnique ){
91928  if( pIdx->nKeyCol>nExpr
91929  ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
91930  ){
91931  continue; /* This index is not unique over the IN RHS columns */
91932  }
91933  }
91934 
91935  colUsed = 0; /* Columns of index used so far */
91936  for(i=0; i<nExpr; i++){
91937  Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
91938  Expr *pRhs = pEList->a[i].pExpr;
91939  CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
91940  int j;
91941 
91942  assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
91943  for(j=0; j<nExpr; j++){
91944  if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
91945  assert( pIdx->azColl[j] );
91946  if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
91947  continue;
91948  }
91949  break;
91950  }
91951  if( j==nExpr ) break;
91952  mCol = MASKBIT(j);
91953  if( mCol & colUsed ) break; /* Each column used only once */
91954  colUsed |= mCol;
91955  if( aiMap ) aiMap[i] = j;
91956  }
91957 
91958  assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
91959  if( colUsed==(MASKBIT(nExpr)-1) ){
91960  /* If we reach this point, that means the index pIdx is usable */
91961  int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
91962 #ifndef SQLITE_OMIT_EXPLAIN
91963  sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
91964  sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
91965  P4_DYNAMIC);
91966 #endif
91967  sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
91968  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91969  VdbeComment((v, "%s", pIdx->zName));
91970  assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
91971  eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
91972 
91973  if( prRhsHasNull ){
91974 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
91975  i64 mask = (1<<nExpr)-1;
91977  iTab, 0, 0, (u8*)&mask, P4_INT64);
91978 #endif
91979  *prRhsHasNull = ++pParse->nMem;
91980  if( nExpr==1 ){
91981  sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
91982  }
91983  }
91984  sqlite3VdbeJumpHere(v, iAddr);
91985  }
91986  } /* End loop over indexes */
91987  } /* End if( affinity_ok ) */
91988  } /* End if not an rowid index */
91989  } /* End attempt to optimize using an index */
91990 
91991  /* If no preexisting index is available for the IN clause
91992  ** and IN_INDEX_NOOP is an allowed reply
91993  ** and the RHS of the IN operator is a list, not a subquery
91994  ** and the RHS is not constant or has two or fewer terms,
91995  ** then it is not worth creating an ephemeral table to evaluate
91996  ** the IN operator so return IN_INDEX_NOOP.
91997  */
91998  if( eType==0
91999  && (inFlags & IN_INDEX_NOOP_OK)
92000  && !ExprHasProperty(pX, EP_xIsSelect)
92001  && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
92002  ){
92003  eType = IN_INDEX_NOOP;
92004  }
92005 
92006  if( eType==0 ){
92007  /* Could not find an existing table or index to use as the RHS b-tree.
92008  ** We will have to generate an ephemeral table to do the job.
92009  */
92010  u32 savedNQueryLoop = pParse->nQueryLoop;
92011  int rMayHaveNull = 0;
92012  eType = IN_INDEX_EPH;
92013  if( inFlags & IN_INDEX_LOOP ){
92014  pParse->nQueryLoop = 0;
92015  if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
92016  eType = IN_INDEX_ROWID;
92017  }
92018  }else if( prRhsHasNull ){
92019  *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
92020  }
92021  sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
92022  pParse->nQueryLoop = savedNQueryLoop;
92023  }else{
92024  pX->iTable = iTab;
92025  }
92026 
92027  if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
92028  int i, n;
92029  n = sqlite3ExprVectorSize(pX->pLeft);
92030  for(i=0; i<n; i++) aiMap[i] = i;
92031  }
92032  return eType;
92033 }
92034 #endif
92035 
92036 #ifndef SQLITE_OMIT_SUBQUERY
92037 /*
92038 ** Argument pExpr is an (?, ?...) IN(...) expression. This
92039 ** function allocates and returns a nul-terminated string containing
92040 ** the affinities to be used for each column of the comparison.
92041 **
92042 ** It is the responsibility of the caller to ensure that the returned
92043 ** string is eventually freed using sqlite3DbFree().
92044 */
92045 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
92046  Expr *pLeft = pExpr->pLeft;
92047  int nVal = sqlite3ExprVectorSize(pLeft);
92048  Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
92049  char *zRet;
92050 
92051  assert( pExpr->op==TK_IN );
92052  zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
92053  if( zRet ){
92054  int i;
92055  for(i=0; i<nVal; i++){
92056  Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
92057  char a = sqlite3ExprAffinity(pA);
92058  if( pSelect ){
92059  zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
92060  }else{
92061  zRet[i] = a;
92062  }
92063  }
92064  zRet[nVal] = '\0';
92065  }
92066  return zRet;
92067 }
92068 #endif
92069 
92070 #ifndef SQLITE_OMIT_SUBQUERY
92071 /*
92072 ** Load the Parse object passed as the first argument with an error
92073 ** message of the form:
92074 **
92075 ** "sub-select returns N columns - expected M"
92076 */
92077 SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
92078  const char *zFmt = "sub-select returns %d columns - expected %d";
92079  sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
92080 }
92081 #endif
92082 
92083 /*
92084 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
92085 ** or IN operators. Examples:
92086 **
92087 ** (SELECT a FROM b) -- subquery
92088 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
92089 ** x IN (4,5,11) -- IN operator with list on right-hand side
92090 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
92091 **
92092 ** The pExpr parameter describes the expression that contains the IN
92093 ** operator or subquery.
92094 **
92095 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
92096 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
92097 ** to some integer key column of a table B-Tree. In this case, use an
92098 ** intkey B-Tree to store the set of IN(...) values instead of the usual
92099 ** (slower) variable length keys B-Tree.
92100 **
92101 ** If rMayHaveNull is non-zero, that means that the operation is an IN
92102 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
92103 ** All this routine does is initialize the register given by rMayHaveNull
92104 ** to NULL. Calling routines will take care of changing this register
92105 ** value to non-NULL if the RHS is NULL-free.
92106 **
92107 ** For a SELECT or EXISTS operator, return the register that holds the
92108 ** result. For a multi-column SELECT, the result is stored in a contiguous
92109 ** array of registers and the return value is the register of the left-most
92110 ** result column. Return 0 for IN operators or if an error occurs.
92111 */
92112 #ifndef SQLITE_OMIT_SUBQUERY
92114  Parse *pParse, /* Parsing context */
92115  Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
92116  int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
92117  int isRowid /* If true, LHS of IN operator is a rowid */
92118 ){
92119  int jmpIfDynamic = -1; /* One-time test address */
92120  int rReg = 0; /* Register storing resulting */
92121  Vdbe *v = sqlite3GetVdbe(pParse);
92122  if( NEVER(v==0) ) return 0;
92123  sqlite3ExprCachePush(pParse);
92124 
92125  /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
92126  ** is encountered if any of the following is true:
92127  **
92128  ** * The right-hand side is a correlated subquery
92129  ** * The right-hand side is an expression list containing variables
92130  ** * We are inside a trigger
92131  **
92132  ** If all of the above are false, then we can run this code just once
92133  ** save the results, and reuse the same result on subsequent invocations.
92134  */
92135  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
92136  jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
92137  }
92138 
92139 #ifndef SQLITE_OMIT_EXPLAIN
92140  if( pParse->explain==2 ){
92141  char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
92142  jmpIfDynamic>=0?"":"CORRELATED ",
92143  pExpr->op==TK_IN?"LIST":"SCALAR",
92144  pParse->iNextSelectId
92145  );
92146  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
92147  }
92148 #endif
92149 
92150  switch( pExpr->op ){
92151  case TK_IN: {
92152  int addr; /* Address of OP_OpenEphemeral instruction */
92153  Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
92154  KeyInfo *pKeyInfo = 0; /* Key information */
92155  int nVal; /* Size of vector pLeft */
92156 
92157  nVal = sqlite3ExprVectorSize(pLeft);
92158  assert( !isRowid || nVal==1 );
92159 
92160  /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
92161  ** expression it is handled the same way. An ephemeral table is
92162  ** filled with index keys representing the results from the
92163  ** SELECT or the <exprlist>.
92164  **
92165  ** If the 'x' expression is a column value, or the SELECT...
92166  ** statement returns a column value, then the affinity of that
92167  ** column is used to build the index keys. If both 'x' and the
92168  ** SELECT... statement are columns, then numeric affinity is used
92169  ** if either column has NUMERIC or INTEGER affinity. If neither
92170  ** 'x' nor the SELECT... statement are columns, then numeric affinity
92171  ** is used.
92172  */
92173  pExpr->iTable = pParse->nTab++;
92175  pExpr->iTable, (isRowid?0:nVal));
92176  pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
92177 
92178  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92179  /* Case 1: expr IN (SELECT ...)
92180  **
92181  ** Generate code to write the results of the select into the temporary
92182  ** table allocated and opened above.
92183  */
92184  Select *pSelect = pExpr->x.pSelect;
92185  ExprList *pEList = pSelect->pEList;
92186 
92187  assert( !isRowid );
92188  /* If the LHS and RHS of the IN operator do not match, that
92189  ** error will have been caught long before we reach this point. */
92190  if( ALWAYS(pEList->nExpr==nVal) ){
92191  SelectDest dest;
92192  int i;
92193  sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
92194  dest.zAffSdst = exprINAffinity(pParse, pExpr);
92195  assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
92196  pSelect->iLimit = 0;
92197  testcase( pSelect->selFlags & SF_Distinct );
92198  testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
92199  if( sqlite3Select(pParse, pSelect, &dest) ){
92200  sqlite3DbFree(pParse->db, dest.zAffSdst);
92201  sqlite3KeyInfoUnref(pKeyInfo);
92202  return 0;
92203  }
92204  sqlite3DbFree(pParse->db, dest.zAffSdst);
92205  assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
92206  assert( pEList!=0 );
92207  assert( pEList->nExpr>0 );
92208  assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
92209  for(i=0; i<nVal; i++){
92210  Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
92211  pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
92212  pParse, p, pEList->a[i].pExpr
92213  );
92214  }
92215  }
92216  }else if( ALWAYS(pExpr->x.pList!=0) ){
92217  /* Case 2: expr IN (exprlist)
92218  **
92219  ** For each expression, build an index key from the evaluation and
92220  ** store it in the temporary table. If <expr> is a column, then use
92221  ** that columns affinity when building index keys. If <expr> is not
92222  ** a column, use numeric affinity.
92223  */
92224  char affinity; /* Affinity of the LHS of the IN */
92225  int i;
92226  ExprList *pList = pExpr->x.pList;
92227  struct ExprList_item *pItem;
92228  int r1, r2, r3;
92229 
92230  affinity = sqlite3ExprAffinity(pLeft);
92231  if( !affinity ){
92232  affinity = SQLITE_AFF_BLOB;
92233  }
92234  if( pKeyInfo ){
92235  assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
92236  pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
92237  }
92238 
92239  /* Loop through each expression in <exprlist>. */
92240  r1 = sqlite3GetTempReg(pParse);
92241  r2 = sqlite3GetTempReg(pParse);
92242  if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
92243  for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
92244  Expr *pE2 = pItem->pExpr;
92245  int iValToIns;
92246 
92247  /* If the expression is not constant then we will need to
92248  ** disable the test that was generated above that makes sure
92249  ** this code only executes once. Because for a non-constant
92250  ** expression we need to rerun this code each time.
92251  */
92252  if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
92253  sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
92254  jmpIfDynamic = -1;
92255  }
92256 
92257  /* Evaluate the expression and insert it into the temp table */
92258  if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
92259  sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
92260  }else{
92261  r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
92262  if( isRowid ){
92264  sqlite3VdbeCurrentAddr(v)+2);
92265  VdbeCoverage(v);
92266  sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
92267  }else{
92268  sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
92269  sqlite3ExprCacheAffinityChange(pParse, r3, 1);
92270  sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
92271  }
92272  }
92273  }
92274  sqlite3ReleaseTempReg(pParse, r1);
92275  sqlite3ReleaseTempReg(pParse, r2);
92276  }
92277  if( pKeyInfo ){
92278  sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
92279  }
92280  break;
92281  }
92282 
92283  case TK_EXISTS:
92284  case TK_SELECT:
92285  default: {
92286  /* Case 3: (SELECT ... FROM ...)
92287  ** or: EXISTS(SELECT ... FROM ...)
92288  **
92289  ** For a SELECT, generate code to put the values for all columns of
92290  ** the first row into an array of registers and return the index of
92291  ** the first register.
92292  **
92293  ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
92294  ** into a register and return that register number.
92295  **
92296  ** In both cases, the query is augmented with "LIMIT 1". Any
92297  ** preexisting limit is discarded in place of the new LIMIT 1.
92298  */
92299  Select *pSel; /* SELECT statement to encode */
92300  SelectDest dest; /* How to deal with SELECT result */
92301  int nReg; /* Registers to allocate */
92302 
92303  testcase( pExpr->op==TK_EXISTS );
92304  testcase( pExpr->op==TK_SELECT );
92305  assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
92306  assert( ExprHasProperty(pExpr, EP_xIsSelect) );
92307 
92308  pSel = pExpr->x.pSelect;
92309  nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
92310  sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
92311  pParse->nMem += nReg;
92312  if( pExpr->op==TK_SELECT ){
92313  dest.eDest = SRT_Mem;
92314  dest.iSdst = dest.iSDParm;
92315  dest.nSdst = nReg;
92316  sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
92317  VdbeComment((v, "Init subquery result"));
92318  }else{
92319  dest.eDest = SRT_Exists;
92320  sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
92321  VdbeComment((v, "Init EXISTS result"));
92322  }
92323  sqlite3ExprDelete(pParse->db, pSel->pLimit);
92324  pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
92325  &sqlite3IntTokens[1], 0);
92326  pSel->iLimit = 0;
92327  pSel->selFlags &= ~SF_MultiValue;
92328  if( sqlite3Select(pParse, pSel, &dest) ){
92329  return 0;
92330  }
92331  rReg = dest.iSDParm;
92333  break;
92334  }
92335  }
92336 
92337  if( rHasNullFlag ){
92338  sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
92339  }
92340 
92341  if( jmpIfDynamic>=0 ){
92342  sqlite3VdbeJumpHere(v, jmpIfDynamic);
92343  }
92344  sqlite3ExprCachePop(pParse);
92345 
92346  return rReg;
92347 }
92348 #endif /* SQLITE_OMIT_SUBQUERY */
92349 
92350 #ifndef SQLITE_OMIT_SUBQUERY
92351 /*
92352 ** Expr pIn is an IN(...) expression. This function checks that the
92353 ** sub-select on the RHS of the IN() operator has the same number of
92354 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
92355 ** a sub-query, that the LHS is a vector of size 1.
92356 */
92358  int nVector = sqlite3ExprVectorSize(pIn->pLeft);
92359  if( (pIn->flags & EP_xIsSelect) ){
92360  if( nVector!=pIn->x.pSelect->pEList->nExpr ){
92361  sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
92362  return 1;
92363  }
92364  }else if( nVector!=1 ){
92365  if( (pIn->pLeft->flags & EP_xIsSelect) ){
92366  sqlite3SubselectError(pParse, nVector, 1);
92367  }else{
92368  sqlite3ErrorMsg(pParse, "row value misused");
92369  }
92370  return 1;
92371  }
92372  return 0;
92373 }
92374 #endif
92375 
92376 #ifndef SQLITE_OMIT_SUBQUERY
92377 /*
92378 ** Generate code for an IN expression.
92379 **
92380 ** x IN (SELECT ...)
92381 ** x IN (value, value, ...)
92382 **
92383 ** The left-hand side (LHS) is a scalar or vector expression. The
92384 ** right-hand side (RHS) is an array of zero or more scalar values, or a
92385 ** subquery. If the RHS is a subquery, the number of result columns must
92386 ** match the number of columns in the vector on the LHS. If the RHS is
92387 ** a list of values, the LHS must be a scalar.
92388 **
92389 ** The IN operator is true if the LHS value is contained within the RHS.
92390 ** The result is false if the LHS is definitely not in the RHS. The
92391 ** result is NULL if the presence of the LHS in the RHS cannot be
92392 ** determined due to NULLs.
92393 **
92394 ** This routine generates code that jumps to destIfFalse if the LHS is not
92395 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
92396 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
92397 ** within the RHS then fall through.
92398 **
92399 ** See the separate in-operator.md documentation file in the canonical
92400 ** SQLite source tree for additional information.
92401 */
92402 static void sqlite3ExprCodeIN(
92403  Parse *pParse, /* Parsing and code generating context */
92404  Expr *pExpr, /* The IN expression */
92405  int destIfFalse, /* Jump here if LHS is not contained in the RHS */
92406  int destIfNull /* Jump here if the results are unknown due to NULLs */
92407 ){
92408  int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
92409  int eType; /* Type of the RHS */
92410  int rLhs; /* Register(s) holding the LHS values */
92411  int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
92412  Vdbe *v; /* Statement under construction */
92413  int *aiMap = 0; /* Map from vector field to index column */
92414  char *zAff = 0; /* Affinity string for comparisons */
92415  int nVector; /* Size of vectors for this IN operator */
92416  int iDummy; /* Dummy parameter to exprCodeVector() */
92417  Expr *pLeft; /* The LHS of the IN operator */
92418  int i; /* loop counter */
92419  int destStep2; /* Where to jump when NULLs seen in step 2 */
92420  int destStep6 = 0; /* Start of code for Step 6 */
92421  int addrTruthOp; /* Address of opcode that determines the IN is true */
92422  int destNotNull; /* Jump here if a comparison is not true in step 6 */
92423  int addrTop; /* Top of the step-6 loop */
92424 
92425  pLeft = pExpr->pLeft;
92426  if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
92427  zAff = exprINAffinity(pParse, pExpr);
92428  nVector = sqlite3ExprVectorSize(pExpr->pLeft);
92429  aiMap = (int*)sqlite3DbMallocZero(
92430  pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
92431  );
92432  if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
92433 
92434  /* Attempt to compute the RHS. After this step, if anything other than
92435  ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
92436  ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
92437  ** the RHS has not yet been coded. */
92438  v = pParse->pVdbe;
92439  assert( v!=0 ); /* OOM detected prior to this routine */
92440  VdbeNoopComment((v, "begin IN expr"));
92441  eType = sqlite3FindInIndex(pParse, pExpr,
92443  destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
92444 
92445  assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
92446  || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
92447  );
92448 #ifdef SQLITE_DEBUG
92449  /* Confirm that aiMap[] contains nVector integer values between 0 and
92450  ** nVector-1. */
92451  for(i=0; i<nVector; i++){
92452  int j, cnt;
92453  for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
92454  assert( cnt==1 );
92455  }
92456 #endif
92457 
92458  /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
92459  ** vector, then it is stored in an array of nVector registers starting
92460  ** at r1.
92461  **
92462  ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
92463  ** so that the fields are in the same order as an existing index. The
92464  ** aiMap[] array contains a mapping from the original LHS field order to
92465  ** the field order that matches the RHS index.
92466  */
92467  sqlite3ExprCachePush(pParse);
92468  rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
92469  for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
92470  if( i==nVector ){
92471  /* LHS fields are not reordered */
92472  rLhs = rLhsOrig;
92473  }else{
92474  /* Need to reorder the LHS fields according to aiMap */
92475  rLhs = sqlite3GetTempRange(pParse, nVector);
92476  for(i=0; i<nVector; i++){
92477  sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
92478  }
92479  }
92480 
92481  /* If sqlite3FindInIndex() did not find or create an index that is
92482  ** suitable for evaluating the IN operator, then evaluate using a
92483  ** sequence of comparisons.
92484  **
92485  ** This is step (1) in the in-operator.md optimized algorithm.
92486  */
92487  if( eType==IN_INDEX_NOOP ){
92488  ExprList *pList = pExpr->x.pList;
92489  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
92490  int labelOk = sqlite3VdbeMakeLabel(v);
92491  int r2, regToFree;
92492  int regCkNull = 0;
92493  int ii;
92494  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92495  if( destIfNull!=destIfFalse ){
92496  regCkNull = sqlite3GetTempReg(pParse);
92497  sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
92498  }
92499  for(ii=0; ii<pList->nExpr; ii++){
92500  r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
92501  if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
92502  sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
92503  }
92504  if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
92505  sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
92506  (void*)pColl, P4_COLLSEQ);
92507  VdbeCoverageIf(v, ii<pList->nExpr-1);
92508  VdbeCoverageIf(v, ii==pList->nExpr-1);
92509  sqlite3VdbeChangeP5(v, zAff[0]);
92510  }else{
92511  assert( destIfNull==destIfFalse );
92512  sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
92513  (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
92514  sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
92515  }
92516  sqlite3ReleaseTempReg(pParse, regToFree);
92517  }
92518  if( regCkNull ){
92519  sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
92520  sqlite3VdbeGoto(v, destIfFalse);
92521  }
92522  sqlite3VdbeResolveLabel(v, labelOk);
92523  sqlite3ReleaseTempReg(pParse, regCkNull);
92524  goto sqlite3ExprCodeIN_finished;
92525  }
92526 
92527  /* Step 2: Check to see if the LHS contains any NULL columns. If the
92528  ** LHS does contain NULLs then the result must be either FALSE or NULL.
92529  ** We will then skip the binary search of the RHS.
92530  */
92531  if( destIfNull==destIfFalse ){
92532  destStep2 = destIfFalse;
92533  }else{
92534  destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
92535  }
92536  for(i=0; i<nVector; i++){
92537  Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
92538  if( sqlite3ExprCanBeNull(p) ){
92539  sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
92540  VdbeCoverage(v);
92541  }
92542  }
92543 
92544  /* Step 3. The LHS is now known to be non-NULL. Do the binary search
92545  ** of the RHS using the LHS as a probe. If found, the result is
92546  ** true.
92547  */
92548  if( eType==IN_INDEX_ROWID ){
92549  /* In this case, the RHS is the ROWID of table b-tree and so we also
92550  ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
92551  ** into a single opcode. */
92552  sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
92553  VdbeCoverage(v);
92554  addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
92555  }else{
92556  sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
92557  if( destIfFalse==destIfNull ){
92558  /* Combine Step 3 and Step 5 into a single opcode */
92559  sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
92560  rLhs, nVector); VdbeCoverage(v);
92561  goto sqlite3ExprCodeIN_finished;
92562  }
92563  /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
92564  addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
92565  rLhs, nVector); VdbeCoverage(v);
92566  }
92567 
92568  /* Step 4. If the RHS is known to be non-NULL and we did not find
92569  ** an match on the search above, then the result must be FALSE.
92570  */
92571  if( rRhsHasNull && nVector==1 ){
92572  sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
92573  VdbeCoverage(v);
92574  }
92575 
92576  /* Step 5. If we do not care about the difference between NULL and
92577  ** FALSE, then just return false.
92578  */
92579  if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
92580 
92581  /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
92582  ** If any comparison is NULL, then the result is NULL. If all
92583  ** comparisons are FALSE then the final result is FALSE.
92584  **
92585  ** For a scalar LHS, it is sufficient to check just the first row
92586  ** of the RHS.
92587  */
92588  if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
92589  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
92590  VdbeCoverage(v);
92591  if( nVector>1 ){
92592  destNotNull = sqlite3VdbeMakeLabel(v);
92593  }else{
92594  /* For nVector==1, combine steps 6 and 7 by immediately returning
92595  ** FALSE if the first comparison is not NULL */
92596  destNotNull = destIfFalse;
92597  }
92598  for(i=0; i<nVector; i++){
92599  Expr *p;
92600  CollSeq *pColl;
92601  int r3 = sqlite3GetTempReg(pParse);
92602  p = sqlite3VectorFieldSubexpr(pLeft, i);
92603  pColl = sqlite3ExprCollSeq(pParse, p);
92604  sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
92605  sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
92606  (void*)pColl, P4_COLLSEQ);
92607  VdbeCoverage(v);
92608  sqlite3ReleaseTempReg(pParse, r3);
92609  }
92610  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
92611  if( nVector>1 ){
92612  sqlite3VdbeResolveLabel(v, destNotNull);
92613  sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
92614  VdbeCoverage(v);
92615 
92616  /* Step 7: If we reach this point, we know that the result must
92617  ** be false. */
92618  sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
92619  }
92620 
92621  /* Jumps here in order to return true. */
92622  sqlite3VdbeJumpHere(v, addrTruthOp);
92623 
92624 sqlite3ExprCodeIN_finished:
92625  if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
92626  sqlite3ExprCachePop(pParse);
92627  VdbeComment((v, "end IN expr"));
92628 sqlite3ExprCodeIN_oom_error:
92629  sqlite3DbFree(pParse->db, aiMap);
92630  sqlite3DbFree(pParse->db, zAff);
92631 }
92632 #endif /* SQLITE_OMIT_SUBQUERY */
92633 
92634 #ifndef SQLITE_OMIT_FLOATING_POINT
92635 /*
92636 ** Generate an instruction that will put the floating point
92637 ** value described by z[0..n-1] into register iMem.
92638 **
92639 ** The z[] string will probably not be zero-terminated. But the
92640 ** z[n] character is guaranteed to be something that does not look
92641 ** like the continuation of the number.
92642 */
92643 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
92644  if( ALWAYS(z!=0) ){
92645  double value;
92646  sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
92647  assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
92648  if( negateFlag ) value = -value;
92649  sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
92650  }
92651 }
92652 #endif
92653 
92654 
92655 /*
92656 ** Generate an instruction that will put the integer describe by
92657 ** text z[0..n-1] into register iMem.
92658 **
92659 ** Expr.u.zToken is always UTF8 and zero-terminated.
92660 */
92661 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
92662  Vdbe *v = pParse->pVdbe;
92663  if( pExpr->flags & EP_IntValue ){
92664  int i = pExpr->u.iValue;
92665  assert( i>=0 );
92666  if( negFlag ) i = -i;
92667  sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
92668  }else{
92669  int c;
92670  i64 value;
92671  const char *z = pExpr->u.zToken;
92672  assert( z!=0 );
92673  c = sqlite3DecOrHexToI64(z, &value);
92674  if( c==0 || (c==2 && negFlag) ){
92675  if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
92676  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
92677  }else{
92678 #ifdef SQLITE_OMIT_FLOATING_POINT
92679  sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
92680 #else
92681 #ifndef SQLITE_OMIT_HEX_INTEGER
92682  if( sqlite3_strnicmp(z,"0x",2)==0 ){
92683  sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
92684  }else
92685 #endif
92686  {
92687  codeReal(v, z, negFlag, iMem);
92688  }
92689 #endif
92690  }
92691  }
92692 }
92693 
92694 /*
92695 ** Erase column-cache entry number i
92696 */
92697 static void cacheEntryClear(Parse *pParse, int i){
92698  if( pParse->aColCache[i].tempReg ){
92699  if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
92700  pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
92701  }
92702  }
92703  pParse->nColCache--;
92704  if( i<pParse->nColCache ){
92705  pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
92706  }
92707 }
92708 
92709 
92710 /*
92711 ** Record in the column cache that a particular column from a
92712 ** particular table is stored in a particular register.
92713 */
92714 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
92715  int i;
92716  int minLru;
92717  int idxLru;
92718  struct yColCache *p;
92719 
92720  /* Unless an error has occurred, register numbers are always positive. */
92721  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
92722  assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
92723 
92724  /* The SQLITE_ColumnCache flag disables the column cache. This is used
92725  ** for testing only - to verify that SQLite always gets the same answer
92726  ** with and without the column cache.
92727  */
92728  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
92729 
92730  /* First replace any existing entry.
92731  **
92732  ** Actually, the way the column cache is currently used, we are guaranteed
92733  ** that the object will never already be in cache. Verify this guarantee.
92734  */
92735 #ifndef NDEBUG
92736  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92737  assert( p->iTable!=iTab || p->iColumn!=iCol );
92738  }
92739 #endif
92740 
92741  /* If the cache is already full, delete the least recently used entry */
92742  if( pParse->nColCache>=SQLITE_N_COLCACHE ){
92743  minLru = 0x7fffffff;
92744  idxLru = -1;
92745  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92746  if( p->lru<minLru ){
92747  idxLru = i;
92748  minLru = p->lru;
92749  }
92750  }
92751  p = &pParse->aColCache[idxLru];
92752  }else{
92753  p = &pParse->aColCache[pParse->nColCache++];
92754  }
92755 
92756  /* Add the new entry to the end of the cache */
92757  p->iLevel = pParse->iCacheLevel;
92758  p->iTable = iTab;
92759  p->iColumn = iCol;
92760  p->iReg = iReg;
92761  p->tempReg = 0;
92762  p->lru = pParse->iCacheCnt++;
92763 }
92764 
92765 /*
92766 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
92767 ** Purge the range of registers from the column cache.
92768 */
92769 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
92770  int i = 0;
92771  while( i<pParse->nColCache ){
92772  struct yColCache *p = &pParse->aColCache[i];
92773  if( p->iReg >= iReg && p->iReg < iReg+nReg ){
92774  cacheEntryClear(pParse, i);
92775  }else{
92776  i++;
92777  }
92778  }
92779 }
92780 
92781 /*
92782 ** Remember the current column cache context. Any new entries added
92783 ** added to the column cache after this call are removed when the
92784 ** corresponding pop occurs.
92785 */
92787  pParse->iCacheLevel++;
92788 #ifdef SQLITE_DEBUG
92789  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92790  printf("PUSH to %d\n", pParse->iCacheLevel);
92791  }
92792 #endif
92793 }
92794 
92795 /*
92796 ** Remove from the column cache any entries that were added since the
92797 ** the previous sqlite3ExprCachePush operation. In other words, restore
92798 ** the cache to the state it was in prior the most recent Push.
92799 */
92801  int i = 0;
92802  assert( pParse->iCacheLevel>=1 );
92803  pParse->iCacheLevel--;
92804 #ifdef SQLITE_DEBUG
92805  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92806  printf("POP to %d\n", pParse->iCacheLevel);
92807  }
92808 #endif
92809  while( i<pParse->nColCache ){
92810  if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
92811  cacheEntryClear(pParse, i);
92812  }else{
92813  i++;
92814  }
92815  }
92816 }
92817 
92818 /*
92819 ** When a cached column is reused, make sure that its register is
92820 ** no longer available as a temp register. ticket #3879: that same
92821 ** register might be in the cache in multiple places, so be sure to
92822 ** get them all.
92823 */
92824 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
92825  int i;
92826  struct yColCache *p;
92827  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92828  if( p->iReg==iReg ){
92829  p->tempReg = 0;
92830  }
92831  }
92832 }
92833 
92834 /* Generate code that will load into register regOut a value that is
92835 ** appropriate for the iIdxCol-th column of index pIdx.
92836 */
92838  Parse *pParse, /* The parsing context */
92839  Index *pIdx, /* The index whose column is to be loaded */
92840  int iTabCur, /* Cursor pointing to a table row */
92841  int iIdxCol, /* The column of the index to be loaded */
92842  int regOut /* Store the index column value in this register */
92843 ){
92844  i16 iTabCol = pIdx->aiColumn[iIdxCol];
92845  if( iTabCol==XN_EXPR ){
92846  assert( pIdx->aColExpr );
92847  assert( pIdx->aColExpr->nExpr>iIdxCol );
92848  pParse->iSelfTab = iTabCur;
92849  sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
92850  }else{
92851  sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
92852  iTabCol, regOut);
92853  }
92854 }
92855 
92856 /*
92857 ** Generate code to extract the value of the iCol-th column of a table.
92858 */
92860  Vdbe *v, /* The VDBE under construction */
92861  Table *pTab, /* The table containing the value */
92862  int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
92863  int iCol, /* Index of the column to extract */
92864  int regOut /* Extract the value into this register */
92865 ){
92866  if( iCol<0 || iCol==pTab->iPKey ){
92867  sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
92868  }else{
92869  int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
92870  int x = iCol;
92871  if( !HasRowid(pTab) && !IsVirtual(pTab) ){
92873  }
92874  sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
92875  }
92876  if( iCol>=0 ){
92877  sqlite3ColumnDefault(v, pTab, iCol, regOut);
92878  }
92879 }
92880 
92881 /*
92882 ** Generate code that will extract the iColumn-th column from
92883 ** table pTab and store the column value in a register.
92884 **
92885 ** An effort is made to store the column value in register iReg. This
92886 ** is not garanteeed for GetColumn() - the result can be stored in
92887 ** any register. But the result is guaranteed to land in register iReg
92888 ** for GetColumnToReg().
92889 **
92890 ** There must be an open cursor to pTab in iTable when this routine
92891 ** is called. If iColumn<0 then code is generated that extracts the rowid.
92892 */
92894  Parse *pParse, /* Parsing and code generating context */
92895  Table *pTab, /* Description of the table we are reading from */
92896  int iColumn, /* Index of the table column */
92897  int iTable, /* The cursor pointing to the table */
92898  int iReg, /* Store results here */
92899  u8 p5 /* P5 value for OP_Column + FLAGS */
92900 ){
92901  Vdbe *v = pParse->pVdbe;
92902  int i;
92903  struct yColCache *p;
92904 
92905  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92906  if( p->iTable==iTable && p->iColumn==iColumn ){
92907  p->lru = pParse->iCacheCnt++;
92908  sqlite3ExprCachePinRegister(pParse, p->iReg);
92909  return p->iReg;
92910  }
92911  }
92912  assert( v!=0 );
92913  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
92914  if( p5 ){
92915  sqlite3VdbeChangeP5(v, p5);
92916  }else{
92917  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
92918  }
92919  return iReg;
92920 }
92922  Parse *pParse, /* Parsing and code generating context */
92923  Table *pTab, /* Description of the table we are reading from */
92924  int iColumn, /* Index of the table column */
92925  int iTable, /* The cursor pointing to the table */
92926  int iReg /* Store results here */
92927 ){
92928  int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
92929  if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
92930 }
92931 
92932 
92933 /*
92934 ** Clear all column cache entries.
92935 */
92937  int i;
92938 
92939 #if SQLITE_DEBUG
92940  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92941  printf("CLEAR\n");
92942  }
92943 #endif
92944  for(i=0; i<pParse->nColCache; i++){
92945  if( pParse->aColCache[i].tempReg
92946  && pParse->nTempReg<ArraySize(pParse->aTempReg)
92947  ){
92948  pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
92949  }
92950  }
92951  pParse->nColCache = 0;
92952 }
92953 
92954 /*
92955 ** Record the fact that an affinity change has occurred on iCount
92956 ** registers starting with iStart.
92957 */
92958 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
92959  sqlite3ExprCacheRemove(pParse, iStart, iCount);
92960 }
92961 
92962 /*
92963 ** Generate code to move content from registers iFrom...iFrom+nReg-1
92964 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
92965 */
92966 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
92967  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
92968  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
92969  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
92970 }
92971 
92972 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
92973 /*
92974 ** Return true if any register in the range iFrom..iTo (inclusive)
92975 ** is used as part of the column cache.
92976 **
92977 ** This routine is used within assert() and testcase() macros only
92978 ** and does not appear in a normal build.
92979 */
92980 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
92981  int i;
92982  struct yColCache *p;
92983  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
92984  int r = p->iReg;
92985  if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
92986  }
92987  return 0;
92988 }
92989 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
92990 
92991 
92992 /*
92993 ** Convert a scalar expression node to a TK_REGISTER referencing
92994 ** register iReg. The caller must ensure that iReg already contains
92995 ** the correct value for the expression.
92996 */
92997 static void exprToRegister(Expr *p, int iReg){
92998  p->op2 = p->op;
92999  p->op = TK_REGISTER;
93000  p->iTable = iReg;
93002 }
93003 
93004 /*
93005 ** Evaluate an expression (either a vector or a scalar expression) and store
93006 ** the result in continguous temporary registers. Return the index of
93007 ** the first register used to store the result.
93008 **
93009 ** If the returned result register is a temporary scalar, then also write
93010 ** that register number into *piFreeable. If the returned result register
93011 ** is not a temporary or if the expression is a vector set *piFreeable
93012 ** to 0.
93013 */
93014 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
93015  int iResult;
93016  int nResult = sqlite3ExprVectorSize(p);
93017  if( nResult==1 ){
93018  iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
93019  }else{
93020  *piFreeable = 0;
93021  if( p->op==TK_SELECT ){
93022  iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
93023  }else{
93024  int i;
93025  iResult = pParse->nMem+1;
93026  pParse->nMem += nResult;
93027  for(i=0; i<nResult; i++){
93028  sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
93029  }
93030  }
93031  }
93032  return iResult;
93033 }
93034 
93035 
93036 /*
93037 ** Generate code into the current Vdbe to evaluate the given
93038 ** expression. Attempt to store the results in register "target".
93039 ** Return the register where results are stored.
93040 **
93041 ** With this routine, there is no guarantee that results will
93042 ** be stored in target. The result might be stored in some other
93043 ** register if it is convenient to do so. The calling function
93044 ** must check the return code and move the results to the desired
93045 ** register.
93046 */
93047 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
93048  Vdbe *v = pParse->pVdbe; /* The VM under construction */
93049  int op; /* The opcode being coded */
93050  int inReg = target; /* Results stored in register inReg */
93051  int regFree1 = 0; /* If non-zero free this temporary register */
93052  int regFree2 = 0; /* If non-zero free this temporary register */
93053  int r1, r2; /* Various register numbers */
93054  Expr tempX; /* Temporary expression node */
93055  int p5 = 0;
93056 
93057  assert( target>0 && target<=pParse->nMem );
93058  if( v==0 ){
93059  assert( pParse->db->mallocFailed );
93060  return 0;
93061  }
93062 
93063  if( pExpr==0 ){
93064  op = TK_NULL;
93065  }else{
93066  op = pExpr->op;
93067  }
93068  switch( op ){
93069  case TK_AGG_COLUMN: {
93070  AggInfo *pAggInfo = pExpr->pAggInfo;
93071  struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
93072  if( !pAggInfo->directMode ){
93073  assert( pCol->iMem>0 );
93074  return pCol->iMem;
93075  }else if( pAggInfo->useSortingIdx ){
93077  pCol->iSorterColumn, target);
93078  return target;
93079  }
93080  /* Otherwise, fall thru into the TK_COLUMN case */
93081  }
93082  case TK_COLUMN: {
93083  int iTab = pExpr->iTable;
93084  if( iTab<0 ){
93085  if( pParse->ckBase>0 ){
93086  /* Generating CHECK constraints or inserting into partial index */
93087  return pExpr->iColumn + pParse->ckBase;
93088  }else{
93089  /* Coding an expression that is part of an index where column names
93090  ** in the index refer to the table to which the index belongs */
93091  iTab = pParse->iSelfTab;
93092  }
93093  }
93094  return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
93095  pExpr->iColumn, iTab, target,
93096  pExpr->op2);
93097  }
93098  case TK_INTEGER: {
93099  codeInteger(pParse, pExpr, 0, target);
93100  return target;
93101  }
93102 #ifndef SQLITE_OMIT_FLOATING_POINT
93103  case TK_FLOAT: {
93104  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93105  codeReal(v, pExpr->u.zToken, 0, target);
93106  return target;
93107  }
93108 #endif
93109  case TK_STRING: {
93110  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93111  sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
93112  return target;
93113  }
93114  case TK_NULL: {
93115  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
93116  return target;
93117  }
93118 #ifndef SQLITE_OMIT_BLOB_LITERAL
93119  case TK_BLOB: {
93120  int n;
93121  const char *z;
93122  char *zBlob;
93123  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93124  assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
93125  assert( pExpr->u.zToken[1]=='\'' );
93126  z = &pExpr->u.zToken[2];
93127  n = sqlite3Strlen30(z) - 1;
93128  assert( z[n]=='\'' );
93129  zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
93130  sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
93131  return target;
93132  }
93133 #endif
93134  case TK_VARIABLE: {
93135  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93136  assert( pExpr->u.zToken!=0 );
93137  assert( pExpr->u.zToken[0]!=0 );
93138  sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
93139  if( pExpr->u.zToken[1]!=0 ){
93140  assert( pExpr->u.zToken[0]=='?'
93141  || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
93142  sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
93143  }
93144  return target;
93145  }
93146  case TK_REGISTER: {
93147  return pExpr->iTable;
93148  }
93149 #ifndef SQLITE_OMIT_CAST
93150  case TK_CAST: {
93151  /* Expressions of the form: CAST(pLeft AS token) */
93152  inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
93153  if( inReg!=target ){
93154  sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
93155  inReg = target;
93156  }
93157  sqlite3VdbeAddOp2(v, OP_Cast, target,
93158  sqlite3AffinityType(pExpr->u.zToken, 0));
93159  testcase( usedAsColumnCache(pParse, inReg, inReg) );
93160  sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
93161  return inReg;
93162  }
93163 #endif /* SQLITE_OMIT_CAST */
93164  case TK_IS:
93165  case TK_ISNOT:
93166  op = (op==TK_IS) ? TK_EQ : TK_NE;
93167  p5 = SQLITE_NULLEQ;
93168  /* fall-through */
93169  case TK_LT:
93170  case TK_LE:
93171  case TK_GT:
93172  case TK_GE:
93173  case TK_NE:
93174  case TK_EQ: {
93175  Expr *pLeft = pExpr->pLeft;
93176  if( sqlite3ExprIsVector(pLeft) ){
93177  codeVectorCompare(pParse, pExpr, target, op, p5);
93178  }else{
93179  r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
93180  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93181  codeCompare(pParse, pLeft, pExpr->pRight, op,
93182  r1, r2, inReg, SQLITE_STOREP2 | p5);
93183  assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93184  assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93185  assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93186  assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93187  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
93188  assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
93189  testcase( regFree1==0 );
93190  testcase( regFree2==0 );
93191  }
93192  break;
93193  }
93194  case TK_AND:
93195  case TK_OR:
93196  case TK_PLUS:
93197  case TK_STAR:
93198  case TK_MINUS:
93199  case TK_REM:
93200  case TK_BITAND:
93201  case TK_BITOR:
93202  case TK_SLASH:
93203  case TK_LSHIFT:
93204  case TK_RSHIFT:
93205  case TK_CONCAT: {
93206  assert( TK_AND==OP_And ); testcase( op==TK_AND );
93207  assert( TK_OR==OP_Or ); testcase( op==TK_OR );
93208  assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
93209  assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
93210  assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
93211  assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
93212  assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
93213  assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
93214  assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
93215  assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
93216  assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
93217  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93218  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93219  sqlite3VdbeAddOp3(v, op, r2, r1, target);
93220  testcase( regFree1==0 );
93221  testcase( regFree2==0 );
93222  break;
93223  }
93224  case TK_UMINUS: {
93225  Expr *pLeft = pExpr->pLeft;
93226  assert( pLeft );
93227  if( pLeft->op==TK_INTEGER ){
93228  codeInteger(pParse, pLeft, 1, target);
93229  return target;
93230 #ifndef SQLITE_OMIT_FLOATING_POINT
93231  }else if( pLeft->op==TK_FLOAT ){
93232  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93233  codeReal(v, pLeft->u.zToken, 1, target);
93234  return target;
93235 #endif
93236  }else{
93237  tempX.op = TK_INTEGER;
93238  tempX.flags = EP_IntValue|EP_TokenOnly;
93239  tempX.u.iValue = 0;
93240  r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
93241  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
93242  sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
93243  testcase( regFree2==0 );
93244  }
93245  break;
93246  }
93247  case TK_BITNOT:
93248  case TK_NOT: {
93249  assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
93250  assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
93251  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93252  testcase( regFree1==0 );
93253  sqlite3VdbeAddOp2(v, op, r1, inReg);
93254  break;
93255  }
93256  case TK_ISNULL:
93257  case TK_NOTNULL: {
93258  int addr;
93259  assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
93260  assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
93261  sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
93262  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93263  testcase( regFree1==0 );
93264  addr = sqlite3VdbeAddOp1(v, op, r1);
93265  VdbeCoverageIf(v, op==TK_ISNULL);
93266  VdbeCoverageIf(v, op==TK_NOTNULL);
93267  sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
93268  sqlite3VdbeJumpHere(v, addr);
93269  break;
93270  }
93271  case TK_AGG_FUNCTION: {
93272  AggInfo *pInfo = pExpr->pAggInfo;
93273  if( pInfo==0 ){
93274  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93275  sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
93276  }else{
93277  return pInfo->aFunc[pExpr->iAgg].iMem;
93278  }
93279  break;
93280  }
93281  case TK_FUNCTION: {
93282  ExprList *pFarg; /* List of function arguments */
93283  int nFarg; /* Number of function arguments */
93284  FuncDef *pDef; /* The function definition object */
93285  const char *zId; /* The function name */
93286  u32 constMask = 0; /* Mask of function arguments that are constant */
93287  int i; /* Loop counter */
93288  sqlite3 *db = pParse->db; /* The database connection */
93289  u8 enc = ENC(db); /* The text encoding used by this database */
93290  CollSeq *pColl = 0; /* A collating sequence */
93291 
93292  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93293  if( ExprHasProperty(pExpr, EP_TokenOnly) ){
93294  pFarg = 0;
93295  }else{
93296  pFarg = pExpr->x.pList;
93297  }
93298  nFarg = pFarg ? pFarg->nExpr : 0;
93299  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93300  zId = pExpr->u.zToken;
93301  pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
93302 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
93303  if( pDef==0 && pParse->explain ){
93304  pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
93305  }
93306 #endif
93307  if( pDef==0 || pDef->xFinalize!=0 ){
93308  sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
93309  break;
93310  }
93311 
93312  /* Attempt a direct implementation of the built-in COALESCE() and
93313  ** IFNULL() functions. This avoids unnecessary evaluation of
93314  ** arguments past the first non-NULL argument.
93315  */
93316  if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
93317  int endCoalesce = sqlite3VdbeMakeLabel(v);
93318  assert( nFarg>=2 );
93319  sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
93320  for(i=1; i<nFarg; i++){
93321  sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
93322  VdbeCoverage(v);
93323  sqlite3ExprCacheRemove(pParse, target, 1);
93324  sqlite3ExprCachePush(pParse);
93325  sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
93326  sqlite3ExprCachePop(pParse);
93327  }
93328  sqlite3VdbeResolveLabel(v, endCoalesce);
93329  break;
93330  }
93331 
93332  /* The UNLIKELY() function is a no-op. The result is the value
93333  ** of the first argument.
93334  */
93335  if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
93336  assert( nFarg>=1 );
93337  return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
93338  }
93339 
93340  for(i=0; i<nFarg; i++){
93341  if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
93342  testcase( i==31 );
93343  constMask |= MASKBIT32(i);
93344  }
93345  if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
93346  pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
93347  }
93348  }
93349  if( pFarg ){
93350  if( constMask ){
93351  r1 = pParse->nMem+1;
93352  pParse->nMem += nFarg;
93353  }else{
93354  r1 = sqlite3GetTempRange(pParse, nFarg);
93355  }
93356 
93357  /* For length() and typeof() functions with a column argument,
93358  ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
93359  ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
93360  ** loading.
93361  */
93362  if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
93363  u8 exprOp;
93364  assert( nFarg==1 );
93365  assert( pFarg->a[0].pExpr!=0 );
93366  exprOp = pFarg->a[0].pExpr->op;
93367  if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
93370  testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
93371  pFarg->a[0].pExpr->op2 =
93373  }
93374  }
93375 
93376  sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
93377  sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
93379  sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
93380  }else{
93381  r1 = 0;
93382  }
93383 #ifndef SQLITE_OMIT_VIRTUALTABLE
93384  /* Possibly overload the function if the first argument is
93385  ** a virtual table column.
93386  **
93387  ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
93388  ** second argument, not the first, as the argument to test to
93389  ** see if it is a column in a virtual table. This is done because
93390  ** the left operand of infix functions (the operand we want to
93391  ** control overloading) ends up as the second argument to the
93392  ** function. The expression "A glob B" is equivalent to
93393  ** "glob(B,A). We want to use the A in "A glob B" to test
93394  ** for function overloading. But we use the B term in "glob(B,A)".
93395  */
93396  if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
93397  pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
93398  }else if( nFarg>0 ){
93399  pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
93400  }
93401 #endif
93402  if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
93403  if( !pColl ) pColl = db->pDfltColl;
93404  sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
93405  }
93406  sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
93407  (char*)pDef, P4_FUNCDEF);
93408  sqlite3VdbeChangeP5(v, (u8)nFarg);
93409  if( nFarg && constMask==0 ){
93410  sqlite3ReleaseTempRange(pParse, r1, nFarg);
93411  }
93412  return target;
93413  }
93414 #ifndef SQLITE_OMIT_SUBQUERY
93415  case TK_EXISTS:
93416  case TK_SELECT: {
93417  int nCol;
93418  testcase( op==TK_EXISTS );
93419  testcase( op==TK_SELECT );
93420  if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
93421  sqlite3SubselectError(pParse, nCol, 1);
93422  }else{
93423  return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
93424  }
93425  break;
93426  }
93427  case TK_SELECT_COLUMN: {
93428  if( pExpr->pLeft->iTable==0 ){
93429  pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
93430  }
93431  return pExpr->pLeft->iTable + pExpr->iColumn;
93432  }
93433  case TK_IN: {
93434  int destIfFalse = sqlite3VdbeMakeLabel(v);
93435  int destIfNull = sqlite3VdbeMakeLabel(v);
93436  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
93437  sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
93438  sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
93439  sqlite3VdbeResolveLabel(v, destIfFalse);
93440  sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
93441  sqlite3VdbeResolveLabel(v, destIfNull);
93442  return target;
93443  }
93444 #endif /* SQLITE_OMIT_SUBQUERY */
93445 
93446 
93447  /*
93448  ** x BETWEEN y AND z
93449  **
93450  ** This is equivalent to
93451  **
93452  ** x>=y AND x<=z
93453  **
93454  ** X is stored in pExpr->pLeft.
93455  ** Y is stored in pExpr->pList->a[0].pExpr.
93456  ** Z is stored in pExpr->pList->a[1].pExpr.
93457  */
93458  case TK_BETWEEN: {
93459  exprCodeBetween(pParse, pExpr, target, 0, 0);
93460  return target;
93461  }
93462  case TK_SPAN:
93463  case TK_COLLATE:
93464  case TK_UPLUS: {
93465  return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
93466  }
93467 
93468  case TK_TRIGGER: {
93469  /* If the opcode is TK_TRIGGER, then the expression is a reference
93470  ** to a column in the new.* or old.* pseudo-tables available to
93471  ** trigger programs. In this case Expr.iTable is set to 1 for the
93472  ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
93473  ** is set to the column of the pseudo-table to read, or to -1 to
93474  ** read the rowid field.
93475  **
93476  ** The expression is implemented using an OP_Param opcode. The p1
93477  ** parameter is set to 0 for an old.rowid reference, or to (i+1)
93478  ** to reference another column of the old.* pseudo-table, where
93479  ** i is the index of the column. For a new.rowid reference, p1 is
93480  ** set to (n+1), where n is the number of columns in each pseudo-table.
93481  ** For a reference to any other column in the new.* pseudo-table, p1
93482  ** is set to (n+2+i), where n and i are as defined previously. For
93483  ** example, if the table on which triggers are being fired is
93484  ** declared as:
93485  **
93486  ** CREATE TABLE t1(a, b);
93487  **
93488  ** Then p1 is interpreted as follows:
93489  **
93490  ** p1==0 -> old.rowid p1==3 -> new.rowid
93491  ** p1==1 -> old.a p1==4 -> new.a
93492  ** p1==2 -> old.b p1==5 -> new.b
93493  */
93494  Table *pTab = pExpr->pTab;
93495  int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
93496 
93497  assert( pExpr->iTable==0 || pExpr->iTable==1 );
93498  assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
93499  assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
93500  assert( p1>=0 && p1<(pTab->nCol*2+2) );
93501 
93502  sqlite3VdbeAddOp2(v, OP_Param, p1, target);
93503  VdbeComment((v, "%s.%s -> $%d",
93504  (pExpr->iTable ? "new" : "old"),
93505  (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
93506  target
93507  ));
93508 
93509 #ifndef SQLITE_OMIT_FLOATING_POINT
93510  /* If the column has REAL affinity, it may currently be stored as an
93511  ** integer. Use OP_RealAffinity to make sure it is really real.
93512  **
93513  ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
93514  ** floating point when extracting it from the record. */
93515  if( pExpr->iColumn>=0
93516  && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
93517  ){
93518  sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
93519  }
93520 #endif
93521  break;
93522  }
93523 
93524  case TK_VECTOR: {
93525  sqlite3ErrorMsg(pParse, "row value misused");
93526  break;
93527  }
93528 
93529  /*
93530  ** Form A:
93531  ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
93532  **
93533  ** Form B:
93534  ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
93535  **
93536  ** Form A is can be transformed into the equivalent form B as follows:
93537  ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
93538  ** WHEN x=eN THEN rN ELSE y END
93539  **
93540  ** X (if it exists) is in pExpr->pLeft.
93541  ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
93542  ** odd. The Y is also optional. If the number of elements in x.pList
93543  ** is even, then Y is omitted and the "otherwise" result is NULL.
93544  ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
93545  **
93546  ** The result of the expression is the Ri for the first matching Ei,
93547  ** or if there is no matching Ei, the ELSE term Y, or if there is
93548  ** no ELSE term, NULL.
93549  */
93550  default: assert( op==TK_CASE ); {
93551  int endLabel; /* GOTO label for end of CASE stmt */
93552  int nextCase; /* GOTO label for next WHEN clause */
93553  int nExpr; /* 2x number of WHEN terms */
93554  int i; /* Loop counter */
93555  ExprList *pEList; /* List of WHEN terms */
93556  struct ExprList_item *aListelem; /* Array of WHEN terms */
93557  Expr opCompare; /* The X==Ei expression */
93558  Expr *pX; /* The X expression */
93559  Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
93560  VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
93561 
93562  assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
93563  assert(pExpr->x.pList->nExpr > 0);
93564  pEList = pExpr->x.pList;
93565  aListelem = pEList->a;
93566  nExpr = pEList->nExpr;
93567  endLabel = sqlite3VdbeMakeLabel(v);
93568  if( (pX = pExpr->pLeft)!=0 ){
93569  tempX = *pX;
93570  testcase( pX->op==TK_COLUMN );
93571  exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
93572  testcase( regFree1==0 );
93573  memset(&opCompare, 0, sizeof(opCompare));
93574  opCompare.op = TK_EQ;
93575  opCompare.pLeft = &tempX;
93576  pTest = &opCompare;
93577  /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
93578  ** The value in regFree1 might get SCopy-ed into the file result.
93579  ** So make sure that the regFree1 register is not reused for other
93580  ** purposes and possibly overwritten. */
93581  regFree1 = 0;
93582  }
93583  for(i=0; i<nExpr-1; i=i+2){
93584  sqlite3ExprCachePush(pParse);
93585  if( pX ){
93586  assert( pTest!=0 );
93587  opCompare.pRight = aListelem[i].pExpr;
93588  }else{
93589  pTest = aListelem[i].pExpr;
93590  }
93591  nextCase = sqlite3VdbeMakeLabel(v);
93592  testcase( pTest->op==TK_COLUMN );
93593  sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
93594  testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
93595  sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
93596  sqlite3VdbeGoto(v, endLabel);
93597  sqlite3ExprCachePop(pParse);
93598  sqlite3VdbeResolveLabel(v, nextCase);
93599  }
93600  if( (nExpr&1)!=0 ){
93601  sqlite3ExprCachePush(pParse);
93602  sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
93603  sqlite3ExprCachePop(pParse);
93604  }else{
93605  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
93606  }
93607  assert( pParse->db->mallocFailed || pParse->nErr>0
93608  || pParse->iCacheLevel==iCacheLevel );
93609  sqlite3VdbeResolveLabel(v, endLabel);
93610  break;
93611  }
93612 #ifndef SQLITE_OMIT_TRIGGER
93613  case TK_RAISE: {
93614  assert( pExpr->affinity==OE_Rollback
93615  || pExpr->affinity==OE_Abort
93616  || pExpr->affinity==OE_Fail
93617  || pExpr->affinity==OE_Ignore
93618  );
93619  if( !pParse->pTriggerTab ){
93620  sqlite3ErrorMsg(pParse,
93621  "RAISE() may only be used within a trigger-program");
93622  return 0;
93623  }
93624  if( pExpr->affinity==OE_Abort ){
93625  sqlite3MayAbort(pParse);
93626  }
93627  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93628  if( pExpr->affinity==OE_Ignore ){
93630  v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
93631  VdbeCoverage(v);
93632  }else{
93634  pExpr->affinity, pExpr->u.zToken, 0, 0);
93635  }
93636 
93637  break;
93638  }
93639 #endif
93640  }
93641  sqlite3ReleaseTempReg(pParse, regFree1);
93642  sqlite3ReleaseTempReg(pParse, regFree2);
93643  return inReg;
93644 }
93645 
93646 /*
93647 ** Factor out the code of the given expression to initialization time.
93648 */
93650  Parse *pParse, /* Parsing context */
93651  Expr *pExpr, /* The expression to code when the VDBE initializes */
93652  int regDest, /* Store the value in this register */
93653  u8 reusable /* True if this expression is reusable */
93654 ){
93655  ExprList *p;
93656  assert( ConstFactorOk(pParse) );
93657  p = pParse->pConstExpr;
93658  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
93659  p = sqlite3ExprListAppend(pParse, p, pExpr);
93660  if( p ){
93661  struct ExprList_item *pItem = &p->a[p->nExpr-1];
93662  pItem->u.iConstExprReg = regDest;
93663  pItem->reusable = reusable;
93664  }
93665  pParse->pConstExpr = p;
93666 }
93667 
93668 /*
93669 ** Generate code to evaluate an expression and store the results
93670 ** into a register. Return the register number where the results
93671 ** are stored.
93672 **
93673 ** If the register is a temporary register that can be deallocated,
93674 ** then write its number into *pReg. If the result register is not
93675 ** a temporary, then set *pReg to zero.
93676 **
93677 ** If pExpr is a constant, then this routine might generate this
93678 ** code to fill the register in the initialization section of the
93679 ** VDBE program, in order to factor it out of the evaluation loop.
93680 */
93681 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
93682  int r2;
93683  pExpr = sqlite3ExprSkipCollate(pExpr);
93684  if( ConstFactorOk(pParse)
93685  && pExpr->op!=TK_REGISTER
93687  ){
93688  ExprList *p = pParse->pConstExpr;
93689  int i;
93690  *pReg = 0;
93691  if( p ){
93692  struct ExprList_item *pItem;
93693  for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
93694  if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
93695  return pItem->u.iConstExprReg;
93696  }
93697  }
93698  }
93699  r2 = ++pParse->nMem;
93700  sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
93701  }else{
93702  int r1 = sqlite3GetTempReg(pParse);
93703  r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
93704  if( r2==r1 ){
93705  *pReg = r1;
93706  }else{
93707  sqlite3ReleaseTempReg(pParse, r1);
93708  *pReg = 0;
93709  }
93710  }
93711  return r2;
93712 }
93713 
93714 /*
93715 ** Generate code that will evaluate expression pExpr and store the
93716 ** results in register target. The results are guaranteed to appear
93717 ** in register target.
93718 */
93719 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
93720  int inReg;
93721 
93722  assert( target>0 && target<=pParse->nMem );
93723  if( pExpr && pExpr->op==TK_REGISTER ){
93724  sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
93725  }else{
93726  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
93727  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
93728  if( inReg!=target && pParse->pVdbe ){
93729  sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
93730  }
93731  }
93732 }
93733 
93734 /*
93735 ** Make a transient copy of expression pExpr and then code it using
93736 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
93737 ** except that the input expression is guaranteed to be unchanged.
93738 */
93739 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
93740  sqlite3 *db = pParse->db;
93741  pExpr = sqlite3ExprDup(db, pExpr, 0);
93742  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
93743  sqlite3ExprDelete(db, pExpr);
93744 }
93745 
93746 /*
93747 ** Generate code that will evaluate expression pExpr and store the
93748 ** results in register target. The results are guaranteed to appear
93749 ** in register target. If the expression is constant, then this routine
93750 ** might choose to code the expression at initialization time.
93751 */
93752 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
93753  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
93754  sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
93755  }else{
93756  sqlite3ExprCode(pParse, pExpr, target);
93757  }
93758 }
93759 
93760 /*
93761 ** Generate code that evaluates the given expression and puts the result
93762 ** in register target.
93763 **
93764 ** Also make a copy of the expression results into another "cache" register
93765 ** and modify the expression so that the next time it is evaluated,
93766 ** the result is a copy of the cache register.
93767 **
93768 ** This routine is used for expressions that are used multiple
93769 ** times. They are evaluated once and the results of the expression
93770 ** are reused.
93771 */
93772 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
93773  Vdbe *v = pParse->pVdbe;
93774  int iMem;
93775 
93776  assert( target>0 );
93777  assert( pExpr->op!=TK_REGISTER );
93778  sqlite3ExprCode(pParse, pExpr, target);
93779  iMem = ++pParse->nMem;
93780  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
93781  exprToRegister(pExpr, iMem);
93782 }
93783 
93784 /*
93785 ** Generate code that pushes the value of every element of the given
93786 ** expression list into a sequence of registers beginning at target.
93787 **
93788 ** Return the number of elements evaluated.
93789 **
93790 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
93791 ** filled using OP_SCopy. OP_Copy must be used instead.
93792 **
93793 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
93794 ** factored out into initialization code.
93795 **
93796 ** The SQLITE_ECEL_REF flag means that expressions in the list with
93797 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
93798 ** in registers at srcReg, and so the value can be copied from there.
93799 */
93801  Parse *pParse, /* Parsing context */
93802  ExprList *pList, /* The expression list to be coded */
93803  int target, /* Where to write results */
93804  int srcReg, /* Source registers if SQLITE_ECEL_REF */
93805  u8 flags /* SQLITE_ECEL_* flags */
93806 ){
93807  struct ExprList_item *pItem;
93808  int i, j, n;
93809  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
93810  Vdbe *v = pParse->pVdbe;
93811  assert( pList!=0 );
93812  assert( target>0 );
93813  assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
93814  n = pList->nExpr;
93815  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
93816  for(pItem=pList->a, i=0; i<n; i++, pItem++){
93817  Expr *pExpr = pItem->pExpr;
93818  if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
93819  sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
93820  }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
93821  sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
93822  }else{
93823  int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
93824  if( inReg!=target+i ){
93825  VdbeOp *pOp;
93826  if( copyOp==OP_Copy
93827  && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
93828  && pOp->p1+pOp->p3+1==inReg
93829  && pOp->p2+pOp->p3+1==target+i
93830  ){
93831  pOp->p3++;
93832  }else{
93833  sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
93834  }
93835  }
93836  }
93837  }
93838  return n;
93839 }
93840 
93841 /*
93842 ** Generate code for a BETWEEN operator.
93843 **
93844 ** x BETWEEN y AND z
93845 **
93846 ** The above is equivalent to
93847 **
93848 ** x>=y AND x<=z
93849 **
93850 ** Code it as such, taking care to do the common subexpression
93851 ** elimination of x.
93852 **
93853 ** The xJumpIf parameter determines details:
93854 **
93855 ** NULL: Store the boolean result in reg[dest]
93856 ** sqlite3ExprIfTrue: Jump to dest if true
93857 ** sqlite3ExprIfFalse: Jump to dest if false
93858 **
93859 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
93860 */
93861 static void exprCodeBetween(
93862  Parse *pParse, /* Parsing and code generating context */
93863  Expr *pExpr, /* The BETWEEN expression */
93864  int dest, /* Jump destination or storage location */
93865  void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
93866  int jumpIfNull /* Take the jump if the BETWEEN is NULL */
93867 ){
93868  Expr exprAnd; /* The AND operator in x>=y AND x<=z */
93869  Expr compLeft; /* The x>=y term */
93870  Expr compRight; /* The x<=z term */
93871  Expr exprX; /* The x subexpression */
93872  int regFree1 = 0; /* Temporary use register */
93873 
93874 
93875  memset(&compLeft, 0, sizeof(Expr));
93876  memset(&compRight, 0, sizeof(Expr));
93877  memset(&exprAnd, 0, sizeof(Expr));
93878 
93879  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93880  exprX = *pExpr->pLeft;
93881  exprAnd.op = TK_AND;
93882  exprAnd.pLeft = &compLeft;
93883  exprAnd.pRight = &compRight;
93884  compLeft.op = TK_GE;
93885  compLeft.pLeft = &exprX;
93886  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
93887  compRight.op = TK_LE;
93888  compRight.pLeft = &exprX;
93889  compRight.pRight = pExpr->x.pList->a[1].pExpr;
93890  exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
93891  if( xJump ){
93892  xJump(pParse, &exprAnd, dest, jumpIfNull);
93893  }else{
93894  exprX.flags |= EP_FromJoin;
93895  sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
93896  }
93897  sqlite3ReleaseTempReg(pParse, regFree1);
93898 
93899  /* Ensure adequate test coverage */
93900  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
93901  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
93902  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
93903  testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
93904  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
93905  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
93906  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
93907  testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
93908  testcase( xJump==0 );
93909 }
93910 
93911 /*
93912 ** Generate code for a boolean expression such that a jump is made
93913 ** to the label "dest" if the expression is true but execution
93914 ** continues straight thru if the expression is false.
93915 **
93916 ** If the expression evaluates to NULL (neither true nor false), then
93917 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
93918 **
93919 ** This code depends on the fact that certain token values (ex: TK_EQ)
93920 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
93921 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
93922 ** the make process cause these values to align. Assert()s in the code
93923 ** below verify that the numbers are aligned correctly.
93924 */
93925 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93926  Vdbe *v = pParse->pVdbe;
93927  int op = 0;
93928  int regFree1 = 0;
93929  int regFree2 = 0;
93930  int r1, r2;
93931 
93932  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93933  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
93934  if( NEVER(pExpr==0) ) return; /* No way this can happen */
93935  op = pExpr->op;
93936  switch( op ){
93937  case TK_AND: {
93938  int d2 = sqlite3VdbeMakeLabel(v);
93939  testcase( jumpIfNull==0 );
93940  sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
93941  sqlite3ExprCachePush(pParse);
93942  sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93943  sqlite3VdbeResolveLabel(v, d2);
93944  sqlite3ExprCachePop(pParse);
93945  break;
93946  }
93947  case TK_OR: {
93948  testcase( jumpIfNull==0 );
93949  sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93950  sqlite3ExprCachePush(pParse);
93951  sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93952  sqlite3ExprCachePop(pParse);
93953  break;
93954  }
93955  case TK_NOT: {
93956  testcase( jumpIfNull==0 );
93957  sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93958  break;
93959  }
93960  case TK_IS:
93961  case TK_ISNOT:
93962  testcase( op==TK_IS );
93963  testcase( op==TK_ISNOT );
93964  op = (op==TK_IS) ? TK_EQ : TK_NE;
93965  jumpIfNull = SQLITE_NULLEQ;
93966  /* Fall thru */
93967  case TK_LT:
93968  case TK_LE:
93969  case TK_GT:
93970  case TK_GE:
93971  case TK_NE:
93972  case TK_EQ: {
93973  if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
93974  testcase( jumpIfNull==0 );
93975  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93976  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93977  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93978  r1, r2, dest, jumpIfNull);
93979  assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93980  assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93981  assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93982  assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93983  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93984  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93985  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93986  assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93987  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93988  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93989  testcase( regFree1==0 );
93990  testcase( regFree2==0 );
93991  break;
93992  }
93993  case TK_ISNULL:
93994  case TK_NOTNULL: {
93995  assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
93996  assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
93997  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93998  sqlite3VdbeAddOp2(v, op, r1, dest);
93999  VdbeCoverageIf(v, op==TK_ISNULL);
94000  VdbeCoverageIf(v, op==TK_NOTNULL);
94001  testcase( regFree1==0 );
94002  break;
94003  }
94004  case TK_BETWEEN: {
94005  testcase( jumpIfNull==0 );
94006  exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
94007  break;
94008  }
94009 #ifndef SQLITE_OMIT_SUBQUERY
94010  case TK_IN: {
94011  int destIfFalse = sqlite3VdbeMakeLabel(v);
94012  int destIfNull = jumpIfNull ? dest : destIfFalse;
94013  sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
94014  sqlite3VdbeGoto(v, dest);
94015  sqlite3VdbeResolveLabel(v, destIfFalse);
94016  break;
94017  }
94018 #endif
94019  default: {
94020  default_expr:
94021  if( exprAlwaysTrue(pExpr) ){
94022  sqlite3VdbeGoto(v, dest);
94023  }else if( exprAlwaysFalse(pExpr) ){
94024  /* No-op */
94025  }else{
94026  r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
94027  sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
94028  VdbeCoverage(v);
94029  testcase( regFree1==0 );
94030  testcase( jumpIfNull==0 );
94031  }
94032  break;
94033  }
94034  }
94035  sqlite3ReleaseTempReg(pParse, regFree1);
94036  sqlite3ReleaseTempReg(pParse, regFree2);
94037 }
94038 
94039 /*
94040 ** Generate code for a boolean expression such that a jump is made
94041 ** to the label "dest" if the expression is false but execution
94042 ** continues straight thru if the expression is true.
94043 **
94044 ** If the expression evaluates to NULL (neither true nor false) then
94045 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
94046 ** is 0.
94047 */
94048 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
94049  Vdbe *v = pParse->pVdbe;
94050  int op = 0;
94051  int regFree1 = 0;
94052  int regFree2 = 0;
94053  int r1, r2;
94054 
94055  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
94056  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
94057  if( pExpr==0 ) return;
94058 
94059  /* The value of pExpr->op and op are related as follows:
94060  **
94061  ** pExpr->op op
94062  ** --------- ----------
94063  ** TK_ISNULL OP_NotNull
94064  ** TK_NOTNULL OP_IsNull
94065  ** TK_NE OP_Eq
94066  ** TK_EQ OP_Ne
94067  ** TK_GT OP_Le
94068  ** TK_LE OP_Gt
94069  ** TK_GE OP_Lt
94070  ** TK_LT OP_Ge
94071  **
94072  ** For other values of pExpr->op, op is undefined and unused.
94073  ** The value of TK_ and OP_ constants are arranged such that we
94074  ** can compute the mapping above using the following expression.
94075  ** Assert()s verify that the computation is correct.
94076  */
94077  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
94078 
94079  /* Verify correct alignment of TK_ and OP_ constants
94080  */
94081  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
94082  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
94083  assert( pExpr->op!=TK_NE || op==OP_Eq );
94084  assert( pExpr->op!=TK_EQ || op==OP_Ne );
94085  assert( pExpr->op!=TK_LT || op==OP_Ge );
94086  assert( pExpr->op!=TK_LE || op==OP_Gt );
94087  assert( pExpr->op!=TK_GT || op==OP_Le );
94088  assert( pExpr->op!=TK_GE || op==OP_Lt );
94089 
94090  switch( pExpr->op ){
94091  case TK_AND: {
94092  testcase( jumpIfNull==0 );
94093  sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
94094  sqlite3ExprCachePush(pParse);
94095  sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
94096  sqlite3ExprCachePop(pParse);
94097  break;
94098  }
94099  case TK_OR: {
94100  int d2 = sqlite3VdbeMakeLabel(v);
94101  testcase( jumpIfNull==0 );
94102  sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
94103  sqlite3ExprCachePush(pParse);
94104  sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
94105  sqlite3VdbeResolveLabel(v, d2);
94106  sqlite3ExprCachePop(pParse);
94107  break;
94108  }
94109  case TK_NOT: {
94110  testcase( jumpIfNull==0 );
94111  sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
94112  break;
94113  }
94114  case TK_IS:
94115  case TK_ISNOT:
94116  testcase( pExpr->op==TK_IS );
94117  testcase( pExpr->op==TK_ISNOT );
94118  op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
94119  jumpIfNull = SQLITE_NULLEQ;
94120  /* Fall thru */
94121  case TK_LT:
94122  case TK_LE:
94123  case TK_GT:
94124  case TK_GE:
94125  case TK_NE:
94126  case TK_EQ: {
94127  if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
94128  testcase( jumpIfNull==0 );
94129  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94130  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
94131  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
94132  r1, r2, dest, jumpIfNull);
94133  assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
94134  assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
94135  assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
94136  assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
94137  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
94138  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
94139  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
94140  assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
94141  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
94142  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
94143  testcase( regFree1==0 );
94144  testcase( regFree2==0 );
94145  break;
94146  }
94147  case TK_ISNULL:
94148  case TK_NOTNULL: {
94149  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
94150  sqlite3VdbeAddOp2(v, op, r1, dest);
94151  testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
94152  testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
94153  testcase( regFree1==0 );
94154  break;
94155  }
94156  case TK_BETWEEN: {
94157  testcase( jumpIfNull==0 );
94158  exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
94159  break;
94160  }
94161 #ifndef SQLITE_OMIT_SUBQUERY
94162  case TK_IN: {
94163  if( jumpIfNull ){
94164  sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
94165  }else{
94166  int destIfNull = sqlite3VdbeMakeLabel(v);
94167  sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
94168  sqlite3VdbeResolveLabel(v, destIfNull);
94169  }
94170  break;
94171  }
94172 #endif
94173  default: {
94174  default_expr:
94175  if( exprAlwaysFalse(pExpr) ){
94176  sqlite3VdbeGoto(v, dest);
94177  }else if( exprAlwaysTrue(pExpr) ){
94178  /* no-op */
94179  }else{
94180  r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
94181  sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
94182  VdbeCoverage(v);
94183  testcase( regFree1==0 );
94184  testcase( jumpIfNull==0 );
94185  }
94186  break;
94187  }
94188  }
94189  sqlite3ReleaseTempReg(pParse, regFree1);
94190  sqlite3ReleaseTempReg(pParse, regFree2);
94191 }
94192 
94193 /*
94194 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
94195 ** code generation, and that copy is deleted after code generation. This
94196 ** ensures that the original pExpr is unchanged.
94197 */
94198 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
94199  sqlite3 *db = pParse->db;
94200  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
94201  if( db->mallocFailed==0 ){
94202  sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
94203  }
94204  sqlite3ExprDelete(db, pCopy);
94205 }
94206 
94207 
94208 /*
94209 ** Do a deep comparison of two expression trees. Return 0 if the two
94210 ** expressions are completely identical. Return 1 if they differ only
94211 ** by a COLLATE operator at the top level. Return 2 if there are differences
94212 ** other than the top-level COLLATE operator.
94213 **
94214 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
94215 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
94216 **
94217 ** The pA side might be using TK_REGISTER. If that is the case and pB is
94218 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
94219 **
94220 ** Sometimes this routine will return 2 even if the two expressions
94221 ** really are equivalent. If we cannot prove that the expressions are
94222 ** identical, we return 2 just to be safe. So if this routine
94223 ** returns 2, then you do not really know for certain if the two
94224 ** expressions are the same. But if you get a 0 or 1 return, then you
94225 ** can be sure the expressions are the same. In the places where
94226 ** this routine is used, it does not hurt to get an extra 2 - that
94227 ** just might result in some slightly slower code. But returning
94228 ** an incorrect 0 or 1 could lead to a malfunction.
94229 */
94230 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
94231  u32 combinedFlags;
94232  if( pA==0 || pB==0 ){
94233  return pB==pA ? 0 : 2;
94234  }
94235  combinedFlags = pA->flags | pB->flags;
94236  if( combinedFlags & EP_IntValue ){
94237  if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
94238  return 0;
94239  }
94240  return 2;
94241  }
94242  if( pA->op!=pB->op ){
94243  if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
94244  return 1;
94245  }
94246  if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
94247  return 1;
94248  }
94249  return 2;
94250  }
94251  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
94252  if( pA->op==TK_FUNCTION ){
94253  if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
94254  }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
94255  return pA->op==TK_COLLATE ? 1 : 2;
94256  }
94257  }
94258  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
94259  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
94260  if( combinedFlags & EP_xIsSelect ) return 2;
94261  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
94262  if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
94263  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
94264  if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
94265  if( pA->iColumn!=pB->iColumn ) return 2;
94266  if( pA->iTable!=pB->iTable
94267  && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
94268  }
94269  }
94270  return 0;
94271 }
94272 
94273 /*
94274 ** Compare two ExprList objects. Return 0 if they are identical and
94275 ** non-zero if they differ in any way.
94276 **
94277 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
94278 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
94279 **
94280 ** This routine might return non-zero for equivalent ExprLists. The
94281 ** only consequence will be disabled optimizations. But this routine
94282 ** must never return 0 if the two ExprList objects are different, or
94283 ** a malfunction will result.
94284 **
94285 ** Two NULL pointers are considered to be the same. But a NULL pointer
94286 ** always differs from a non-NULL pointer.
94287 */
94289  int i;
94290  if( pA==0 && pB==0 ) return 0;
94291  if( pA==0 || pB==0 ) return 1;
94292  if( pA->nExpr!=pB->nExpr ) return 1;
94293  for(i=0; i<pA->nExpr; i++){
94294  Expr *pExprA = pA->a[i].pExpr;
94295  Expr *pExprB = pB->a[i].pExpr;
94296  if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
94297  if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
94298  }
94299  return 0;
94300 }
94301 
94302 /*
94303 ** Return true if we can prove the pE2 will always be true if pE1 is
94304 ** true. Return false if we cannot complete the proof or if pE2 might
94305 ** be false. Examples:
94306 **
94307 ** pE1: x==5 pE2: x==5 Result: true
94308 ** pE1: x>0 pE2: x==5 Result: false
94309 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
94310 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
94311 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
94312 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
94313 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
94314 **
94315 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
94316 ** Expr.iTable<0 then assume a table number given by iTab.
94317 **
94318 ** When in doubt, return false. Returning true might give a performance
94319 ** improvement. Returning false might cause a performance reduction, but
94320 ** it will always give the correct answer and is hence always safe.
94321 */
94323  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
94324  return 1;
94325  }
94326  if( pE2->op==TK_OR
94327  && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
94328  || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
94329  ){
94330  return 1;
94331  }
94332  if( pE2->op==TK_NOTNULL
94333  && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
94334  && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
94335  ){
94336  return 1;
94337  }
94338  return 0;
94339 }
94340 
94341 /*
94342 ** An instance of the following structure is used by the tree walker
94343 ** to determine if an expression can be evaluated by reference to the
94344 ** index only, without having to do a search for the corresponding
94345 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
94346 ** is the cursor for the table.
94347 */
94348 struct IdxCover {
94349  Index *pIdx; /* The index to be tested for coverage */
94350  int iCur; /* Cursor number for the table corresponding to the index */
94351 };
94352 
94353 /*
94354 ** Check to see if there are references to columns in table
94355 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
94356 ** pWalker->u.pIdxCover->pIdx.
94357 */
94358 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
94359  if( pExpr->op==TK_COLUMN
94360  && pExpr->iTable==pWalker->u.pIdxCover->iCur
94361  && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
94362  ){
94363  pWalker->eCode = 1;
94364  return WRC_Abort;
94365  }
94366  return WRC_Continue;
94367 }
94368 
94369 /*
94370 ** Determine if an index pIdx on table with cursor iCur contains will
94371 ** the expression pExpr. Return true if the index does cover the
94372 ** expression and false if the pExpr expression references table columns
94373 ** that are not found in the index pIdx.
94374 **
94375 ** An index covering an expression means that the expression can be
94376 ** evaluated using only the index and without having to lookup the
94377 ** corresponding table entry.
94378 */
94380  Expr *pExpr, /* The index to be tested */
94381  int iCur, /* The cursor number for the corresponding table */
94382  Index *pIdx /* The index that might be used for coverage */
94383 ){
94384  Walker w;
94385  struct IdxCover xcov;
94386  memset(&w, 0, sizeof(w));
94387  xcov.iCur = iCur;
94388  xcov.pIdx = pIdx;
94390  w.u.pIdxCover = &xcov;
94391  sqlite3WalkExpr(&w, pExpr);
94392  return !w.eCode;
94393 }
94394 
94395 
94396 /*
94397 ** An instance of the following structure is used by the tree walker
94398 ** to count references to table columns in the arguments of an
94399 ** aggregate function, in order to implement the
94400 ** sqlite3FunctionThisSrc() routine.
94401 */
94402 struct SrcCount {
94403  SrcList *pSrc; /* One particular FROM clause in a nested query */
94404  int nThis; /* Number of references to columns in pSrcList */
94405  int nOther; /* Number of references to columns in other FROM clauses */
94406 };
94407 
94408 /*
94409 ** Count the number of references to columns.
94410 */
94411 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
94412  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
94413  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
94414  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
94415  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
94416  ** NEVER() will need to be removed. */
94417  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
94418  int i;
94419  struct SrcCount *p = pWalker->u.pSrcCount;
94420  SrcList *pSrc = p->pSrc;
94421  int nSrc = pSrc ? pSrc->nSrc : 0;
94422  for(i=0; i<nSrc; i++){
94423  if( pExpr->iTable==pSrc->a[i].iCursor ) break;
94424  }
94425  if( i<nSrc ){
94426  p->nThis++;
94427  }else{
94428  p->nOther++;
94429  }
94430  }
94431  return WRC_Continue;
94432 }
94433 
94434 /*
94435 ** Determine if any of the arguments to the pExpr Function reference
94436 ** pSrcList. Return true if they do. Also return true if the function
94437 ** has no arguments or has only constant arguments. Return false if pExpr
94438 ** references columns but not columns of tables found in pSrcList.
94439 */
94441  Walker w;
94442  struct SrcCount cnt;
94443  assert( pExpr->op==TK_AGG_FUNCTION );
94444  memset(&w, 0, sizeof(w));
94446  w.u.pSrcCount = &cnt;
94447  cnt.pSrc = pSrcList;
94448  cnt.nThis = 0;
94449  cnt.nOther = 0;
94450  sqlite3WalkExprList(&w, pExpr->x.pList);
94451  return cnt.nThis>0 || cnt.nOther==0;
94452 }
94453 
94454 /*
94455 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
94456 ** the new element. Return a negative number if malloc fails.
94457 */
94458 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
94459  int i;
94460  pInfo->aCol = sqlite3ArrayAllocate(
94461  db,
94462  pInfo->aCol,
94463  sizeof(pInfo->aCol[0]),
94464  &pInfo->nColumn,
94465  &i
94466  );
94467  return i;
94468 }
94469 
94470 /*
94471 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
94472 ** the new element. Return a negative number if malloc fails.
94473 */
94474 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
94475  int i;
94476  pInfo->aFunc = sqlite3ArrayAllocate(
94477  db,
94478  pInfo->aFunc,
94479  sizeof(pInfo->aFunc[0]),
94480  &pInfo->nFunc,
94481  &i
94482  );
94483  return i;
94484 }
94485 
94486 /*
94487 ** This is the xExprCallback for a tree walker. It is used to
94488 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
94489 ** for additional information.
94490 */
94491 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
94492  int i;
94493  NameContext *pNC = pWalker->u.pNC;
94494  Parse *pParse = pNC->pParse;
94495  SrcList *pSrcList = pNC->pSrcList;
94496  AggInfo *pAggInfo = pNC->pAggInfo;
94497 
94498  switch( pExpr->op ){
94499  case TK_AGG_COLUMN:
94500  case TK_COLUMN: {
94501  testcase( pExpr->op==TK_AGG_COLUMN );
94502  testcase( pExpr->op==TK_COLUMN );
94503  /* Check to see if the column is in one of the tables in the FROM
94504  ** clause of the aggregate query */
94505  if( ALWAYS(pSrcList!=0) ){
94506  struct SrcList_item *pItem = pSrcList->a;
94507  for(i=0; i<pSrcList->nSrc; i++, pItem++){
94508  struct AggInfo_col *pCol;
94509  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
94510  if( pExpr->iTable==pItem->iCursor ){
94511  /* If we reach this point, it means that pExpr refers to a table
94512  ** that is in the FROM clause of the aggregate query.
94513  **
94514  ** Make an entry for the column in pAggInfo->aCol[] if there
94515  ** is not an entry there already.
94516  */
94517  int k;
94518  pCol = pAggInfo->aCol;
94519  for(k=0; k<pAggInfo->nColumn; k++, pCol++){
94520  if( pCol->iTable==pExpr->iTable &&
94521  pCol->iColumn==pExpr->iColumn ){
94522  break;
94523  }
94524  }
94525  if( (k>=pAggInfo->nColumn)
94526  && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
94527  ){
94528  pCol = &pAggInfo->aCol[k];
94529  pCol->pTab = pExpr->pTab;
94530  pCol->iTable = pExpr->iTable;
94531  pCol->iColumn = pExpr->iColumn;
94532  pCol->iMem = ++pParse->nMem;
94533  pCol->iSorterColumn = -1;
94534  pCol->pExpr = pExpr;
94535  if( pAggInfo->pGroupBy ){
94536  int j, n;
94537  ExprList *pGB = pAggInfo->pGroupBy;
94538  struct ExprList_item *pTerm = pGB->a;
94539  n = pGB->nExpr;
94540  for(j=0; j<n; j++, pTerm++){
94541  Expr *pE = pTerm->pExpr;
94542  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
94543  pE->iColumn==pExpr->iColumn ){
94544  pCol->iSorterColumn = j;
94545  break;
94546  }
94547  }
94548  }
94549  if( pCol->iSorterColumn<0 ){
94550  pCol->iSorterColumn = pAggInfo->nSortingColumn++;
94551  }
94552  }
94553  /* There is now an entry for pExpr in pAggInfo->aCol[] (either
94554  ** because it was there before or because we just created it).
94555  ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
94556  ** pAggInfo->aCol[] entry.
94557  */
94559  pExpr->pAggInfo = pAggInfo;
94560  pExpr->op = TK_AGG_COLUMN;
94561  pExpr->iAgg = (i16)k;
94562  break;
94563  } /* endif pExpr->iTable==pItem->iCursor */
94564  } /* end loop over pSrcList */
94565  }
94566  return WRC_Prune;
94567  }
94568  case TK_AGG_FUNCTION: {
94569  if( (pNC->ncFlags & NC_InAggFunc)==0
94570  && pWalker->walkerDepth==pExpr->op2
94571  ){
94572  /* Check to see if pExpr is a duplicate of another aggregate
94573  ** function that is already in the pAggInfo structure
94574  */
94575  struct AggInfo_func *pItem = pAggInfo->aFunc;
94576  for(i=0; i<pAggInfo->nFunc; i++, pItem++){
94577  if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
94578  break;
94579  }
94580  }
94581  if( i>=pAggInfo->nFunc ){
94582  /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
94583  */
94584  u8 enc = ENC(pParse->db);
94585  i = addAggInfoFunc(pParse->db, pAggInfo);
94586  if( i>=0 ){
94587  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
94588  pItem = &pAggInfo->aFunc[i];
94589  pItem->pExpr = pExpr;
94590  pItem->iMem = ++pParse->nMem;
94591  assert( !ExprHasProperty(pExpr, EP_IntValue) );
94592  pItem->pFunc = sqlite3FindFunction(pParse->db,
94593  pExpr->u.zToken,
94594  pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
94595  if( pExpr->flags & EP_Distinct ){
94596  pItem->iDistinct = pParse->nTab++;
94597  }else{
94598  pItem->iDistinct = -1;
94599  }
94600  }
94601  }
94602  /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
94603  */
94604  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
94606  pExpr->iAgg = (i16)i;
94607  pExpr->pAggInfo = pAggInfo;
94608  return WRC_Prune;
94609  }else{
94610  return WRC_Continue;
94611  }
94612  }
94613  }
94614  return WRC_Continue;
94615 }
94616 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
94617  UNUSED_PARAMETER(pWalker);
94618  UNUSED_PARAMETER(pSelect);
94619  return WRC_Continue;
94620 }
94621 
94622 /*
94623 ** Analyze the pExpr expression looking for aggregate functions and
94624 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
94625 ** points to. Additional entries are made on the AggInfo object as
94626 ** necessary.
94627 **
94628 ** This routine should only be called after the expression has been
94629 ** analyzed by sqlite3ResolveExprNames().
94630 */
94632  Walker w;
94633  memset(&w, 0, sizeof(w));
94636  w.u.pNC = pNC;
94637  assert( pNC->pSrcList!=0 );
94638  sqlite3WalkExpr(&w, pExpr);
94639 }
94640 
94641 /*
94642 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
94643 ** expression list. Return the number of errors.
94644 **
94645 ** If an error is found, the analysis is cut short.
94646 */
94648  struct ExprList_item *pItem;
94649  int i;
94650  if( pList ){
94651  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
94652  sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
94653  }
94654  }
94655 }
94656 
94657 /*
94658 ** Allocate a single new register for use to hold some intermediate result.
94659 */
94661  if( pParse->nTempReg==0 ){
94662  return ++pParse->nMem;
94663  }
94664  return pParse->aTempReg[--pParse->nTempReg];
94665 }
94666 
94667 /*
94668 ** Deallocate a register, making available for reuse for some other
94669 ** purpose.
94670 **
94671 ** If a register is currently being used by the column cache, then
94672 ** the deallocation is deferred until the column cache line that uses
94673 ** the register becomes stale.
94674 */
94676  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
94677  int i;
94678  struct yColCache *p;
94679  for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
94680  if( p->iReg==iReg ){
94681  p->tempReg = 1;
94682  return;
94683  }
94684  }
94685  pParse->aTempReg[pParse->nTempReg++] = iReg;
94686  }
94687 }
94688 
94689 /*
94690 ** Allocate or deallocate a block of nReg consecutive registers.
94691 */
94693  int i, n;
94694  if( nReg==1 ) return sqlite3GetTempReg(pParse);
94695  i = pParse->iRangeReg;
94696  n = pParse->nRangeReg;
94697  if( nReg<=n ){
94698  assert( !usedAsColumnCache(pParse, i, i+n-1) );
94699  pParse->iRangeReg += nReg;
94700  pParse->nRangeReg -= nReg;
94701  }else{
94702  i = pParse->nMem+1;
94703  pParse->nMem += nReg;
94704  }
94705  return i;
94706 }
94707 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
94708  if( nReg==1 ){
94709  sqlite3ReleaseTempReg(pParse, iReg);
94710  return;
94711  }
94712  sqlite3ExprCacheRemove(pParse, iReg, nReg);
94713  if( nReg>pParse->nRangeReg ){
94714  pParse->nRangeReg = nReg;
94715  pParse->iRangeReg = iReg;
94716  }
94717 }
94718 
94719 /*
94720 ** Mark all temporary registers as being unavailable for reuse.
94721 */
94723  pParse->nTempReg = 0;
94724  pParse->nRangeReg = 0;
94725 }
94726 
94727 /*
94728 ** Validate that no temporary register falls within the range of
94729 ** iFirst..iLast, inclusive. This routine is only call from within assert()
94730 ** statements.
94731 */
94732 #ifdef SQLITE_DEBUG
94733 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
94734  int i;
94735  if( pParse->nRangeReg>0
94736  && pParse->iRangeReg+pParse->nRangeReg<iLast
94737  && pParse->iRangeReg>=iFirst
94738  ){
94739  return 0;
94740  }
94741  for(i=0; i<pParse->nTempReg; i++){
94742  if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
94743  return 0;
94744  }
94745  }
94746  return 1;
94747 }
94748 #endif /* SQLITE_DEBUG */
94749 
94750 /************** End of expr.c ************************************************/
94751 /************** Begin file alter.c *******************************************/
94752 /*
94753 ** 2005 February 15
94754 **
94755 ** The author disclaims copyright to this source code. In place of
94756 ** a legal notice, here is a blessing:
94757 **
94758 ** May you do good and not evil.
94759 ** May you find forgiveness for yourself and forgive others.
94760 ** May you share freely, never taking more than you give.
94761 **
94762 *************************************************************************
94763 ** This file contains C code routines that used to generate VDBE code
94764 ** that implements the ALTER TABLE command.
94765 */
94766 /* #include "sqliteInt.h" */
94767 
94768 /*
94769 ** The code in this file only exists if we are not omitting the
94770 ** ALTER TABLE logic from the build.
94771 */
94772 #ifndef SQLITE_OMIT_ALTERTABLE
94773 
94774 
94775 /*
94776 ** This function is used by SQL generated to implement the
94777 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
94778 ** CREATE INDEX command. The second is a table name. The table name in
94779 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
94780 ** argument and the result returned. Examples:
94781 **
94782 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
94783 ** -> 'CREATE TABLE def(a, b, c)'
94784 **
94785 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
94786 ** -> 'CREATE INDEX i ON def(a, b, c)'
94787 */
94788 static void renameTableFunc(
94789  sqlite3_context *context,
94790  int NotUsed,
94791  sqlite3_value **argv
94792 ){
94793  unsigned char const *zSql = sqlite3_value_text(argv[0]);
94794  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
94795 
94796  int token;
94797  Token tname;
94798  unsigned char const *zCsr = zSql;
94799  int len = 0;
94800  char *zRet;
94801 
94802  sqlite3 *db = sqlite3_context_db_handle(context);
94803 
94804  UNUSED_PARAMETER(NotUsed);
94805 
94806  /* The principle used to locate the table name in the CREATE TABLE
94807  ** statement is that the table name is the first non-space token that
94808  ** is immediately followed by a TK_LP or TK_USING token.
94809  */
94810  if( zSql ){
94811  do {
94812  if( !*zCsr ){
94813  /* Ran out of input before finding an opening bracket. Return NULL. */
94814  return;
94815  }
94816 
94817  /* Store the token that zCsr points to in tname. */
94818  tname.z = (char*)zCsr;
94819  tname.n = len;
94820 
94821  /* Advance zCsr to the next token. Store that token type in 'token',
94822  ** and its length in 'len' (to be used next iteration of this loop).
94823  */
94824  do {
94825  zCsr += len;
94826  len = sqlite3GetToken(zCsr, &token);
94827  } while( token==TK_SPACE );
94828  assert( len>0 );
94829  } while( token!=TK_LP && token!=TK_USING );
94830 
94831  zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
94832  zSql, zTableName, tname.z+tname.n);
94833  sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
94834  }
94835 }
94836 
94837 /*
94838 ** This C function implements an SQL user function that is used by SQL code
94839 ** generated by the ALTER TABLE ... RENAME command to modify the definition
94840 ** of any foreign key constraints that use the table being renamed as the
94841 ** parent table. It is passed three arguments:
94842 **
94843 ** 1) The complete text of the CREATE TABLE statement being modified,
94844 ** 2) The old name of the table being renamed, and
94845 ** 3) The new name of the table being renamed.
94846 **
94847 ** It returns the new CREATE TABLE statement. For example:
94848 **
94849 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
94850 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
94851 */
94852 #ifndef SQLITE_OMIT_FOREIGN_KEY
94853 static void renameParentFunc(
94854  sqlite3_context *context,
94855  int NotUsed,
94856  sqlite3_value **argv
94857 ){
94858  sqlite3 *db = sqlite3_context_db_handle(context);
94859  char *zOutput = 0;
94860  char *zResult;
94861  unsigned char const *zInput = sqlite3_value_text(argv[0]);
94862  unsigned char const *zOld = sqlite3_value_text(argv[1]);
94863  unsigned char const *zNew = sqlite3_value_text(argv[2]);
94864 
94865  unsigned const char *z; /* Pointer to token */
94866  int n; /* Length of token z */
94867  int token; /* Type of token */
94868 
94869  UNUSED_PARAMETER(NotUsed);
94870  if( zInput==0 || zOld==0 ) return;
94871  for(z=zInput; *z; z=z+n){
94872  n = sqlite3GetToken(z, &token);
94873  if( token==TK_REFERENCES ){
94874  char *zParent;
94875  do {
94876  z += n;
94877  n = sqlite3GetToken(z, &token);
94878  }while( token==TK_SPACE );
94879 
94880  if( token==TK_ILLEGAL ) break;
94881  zParent = sqlite3DbStrNDup(db, (const char *)z, n);
94882  if( zParent==0 ) break;
94883  sqlite3Dequote(zParent);
94884  if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
94885  char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
94886  (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
94887  );
94888  sqlite3DbFree(db, zOutput);
94889  zOutput = zOut;
94890  zInput = &z[n];
94891  }
94892  sqlite3DbFree(db, zParent);
94893  }
94894  }
94895 
94896  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
94897  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
94898  sqlite3DbFree(db, zOutput);
94899 }
94900 #endif
94901 
94902 #ifndef SQLITE_OMIT_TRIGGER
94903 /* This function is used by SQL generated to implement the
94904 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
94905 ** statement. The second is a table name. The table name in the CREATE
94906 ** TRIGGER statement is replaced with the third argument and the result
94907 ** returned. This is analagous to renameTableFunc() above, except for CREATE
94908 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
94909 */
94910 static void renameTriggerFunc(
94911  sqlite3_context *context,
94912  int NotUsed,
94913  sqlite3_value **argv
94914 ){
94915  unsigned char const *zSql = sqlite3_value_text(argv[0]);
94916  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
94917 
94918  int token;
94919  Token tname;
94920  int dist = 3;
94921  unsigned char const *zCsr = zSql;
94922  int len = 0;
94923  char *zRet;
94924  sqlite3 *db = sqlite3_context_db_handle(context);
94925 
94926  UNUSED_PARAMETER(NotUsed);
94927 
94928  /* The principle used to locate the table name in the CREATE TRIGGER
94929  ** statement is that the table name is the first token that is immediately
94930  ** preceded by either TK_ON or TK_DOT and immediately followed by one
94931  ** of TK_WHEN, TK_BEGIN or TK_FOR.
94932  */
94933  if( zSql ){
94934  do {
94935 
94936  if( !*zCsr ){
94937  /* Ran out of input before finding the table name. Return NULL. */
94938  return;
94939  }
94940 
94941  /* Store the token that zCsr points to in tname. */
94942  tname.z = (char*)zCsr;
94943  tname.n = len;
94944 
94945  /* Advance zCsr to the next token. Store that token type in 'token',
94946  ** and its length in 'len' (to be used next iteration of this loop).
94947  */
94948  do {
94949  zCsr += len;
94950  len = sqlite3GetToken(zCsr, &token);
94951  }while( token==TK_SPACE );
94952  assert( len>0 );
94953 
94954  /* Variable 'dist' stores the number of tokens read since the most
94955  ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
94956  ** token is read and 'dist' equals 2, the condition stated above
94957  ** to be met.
94958  **
94959  ** Note that ON cannot be a database, table or column name, so
94960  ** there is no need to worry about syntax like
94961  ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
94962  */
94963  dist++;
94964  if( token==TK_DOT || token==TK_ON ){
94965  dist = 0;
94966  }
94967  } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
94968 
94969  /* Variable tname now contains the token that is the old table-name
94970  ** in the CREATE TRIGGER statement.
94971  */
94972  zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
94973  zSql, zTableName, tname.z+tname.n);
94974  sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
94975  }
94976 }
94977 #endif /* !SQLITE_OMIT_TRIGGER */
94978 
94979 /*
94980 ** Register built-in functions used to help implement ALTER TABLE
94981 */
94983  static FuncDef aAlterTableFuncs[] = {
94984  FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
94985 #ifndef SQLITE_OMIT_TRIGGER
94986  FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
94987 #endif
94988 #ifndef SQLITE_OMIT_FOREIGN_KEY
94989  FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
94990 #endif
94991  };
94992  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
94993 }
94994 
94995 /*
94996 ** This function is used to create the text of expressions of the form:
94997 **
94998 ** name=<constant1> OR name=<constant2> OR ...
94999 **
95000 ** If argument zWhere is NULL, then a pointer string containing the text
95001 ** "name=<constant>" is returned, where <constant> is the quoted version
95002 ** of the string passed as argument zConstant. The returned buffer is
95003 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
95004 ** caller to ensure that it is eventually freed.
95005 **
95006 ** If argument zWhere is not NULL, then the string returned is
95007 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
95008 ** In this case zWhere is passed to sqlite3DbFree() before returning.
95009 **
95010 */
95011 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
95012  char *zNew;
95013  if( !zWhere ){
95014  zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
95015  }else{
95016  zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
95017  sqlite3DbFree(db, zWhere);
95018  }
95019  return zNew;
95020 }
95021 
95022 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
95023 /*
95024 ** Generate the text of a WHERE expression which can be used to select all
95025 ** tables that have foreign key constraints that refer to table pTab (i.e.
95026 ** constraints for which pTab is the parent table) from the sqlite_master
95027 ** table.
95028 */
95029 static char *whereForeignKeys(Parse *pParse, Table *pTab){
95030  FKey *p;
95031  char *zWhere = 0;
95032  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
95033  zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
95034  }
95035  return zWhere;
95036 }
95037 #endif
95038 
95039 /*
95040 ** Generate the text of a WHERE expression which can be used to select all
95041 ** temporary triggers on table pTab from the sqlite_temp_master table. If
95042 ** table pTab has no temporary triggers, or is itself stored in the
95043 ** temporary database, NULL is returned.
95044 */
95045 static char *whereTempTriggers(Parse *pParse, Table *pTab){
95046  Trigger *pTrig;
95047  char *zWhere = 0;
95048  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
95049 
95050  /* If the table is not located in the temp-db (in which case NULL is
95051  ** returned, loop through the tables list of triggers. For each trigger
95052  ** that is not part of the temp-db schema, add a clause to the WHERE
95053  ** expression being built up in zWhere.
95054  */
95055  if( pTab->pSchema!=pTempSchema ){
95056  sqlite3 *db = pParse->db;
95057  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
95058  if( pTrig->pSchema==pTempSchema ){
95059  zWhere = whereOrName(db, zWhere, pTrig->zName);
95060  }
95061  }
95062  }
95063  if( zWhere ){
95064  char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
95065  sqlite3DbFree(pParse->db, zWhere);
95066  zWhere = zNew;
95067  }
95068  return zWhere;
95069 }
95070 
95071 /*
95072 ** Generate code to drop and reload the internal representation of table
95073 ** pTab from the database, including triggers and temporary triggers.
95074 ** Argument zName is the name of the table in the database schema at
95075 ** the time the generated code is executed. This can be different from
95076 ** pTab->zName if this function is being called to code part of an
95077 ** "ALTER TABLE RENAME TO" statement.
95078 */
95079 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
95080  Vdbe *v;
95081  char *zWhere;
95082  int iDb; /* Index of database containing pTab */
95083 #ifndef SQLITE_OMIT_TRIGGER
95084  Trigger *pTrig;
95085 #endif
95086 
95087  v = sqlite3GetVdbe(pParse);
95088  if( NEVER(v==0) ) return;
95089  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95090  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95091  assert( iDb>=0 );
95092 
95093 #ifndef SQLITE_OMIT_TRIGGER
95094  /* Drop any table triggers from the internal schema. */
95095  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
95096  int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
95097  assert( iTrigDb==iDb || iTrigDb==1 );
95098  sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
95099  }
95100 #endif
95101 
95102  /* Drop the table and index from the internal schema. */
95103  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
95104 
95105  /* Reload the table, index and permanent trigger schemas. */
95106  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
95107  if( !zWhere ) return;
95108  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
95109 
95110 #ifndef SQLITE_OMIT_TRIGGER
95111  /* Now, if the table is not stored in the temp database, reload any temp
95112  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
95113  */
95114  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
95115  sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
95116  }
95117 #endif
95118 }
95119 
95120 /*
95121 ** Parameter zName is the name of a table that is about to be altered
95122 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
95123 ** If the table is a system table, this function leaves an error message
95124 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
95125 **
95126 ** Or, if zName is not a system table, zero is returned.
95127 */
95128 static int isSystemTable(Parse *pParse, const char *zName){
95129  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
95130  sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
95131  return 1;
95132  }
95133  return 0;
95134 }
95135 
95136 /*
95137 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
95138 ** command.
95139 */
95141  Parse *pParse, /* Parser context. */
95142  SrcList *pSrc, /* The table to rename. */
95143  Token *pName /* The new table name. */
95144 ){
95145  int iDb; /* Database that contains the table */
95146  char *zDb; /* Name of database iDb */
95147  Table *pTab; /* Table being renamed */
95148  char *zName = 0; /* NULL-terminated version of pName */
95149  sqlite3 *db = pParse->db; /* Database connection */
95150  int nTabName; /* Number of UTF-8 characters in zTabName */
95151  const char *zTabName; /* Original name of the table */
95152  Vdbe *v;
95153 #ifndef SQLITE_OMIT_TRIGGER
95154  char *zWhere = 0; /* Where clause to locate temp triggers */
95155 #endif
95156  VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
95157  int savedDbFlags; /* Saved value of db->flags */
95158 
95159  savedDbFlags = db->flags;
95160  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
95161  assert( pSrc->nSrc==1 );
95162  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95163 
95164  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
95165  if( !pTab ) goto exit_rename_table;
95166  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95167  zDb = db->aDb[iDb].zDbSName;
95168  db->flags |= SQLITE_PreferBuiltin;
95169 
95170  /* Get a NULL terminated version of the new table name. */
95171  zName = sqlite3NameFromToken(db, pName);
95172  if( !zName ) goto exit_rename_table;
95173 
95174  /* Check that a table or index named 'zName' does not already exist
95175  ** in database iDb. If so, this is an error.
95176  */
95177  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
95178  sqlite3ErrorMsg(pParse,
95179  "there is already another table or index with this name: %s", zName);
95180  goto exit_rename_table;
95181  }
95182 
95183  /* Make sure it is not a system table being altered, or a reserved name
95184  ** that the table is being renamed to.
95185  */
95186  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
95187  goto exit_rename_table;
95188  }
95189  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
95190  exit_rename_table;
95191  }
95192 
95193 #ifndef SQLITE_OMIT_VIEW
95194  if( pTab->pSelect ){
95195  sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
95196  goto exit_rename_table;
95197  }
95198 #endif
95199 
95200 #ifndef SQLITE_OMIT_AUTHORIZATION
95201  /* Invoke the authorization callback. */
95202  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
95203  goto exit_rename_table;
95204  }
95205 #endif
95206 
95207 #ifndef SQLITE_OMIT_VIRTUALTABLE
95208  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
95209  goto exit_rename_table;
95210  }
95211  if( IsVirtual(pTab) ){
95212  pVTab = sqlite3GetVTable(db, pTab);
95213  if( pVTab->pVtab->pModule->xRename==0 ){
95214  pVTab = 0;
95215  }
95216  }
95217 #endif
95218 
95219  /* Begin a transaction for database iDb.
95220  ** Then modify the schema cookie (since the ALTER TABLE modifies the
95221  ** schema). Open a statement transaction if the table is a virtual
95222  ** table.
95223  */
95224  v = sqlite3GetVdbe(pParse);
95225  if( v==0 ){
95226  goto exit_rename_table;
95227  }
95228  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
95229  sqlite3ChangeCookie(pParse, iDb);
95230 
95231  /* If this is a virtual table, invoke the xRename() function if
95232  ** one is defined. The xRename() callback will modify the names
95233  ** of any resources used by the v-table implementation (including other
95234  ** SQLite tables) that are identified by the name of the virtual table.
95235  */
95236 #ifndef SQLITE_OMIT_VIRTUALTABLE
95237  if( pVTab ){
95238  int i = ++pParse->nMem;
95239  sqlite3VdbeLoadString(v, i, zName);
95240  sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
95241  sqlite3MayAbort(pParse);
95242  }
95243 #endif
95244 
95245  /* figure out how many UTF-8 characters are in zName */
95246  zTabName = pTab->zName;
95247  nTabName = sqlite3Utf8CharLen(zTabName, -1);
95248 
95249 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
95250  if( db->flags&SQLITE_ForeignKeys ){
95251  /* If foreign-key support is enabled, rewrite the CREATE TABLE
95252  ** statements corresponding to all child tables of foreign key constraints
95253  ** for which the renamed table is the parent table. */
95254  if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
95255  sqlite3NestedParse(pParse,
95256  "UPDATE \"%w\".%s SET "
95257  "sql = sqlite_rename_parent(sql, %Q, %Q) "
95258  "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
95259  sqlite3DbFree(db, zWhere);
95260  }
95261  }
95262 #endif
95263 
95264  /* Modify the sqlite_master table to use the new table name. */
95265  sqlite3NestedParse(pParse,
95266  "UPDATE %Q.%s SET "
95267 #ifdef SQLITE_OMIT_TRIGGER
95268  "sql = sqlite_rename_table(sql, %Q), "
95269 #else
95270  "sql = CASE "
95271  "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
95272  "ELSE sqlite_rename_table(sql, %Q) END, "
95273 #endif
95274  "tbl_name = %Q, "
95275  "name = CASE "
95276  "WHEN type='table' THEN %Q "
95277  "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
95278  "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
95279  "ELSE name END "
95280  "WHERE tbl_name=%Q COLLATE nocase AND "
95281  "(type='table' OR type='index' OR type='trigger');",
95282  zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
95283 #ifndef SQLITE_OMIT_TRIGGER
95284  zName,
95285 #endif
95286  zName, nTabName, zTabName
95287  );
95288 
95289 #ifndef SQLITE_OMIT_AUTOINCREMENT
95290  /* If the sqlite_sequence table exists in this database, then update
95291  ** it with the new table name.
95292  */
95293  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
95294  sqlite3NestedParse(pParse,
95295  "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
95296  zDb, zName, pTab->zName);
95297  }
95298 #endif
95299 
95300 #ifndef SQLITE_OMIT_TRIGGER
95301  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
95302  ** table. Don't do this if the table being ALTERed is itself located in
95303  ** the temp database.
95304  */
95305  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
95306  sqlite3NestedParse(pParse,
95307  "UPDATE sqlite_temp_master SET "
95308  "sql = sqlite_rename_trigger(sql, %Q), "
95309  "tbl_name = %Q "
95310  "WHERE %s;", zName, zName, zWhere);
95311  sqlite3DbFree(db, zWhere);
95312  }
95313 #endif
95314 
95315 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
95316  if( db->flags&SQLITE_ForeignKeys ){
95317  FKey *p;
95318  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
95319  Table *pFrom = p->pFrom;
95320  if( pFrom!=pTab ){
95321  reloadTableSchema(pParse, p->pFrom, pFrom->zName);
95322  }
95323  }
95324  }
95325 #endif
95326 
95327  /* Drop and reload the internal table schema. */
95328  reloadTableSchema(pParse, pTab, zName);
95329 
95330 exit_rename_table:
95331  sqlite3SrcListDelete(db, pSrc);
95332  sqlite3DbFree(db, zName);
95333  db->flags = savedDbFlags;
95334 }
95335 
95336 /*
95337 ** This function is called after an "ALTER TABLE ... ADD" statement
95338 ** has been parsed. Argument pColDef contains the text of the new
95339 ** column definition.
95340 **
95341 ** The Table structure pParse->pNewTable was extended to include
95342 ** the new column during parsing.
95343 */
95345  Table *pNew; /* Copy of pParse->pNewTable */
95346  Table *pTab; /* Table being altered */
95347  int iDb; /* Database number */
95348  const char *zDb; /* Database name */
95349  const char *zTab; /* Table name */
95350  char *zCol; /* Null-terminated column definition */
95351  Column *pCol; /* The new column */
95352  Expr *pDflt; /* Default value for the new column */
95353  sqlite3 *db; /* The database connection; */
95354  Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
95355  int r1; /* Temporary registers */
95356 
95357  db = pParse->db;
95358  if( pParse->nErr || db->mallocFailed ) return;
95359  assert( v!=0 );
95360  pNew = pParse->pNewTable;
95361  assert( pNew );
95362 
95363  assert( sqlite3BtreeHoldsAllMutexes(db) );
95364  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
95365  zDb = db->aDb[iDb].zDbSName;
95366  zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
95367  pCol = &pNew->aCol[pNew->nCol-1];
95368  pDflt = pCol->pDflt;
95369  pTab = sqlite3FindTable(db, zTab, zDb);
95370  assert( pTab );
95371 
95372 #ifndef SQLITE_OMIT_AUTHORIZATION
95373  /* Invoke the authorization callback. */
95374  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
95375  return;
95376  }
95377 #endif
95378 
95379  /* If the default value for the new column was specified with a
95380  ** literal NULL, then set pDflt to 0. This simplifies checking
95381  ** for an SQL NULL default below.
95382  */
95383  assert( pDflt==0 || pDflt->op==TK_SPAN );
95384  if( pDflt && pDflt->pLeft->op==TK_NULL ){
95385  pDflt = 0;
95386  }
95387 
95388  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
95389  ** If there is a NOT NULL constraint, then the default value for the
95390  ** column must not be NULL.
95391  */
95392  if( pCol->colFlags & COLFLAG_PRIMKEY ){
95393  sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
95394  return;
95395  }
95396  if( pNew->pIndex ){
95397  sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
95398  return;
95399  }
95400  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
95401  sqlite3ErrorMsg(pParse,
95402  "Cannot add a REFERENCES column with non-NULL default value");
95403  return;
95404  }
95405  if( pCol->notNull && !pDflt ){
95406  sqlite3ErrorMsg(pParse,
95407  "Cannot add a NOT NULL column with default value NULL");
95408  return;
95409  }
95410 
95411  /* Ensure the default expression is something that sqlite3ValueFromExpr()
95412  ** can handle (i.e. not CURRENT_TIME etc.)
95413  */
95414  if( pDflt ){
95415  sqlite3_value *pVal = 0;
95416  int rc;
95417  rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
95418  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
95419  if( rc!=SQLITE_OK ){
95420  assert( db->mallocFailed == 1 );
95421  return;
95422  }
95423  if( !pVal ){
95424  sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
95425  return;
95426  }
95427  sqlite3ValueFree(pVal);
95428  }
95429 
95430  /* Modify the CREATE TABLE statement. */
95431  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
95432  if( zCol ){
95433  char *zEnd = &zCol[pColDef->n-1];
95434  int savedDbFlags = db->flags;
95435  while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
95436  *zEnd-- = '\0';
95437  }
95438  db->flags |= SQLITE_PreferBuiltin;
95439  sqlite3NestedParse(pParse,
95440  "UPDATE \"%w\".%s SET "
95441  "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
95442  "WHERE type = 'table' AND name = %Q",
95443  zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
95444  zTab
95445  );
95446  sqlite3DbFree(db, zCol);
95447  db->flags = savedDbFlags;
95448  }
95449 
95450  /* Make sure the schema version is at least 3. But do not upgrade
95451  ** from less than 3 to 4, as that will corrupt any preexisting DESC
95452  ** index.
95453  */
95454  r1 = sqlite3GetTempReg(pParse);
95456  sqlite3VdbeUsesBtree(v, iDb);
95457  sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
95459  VdbeCoverage(v);
95461  sqlite3ReleaseTempReg(pParse, r1);
95462 
95463  /* Reload the schema of the modified table. */
95464  reloadTableSchema(pParse, pTab, pTab->zName);
95465 }
95466 
95467 /*
95468 ** This function is called by the parser after the table-name in
95469 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
95470 ** pSrc is the full-name of the table being altered.
95471 **
95472 ** This routine makes a (partial) copy of the Table structure
95473 ** for the table being altered and sets Parse.pNewTable to point
95474 ** to it. Routines called by the parser as the column definition
95475 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
95476 ** the copy. The copy of the Table structure is deleted by tokenize.c
95477 ** after parsing is finished.
95478 **
95479 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
95480 ** coding the "ALTER TABLE ... ADD" statement.
95481 */
95483  Table *pNew;
95484  Table *pTab;
95485  Vdbe *v;
95486  int iDb;
95487  int i;
95488  int nAlloc;
95489  sqlite3 *db = pParse->db;
95490 
95491  /* Look up the table being altered. */
95492  assert( pParse->pNewTable==0 );
95493  assert( sqlite3BtreeHoldsAllMutexes(db) );
95494  if( db->mallocFailed ) goto exit_begin_add_column;
95495  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
95496  if( !pTab ) goto exit_begin_add_column;
95497 
95498 #ifndef SQLITE_OMIT_VIRTUALTABLE
95499  if( IsVirtual(pTab) ){
95500  sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
95501  goto exit_begin_add_column;
95502  }
95503 #endif
95504 
95505  /* Make sure this is not an attempt to ALTER a view. */
95506  if( pTab->pSelect ){
95507  sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
95508  goto exit_begin_add_column;
95509  }
95510  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
95511  goto exit_begin_add_column;
95512  }
95513 
95514  assert( pTab->addColOffset>0 );
95515  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95516 
95517  /* Put a copy of the Table struct in Parse.pNewTable for the
95518  ** sqlite3AddColumn() function and friends to modify. But modify
95519  ** the name by adding an "sqlite_altertab_" prefix. By adding this
95520  ** prefix, we insure that the name will not collide with an existing
95521  ** table because user table are not allowed to have the "sqlite_"
95522  ** prefix on their name.
95523  */
95524  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
95525  if( !pNew ) goto exit_begin_add_column;
95526  pParse->pNewTable = pNew;
95527  pNew->nRef = 1;
95528  pNew->nCol = pTab->nCol;
95529  assert( pNew->nCol>0 );
95530  nAlloc = (((pNew->nCol-1)/8)*8)+8;
95531  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
95532  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
95533  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
95534  if( !pNew->aCol || !pNew->zName ){
95535  assert( db->mallocFailed );
95536  goto exit_begin_add_column;
95537  }
95538  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
95539  for(i=0; i<pNew->nCol; i++){
95540  Column *pCol = &pNew->aCol[i];
95541  pCol->zName = sqlite3DbStrDup(db, pCol->zName);
95542  pCol->zColl = 0;
95543  pCol->pDflt = 0;
95544  }
95545  pNew->pSchema = db->aDb[iDb].pSchema;
95546  pNew->addColOffset = pTab->addColOffset;
95547  pNew->nRef = 1;
95548 
95549  /* Begin a transaction and increment the schema cookie. */
95550  sqlite3BeginWriteOperation(pParse, 0, iDb);
95551  v = sqlite3GetVdbe(pParse);
95552  if( !v ) goto exit_begin_add_column;
95553  sqlite3ChangeCookie(pParse, iDb);
95554 
95555 exit_begin_add_column:
95556  sqlite3SrcListDelete(db, pSrc);
95557  return;
95558 }
95559 #endif /* SQLITE_ALTER_TABLE */
95560 
95561 /************** End of alter.c ***********************************************/
95562 /************** Begin file analyze.c *****************************************/
95563 /*
95564 ** 2005-07-08
95565 **
95566 ** The author disclaims copyright to this source code. In place of
95567 ** a legal notice, here is a blessing:
95568 **
95569 ** May you do good and not evil.
95570 ** May you find forgiveness for yourself and forgive others.
95571 ** May you share freely, never taking more than you give.
95572 **
95573 *************************************************************************
95574 ** This file contains code associated with the ANALYZE command.
95575 **
95576 ** The ANALYZE command gather statistics about the content of tables
95577 ** and indices. These statistics are made available to the query planner
95578 ** to help it make better decisions about how to perform queries.
95579 **
95580 ** The following system tables are or have been supported:
95581 **
95582 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
95583 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
95584 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
95585 ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
95586 **
95587 ** Additional tables might be added in future releases of SQLite.
95588 ** The sqlite_stat2 table is not created or used unless the SQLite version
95589 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
95590 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
95591 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
95592 ** created and used by SQLite versions 3.7.9 and later and with
95593 ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
95594 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
95595 ** version of sqlite_stat3 and is only available when compiled with
95596 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
95597 ** not possible to enable both STAT3 and STAT4 at the same time. If they
95598 ** are both enabled, then STAT4 takes precedence.
95599 **
95600 ** For most applications, sqlite_stat1 provides all the statistics required
95601 ** for the query planner to make good choices.
95602 **
95603 ** Format of sqlite_stat1:
95604 **
95605 ** There is normally one row per index, with the index identified by the
95606 ** name in the idx column. The tbl column is the name of the table to
95607 ** which the index belongs. In each such row, the stat column will be
95608 ** a string consisting of a list of integers. The first integer in this
95609 ** list is the number of rows in the index. (This is the same as the
95610 ** number of rows in the table, except for partial indices.) The second
95611 ** integer is the average number of rows in the index that have the same
95612 ** value in the first column of the index. The third integer is the average
95613 ** number of rows in the index that have the same value for the first two
95614 ** columns. The N-th integer (for N>1) is the average number of rows in
95615 ** the index which have the same value for the first N-1 columns. For
95616 ** a K-column index, there will be K+1 integers in the stat column. If
95617 ** the index is unique, then the last integer will be 1.
95618 **
95619 ** The list of integers in the stat column can optionally be followed
95620 ** by the keyword "unordered". The "unordered" keyword, if it is present,
95621 ** must be separated from the last integer by a single space. If the
95622 ** "unordered" keyword is present, then the query planner assumes that
95623 ** the index is unordered and will not use the index for a range query.
95624 **
95625 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
95626 ** column contains a single integer which is the (estimated) number of
95627 ** rows in the table identified by sqlite_stat1.tbl.
95628 **
95629 ** Format of sqlite_stat2:
95630 **
95631 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
95632 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
95633 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
95634 ** about the distribution of keys within an index. The index is identified by
95635 ** the "idx" column and the "tbl" column is the name of the table to which
95636 ** the index belongs. There are usually 10 rows in the sqlite_stat2
95637 ** table for each index.
95638 **
95639 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
95640 ** inclusive are samples of the left-most key value in the index taken at
95641 ** evenly spaced points along the index. Let the number of samples be S
95642 ** (10 in the standard build) and let C be the number of rows in the index.
95643 ** Then the sampled rows are given by:
95644 **
95645 ** rownumber = (i*C*2 + C)/(S*2)
95646 **
95647 ** For i between 0 and S-1. Conceptually, the index space is divided into
95648 ** S uniform buckets and the samples are the middle row from each bucket.
95649 **
95650 ** The format for sqlite_stat2 is recorded here for legacy reference. This
95651 ** version of SQLite does not support sqlite_stat2. It neither reads nor
95652 ** writes the sqlite_stat2 table. This version of SQLite only supports
95653 ** sqlite_stat3.
95654 **
95655 ** Format for sqlite_stat3:
95656 **
95657 ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
95658 ** sqlite_stat4 format will be described first. Further information
95659 ** about sqlite_stat3 follows the sqlite_stat4 description.
95660 **
95661 ** Format for sqlite_stat4:
95662 **
95663 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
95664 ** to aid the query planner in choosing good indices based on the values
95665 ** that indexed columns are compared against in the WHERE clauses of
95666 ** queries.
95667 **
95668 ** The sqlite_stat4 table contains multiple entries for each index.
95669 ** The idx column names the index and the tbl column is the table of the
95670 ** index. If the idx and tbl columns are the same, then the sample is
95671 ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
95672 ** binary encoding of a key from the index. The nEq column is a
95673 ** list of integers. The first integer is the approximate number
95674 ** of entries in the index whose left-most column exactly matches
95675 ** the left-most column of the sample. The second integer in nEq
95676 ** is the approximate number of entries in the index where the
95677 ** first two columns match the first two columns of the sample.
95678 ** And so forth. nLt is another list of integers that show the approximate
95679 ** number of entries that are strictly less than the sample. The first
95680 ** integer in nLt contains the number of entries in the index where the
95681 ** left-most column is less than the left-most column of the sample.
95682 ** The K-th integer in the nLt entry is the number of index entries
95683 ** where the first K columns are less than the first K columns of the
95684 ** sample. The nDLt column is like nLt except that it contains the
95685 ** number of distinct entries in the index that are less than the
95686 ** sample.
95687 **
95688 ** There can be an arbitrary number of sqlite_stat4 entries per index.
95689 ** The ANALYZE command will typically generate sqlite_stat4 tables
95690 ** that contain between 10 and 40 samples which are distributed across
95691 ** the key space, though not uniformly, and which include samples with
95692 ** large nEq values.
95693 **
95694 ** Format for sqlite_stat3 redux:
95695 **
95696 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
95697 ** looks at the left-most column of the index. The sqlite_stat3.sample
95698 ** column contains the actual value of the left-most column instead
95699 ** of a blob encoding of the complete index key as is found in
95700 ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
95701 ** all contain just a single integer which is the same as the first
95702 ** integer in the equivalent columns in sqlite_stat4.
95703 */
95704 #ifndef SQLITE_OMIT_ANALYZE
95705 /* #include "sqliteInt.h" */
95706 
95707 #if defined(SQLITE_ENABLE_STAT4)
95708 # define IsStat4 1
95709 # define IsStat3 0
95710 #elif defined(SQLITE_ENABLE_STAT3)
95711 # define IsStat4 0
95712 # define IsStat3 1
95713 #else
95714 # define IsStat4 0
95715 # define IsStat3 0
95716 # undef SQLITE_STAT4_SAMPLES
95717 # define SQLITE_STAT4_SAMPLES 1
95718 #endif
95719 #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
95720 
95721 /*
95722 ** This routine generates code that opens the sqlite_statN tables.
95723 ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
95724 ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
95725 ** appropriate compile-time options are provided.
95726 **
95727 ** If the sqlite_statN tables do not previously exist, it is created.
95728 **
95729 ** Argument zWhere may be a pointer to a buffer containing a table name,
95730 ** or it may be a NULL pointer. If it is not NULL, then all entries in
95731 ** the sqlite_statN tables associated with the named table are deleted.
95732 ** If zWhere==0, then code is generated to delete all stat table entries.
95733 */
95734 static void openStatTable(
95735  Parse *pParse, /* Parsing context */
95736  int iDb, /* The database we are looking in */
95737  int iStatCur, /* Open the sqlite_stat1 table on this cursor */
95738  const char *zWhere, /* Delete entries for this table or index */
95739  const char *zWhereType /* Either "tbl" or "idx" */
95740 ){
95741  static const struct {
95742  const char *zName;
95743  const char *zCols;
95744  } aTable[] = {
95745  { "sqlite_stat1", "tbl,idx,stat" },
95746 #if defined(SQLITE_ENABLE_STAT4)
95747  { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
95748  { "sqlite_stat3", 0 },
95749 #elif defined(SQLITE_ENABLE_STAT3)
95750  { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
95751  { "sqlite_stat4", 0 },
95752 #else
95753  { "sqlite_stat3", 0 },
95754  { "sqlite_stat4", 0 },
95755 #endif
95756  };
95757  int i;
95758  sqlite3 *db = pParse->db;
95759  Db *pDb;
95760  Vdbe *v = sqlite3GetVdbe(pParse);
95761  int aRoot[ArraySize(aTable)];
95762  u8 aCreateTbl[ArraySize(aTable)];
95763 
95764  if( v==0 ) return;
95765  assert( sqlite3BtreeHoldsAllMutexes(db) );
95766  assert( sqlite3VdbeDb(v)==db );
95767  pDb = &db->aDb[iDb];
95768 
95769  /* Create new statistic tables if they do not exist, or clear them
95770  ** if they do already exist.
95771  */
95772  for(i=0; i<ArraySize(aTable); i++){
95773  const char *zTab = aTable[i].zName;
95774  Table *pStat;
95775  if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
95776  if( aTable[i].zCols ){
95777  /* The sqlite_statN table does not exist. Create it. Note that a
95778  ** side-effect of the CREATE TABLE statement is to leave the rootpage
95779  ** of the new table in register pParse->regRoot. This is important
95780  ** because the OpenWrite opcode below will be needing it. */
95781  sqlite3NestedParse(pParse,
95782  "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
95783  );
95784  aRoot[i] = pParse->regRoot;
95785  aCreateTbl[i] = OPFLAG_P2ISREG;
95786  }
95787  }else{
95788  /* The table already exists. If zWhere is not NULL, delete all entries
95789  ** associated with the table zWhere. If zWhere is NULL, delete the
95790  ** entire contents of the table. */
95791  aRoot[i] = pStat->tnum;
95792  aCreateTbl[i] = 0;
95793  sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
95794  if( zWhere ){
95795  sqlite3NestedParse(pParse,
95796  "DELETE FROM %Q.%s WHERE %s=%Q",
95797  pDb->zDbSName, zTab, zWhereType, zWhere
95798  );
95799  }else{
95800  /* The sqlite_stat[134] table already exists. Delete all rows. */
95801  sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
95802  }
95803  }
95804  }
95805 
95806  /* Open the sqlite_stat[134] tables for writing. */
95807  for(i=0; aTable[i].zCols; i++){
95808  assert( i<ArraySize(aTable) );
95809  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
95810  sqlite3VdbeChangeP5(v, aCreateTbl[i]);
95811  VdbeComment((v, aTable[i].zName));
95812  }
95813 }
95814 
95815 /*
95816 ** Recommended number of samples for sqlite_stat4
95817 */
95818 #ifndef SQLITE_STAT4_SAMPLES
95819 # define SQLITE_STAT4_SAMPLES 24
95820 #endif
95821 
95822 /*
95823 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
95824 ** share an instance of the following structure to hold their state
95825 ** information.
95826 */
95827 typedef struct Stat4Accum Stat4Accum;
95828 typedef struct Stat4Sample Stat4Sample;
95829 struct Stat4Sample {
95830  tRowcnt *anEq; /* sqlite_stat4.nEq */
95831  tRowcnt *anDLt; /* sqlite_stat4.nDLt */
95832 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95833  tRowcnt *anLt; /* sqlite_stat4.nLt */
95834  union {
95835  i64 iRowid; /* Rowid in main table of the key */
95836  u8 *aRowid; /* Key for WITHOUT ROWID tables */
95837  } u;
95838  u32 nRowid; /* Sizeof aRowid[] */
95839  u8 isPSample; /* True if a periodic sample */
95840  int iCol; /* If !isPSample, the reason for inclusion */
95841  u32 iHash; /* Tiebreaker hash */
95842 #endif
95843 };
95844 struct Stat4Accum {
95845  tRowcnt nRow; /* Number of rows in the entire table */
95846  tRowcnt nPSample; /* How often to do a periodic sample */
95847  int nCol; /* Number of columns in index + pk/rowid */
95848  int nKeyCol; /* Number of index columns w/o the pk/rowid */
95849  int mxSample; /* Maximum number of samples to accumulate */
95850  Stat4Sample current; /* Current row as a Stat4Sample */
95851  u32 iPrn; /* Pseudo-random number used for sampling */
95852  Stat4Sample *aBest; /* Array of nCol best samples */
95853  int iMin; /* Index in a[] of entry with minimum score */
95854  int nSample; /* Current number of samples */
95855  int iGet; /* Index of current sample accessed by stat_get() */
95856  Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
95857  sqlite3 *db; /* Database connection, for malloc() */
95858 };
95859 
95860 /* Reclaim memory used by a Stat4Sample
95861 */
95862 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95863 static void sampleClear(sqlite3 *db, Stat4Sample *p){
95864  assert( db!=0 );
95865  if( p->nRowid ){
95866  sqlite3DbFree(db, p->u.aRowid);
95867  p->nRowid = 0;
95868  }
95869 }
95870 #endif
95871 
95872 /* Initialize the BLOB value of a ROWID
95873 */
95874 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95875 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
95876  assert( db!=0 );
95877  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
95878  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
95879  if( p->u.aRowid ){
95880  p->nRowid = n;
95881  memcpy(p->u.aRowid, pData, n);
95882  }else{
95883  p->nRowid = 0;
95884  }
95885 }
95886 #endif
95887 
95888 /* Initialize the INTEGER value of a ROWID.
95889 */
95890 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95891 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
95892  assert( db!=0 );
95893  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
95894  p->nRowid = 0;
95895  p->u.iRowid = iRowid;
95896 }
95897 #endif
95898 
95899 
95900 /*
95901 ** Copy the contents of object (*pFrom) into (*pTo).
95902 */
95903 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95904 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
95905  pTo->isPSample = pFrom->isPSample;
95906  pTo->iCol = pFrom->iCol;
95907  pTo->iHash = pFrom->iHash;
95908  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
95909  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
95910  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
95911  if( pFrom->nRowid ){
95912  sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
95913  }else{
95914  sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
95915  }
95916 }
95917 #endif
95918 
95919 /*
95920 ** Reclaim all memory of a Stat4Accum structure.
95921 */
95922 static void stat4Destructor(void *pOld){
95923  Stat4Accum *p = (Stat4Accum*)pOld;
95924 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95925  int i;
95926  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
95927  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
95928  sampleClear(p->db, &p->current);
95929 #endif
95930  sqlite3DbFree(p->db, p);
95931 }
95932 
95933 /*
95934 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
95935 ** are:
95936 ** N: The number of columns in the index including the rowid/pk (note 1)
95937 ** K: The number of columns in the index excluding the rowid/pk.
95938 ** C: The number of rows in the index (note 2)
95939 **
95940 ** Note 1: In the special case of the covering index that implements a
95941 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
95942 ** total number of columns in the table.
95943 **
95944 ** Note 2: C is only used for STAT3 and STAT4.
95945 **
95946 ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
95947 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
95948 ** PRIMARY KEY of the table. The covering index that implements the
95949 ** original WITHOUT ROWID table as N==K as a special case.
95950 **
95951 ** This routine allocates the Stat4Accum object in heap memory. The return
95952 ** value is a pointer to the Stat4Accum object. The datatype of the
95953 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
95954 ** object.
95955 */
95956 static void statInit(
95957  sqlite3_context *context,
95958  int argc,
95959  sqlite3_value **argv
95960 ){
95961  Stat4Accum *p;
95962  int nCol; /* Number of columns in index being sampled */
95963  int nKeyCol; /* Number of key columns */
95964  int nColUp; /* nCol rounded up for alignment */
95965  int n; /* Bytes of space to allocate */
95966  sqlite3 *db; /* Database connection */
95967 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95968  int mxSample = SQLITE_STAT4_SAMPLES;
95969 #endif
95970 
95971  /* Decode the three function arguments */
95972  UNUSED_PARAMETER(argc);
95973  nCol = sqlite3_value_int(argv[0]);
95974  assert( nCol>0 );
95975  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
95976  nKeyCol = sqlite3_value_int(argv[1]);
95977  assert( nKeyCol<=nCol );
95978  assert( nKeyCol>0 );
95979 
95980  /* Allocate the space required for the Stat4Accum object */
95981  n = sizeof(*p)
95982  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
95983  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
95984 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95985  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
95986  + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
95987  + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
95988 #endif
95989  ;
95990  db = sqlite3_context_db_handle(context);
95991  p = sqlite3DbMallocZero(db, n);
95992  if( p==0 ){
95993  sqlite3_result_error_nomem(context);
95994  return;
95995  }
95996 
95997  p->db = db;
95998  p->nRow = 0;
95999  p->nCol = nCol;
96000  p->nKeyCol = nKeyCol;
96001  p->current.anDLt = (tRowcnt*)&p[1];
96002  p->current.anEq = &p->current.anDLt[nColUp];
96003 
96004 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96005  {
96006  u8 *pSpace; /* Allocated space not yet assigned */
96007  int i; /* Used to iterate through p->aSample[] */
96008 
96009  p->iGet = -1;
96010  p->mxSample = mxSample;
96011  p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
96012  p->current.anLt = &p->current.anEq[nColUp];
96013  p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
96014 
96015  /* Set up the Stat4Accum.a[] and aBest[] arrays */
96016  p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
96017  p->aBest = &p->a[mxSample];
96018  pSpace = (u8*)(&p->a[mxSample+nCol]);
96019  for(i=0; i<(mxSample+nCol); i++){
96020  p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
96021  p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
96022  p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
96023  }
96024  assert( (pSpace - (u8*)p)==n );
96025 
96026  for(i=0; i<nCol; i++){
96027  p->aBest[i].iCol = i;
96028  }
96029  }
96030 #endif
96031 
96032  /* Return a pointer to the allocated object to the caller. Note that
96033  ** only the pointer (the 2nd parameter) matters. The size of the object
96034  ** (given by the 3rd parameter) is never used and can be any positive
96035  ** value. */
96036  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
96037 }
96038 static const FuncDef statInitFuncdef = {
96039  2+IsStat34, /* nArg */
96040  SQLITE_UTF8, /* funcFlags */
96041  0, /* pUserData */
96042  0, /* pNext */
96043  statInit, /* xSFunc */
96044  0, /* xFinalize */
96045  "stat_init", /* zName */
96046  {0}
96047 };
96048 
96049 #ifdef SQLITE_ENABLE_STAT4
96050 /*
96051 ** pNew and pOld are both candidate non-periodic samples selected for
96052 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
96053 ** considering only any trailing columns and the sample hash value, this
96054 ** function returns true if sample pNew is to be preferred over pOld.
96055 ** In other words, if we assume that the cardinalities of the selected
96056 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
96057 **
96058 ** This function assumes that for each argument sample, the contents of
96059 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
96060 */
96061 static int sampleIsBetterPost(
96062  Stat4Accum *pAccum,
96063  Stat4Sample *pNew,
96064  Stat4Sample *pOld
96065 ){
96066  int nCol = pAccum->nCol;
96067  int i;
96068  assert( pNew->iCol==pOld->iCol );
96069  for(i=pNew->iCol+1; i<nCol; i++){
96070  if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
96071  if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
96072  }
96073  if( pNew->iHash>pOld->iHash ) return 1;
96074  return 0;
96075 }
96076 #endif
96077 
96078 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96079 /*
96080 ** Return true if pNew is to be preferred over pOld.
96081 **
96082 ** This function assumes that for each argument sample, the contents of
96083 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
96084 */
96085 static int sampleIsBetter(
96086  Stat4Accum *pAccum,
96087  Stat4Sample *pNew,
96088  Stat4Sample *pOld
96089 ){
96090  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
96091  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
96092 
96093  assert( pOld->isPSample==0 && pNew->isPSample==0 );
96094  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
96095 
96096  if( (nEqNew>nEqOld) ) return 1;
96097 #ifdef SQLITE_ENABLE_STAT4
96098  if( nEqNew==nEqOld ){
96099  if( pNew->iCol<pOld->iCol ) return 1;
96100  return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
96101  }
96102  return 0;
96103 #else
96104  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
96105 #endif
96106 }
96107 
96108 /*
96109 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
96110 ** remove the least desirable sample from p->a[] to make room.
96111 */
96112 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
96113  Stat4Sample *pSample = 0;
96114  int i;
96115 
96116  assert( IsStat4 || nEqZero==0 );
96117 
96118 #ifdef SQLITE_ENABLE_STAT4
96119  if( pNew->isPSample==0 ){
96120  Stat4Sample *pUpgrade = 0;
96121  assert( pNew->anEq[pNew->iCol]>0 );
96122 
96123  /* This sample is being added because the prefix that ends in column
96124  ** iCol occurs many times in the table. However, if we have already
96125  ** added a sample that shares this prefix, there is no need to add
96126  ** this one. Instead, upgrade the priority of the highest priority
96127  ** existing sample that shares this prefix. */
96128  for(i=p->nSample-1; i>=0; i--){
96129  Stat4Sample *pOld = &p->a[i];
96130  if( pOld->anEq[pNew->iCol]==0 ){
96131  if( pOld->isPSample ) return;
96132  assert( pOld->iCol>pNew->iCol );
96133  assert( sampleIsBetter(p, pNew, pOld) );
96134  if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
96135  pUpgrade = pOld;
96136  }
96137  }
96138  }
96139  if( pUpgrade ){
96140  pUpgrade->iCol = pNew->iCol;
96141  pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
96142  goto find_new_min;
96143  }
96144  }
96145 #endif
96146 
96147  /* If necessary, remove sample iMin to make room for the new sample. */
96148  if( p->nSample>=p->mxSample ){
96149  Stat4Sample *pMin = &p->a[p->iMin];
96150  tRowcnt *anEq = pMin->anEq;
96151  tRowcnt *anLt = pMin->anLt;
96152  tRowcnt *anDLt = pMin->anDLt;
96153  sampleClear(p->db, pMin);
96154  memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
96155  pSample = &p->a[p->nSample-1];
96156  pSample->nRowid = 0;
96157  pSample->anEq = anEq;
96158  pSample->anDLt = anDLt;
96159  pSample->anLt = anLt;
96160  p->nSample = p->mxSample-1;
96161  }
96162 
96163  /* The "rows less-than" for the rowid column must be greater than that
96164  ** for the last sample in the p->a[] array. Otherwise, the samples would
96165  ** be out of order. */
96166 #ifdef SQLITE_ENABLE_STAT4
96167  assert( p->nSample==0
96168  || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
96169 #endif
96170 
96171  /* Insert the new sample */
96172  pSample = &p->a[p->nSample];
96173  sampleCopy(p, pSample, pNew);
96174  p->nSample++;
96175 
96176  /* Zero the first nEqZero entries in the anEq[] array. */
96177  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
96178 
96179 #ifdef SQLITE_ENABLE_STAT4
96180  find_new_min:
96181 #endif
96182  if( p->nSample>=p->mxSample ){
96183  int iMin = -1;
96184  for(i=0; i<p->mxSample; i++){
96185  if( p->a[i].isPSample ) continue;
96186  if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
96187  iMin = i;
96188  }
96189  }
96190  assert( iMin>=0 );
96191  p->iMin = iMin;
96192  }
96193 }
96194 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96195 
96196 /*
96197 ** Field iChng of the index being scanned has changed. So at this point
96198 ** p->current contains a sample that reflects the previous row of the
96199 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
96200 ** correct at this point.
96201 */
96202 static void samplePushPrevious(Stat4Accum *p, int iChng){
96203 #ifdef SQLITE_ENABLE_STAT4
96204  int i;
96205 
96206  /* Check if any samples from the aBest[] array should be pushed
96207  ** into IndexSample.a[] at this point. */
96208  for(i=(p->nCol-2); i>=iChng; i--){
96209  Stat4Sample *pBest = &p->aBest[i];
96210  pBest->anEq[i] = p->current.anEq[i];
96211  if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
96212  sampleInsert(p, pBest, i);
96213  }
96214  }
96215 
96216  /* Update the anEq[] fields of any samples already collected. */
96217  for(i=p->nSample-1; i>=0; i--){
96218  int j;
96219  for(j=iChng; j<p->nCol; j++){
96220  if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
96221  }
96222  }
96223 #endif
96224 
96225 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
96226  if( iChng==0 ){
96227  tRowcnt nLt = p->current.anLt[0];
96228  tRowcnt nEq = p->current.anEq[0];
96229 
96230  /* Check if this is to be a periodic sample. If so, add it. */
96231  if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
96232  p->current.isPSample = 1;
96233  sampleInsert(p, &p->current, 0);
96234  p->current.isPSample = 0;
96235  }else
96236 
96237  /* Or if it is a non-periodic sample. Add it in this case too. */
96238  if( p->nSample<p->mxSample
96239  || sampleIsBetter(p, &p->current, &p->a[p->iMin])
96240  ){
96241  sampleInsert(p, &p->current, 0);
96242  }
96243  }
96244 #endif
96245 
96246 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
96247  UNUSED_PARAMETER( p );
96248  UNUSED_PARAMETER( iChng );
96249 #endif
96250 }
96251 
96252 /*
96253 ** Implementation of the stat_push SQL function: stat_push(P,C,R)
96254 ** Arguments:
96255 **
96256 ** P Pointer to the Stat4Accum object created by stat_init()
96257 ** C Index of left-most column to differ from previous row
96258 ** R Rowid for the current row. Might be a key record for
96259 ** WITHOUT ROWID tables.
96260 **
96261 ** This SQL function always returns NULL. It's purpose it to accumulate
96262 ** statistical data and/or samples in the Stat4Accum object about the
96263 ** index being analyzed. The stat_get() SQL function will later be used to
96264 ** extract relevant information for constructing the sqlite_statN tables.
96265 **
96266 ** The R parameter is only used for STAT3 and STAT4
96267 */
96268 static void statPush(
96269  sqlite3_context *context,
96270  int argc,
96271  sqlite3_value **argv
96272 ){
96273  int i;
96274 
96275  /* The three function arguments */
96276  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
96277  int iChng = sqlite3_value_int(argv[1]);
96278 
96279  UNUSED_PARAMETER( argc );
96280  UNUSED_PARAMETER( context );
96281  assert( p->nCol>0 );
96282  assert( iChng<p->nCol );
96283 
96284  if( p->nRow==0 ){
96285  /* This is the first call to this function. Do initialization. */
96286  for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
96287  }else{
96288  /* Second and subsequent calls get processed here */
96289  samplePushPrevious(p, iChng);
96290 
96291  /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
96292  ** to the current row of the index. */
96293  for(i=0; i<iChng; i++){
96294  p->current.anEq[i]++;
96295  }
96296  for(i=iChng; i<p->nCol; i++){
96297  p->current.anDLt[i]++;
96298 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96299  p->current.anLt[i] += p->current.anEq[i];
96300 #endif
96301  p->current.anEq[i] = 1;
96302  }
96303  }
96304  p->nRow++;
96305 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96306  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
96307  sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
96308  }else{
96309  sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
96310  sqlite3_value_blob(argv[2]));
96311  }
96312  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
96313 #endif
96314 
96315 #ifdef SQLITE_ENABLE_STAT4
96316  {
96317  tRowcnt nLt = p->current.anLt[p->nCol-1];
96318 
96319  /* Check if this is to be a periodic sample. If so, add it. */
96320  if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
96321  p->current.isPSample = 1;
96322  p->current.iCol = 0;
96323  sampleInsert(p, &p->current, p->nCol-1);
96324  p->current.isPSample = 0;
96325  }
96326 
96327  /* Update the aBest[] array. */
96328  for(i=0; i<(p->nCol-1); i++){
96329  p->current.iCol = i;
96330  if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
96331  sampleCopy(p, &p->aBest[i], &p->current);
96332  }
96333  }
96334  }
96335 #endif
96336 }
96337 static const FuncDef statPushFuncdef = {
96338  2+IsStat34, /* nArg */
96339  SQLITE_UTF8, /* funcFlags */
96340  0, /* pUserData */
96341  0, /* pNext */
96342  statPush, /* xSFunc */
96343  0, /* xFinalize */
96344  "stat_push", /* zName */
96345  {0}
96346 };
96347 
96348 #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
96349 #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
96350 #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
96351 #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
96352 #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
96353 
96354 /*
96355 ** Implementation of the stat_get(P,J) SQL function. This routine is
96356 ** used to query statistical information that has been gathered into
96357 ** the Stat4Accum object by prior calls to stat_push(). The P parameter
96358 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
96359 ** The content to returned is determined by the parameter J
96360 ** which is one of the STAT_GET_xxxx values defined above.
96361 **
96362 ** If neither STAT3 nor STAT4 are enabled, then J is always
96363 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
96364 ** a one-parameter function, stat_get(P), that always returns the
96365 ** stat1 table entry information.
96366 */
96367 static void statGet(
96368  sqlite3_context *context,
96369  int argc,
96370  sqlite3_value **argv
96371 ){
96372  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
96373 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96374  /* STAT3 and STAT4 have a parameter on this routine. */
96375  int eCall = sqlite3_value_int(argv[1]);
96376  assert( argc==2 );
96377  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
96378  || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
96379  || eCall==STAT_GET_NDLT
96380  );
96381  if( eCall==STAT_GET_STAT1 )
96382 #else
96383  assert( argc==1 );
96384 #endif
96385  {
96386  /* Return the value to store in the "stat" column of the sqlite_stat1
96387  ** table for this index.
96388  **
96389  ** The value is a string composed of a list of integers describing
96390  ** the index. The first integer in the list is the total number of
96391  ** entries in the index. There is one additional integer in the list
96392  ** for each indexed column. This additional integer is an estimate of
96393  ** the number of rows matched by a stabbing query on the index using
96394  ** a key with the corresponding number of fields. In other words,
96395  ** if the index is on columns (a,b) and the sqlite_stat1 value is
96396  ** "100 10 2", then SQLite estimates that:
96397  **
96398  ** * the index contains 100 rows,
96399  ** * "WHERE a=?" matches 10 rows, and
96400  ** * "WHERE a=? AND b=?" matches 2 rows.
96401  **
96402  ** If D is the count of distinct values and K is the total number of
96403  ** rows, then each estimate is computed as:
96404  **
96405  ** I = (K+D-1)/D
96406  */
96407  char *z;
96408  int i;
96409 
96410  char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
96411  if( zRet==0 ){
96412  sqlite3_result_error_nomem(context);
96413  return;
96414  }
96415 
96416  sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
96417  z = zRet + sqlite3Strlen30(zRet);
96418  for(i=0; i<p->nKeyCol; i++){
96419  u64 nDistinct = p->current.anDLt[i] + 1;
96420  u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
96421  sqlite3_snprintf(24, z, " %llu", iVal);
96422  z += sqlite3Strlen30(z);
96423  assert( p->current.anEq[i] );
96424  }
96425  assert( z[0]=='\0' && z>zRet );
96426 
96427  sqlite3_result_text(context, zRet, -1, sqlite3_free);
96428  }
96429 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96430  else if( eCall==STAT_GET_ROWID ){
96431  if( p->iGet<0 ){
96432  samplePushPrevious(p, 0);
96433  p->iGet = 0;
96434  }
96435  if( p->iGet<p->nSample ){
96436  Stat4Sample *pS = p->a + p->iGet;
96437  if( pS->nRowid==0 ){
96438  sqlite3_result_int64(context, pS->u.iRowid);
96439  }else{
96440  sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
96442  }
96443  }
96444  }else{
96445  tRowcnt *aCnt = 0;
96446 
96447  assert( p->iGet<p->nSample );
96448  switch( eCall ){
96449  case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
96450  case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
96451  default: {
96452  aCnt = p->a[p->iGet].anDLt;
96453  p->iGet++;
96454  break;
96455  }
96456  }
96457 
96458  if( IsStat3 ){
96459  sqlite3_result_int64(context, (i64)aCnt[0]);
96460  }else{
96461  char *zRet = sqlite3MallocZero(p->nCol * 25);
96462  if( zRet==0 ){
96463  sqlite3_result_error_nomem(context);
96464  }else{
96465  int i;
96466  char *z = zRet;
96467  for(i=0; i<p->nCol; i++){
96468  sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
96469  z += sqlite3Strlen30(z);
96470  }
96471  assert( z[0]=='\0' && z>zRet );
96472  z[-1] = '\0';
96473  sqlite3_result_text(context, zRet, -1, sqlite3_free);
96474  }
96475  }
96476  }
96477 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96478 #ifndef SQLITE_DEBUG
96479  UNUSED_PARAMETER( argc );
96480 #endif
96481 }
96482 static const FuncDef statGetFuncdef = {
96483  1+IsStat34, /* nArg */
96484  SQLITE_UTF8, /* funcFlags */
96485  0, /* pUserData */
96486  0, /* pNext */
96487  statGet, /* xSFunc */
96488  0, /* xFinalize */
96489  "stat_get", /* zName */
96490  {0}
96491 };
96492 
96493 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
96494  assert( regOut!=regStat4 && regOut!=regStat4+1 );
96495 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96496  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
96497 #elif SQLITE_DEBUG
96498  assert( iParam==STAT_GET_STAT1 );
96499 #else
96500  UNUSED_PARAMETER( iParam );
96501 #endif
96502  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
96503  (char*)&statGetFuncdef, P4_FUNCDEF);
96504  sqlite3VdbeChangeP5(v, 1 + IsStat34);
96505 }
96506 
96507 /*
96508 ** Generate code to do an analysis of all indices associated with
96509 ** a single table.
96510 */
96511 static void analyzeOneTable(
96512  Parse *pParse, /* Parser context */
96513  Table *pTab, /* Table whose indices are to be analyzed */
96514  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
96515  int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
96516  int iMem, /* Available memory locations begin here */
96517  int iTab /* Next available cursor */
96518 ){
96519  sqlite3 *db = pParse->db; /* Database handle */
96520  Index *pIdx; /* An index to being analyzed */
96521  int iIdxCur; /* Cursor open on index being analyzed */
96522  int iTabCur; /* Table cursor */
96523  Vdbe *v; /* The virtual machine being built up */
96524  int i; /* Loop counter */
96525  int jZeroRows = -1; /* Jump from here if number of rows is zero */
96526  int iDb; /* Index of database containing pTab */
96527  u8 needTableCnt = 1; /* True to count the table */
96528  int regNewRowid = iMem++; /* Rowid for the inserted record */
96529  int regStat4 = iMem++; /* Register to hold Stat4Accum object */
96530  int regChng = iMem++; /* Index of changed index field */
96531 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96532  int regRowid = iMem++; /* Rowid argument passed to stat_push() */
96533 #endif
96534  int regTemp = iMem++; /* Temporary use register */
96535  int regTabname = iMem++; /* Register containing table name */
96536  int regIdxname = iMem++; /* Register containing index name */
96537  int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
96538  int regPrev = iMem; /* MUST BE LAST (see below) */
96539 
96540  pParse->nMem = MAX(pParse->nMem, iMem);
96541  v = sqlite3GetVdbe(pParse);
96542  if( v==0 || NEVER(pTab==0) ){
96543  return;
96544  }
96545  if( pTab->tnum==0 ){
96546  /* Do not gather statistics on views or virtual tables */
96547  return;
96548  }
96549  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
96550  /* Do not gather statistics on system tables */
96551  return;
96552  }
96553  assert( sqlite3BtreeHoldsAllMutexes(db) );
96554  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
96555  assert( iDb>=0 );
96556  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96557 #ifndef SQLITE_OMIT_AUTHORIZATION
96558  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
96559  db->aDb[iDb].zDbSName ) ){
96560  return;
96561  }
96562 #endif
96563 
96564  /* Establish a read-lock on the table at the shared-cache level.
96565  ** Open a read-only cursor on the table. Also allocate a cursor number
96566  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
96567  ** this time though. */
96568  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
96569  iTabCur = iTab++;
96570  iIdxCur = iTab++;
96571  pParse->nTab = MAX(pParse->nTab, iTab);
96572  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
96573  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
96574 
96575  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96576  int nCol; /* Number of columns in pIdx. "N" */
96577  int addrRewind; /* Address of "OP_Rewind iIdxCur" */
96578  int addrNextRow; /* Address of "next_row:" */
96579  const char *zIdxName; /* Name of the index */
96580  int nColTest; /* Number of columns to test for changes */
96581 
96582  if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
96583  if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
96584  if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
96585  nCol = pIdx->nKeyCol;
96586  zIdxName = pTab->zName;
96587  nColTest = nCol - 1;
96588  }else{
96589  nCol = pIdx->nColumn;
96590  zIdxName = pIdx->zName;
96591  nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
96592  }
96593 
96594  /* Populate the register containing the index name. */
96595  sqlite3VdbeLoadString(v, regIdxname, zIdxName);
96596  VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
96597 
96598  /*
96599  ** Pseudo-code for loop that calls stat_push():
96600  **
96601  ** Rewind csr
96602  ** if eof(csr) goto end_of_scan;
96603  ** regChng = 0
96604  ** goto chng_addr_0;
96605  **
96606  ** next_row:
96607  ** regChng = 0
96608  ** if( idx(0) != regPrev(0) ) goto chng_addr_0
96609  ** regChng = 1
96610  ** if( idx(1) != regPrev(1) ) goto chng_addr_1
96611  ** ...
96612  ** regChng = N
96613  ** goto chng_addr_N
96614  **
96615  ** chng_addr_0:
96616  ** regPrev(0) = idx(0)
96617  ** chng_addr_1:
96618  ** regPrev(1) = idx(1)
96619  ** ...
96620  **
96621  ** endDistinctTest:
96622  ** regRowid = idx(rowid)
96623  ** stat_push(P, regChng, regRowid)
96624  ** Next csr
96625  ** if !eof(csr) goto next_row;
96626  **
96627  ** end_of_scan:
96628  */
96629 
96630  /* Make sure there are enough memory cells allocated to accommodate
96631  ** the regPrev array and a trailing rowid (the rowid slot is required
96632  ** when building a record to insert into the sample column of
96633  ** the sqlite_stat4 table. */
96634  pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
96635 
96636  /* Open a read-only cursor on the index being analyzed. */
96637  assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
96638  sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
96639  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
96640  VdbeComment((v, "%s", pIdx->zName));
96641 
96642  /* Invoke the stat_init() function. The arguments are:
96643  **
96644  ** (1) the number of columns in the index including the rowid
96645  ** (or for a WITHOUT ROWID table, the number of PK columns),
96646  ** (2) the number of columns in the key without the rowid/pk
96647  ** (3) the number of rows in the index,
96648  **
96649  **
96650  ** The third argument is only used for STAT3 and STAT4
96651  */
96652 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96653  sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
96654 #endif
96655  sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
96656  sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
96657  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
96658  (char*)&statInitFuncdef, P4_FUNCDEF);
96660 
96661  /* Implementation of the following:
96662  **
96663  ** Rewind csr
96664  ** if eof(csr) goto end_of_scan;
96665  ** regChng = 0
96666  ** goto next_push_0;
96667  **
96668  */
96669  addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
96670  VdbeCoverage(v);
96671  sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
96672  addrNextRow = sqlite3VdbeCurrentAddr(v);
96673 
96674  if( nColTest>0 ){
96675  int endDistinctTest = sqlite3VdbeMakeLabel(v);
96676  int *aGotoChng; /* Array of jump instruction addresses */
96677  aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
96678  if( aGotoChng==0 ) continue;
96679 
96680  /*
96681  ** next_row:
96682  ** regChng = 0
96683  ** if( idx(0) != regPrev(0) ) goto chng_addr_0
96684  ** regChng = 1
96685  ** if( idx(1) != regPrev(1) ) goto chng_addr_1
96686  ** ...
96687  ** regChng = N
96688  ** goto endDistinctTest
96689  */
96691  addrNextRow = sqlite3VdbeCurrentAddr(v);
96692  if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
96693  /* For a single-column UNIQUE index, once we have found a non-NULL
96694  ** row, we know that all the rest will be distinct, so skip
96695  ** subsequent distinctness tests. */
96696  sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
96697  VdbeCoverage(v);
96698  }
96699  for(i=0; i<nColTest; i++){
96700  char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
96701  sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
96702  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
96703  aGotoChng[i] =
96704  sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
96706  VdbeCoverage(v);
96707  }
96708  sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
96709  sqlite3VdbeGoto(v, endDistinctTest);
96710 
96711 
96712  /*
96713  ** chng_addr_0:
96714  ** regPrev(0) = idx(0)
96715  ** chng_addr_1:
96716  ** regPrev(1) = idx(1)
96717  ** ...
96718  */
96719  sqlite3VdbeJumpHere(v, addrNextRow-1);
96720  for(i=0; i<nColTest; i++){
96721  sqlite3VdbeJumpHere(v, aGotoChng[i]);
96722  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
96723  }
96724  sqlite3VdbeResolveLabel(v, endDistinctTest);
96725  sqlite3DbFree(db, aGotoChng);
96726  }
96727 
96728  /*
96729  ** chng_addr_N:
96730  ** regRowid = idx(rowid) // STAT34 only
96731  ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
96732  ** Next csr
96733  ** if !eof(csr) goto next_row;
96734  */
96735 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96736  assert( regRowid==(regStat4+2) );
96737  if( HasRowid(pTab) ){
96738  sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
96739  }else{
96740  Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
96741  int j, k, regKey;
96742  regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
96743  for(j=0; j<pPk->nKeyCol; j++){
96744  k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
96745  assert( k>=0 && k<pTab->nCol );
96746  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
96747  VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
96748  }
96749  sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
96750  sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
96751  }
96752 #endif
96753  assert( regChng==(regStat4+1) );
96754  sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
96755  (char*)&statPushFuncdef, P4_FUNCDEF);
96757  sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
96758 
96759  /* Add the entry to the stat1 table. */
96760  callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
96761  assert( "BBB"[0]==SQLITE_AFF_TEXT );
96762  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
96763  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
96764  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
96766 
96767  /* Add the entries to the stat3 or stat4 table. */
96768 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96769  {
96770  int regEq = regStat1;
96771  int regLt = regStat1+1;
96772  int regDLt = regStat1+2;
96773  int regSample = regStat1+3;
96774  int regCol = regStat1+4;
96775  int regSampleRowid = regCol + nCol;
96776  int addrNext;
96777  int addrIsNull;
96778  u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
96779 
96780  pParse->nMem = MAX(pParse->nMem, regCol+nCol);
96781 
96782  addrNext = sqlite3VdbeCurrentAddr(v);
96783  callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
96784  addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
96785  VdbeCoverage(v);
96786  callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
96787  callStatGet(v, regStat4, STAT_GET_NLT, regLt);
96788  callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
96789  sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
96790  /* We know that the regSampleRowid row exists because it was read by
96791  ** the previous loop. Thus the not-found jump of seekOp will never
96792  ** be taken */
96794 #ifdef SQLITE_ENABLE_STAT3
96795  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
96796 #else
96797  for(i=0; i<nCol; i++){
96798  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
96799  }
96800  sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
96801 #endif
96802  sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
96803  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
96804  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
96805  sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
96806  sqlite3VdbeJumpHere(v, addrIsNull);
96807  }
96808 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96809 
96810  /* End of analysis */
96811  sqlite3VdbeJumpHere(v, addrRewind);
96812  }
96813 
96814 
96815  /* Create a single sqlite_stat1 entry containing NULL as the index
96816  ** name and the row count as the content.
96817  */
96818  if( pOnlyIdx==0 && needTableCnt ){
96819  VdbeComment((v, "%s", pTab->zName));
96820  sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
96821  jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
96822  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
96823  assert( "BBB"[0]==SQLITE_AFF_TEXT );
96824  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
96825  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
96826  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
96828  sqlite3VdbeJumpHere(v, jZeroRows);
96829  }
96830 }
96831 
96832 
96833 /*
96834 ** Generate code that will cause the most recent index analysis to
96835 ** be loaded into internal hash tables where is can be used.
96836 */
96837 static void loadAnalysis(Parse *pParse, int iDb){
96838  Vdbe *v = sqlite3GetVdbe(pParse);
96839  if( v ){
96841  }
96842 }
96843 
96844 /*
96845 ** Generate code that will do an analysis of an entire database
96846 */
96847 static void analyzeDatabase(Parse *pParse, int iDb){
96848  sqlite3 *db = pParse->db;
96849  Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
96850  HashElem *k;
96851  int iStatCur;
96852  int iMem;
96853  int iTab;
96854 
96855  sqlite3BeginWriteOperation(pParse, 0, iDb);
96856  iStatCur = pParse->nTab;
96857  pParse->nTab += 3;
96858  openStatTable(pParse, iDb, iStatCur, 0, 0);
96859  iMem = pParse->nMem+1;
96860  iTab = pParse->nTab;
96861  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96862  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
96863  Table *pTab = (Table*)sqliteHashData(k);
96864  analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
96865  }
96866  loadAnalysis(pParse, iDb);
96867 }
96868 
96869 /*
96870 ** Generate code that will do an analysis of a single table in
96871 ** a database. If pOnlyIdx is not NULL then it is a single index
96872 ** in pTab that should be analyzed.
96873 */
96874 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
96875  int iDb;
96876  int iStatCur;
96877 
96878  assert( pTab!=0 );
96879  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96880  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96881  sqlite3BeginWriteOperation(pParse, 0, iDb);
96882  iStatCur = pParse->nTab;
96883  pParse->nTab += 3;
96884  if( pOnlyIdx ){
96885  openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
96886  }else{
96887  openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
96888  }
96889  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
96890  loadAnalysis(pParse, iDb);
96891 }
96892 
96893 /*
96894 ** Generate code for the ANALYZE command. The parser calls this routine
96895 ** when it recognizes an ANALYZE command.
96896 **
96897 ** ANALYZE -- 1
96898 ** ANALYZE <database> -- 2
96899 ** ANALYZE ?<database>.?<tablename> -- 3
96900 **
96901 ** Form 1 causes all indices in all attached databases to be analyzed.
96902 ** Form 2 analyzes all indices the single database named.
96903 ** Form 3 analyzes all indices associated with the named table.
96904 */
96905 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
96906  sqlite3 *db = pParse->db;
96907  int iDb;
96908  int i;
96909  char *z, *zDb;
96910  Table *pTab;
96911  Index *pIdx;
96912  Token *pTableName;
96913  Vdbe *v;
96914 
96915  /* Read the database schema. If an error occurs, leave an error message
96916  ** and code in pParse and return NULL. */
96917  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96918  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
96919  return;
96920  }
96921 
96922  assert( pName2!=0 || pName1==0 );
96923  if( pName1==0 ){
96924  /* Form 1: Analyze everything */
96925  for(i=0; i<db->nDb; i++){
96926  if( i==1 ) continue; /* Do not analyze the TEMP database */
96927  analyzeDatabase(pParse, i);
96928  }
96929  }else if( pName2->n==0 ){
96930  /* Form 2: Analyze the database or table named */
96931  iDb = sqlite3FindDb(db, pName1);
96932  if( iDb>=0 ){
96933  analyzeDatabase(pParse, iDb);
96934  }else{
96935  z = sqlite3NameFromToken(db, pName1);
96936  if( z ){
96937  if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
96938  analyzeTable(pParse, pIdx->pTable, pIdx);
96939  }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
96940  analyzeTable(pParse, pTab, 0);
96941  }
96942  sqlite3DbFree(db, z);
96943  }
96944  }
96945  }else{
96946  /* Form 3: Analyze the fully qualified table name */
96947  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
96948  if( iDb>=0 ){
96949  zDb = db->aDb[iDb].zDbSName;
96950  z = sqlite3NameFromToken(db, pTableName);
96951  if( z ){
96952  if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
96953  analyzeTable(pParse, pIdx->pTable, pIdx);
96954  }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
96955  analyzeTable(pParse, pTab, 0);
96956  }
96957  sqlite3DbFree(db, z);
96958  }
96959  }
96960  }
96961  v = sqlite3GetVdbe(pParse);
96962  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
96963 }
96964 
96965 /*
96966 ** Used to pass information from the analyzer reader through to the
96967 ** callback routine.
96968 */
96972  const char *zDatabase;
96973 };
96974 
96975 /*
96976 ** The first argument points to a nul-terminated string containing a
96977 ** list of space separated integers. Read the first nOut of these into
96978 ** the array aOut[].
96979 */
96980 static void decodeIntArray(
96981  char *zIntArray, /* String containing int array to decode */
96982  int nOut, /* Number of slots in aOut[] */
96983  tRowcnt *aOut, /* Store integers here */
96984  LogEst *aLog, /* Or, if aOut==0, here */
96985  Index *pIndex /* Handle extra flags for this index, if not NULL */
96986 ){
96987  char *z = zIntArray;
96988  int c;
96989  int i;
96990  tRowcnt v;
96991 
96992 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96993  if( z==0 ) z = "";
96994 #else
96995  assert( z!=0 );
96996 #endif
96997  for(i=0; *z && i<nOut; i++){
96998  v = 0;
96999  while( (c=z[0])>='0' && c<='9' ){
97000  v = v*10 + c - '0';
97001  z++;
97002  }
97003 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97004  if( aOut ) aOut[i] = v;
97005  if( aLog ) aLog[i] = sqlite3LogEst(v);
97006 #else
97007  assert( aOut==0 );
97008  UNUSED_PARAMETER(aOut);
97009  assert( aLog!=0 );
97010  aLog[i] = sqlite3LogEst(v);
97011 #endif
97012  if( *z==' ' ) z++;
97013  }
97014 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
97015  assert( pIndex!=0 ); {
97016 #else
97017  if( pIndex ){
97018 #endif
97019  pIndex->bUnordered = 0;
97020  pIndex->noSkipScan = 0;
97021  while( z[0] ){
97022  if( sqlite3_strglob("unordered*", z)==0 ){
97023  pIndex->bUnordered = 1;
97024  }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
97025  pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
97026  }else if( sqlite3_strglob("noskipscan*", z)==0 ){
97027  pIndex->noSkipScan = 1;
97028  }
97029 #ifdef SQLITE_ENABLE_COSTMULT
97030  else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
97031  pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
97032  }
97033 #endif
97034  while( z[0]!=0 && z[0]!=' ' ) z++;
97035  while( z[0]==' ' ) z++;
97036  }
97037  }
97038 }
97039 
97040 /*
97041 ** This callback is invoked once for each index when reading the
97042 ** sqlite_stat1 table.
97043 **
97044 ** argv[0] = name of the table
97045 ** argv[1] = name of the index (might be NULL)
97046 ** argv[2] = results of analysis - on integer for each column
97047 **
97048 ** Entries for which argv[1]==NULL simply record the number of rows in
97049 ** the table.
97050 */
97051 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
97052  analysisInfo *pInfo = (analysisInfo*)pData;
97053  Index *pIndex;
97054  Table *pTable;
97055  const char *z;
97056 
97057  assert( argc==3 );
97058  UNUSED_PARAMETER2(NotUsed, argc);
97059 
97060  if( argv==0 || argv[0]==0 || argv[2]==0 ){
97061  return 0;
97062  }
97063  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
97064  if( pTable==0 ){
97065  return 0;
97066  }
97067  if( argv[1]==0 ){
97068  pIndex = 0;
97069  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
97070  pIndex = sqlite3PrimaryKeyIndex(pTable);
97071  }else{
97072  pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
97073  }
97074  z = argv[2];
97075 
97076  if( pIndex ){
97077  tRowcnt *aiRowEst = 0;
97078  int nCol = pIndex->nKeyCol+1;
97079 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97080  /* Index.aiRowEst may already be set here if there are duplicate
97081  ** sqlite_stat1 entries for this index. In that case just clobber
97082  ** the old data with the new instead of allocating a new array. */
97083  if( pIndex->aiRowEst==0 ){
97084  pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
97085  if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
97086  }
97087  aiRowEst = pIndex->aiRowEst;
97088 #endif
97089  pIndex->bUnordered = 0;
97090  decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
97091  if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
97092  }else{
97093  Index fakeIdx;
97094  fakeIdx.szIdxRow = pTable->szTabRow;
97095 #ifdef SQLITE_ENABLE_COSTMULT
97096  fakeIdx.pTable = pTable;
97097 #endif
97098  decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
97099  pTable->szTabRow = fakeIdx.szIdxRow;
97100  }
97101 
97102  return 0;
97103 }
97104 
97105 /*
97106 ** If the Index.aSample variable is not NULL, delete the aSample[] array
97107 ** and its contents.
97108 */
97110 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97111  if( pIdx->aSample ){
97112  int j;
97113  for(j=0; j<pIdx->nSample; j++){
97114  IndexSample *p = &pIdx->aSample[j];
97115  sqlite3DbFree(db, p->p);
97116  }
97117  sqlite3DbFree(db, pIdx->aSample);
97118  }
97119  if( db && db->pnBytesFreed==0 ){
97120  pIdx->nSample = 0;
97121  pIdx->aSample = 0;
97122  }
97123 #else
97124  UNUSED_PARAMETER(db);
97125  UNUSED_PARAMETER(pIdx);
97126 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
97127 }
97128 
97129 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97130 /*
97131 ** Populate the pIdx->aAvgEq[] array based on the samples currently
97132 ** stored in pIdx->aSample[].
97133 */
97134 static void initAvgEq(Index *pIdx){
97135  if( pIdx ){
97136  IndexSample *aSample = pIdx->aSample;
97137  IndexSample *pFinal = &aSample[pIdx->nSample-1];
97138  int iCol;
97139  int nCol = 1;
97140  if( pIdx->nSampleCol>1 ){
97141  /* If this is stat4 data, then calculate aAvgEq[] values for all
97142  ** sample columns except the last. The last is always set to 1, as
97143  ** once the trailing PK fields are considered all index keys are
97144  ** unique. */
97145  nCol = pIdx->nSampleCol-1;
97146  pIdx->aAvgEq[nCol] = 1;
97147  }
97148  for(iCol=0; iCol<nCol; iCol++){
97149  int nSample = pIdx->nSample;
97150  int i; /* Used to iterate through samples */
97151  tRowcnt sumEq = 0; /* Sum of the nEq values */
97152  tRowcnt avgEq = 0;
97153  tRowcnt nRow; /* Number of rows in index */
97154  i64 nSum100 = 0; /* Number of terms contributing to sumEq */
97155  i64 nDist100; /* Number of distinct values in index */
97156 
97157  if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
97158  nRow = pFinal->anLt[iCol];
97159  nDist100 = (i64)100 * pFinal->anDLt[iCol];
97160  nSample--;
97161  }else{
97162  nRow = pIdx->aiRowEst[0];
97163  nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
97164  }
97165  pIdx->nRowEst0 = nRow;
97166 
97167  /* Set nSum to the number of distinct (iCol+1) field prefixes that
97168  ** occur in the stat4 table for this index. Set sumEq to the sum of
97169  ** the nEq values for column iCol for the same set (adding the value
97170  ** only once where there exist duplicate prefixes). */
97171  for(i=0; i<nSample; i++){
97172  if( i==(pIdx->nSample-1)
97173  || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
97174  ){
97175  sumEq += aSample[i].anEq[iCol];
97176  nSum100 += 100;
97177  }
97178  }
97179 
97180  if( nDist100>nSum100 ){
97181  avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
97182  }
97183  if( avgEq==0 ) avgEq = 1;
97184  pIdx->aAvgEq[iCol] = avgEq;
97185  }
97186  }
97187 }
97188 
97189 /*
97190 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
97191 ** is supplied instead, find the PRIMARY KEY index for that table.
97192 */
97193 static Index *findIndexOrPrimaryKey(
97194  sqlite3 *db,
97195  const char *zName,
97196  const char *zDb
97197 ){
97198  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
97199  if( pIdx==0 ){
97200  Table *pTab = sqlite3FindTable(db, zName, zDb);
97201  if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
97202  }
97203  return pIdx;
97204 }
97205 
97206 /*
97207 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
97208 ** into the relevant Index.aSample[] arrays.
97209 **
97210 ** Arguments zSql1 and zSql2 must point to SQL statements that return
97211 ** data equivalent to the following (statements are different for stat3,
97212 ** see the caller of this function for details):
97213 **
97214 ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
97215 ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
97216 **
97217 ** where %Q is replaced with the database name before the SQL is executed.
97218 */
97219 static int loadStatTbl(
97220  sqlite3 *db, /* Database handle */
97221  int bStat3, /* Assume single column records only */
97222  const char *zSql1, /* SQL statement 1 (see above) */
97223  const char *zSql2, /* SQL statement 2 (see above) */
97224  const char *zDb /* Database name (e.g. "main") */
97225 ){
97226  int rc; /* Result codes from subroutines */
97227  sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
97228  char *zSql; /* Text of the SQL statement */
97229  Index *pPrevIdx = 0; /* Previous index in the loop */
97230  IndexSample *pSample; /* A slot in pIdx->aSample[] */
97231 
97232  assert( db->lookaside.bDisable );
97233  zSql = sqlite3MPrintf(db, zSql1, zDb);
97234  if( !zSql ){
97235  return SQLITE_NOMEM_BKPT;
97236  }
97237  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
97238  sqlite3DbFree(db, zSql);
97239  if( rc ) return rc;
97240 
97241  while( sqlite3_step(pStmt)==SQLITE_ROW ){
97242  int nIdxCol = 1; /* Number of columns in stat4 records */
97243 
97244  char *zIndex; /* Index name */
97245  Index *pIdx; /* Pointer to the index object */
97246  int nSample; /* Number of samples */
97247  int nByte; /* Bytes of space required */
97248  int i; /* Bytes of space required */
97249  tRowcnt *pSpace;
97250 
97251  zIndex = (char *)sqlite3_column_text(pStmt, 0);
97252  if( zIndex==0 ) continue;
97253  nSample = sqlite3_column_int(pStmt, 1);
97254  pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
97255  assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
97256  /* Index.nSample is non-zero at this point if data has already been
97257  ** loaded from the stat4 table. In this case ignore stat3 data. */
97258  if( pIdx==0 || pIdx->nSample ) continue;
97259  if( bStat3==0 ){
97260  assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
97261  if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
97262  nIdxCol = pIdx->nKeyCol;
97263  }else{
97264  nIdxCol = pIdx->nColumn;
97265  }
97266  }
97267  pIdx->nSampleCol = nIdxCol;
97268  nByte = sizeof(IndexSample) * nSample;
97269  nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
97270  nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
97271 
97272  pIdx->aSample = sqlite3DbMallocZero(db, nByte);
97273  if( pIdx->aSample==0 ){
97274  sqlite3_finalize(pStmt);
97275  return SQLITE_NOMEM_BKPT;
97276  }
97277  pSpace = (tRowcnt*)&pIdx->aSample[nSample];
97278  pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
97279  for(i=0; i<nSample; i++){
97280  pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
97281  pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
97282  pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
97283  }
97284  assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
97285  }
97286  rc = sqlite3_finalize(pStmt);
97287  if( rc ) return rc;
97288 
97289  zSql = sqlite3MPrintf(db, zSql2, zDb);
97290  if( !zSql ){
97291  return SQLITE_NOMEM_BKPT;
97292  }
97293  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
97294  sqlite3DbFree(db, zSql);
97295  if( rc ) return rc;
97296 
97297  while( sqlite3_step(pStmt)==SQLITE_ROW ){
97298  char *zIndex; /* Index name */
97299  Index *pIdx; /* Pointer to the index object */
97300  int nCol = 1; /* Number of columns in index */
97301 
97302  zIndex = (char *)sqlite3_column_text(pStmt, 0);
97303  if( zIndex==0 ) continue;
97304  pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
97305  if( pIdx==0 ) continue;
97306  /* This next condition is true if data has already been loaded from
97307  ** the sqlite_stat4 table. In this case ignore stat3 data. */
97308  nCol = pIdx->nSampleCol;
97309  if( bStat3 && nCol>1 ) continue;
97310  if( pIdx!=pPrevIdx ){
97311  initAvgEq(pPrevIdx);
97312  pPrevIdx = pIdx;
97313  }
97314  pSample = &pIdx->aSample[pIdx->nSample];
97315  decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
97316  decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
97317  decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
97318 
97319  /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
97320  ** This is in case the sample record is corrupted. In that case, the
97321  ** sqlite3VdbeRecordCompare() may read up to two varints past the
97322  ** end of the allocated buffer before it realizes it is dealing with
97323  ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
97324  ** a buffer overread. */
97325  pSample->n = sqlite3_column_bytes(pStmt, 4);
97326  pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
97327  if( pSample->p==0 ){
97328  sqlite3_finalize(pStmt);
97329  return SQLITE_NOMEM_BKPT;
97330  }
97331  memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
97332  pIdx->nSample++;
97333  }
97334  rc = sqlite3_finalize(pStmt);
97335  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
97336  return rc;
97337 }
97338 
97339 /*
97340 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
97341 ** the Index.aSample[] arrays of all indices.
97342 */
97343 static int loadStat4(sqlite3 *db, const char *zDb){
97344  int rc = SQLITE_OK; /* Result codes from subroutines */
97345 
97346  assert( db->lookaside.bDisable );
97347  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
97348  rc = loadStatTbl(db, 0,
97349  "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
97350  "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
97351  zDb
97352  );
97353  }
97354 
97355  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
97356  rc = loadStatTbl(db, 1,
97357  "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
97358  "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
97359  zDb
97360  );
97361  }
97362 
97363  return rc;
97364 }
97365 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
97366 
97367 /*
97368 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
97369 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
97370 ** arrays. The contents of sqlite_stat3/4 are used to populate the
97371 ** Index.aSample[] arrays.
97372 **
97373 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
97374 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
97375 ** during compilation and the sqlite_stat3/4 table is present, no data is
97376 ** read from it.
97377 **
97378 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
97379 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
97380 ** returned. However, in this case, data is read from the sqlite_stat1
97381 ** table (if it is present) before returning.
97382 **
97383 ** If an OOM error occurs, this function always sets db->mallocFailed.
97384 ** This means if the caller does not care about other errors, the return
97385 ** code may be ignored.
97386 */
97388  analysisInfo sInfo;
97389  HashElem *i;
97390  char *zSql;
97391  int rc = SQLITE_OK;
97392 
97393  assert( iDb>=0 && iDb<db->nDb );
97394  assert( db->aDb[iDb].pBt!=0 );
97395 
97396  /* Clear any prior statistics */
97397  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97398  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
97399  Index *pIdx = sqliteHashData(i);
97400  pIdx->aiRowLogEst[0] = 0;
97401 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97402  sqlite3DeleteIndexSamples(db, pIdx);
97403  pIdx->aSample = 0;
97404 #endif
97405  }
97406 
97407  /* Load new statistics out of the sqlite_stat1 table */
97408  sInfo.db = db;
97409  sInfo.zDatabase = db->aDb[iDb].zDbSName;
97410  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
97411  zSql = sqlite3MPrintf(db,
97412  "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
97413  if( zSql==0 ){
97414  rc = SQLITE_NOMEM_BKPT;
97415  }else{
97416  rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
97417  sqlite3DbFree(db, zSql);
97418  }
97419  }
97420 
97421  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
97422  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97423  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
97424  Index *pIdx = sqliteHashData(i);
97425  if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
97426  }
97427 
97428  /* Load the statistics from the sqlite_stat4 table. */
97429 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97430  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
97431  db->lookaside.bDisable++;
97432  rc = loadStat4(db, sInfo.zDatabase);
97433  db->lookaside.bDisable--;
97434  }
97435  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
97436  Index *pIdx = sqliteHashData(i);
97437  sqlite3_free(pIdx->aiRowEst);
97438  pIdx->aiRowEst = 0;
97439  }
97440 #endif
97441 
97442  if( rc==SQLITE_NOMEM ){
97443  sqlite3OomFault(db);
97444  }
97445  return rc;
97446 }
97447 
97448 
97449 #endif /* SQLITE_OMIT_ANALYZE */
97450 
97451 /************** End of analyze.c *********************************************/
97452 /************** Begin file attach.c ******************************************/
97453 /*
97454 ** 2003 April 6
97455 **
97456 ** The author disclaims copyright to this source code. In place of
97457 ** a legal notice, here is a blessing:
97458 **
97459 ** May you do good and not evil.
97460 ** May you find forgiveness for yourself and forgive others.
97461 ** May you share freely, never taking more than you give.
97462 **
97463 *************************************************************************
97464 ** This file contains code used to implement the ATTACH and DETACH commands.
97465 */
97466 /* #include "sqliteInt.h" */
97467 
97468 #ifndef SQLITE_OMIT_ATTACH
97469 /*
97470 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
97471 ** is slightly different from resolving a normal SQL expression, because simple
97472 ** identifiers are treated as strings, not possible column names or aliases.
97473 **
97474 ** i.e. if the parser sees:
97475 **
97476 ** ATTACH DATABASE abc AS def
97477 **
97478 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
97479 ** looking for columns of the same name.
97480 **
97481 ** This only applies to the root node of pExpr, so the statement:
97482 **
97483 ** ATTACH DATABASE abc||def AS 'db2'
97484 **
97485 ** will fail because neither abc or def can be resolved.
97486 */
97487 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
97488 {
97489  int rc = SQLITE_OK;
97490  if( pExpr ){
97491  if( pExpr->op!=TK_ID ){
97492  rc = sqlite3ResolveExprNames(pName, pExpr);
97493  }else{
97494  pExpr->op = TK_STRING;
97495  }
97496  }
97497  return rc;
97498 }
97499 
97500 /*
97501 ** An SQL user-function registered to do the work of an ATTACH statement. The
97502 ** three arguments to the function come directly from an attach statement:
97503 **
97504 ** ATTACH DATABASE x AS y KEY z
97505 **
97506 ** SELECT sqlite_attach(x, y, z)
97507 **
97508 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
97509 ** third argument.
97510 */
97511 static void attachFunc(
97512  sqlite3_context *context,
97513  int NotUsed,
97514  sqlite3_value **argv
97515 ){
97516  int i;
97517  int rc = 0;
97518  sqlite3 *db = sqlite3_context_db_handle(context);
97519  const char *zName;
97520  const char *zFile;
97521  char *zPath = 0;
97522  char *zErr = 0;
97523  unsigned int flags;
97524  Db *aNew;
97525  char *zErrDyn = 0;
97526  sqlite3_vfs *pVfs;
97527 
97528  UNUSED_PARAMETER(NotUsed);
97529 
97530  zFile = (const char *)sqlite3_value_text(argv[0]);
97531  zName = (const char *)sqlite3_value_text(argv[1]);
97532  if( zFile==0 ) zFile = "";
97533  if( zName==0 ) zName = "";
97534 
97535  /* Check for the following errors:
97536  **
97537  ** * Too many attached databases,
97538  ** * Transaction currently open
97539  ** * Specified database name already being used.
97540  */
97541  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
97542  zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
97544  );
97545  goto attach_error;
97546  }
97547  if( !db->autoCommit ){
97548  zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
97549  goto attach_error;
97550  }
97551  for(i=0; i<db->nDb; i++){
97552  char *z = db->aDb[i].zDbSName;
97553  assert( z && zName );
97554  if( sqlite3StrICmp(z, zName)==0 ){
97555  zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
97556  goto attach_error;
97557  }
97558  }
97559 
97560  /* Allocate the new entry in the db->aDb[] array and initialize the schema
97561  ** hash tables.
97562  */
97563  if( db->aDb==db->aDbStatic ){
97564  aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
97565  if( aNew==0 ) return;
97566  memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
97567  }else{
97568  aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
97569  if( aNew==0 ) return;
97570  }
97571  db->aDb = aNew;
97572  aNew = &db->aDb[db->nDb];
97573  memset(aNew, 0, sizeof(*aNew));
97574 
97575  /* Open the database file. If the btree is successfully opened, use
97576  ** it to obtain the database schema. At this point the schema may
97577  ** or may not be initialized.
97578  */
97579  flags = db->openFlags;
97580  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
97581  if( rc!=SQLITE_OK ){
97582  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
97583  sqlite3_result_error(context, zErr, -1);
97584  sqlite3_free(zErr);
97585  return;
97586  }
97587  assert( pVfs );
97588  flags |= SQLITE_OPEN_MAIN_DB;
97589  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
97590  sqlite3_free( zPath );
97591  db->nDb++;
97592  if( rc==SQLITE_CONSTRAINT ){
97593  rc = SQLITE_ERROR;
97594  zErrDyn = sqlite3MPrintf(db, "database is already attached");
97595  }else if( rc==SQLITE_OK ){
97596  Pager *pPager;
97597  aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
97598  if( !aNew->pSchema ){
97599  rc = SQLITE_NOMEM_BKPT;
97600  }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
97601  zErrDyn = sqlite3MPrintf(db,
97602  "attached databases must use the same text encoding as main database");
97603  rc = SQLITE_ERROR;
97604  }
97605  sqlite3BtreeEnter(aNew->pBt);
97606  pPager = sqlite3BtreePager(aNew->pBt);
97609  sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
97610 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
97613 #endif
97614  sqlite3BtreeLeave(aNew->pBt);
97615  }
97617  aNew->zDbSName = sqlite3DbStrDup(db, zName);
97618  if( rc==SQLITE_OK && aNew->zDbSName==0 ){
97619  rc = SQLITE_NOMEM_BKPT;
97620  }
97621 
97622 
97623 #ifdef SQLITE_HAS_CODEC
97624  if( rc==SQLITE_OK ){
97625  extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
97626  extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
97627  int nKey;
97628  char *zKey;
97629  int t = sqlite3_value_type(argv[2]);
97630  switch( t ){
97631  case SQLITE_INTEGER:
97632  case SQLITE_FLOAT:
97633  zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
97634  rc = SQLITE_ERROR;
97635  break;
97636 
97637  case SQLITE_TEXT:
97638  case SQLITE_BLOB:
97639  nKey = sqlite3_value_bytes(argv[2]);
97640  zKey = (char *)sqlite3_value_blob(argv[2]);
97641  rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
97642  break;
97643 
97644  case SQLITE_NULL:
97645  /* No key specified. Use the key from the main database */
97646  sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
97647  if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
97648  rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
97649  }
97650  break;
97651  }
97652  }
97653 #endif
97654 
97655  /* If the file was opened successfully, read the schema for the new database.
97656  ** If this fails, or if opening the file failed, then close the file and
97657  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
97658  ** we found it.
97659  */
97660  if( rc==SQLITE_OK ){
97662  rc = sqlite3Init(db, &zErrDyn);
97664  }
97665 #ifdef SQLITE_USER_AUTHENTICATION
97666  if( rc==SQLITE_OK ){
97667  u8 newAuth = 0;
97668  rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
97669  if( newAuth<db->auth.authLevel ){
97670  rc = SQLITE_AUTH_USER;
97671  }
97672  }
97673 #endif
97674  if( rc ){
97675  int iDb = db->nDb - 1;
97676  assert( iDb>=2 );
97677  if( db->aDb[iDb].pBt ){
97678  sqlite3BtreeClose(db->aDb[iDb].pBt);
97679  db->aDb[iDb].pBt = 0;
97680  db->aDb[iDb].pSchema = 0;
97681  }
97683  db->nDb = iDb;
97684  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
97685  sqlite3OomFault(db);
97686  sqlite3DbFree(db, zErrDyn);
97687  zErrDyn = sqlite3MPrintf(db, "out of memory");
97688  }else if( zErrDyn==0 ){
97689  zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
97690  }
97691  goto attach_error;
97692  }
97693 
97694  return;
97695 
97696 attach_error:
97697  /* Return an error if we get here */
97698  if( zErrDyn ){
97699  sqlite3_result_error(context, zErrDyn, -1);
97700  sqlite3DbFree(db, zErrDyn);
97701  }
97702  if( rc ) sqlite3_result_error_code(context, rc);
97703 }
97704 
97705 /*
97706 ** An SQL user-function registered to do the work of an DETACH statement. The
97707 ** three arguments to the function come directly from a detach statement:
97708 **
97709 ** DETACH DATABASE x
97710 **
97711 ** SELECT sqlite_detach(x)
97712 */
97713 static void detachFunc(
97714  sqlite3_context *context,
97715  int NotUsed,
97716  sqlite3_value **argv
97717 ){
97718  const char *zName = (const char *)sqlite3_value_text(argv[0]);
97719  sqlite3 *db = sqlite3_context_db_handle(context);
97720  int i;
97721  Db *pDb = 0;
97722  char zErr[128];
97723 
97724  UNUSED_PARAMETER(NotUsed);
97725 
97726  if( zName==0 ) zName = "";
97727  for(i=0; i<db->nDb; i++){
97728  pDb = &db->aDb[i];
97729  if( pDb->pBt==0 ) continue;
97730  if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
97731  }
97732 
97733  if( i>=db->nDb ){
97734  sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
97735  goto detach_error;
97736  }
97737  if( i<2 ){
97738  sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
97739  goto detach_error;
97740  }
97741  if( !db->autoCommit ){
97742  sqlite3_snprintf(sizeof(zErr), zErr,
97743  "cannot DETACH database within transaction");
97744  goto detach_error;
97745  }
97747  sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
97748  goto detach_error;
97749  }
97750 
97751  sqlite3BtreeClose(pDb->pBt);
97752  pDb->pBt = 0;
97753  pDb->pSchema = 0;
97755  return;
97756 
97757 detach_error:
97758  sqlite3_result_error(context, zErr, -1);
97759 }
97760 
97761 /*
97762 ** This procedure generates VDBE code for a single invocation of either the
97763 ** sqlite_detach() or sqlite_attach() SQL user functions.
97764 */
97765 static void codeAttach(
97766  Parse *pParse, /* The parser context */
97767  int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
97768  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
97769  Expr *pAuthArg, /* Expression to pass to authorization callback */
97770  Expr *pFilename, /* Name of database file */
97771  Expr *pDbname, /* Name of the database to use internally */
97772  Expr *pKey /* Database key for encryption extension */
97773 ){
97774  int rc;
97775  NameContext sName;
97776  Vdbe *v;
97777  sqlite3* db = pParse->db;
97778  int regArgs;
97779 
97780  if( pParse->nErr ) goto attach_end;
97781  memset(&sName, 0, sizeof(NameContext));
97782  sName.pParse = pParse;
97783 
97784  if(
97785  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
97786  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
97787  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
97788  ){
97789  goto attach_end;
97790  }
97791 
97792 #ifndef SQLITE_OMIT_AUTHORIZATION
97793  if( pAuthArg ){
97794  char *zAuthArg;
97795  if( pAuthArg->op==TK_STRING ){
97796  zAuthArg = pAuthArg->u.zToken;
97797  }else{
97798  zAuthArg = 0;
97799  }
97800  rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
97801  if(rc!=SQLITE_OK ){
97802  goto attach_end;
97803  }
97804  }
97805 #endif /* SQLITE_OMIT_AUTHORIZATION */
97806 
97807 
97808  v = sqlite3GetVdbe(pParse);
97809  regArgs = sqlite3GetTempRange(pParse, 4);
97810  sqlite3ExprCode(pParse, pFilename, regArgs);
97811  sqlite3ExprCode(pParse, pDbname, regArgs+1);
97812  sqlite3ExprCode(pParse, pKey, regArgs+2);
97813 
97814  assert( v || db->mallocFailed );
97815  if( v ){
97816  sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
97817  (char *)pFunc, P4_FUNCDEF);
97818  assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
97819  sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
97820 
97821  /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
97822  ** statement only). For DETACH, set it to false (expire all existing
97823  ** statements).
97824  */
97826  }
97827 
97828 attach_end:
97829  sqlite3ExprDelete(db, pFilename);
97830  sqlite3ExprDelete(db, pDbname);
97831  sqlite3ExprDelete(db, pKey);
97832 }
97833 
97834 /*
97835 ** Called by the parser to compile a DETACH statement.
97836 **
97837 ** DETACH pDbname
97838 */
97839 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
97840  static const FuncDef detach_func = {
97841  1, /* nArg */
97842  SQLITE_UTF8, /* funcFlags */
97843  0, /* pUserData */
97844  0, /* pNext */
97845  detachFunc, /* xSFunc */
97846  0, /* xFinalize */
97847  "sqlite_detach", /* zName */
97848  {0}
97849  };
97850  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
97851 }
97852 
97853 /*
97854 ** Called by the parser to compile an ATTACH statement.
97855 **
97856 ** ATTACH p AS pDbname KEY pKey
97857 */
97858 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
97859  static const FuncDef attach_func = {
97860  3, /* nArg */
97861  SQLITE_UTF8, /* funcFlags */
97862  0, /* pUserData */
97863  0, /* pNext */
97864  attachFunc, /* xSFunc */
97865  0, /* xFinalize */
97866  "sqlite_attach", /* zName */
97867  {0}
97868  };
97869  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
97870 }
97871 #endif /* SQLITE_OMIT_ATTACH */
97872 
97873 /*
97874 ** Initialize a DbFixer structure. This routine must be called prior
97875 ** to passing the structure to one of the sqliteFixAAAA() routines below.
97876 */
97878  DbFixer *pFix, /* The fixer to be initialized */
97879  Parse *pParse, /* Error messages will be written here */
97880  int iDb, /* This is the database that must be used */
97881  const char *zType, /* "view", "trigger", or "index" */
97882  const Token *pName /* Name of the view, trigger, or index */
97883 ){
97884  sqlite3 *db;
97885 
97886  db = pParse->db;
97887  assert( db->nDb>iDb );
97888  pFix->pParse = pParse;
97889  pFix->zDb = db->aDb[iDb].zDbSName;
97890  pFix->pSchema = db->aDb[iDb].pSchema;
97891  pFix->zType = zType;
97892  pFix->pName = pName;
97893  pFix->bVarOnly = (iDb==1);
97894 }
97895 
97896 /*
97897 ** The following set of routines walk through the parse tree and assign
97898 ** a specific database to all table references where the database name
97899 ** was left unspecified in the original SQL statement. The pFix structure
97900 ** must have been initialized by a prior call to sqlite3FixInit().
97901 **
97902 ** These routines are used to make sure that an index, trigger, or
97903 ** view in one database does not refer to objects in a different database.
97904 ** (Exception: indices, triggers, and views in the TEMP database are
97905 ** allowed to refer to anything.) If a reference is explicitly made
97906 ** to an object in a different database, an error message is added to
97907 ** pParse->zErrMsg and these routines return non-zero. If everything
97908 ** checks out, these routines return 0.
97909 */
97911  DbFixer *pFix, /* Context of the fixation */
97912  SrcList *pList /* The Source list to check and modify */
97913 ){
97914  int i;
97915  const char *zDb;
97916  struct SrcList_item *pItem;
97917 
97918  if( NEVER(pList==0) ) return 0;
97919  zDb = pFix->zDb;
97920  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
97921  if( pFix->bVarOnly==0 ){
97922  if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
97923  sqlite3ErrorMsg(pFix->pParse,
97924  "%s %T cannot reference objects in database %s",
97925  pFix->zType, pFix->pName, pItem->zDatabase);
97926  return 1;
97927  }
97928  sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
97929  pItem->zDatabase = 0;
97930  pItem->pSchema = pFix->pSchema;
97931  }
97932 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97933  if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
97934  if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
97935 #endif
97936  }
97937  return 0;
97938 }
97939 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97941  DbFixer *pFix, /* Context of the fixation */
97942  Select *pSelect /* The SELECT statement to be fixed to one database */
97943 ){
97944  while( pSelect ){
97945  if( sqlite3FixExprList(pFix, pSelect->pEList) ){
97946  return 1;
97947  }
97948  if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
97949  return 1;
97950  }
97951  if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
97952  return 1;
97953  }
97954  if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
97955  return 1;
97956  }
97957  if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
97958  return 1;
97959  }
97960  if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
97961  return 1;
97962  }
97963  if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
97964  return 1;
97965  }
97966  if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
97967  return 1;
97968  }
97969  pSelect = pSelect->pPrior;
97970  }
97971  return 0;
97972 }
97974  DbFixer *pFix, /* Context of the fixation */
97975  Expr *pExpr /* The expression to be fixed to one database */
97976 ){
97977  while( pExpr ){
97978  if( pExpr->op==TK_VARIABLE ){
97979  if( pFix->pParse->db->init.busy ){
97980  pExpr->op = TK_NULL;
97981  }else{
97982  sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
97983  return 1;
97984  }
97985  }
97986  if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
97987  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97988  if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
97989  }else{
97990  if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
97991  }
97992  if( sqlite3FixExpr(pFix, pExpr->pRight) ){
97993  return 1;
97994  }
97995  pExpr = pExpr->pLeft;
97996  }
97997  return 0;
97998 }
98000  DbFixer *pFix, /* Context of the fixation */
98001  ExprList *pList /* The expression to be fixed to one database */
98002 ){
98003  int i;
98004  struct ExprList_item *pItem;
98005  if( pList==0 ) return 0;
98006  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
98007  if( sqlite3FixExpr(pFix, pItem->pExpr) ){
98008  return 1;
98009  }
98010  }
98011  return 0;
98012 }
98013 #endif
98014 
98015 #ifndef SQLITE_OMIT_TRIGGER
98017  DbFixer *pFix, /* Context of the fixation */
98018  TriggerStep *pStep /* The trigger step be fixed to one database */
98019 ){
98020  while( pStep ){
98021  if( sqlite3FixSelect(pFix, pStep->pSelect) ){
98022  return 1;
98023  }
98024  if( sqlite3FixExpr(pFix, pStep->pWhere) ){
98025  return 1;
98026  }
98027  if( sqlite3FixExprList(pFix, pStep->pExprList) ){
98028  return 1;
98029  }
98030  pStep = pStep->pNext;
98031  }
98032  return 0;
98033 }
98034 #endif
98035 
98036 /************** End of attach.c **********************************************/
98037 /************** Begin file auth.c ********************************************/
98038 /*
98039 ** 2003 January 11
98040 **
98041 ** The author disclaims copyright to this source code. In place of
98042 ** a legal notice, here is a blessing:
98043 **
98044 ** May you do good and not evil.
98045 ** May you find forgiveness for yourself and forgive others.
98046 ** May you share freely, never taking more than you give.
98047 **
98048 *************************************************************************
98049 ** This file contains code used to implement the sqlite3_set_authorizer()
98050 ** API. This facility is an optional feature of the library. Embedded
98051 ** systems that do not need this facility may omit it by recompiling
98052 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
98053 */
98054 /* #include "sqliteInt.h" */
98055 
98056 /*
98057 ** All of the code in this file may be omitted by defining a single
98058 ** macro.
98059 */
98060 #ifndef SQLITE_OMIT_AUTHORIZATION
98061 
98062 /*
98063 ** Set or clear the access authorization function.
98064 **
98065 ** The access authorization function is be called during the compilation
98066 ** phase to verify that the user has read and/or write access permission on
98067 ** various fields of the database. The first argument to the auth function
98068 ** is a copy of the 3rd argument to this routine. The second argument
98069 ** to the auth function is one of these constants:
98070 **
98071 ** SQLITE_CREATE_INDEX
98072 ** SQLITE_CREATE_TABLE
98073 ** SQLITE_CREATE_TEMP_INDEX
98074 ** SQLITE_CREATE_TEMP_TABLE
98075 ** SQLITE_CREATE_TEMP_TRIGGER
98076 ** SQLITE_CREATE_TEMP_VIEW
98077 ** SQLITE_CREATE_TRIGGER
98078 ** SQLITE_CREATE_VIEW
98079 ** SQLITE_DELETE
98080 ** SQLITE_DROP_INDEX
98081 ** SQLITE_DROP_TABLE
98082 ** SQLITE_DROP_TEMP_INDEX
98083 ** SQLITE_DROP_TEMP_TABLE
98084 ** SQLITE_DROP_TEMP_TRIGGER
98085 ** SQLITE_DROP_TEMP_VIEW
98086 ** SQLITE_DROP_TRIGGER
98087 ** SQLITE_DROP_VIEW
98088 ** SQLITE_INSERT
98089 ** SQLITE_PRAGMA
98090 ** SQLITE_READ
98091 ** SQLITE_SELECT
98092 ** SQLITE_TRANSACTION
98093 ** SQLITE_UPDATE
98094 **
98095 ** The third and fourth arguments to the auth function are the name of
98096 ** the table and the column that are being accessed. The auth function
98097 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
98098 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
98099 ** means that the SQL statement will never-run - the sqlite3_exec() call
98100 ** will return with an error. SQLITE_IGNORE means that the SQL statement
98101 ** should run but attempts to read the specified column will return NULL
98102 ** and attempts to write the column will be ignored.
98103 **
98104 ** Setting the auth function to NULL disables this hook. The default
98105 ** setting of the auth function is NULL.
98106 */
98108  sqlite3 *db,
98109  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
98110  void *pArg
98111 ){
98112 #ifdef SQLITE_ENABLE_API_ARMOR
98113  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
98114 #endif
98116  db->xAuth = (sqlite3_xauth)xAuth;
98117  db->pAuthArg = pArg;
98120  return SQLITE_OK;
98121 }
98122 
98123 /*
98124 ** Write an error message into pParse->zErrMsg that explains that the
98125 ** user-supplied authorization function returned an illegal value.
98126 */
98127 static void sqliteAuthBadReturnCode(Parse *pParse){
98128  sqlite3ErrorMsg(pParse, "authorizer malfunction");
98129  pParse->rc = SQLITE_ERROR;
98130 }
98131 
98132 /*
98133 ** Invoke the authorization callback for permission to read column zCol from
98134 ** table zTab in database zDb. This function assumes that an authorization
98135 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
98136 **
98137 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
98138 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
98139 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
98140 */
98142  Parse *pParse, /* The parser context */
98143  const char *zTab, /* Table name */
98144  const char *zCol, /* Column name */
98145  int iDb /* Index of containing database. */
98146 ){
98147  sqlite3 *db = pParse->db; /* Database handle */
98148  char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
98149  int rc; /* Auth callback return code */
98150 
98151  if( db->init.busy ) return SQLITE_OK;
98152  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
98153 #ifdef SQLITE_USER_AUTHENTICATION
98154  ,db->auth.zAuthUser
98155 #endif
98156  );
98157  if( rc==SQLITE_DENY ){
98158  if( db->nDb>2 || iDb!=0 ){
98159  sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
98160  }else{
98161  sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
98162  }
98163  pParse->rc = SQLITE_AUTH;
98164  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
98165  sqliteAuthBadReturnCode(pParse);
98166  }
98167  return rc;
98168 }
98169 
98170 /*
98171 ** The pExpr should be a TK_COLUMN expression. The table referred to
98172 ** is in pTabList or else it is the NEW or OLD table of a trigger.
98173 ** Check to see if it is OK to read this particular column.
98174 **
98175 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
98176 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
98177 ** then generate an error.
98178 */
98180  Parse *pParse, /* The parser context */
98181  Expr *pExpr, /* The expression to check authorization on */
98182  Schema *pSchema, /* The schema of the expression */
98183  SrcList *pTabList /* All table that pExpr might refer to */
98184 ){
98185  sqlite3 *db = pParse->db;
98186  Table *pTab = 0; /* The table being read */
98187  const char *zCol; /* Name of the column of the table */
98188  int iSrc; /* Index in pTabList->a[] of table being read */
98189  int iDb; /* The index of the database the expression refers to */
98190  int iCol; /* Index of column in table */
98191 
98192  if( db->xAuth==0 ) return;
98193  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
98194  if( iDb<0 ){
98195  /* An attempt to read a column out of a subquery or other
98196  ** temporary table. */
98197  return;
98198  }
98199 
98200  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
98201  if( pExpr->op==TK_TRIGGER ){
98202  pTab = pParse->pTriggerTab;
98203  }else{
98204  assert( pTabList );
98205  for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
98206  if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
98207  pTab = pTabList->a[iSrc].pTab;
98208  break;
98209  }
98210  }
98211  }
98212  iCol = pExpr->iColumn;
98213  if( NEVER(pTab==0) ) return;
98214 
98215  if( iCol>=0 ){
98216  assert( iCol<pTab->nCol );
98217  zCol = pTab->aCol[iCol].zName;
98218  }else if( pTab->iPKey>=0 ){
98219  assert( pTab->iPKey<pTab->nCol );
98220  zCol = pTab->aCol[pTab->iPKey].zName;
98221  }else{
98222  zCol = "ROWID";
98223  }
98224  assert( iDb>=0 && iDb<db->nDb );
98225  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
98226  pExpr->op = TK_NULL;
98227  }
98228 }
98229 
98230 /*
98231 ** Do an authorization check using the code and arguments given. Return
98232 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
98233 ** is returned, then the error count and error message in pParse are
98234 ** modified appropriately.
98235 */
98237  Parse *pParse,
98238  int code,
98239  const char *zArg1,
98240  const char *zArg2,
98241  const char *zArg3
98242 ){
98243  sqlite3 *db = pParse->db;
98244  int rc;
98245 
98246  /* Don't do any authorization checks if the database is initialising
98247  ** or if the parser is being invoked from within sqlite3_declare_vtab.
98248  */
98249  if( db->init.busy || IN_DECLARE_VTAB ){
98250  return SQLITE_OK;
98251  }
98252 
98253  if( db->xAuth==0 ){
98254  return SQLITE_OK;
98255  }
98256  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
98257 #ifdef SQLITE_USER_AUTHENTICATION
98258  ,db->auth.zAuthUser
98259 #endif
98260  );
98261  if( rc==SQLITE_DENY ){
98262  sqlite3ErrorMsg(pParse, "not authorized");
98263  pParse->rc = SQLITE_AUTH;
98264  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
98265  rc = SQLITE_DENY;
98266  sqliteAuthBadReturnCode(pParse);
98267  }
98268  return rc;
98269 }
98270 
98271 /*
98272 ** Push an authorization context. After this routine is called, the
98273 ** zArg3 argument to authorization callbacks will be zContext until
98274 ** popped. Or if pParse==0, this routine is a no-op.
98275 */
98277  Parse *pParse,
98278  AuthContext *pContext,
98279  const char *zContext
98280 ){
98281  assert( pParse );
98282  pContext->pParse = pParse;
98283  pContext->zAuthContext = pParse->zAuthContext;
98284  pParse->zAuthContext = zContext;
98285 }
98286 
98287 /*
98288 ** Pop an authorization context that was previously pushed
98289 ** by sqlite3AuthContextPush
98290 */
98292  if( pContext->pParse ){
98293  pContext->pParse->zAuthContext = pContext->zAuthContext;
98294  pContext->pParse = 0;
98295  }
98296 }
98297 
98298 #endif /* SQLITE_OMIT_AUTHORIZATION */
98299 
98300 /************** End of auth.c ************************************************/
98301 /************** Begin file build.c *******************************************/
98302 /*
98303 ** 2001 September 15
98304 **
98305 ** The author disclaims copyright to this source code. In place of
98306 ** a legal notice, here is a blessing:
98307 **
98308 ** May you do good and not evil.
98309 ** May you find forgiveness for yourself and forgive others.
98310 ** May you share freely, never taking more than you give.
98311 **
98312 *************************************************************************
98313 ** This file contains C code routines that are called by the SQLite parser
98314 ** when syntax rules are reduced. The routines in this file handle the
98315 ** following kinds of SQL syntax:
98316 **
98317 ** CREATE TABLE
98318 ** DROP TABLE
98319 ** CREATE INDEX
98320 ** DROP INDEX
98321 ** creating ID lists
98322 ** BEGIN TRANSACTION
98323 ** COMMIT
98324 ** ROLLBACK
98325 */
98326 /* #include "sqliteInt.h" */
98327 
98328 #ifndef SQLITE_OMIT_SHARED_CACHE
98329 /*
98330 ** The TableLock structure is only used by the sqlite3TableLock() and
98331 ** codeTableLocks() functions.
98332 */
98333 struct TableLock {
98334  int iDb; /* The database containing the table to be locked */
98335  int iTab; /* The root page of the table to be locked */
98336  u8 isWriteLock; /* True for write lock. False for a read lock */
98337  const char *zName; /* Name of the table */
98338 };
98339 
98340 /*
98341 ** Record the fact that we want to lock a table at run-time.
98342 **
98343 ** The table to be locked has root page iTab and is found in database iDb.
98344 ** A read or a write lock can be taken depending on isWritelock.
98345 **
98346 ** This routine just records the fact that the lock is desired. The
98347 ** code to make the lock occur is generated by a later call to
98348 ** codeTableLocks() which occurs during sqlite3FinishCoding().
98349 */
98351  Parse *pParse, /* Parsing context */
98352  int iDb, /* Index of the database containing the table to lock */
98353  int iTab, /* Root page number of the table to be locked */
98354  u8 isWriteLock, /* True for a write lock */
98355  const char *zName /* Name of the table to be locked */
98356 ){
98357  Parse *pToplevel = sqlite3ParseToplevel(pParse);
98358  int i;
98359  int nBytes;
98360  TableLock *p;
98361  assert( iDb>=0 );
98362 
98363  for(i=0; i<pToplevel->nTableLock; i++){
98364  p = &pToplevel->aTableLock[i];
98365  if( p->iDb==iDb && p->iTab==iTab ){
98366  p->isWriteLock = (p->isWriteLock || isWriteLock);
98367  return;
98368  }
98369  }
98370 
98371  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
98372  pToplevel->aTableLock =
98373  sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
98374  if( pToplevel->aTableLock ){
98375  p = &pToplevel->aTableLock[pToplevel->nTableLock++];
98376  p->iDb = iDb;
98377  p->iTab = iTab;
98378  p->isWriteLock = isWriteLock;
98379  p->zName = zName;
98380  }else{
98381  pToplevel->nTableLock = 0;
98382  sqlite3OomFault(pToplevel->db);
98383  }
98384 }
98385 
98386 /*
98387 ** Code an OP_TableLock instruction for each table locked by the
98388 ** statement (configured by calls to sqlite3TableLock()).
98389 */
98390 static void codeTableLocks(Parse *pParse){
98391  int i;
98392  Vdbe *pVdbe;
98393 
98394  pVdbe = sqlite3GetVdbe(pParse);
98395  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
98396 
98397  for(i=0; i<pParse->nTableLock; i++){
98398  TableLock *p = &pParse->aTableLock[i];
98399  int p1 = p->iDb;
98400  sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
98401  p->zName, P4_STATIC);
98402  }
98403 }
98404 #else
98405  #define codeTableLocks(x)
98406 #endif
98407 
98408 /*
98409 ** Return TRUE if the given yDbMask object is empty - if it contains no
98410 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
98411 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
98412 */
98413 #if SQLITE_MAX_ATTACHED>30
98414 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
98415  int i;
98416  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
98417  return 1;
98418 }
98419 #endif
98420 
98421 /*
98422 ** This routine is called after a single SQL statement has been
98423 ** parsed and a VDBE program to execute that statement has been
98424 ** prepared. This routine puts the finishing touches on the
98425 ** VDBE program and resets the pParse structure for the next
98426 ** parse.
98427 **
98428 ** Note that if an error occurred, it might be the case that
98429 ** no VDBE code was generated.
98430 */
98432  sqlite3 *db;
98433  Vdbe *v;
98434 
98435  assert( pParse->pToplevel==0 );
98436  db = pParse->db;
98437  if( pParse->nested ) return;
98438  if( db->mallocFailed || pParse->nErr ){
98439  if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
98440  return;
98441  }
98442 
98443  /* Begin by generating some termination code at the end of the
98444  ** vdbe program
98445  */
98446  v = sqlite3GetVdbe(pParse);
98447  assert( !pParse->isMultiWrite
98448  || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
98449  if( v ){
98451 
98452 #if SQLITE_USER_AUTHENTICATION
98453  if( pParse->nTableLock>0 && db->init.busy==0 ){
98454  sqlite3UserAuthInit(db);
98455  if( db->auth.authLevel<UAUTH_User ){
98456  sqlite3ErrorMsg(pParse, "user not authenticated");
98457  pParse->rc = SQLITE_AUTH_USER;
98458  return;
98459  }
98460  }
98461 #endif
98462 
98463  /* The cookie mask contains one bit for each database file open.
98464  ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
98465  ** set for each database that is used. Generate code to start a
98466  ** transaction on each used database and to verify the schema cookie
98467  ** on each used database.
98468  */
98469  if( db->mallocFailed==0
98470  && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
98471  ){
98472  int iDb, i;
98473  assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
98474  sqlite3VdbeJumpHere(v, 0);
98475  for(iDb=0; iDb<db->nDb; iDb++){
98476  Schema *pSchema;
98477  if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
98478  sqlite3VdbeUsesBtree(v, iDb);
98479  pSchema = db->aDb[iDb].pSchema;
98481  OP_Transaction, /* Opcode */
98482  iDb, /* P1 */
98483  DbMaskTest(pParse->writeMask,iDb), /* P2 */
98484  pSchema->schema_cookie, /* P3 */
98485  pSchema->iGeneration /* P4 */
98486  );
98487  if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
98488  VdbeComment((v,
98489  "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
98490  }
98491 #ifndef SQLITE_OMIT_VIRTUALTABLE
98492  for(i=0; i<pParse->nVtabLock; i++){
98493  char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
98494  sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
98495  }
98496  pParse->nVtabLock = 0;
98497 #endif
98498 
98499  /* Once all the cookies have been verified and transactions opened,
98500  ** obtain the required table-locks. This is a no-op unless the
98501  ** shared-cache feature is enabled.
98502  */
98503  codeTableLocks(pParse);
98504 
98505  /* Initialize any AUTOINCREMENT data structures required.
98506  */
98507  sqlite3AutoincrementBegin(pParse);
98508 
98509  /* Code constant expressions that where factored out of inner loops */
98510  if( pParse->pConstExpr ){
98511  ExprList *pEL = pParse->pConstExpr;
98512  pParse->okConstFactor = 0;
98513  for(i=0; i<pEL->nExpr; i++){
98514  sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
98515  }
98516  }
98517 
98518  /* Finally, jump back to the beginning of the executable code. */
98519  sqlite3VdbeGoto(v, 1);
98520  }
98521  }
98522 
98523 
98524  /* Get the VDBE program ready for execution
98525  */
98526  if( v && pParse->nErr==0 && !db->mallocFailed ){
98527  assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
98528  /* A minimum of one cursor is required if autoincrement is used
98529  * See ticket [a696379c1f08866] */
98530  if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
98531  sqlite3VdbeMakeReady(v, pParse);
98532  pParse->rc = SQLITE_DONE;
98533  }else{
98534  pParse->rc = SQLITE_ERROR;
98535  }
98536 }
98537 
98538 /*
98539 ** Run the parser and code generator recursively in order to generate
98540 ** code for the SQL statement given onto the end of the pParse context
98541 ** currently under construction. When the parser is run recursively
98542 ** this way, the final OP_Halt is not appended and other initialization
98543 ** and finalization steps are omitted because those are handling by the
98544 ** outermost parser.
98545 **
98546 ** Not everything is nestable. This facility is designed to permit
98547 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
98548 ** care if you decide to try to use this routine for some other purposes.
98549 */
98550 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
98551  va_list ap;
98552  char *zSql;
98553  char *zErrMsg = 0;
98554  sqlite3 *db = pParse->db;
98555  char saveBuf[PARSE_TAIL_SZ];
98556 
98557  if( pParse->nErr ) return;
98558  assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
98559  va_start(ap, zFormat);
98560  zSql = sqlite3VMPrintf(db, zFormat, ap);
98561  va_end(ap);
98562  if( zSql==0 ){
98563  return; /* A malloc must have failed */
98564  }
98565  pParse->nested++;
98566  memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
98567  memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
98568  sqlite3RunParser(pParse, zSql, &zErrMsg);
98569  sqlite3DbFree(db, zErrMsg);
98570  sqlite3DbFree(db, zSql);
98571  memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
98572  pParse->nested--;
98573 }
98574 
98575 #if SQLITE_USER_AUTHENTICATION
98576 /*
98577 ** Return TRUE if zTable is the name of the system table that stores the
98578 ** list of users and their access credentials.
98579 */
98580 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
98581  return sqlite3_stricmp(zTable, "sqlite_user")==0;
98582 }
98583 #endif
98584 
98585 /*
98586 ** Locate the in-memory structure that describes a particular database
98587 ** table given the name of that table and (optionally) the name of the
98588 ** database containing the table. Return NULL if not found.
98589 **
98590 ** If zDatabase is 0, all databases are searched for the table and the
98591 ** first matching table is returned. (No checking for duplicate table
98592 ** names is done.) The search order is TEMP first, then MAIN, then any
98593 ** auxiliary databases added using the ATTACH command.
98594 **
98595 ** See also sqlite3LocateTable().
98596 */
98597 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
98598  Table *p = 0;
98599  int i;
98600 
98601  /* All mutexes are required for schema access. Make sure we hold them. */
98602  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
98603 #if SQLITE_USER_AUTHENTICATION
98604  /* Only the admin user is allowed to know that the sqlite_user table
98605  ** exists */
98606  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
98607  return 0;
98608  }
98609 #endif
98610  for(i=OMIT_TEMPDB; i<db->nDb; i++){
98611  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
98612  if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
98613  assert( sqlite3SchemaMutexHeld(db, j, 0) );
98614  p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
98615  if( p ) break;
98616  }
98617  }
98618  return p;
98619 }
98620 
98621 /*
98622 ** Locate the in-memory structure that describes a particular database
98623 ** table given the name of that table and (optionally) the name of the
98624 ** database containing the table. Return NULL if not found. Also leave an
98625 ** error message in pParse->zErrMsg.
98626 **
98627 ** The difference between this routine and sqlite3FindTable() is that this
98628 ** routine leaves an error message in pParse->zErrMsg where
98629 ** sqlite3FindTable() does not.
98630 */
98632  Parse *pParse, /* context in which to report errors */
98633  u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
98634  const char *zName, /* Name of the table we are looking for */
98635  const char *zDbase /* Name of the database. Might be NULL */
98636 ){
98637  Table *p;
98638 
98639  /* Read the database schema. If an error occurs, leave an error message
98640  ** and code in pParse and return NULL. */
98641  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
98642  return 0;
98643  }
98644 
98645  p = sqlite3FindTable(pParse->db, zName, zDbase);
98646  if( p==0 ){
98647  const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
98648 #ifndef SQLITE_OMIT_VIRTUALTABLE
98649  if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
98650  /* If zName is the not the name of a table in the schema created using
98651  ** CREATE, then check to see if it is the name of an virtual table that
98652  ** can be an eponymous virtual table. */
98653  Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
98654  if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
98655  return pMod->pEpoTab;
98656  }
98657  }
98658 #endif
98659  if( (flags & LOCATE_NOERR)==0 ){
98660  if( zDbase ){
98661  sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
98662  }else{
98663  sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
98664  }
98665  pParse->checkSchema = 1;
98666  }
98667  }
98668 
98669  return p;
98670 }
98671 
98672 /*
98673 ** Locate the table identified by *p.
98674 **
98675 ** This is a wrapper around sqlite3LocateTable(). The difference between
98676 ** sqlite3LocateTable() and this function is that this function restricts
98677 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
98678 ** non-NULL if it is part of a view or trigger program definition. See
98679 ** sqlite3FixSrcList() for details.
98680 */
98682  Parse *pParse,
98683  u32 flags,
98684  struct SrcList_item *p
98685 ){
98686  const char *zDb;
98687  assert( p->pSchema==0 || p->zDatabase==0 );
98688  if( p->pSchema ){
98689  int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
98690  zDb = pParse->db->aDb[iDb].zDbSName;
98691  }else{
98692  zDb = p->zDatabase;
98693  }
98694  return sqlite3LocateTable(pParse, flags, p->zName, zDb);
98695 }
98696 
98697 /*
98698 ** Locate the in-memory structure that describes
98699 ** a particular index given the name of that index
98700 ** and the name of the database that contains the index.
98701 ** Return NULL if not found.
98702 **
98703 ** If zDatabase is 0, all databases are searched for the
98704 ** table and the first matching index is returned. (No checking
98705 ** for duplicate index names is done.) The search order is
98706 ** TEMP first, then MAIN, then any auxiliary databases added
98707 ** using the ATTACH command.
98708 */
98709 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
98710  Index *p = 0;
98711  int i;
98712  /* All mutexes are required for schema access. Make sure we hold them. */
98713  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
98714  for(i=OMIT_TEMPDB; i<db->nDb; i++){
98715  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
98716  Schema *pSchema = db->aDb[j].pSchema;
98717  assert( pSchema );
98718  if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
98719  assert( sqlite3SchemaMutexHeld(db, j, 0) );
98720  p = sqlite3HashFind(&pSchema->idxHash, zName);
98721  if( p ) break;
98722  }
98723  return p;
98724 }
98725 
98726 /*
98727 ** Reclaim the memory used by an index
98728 */
98729 static void freeIndex(sqlite3 *db, Index *p){
98730 #ifndef SQLITE_OMIT_ANALYZE
98732 #endif
98735  sqlite3DbFree(db, p->zColAff);
98736  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
98737 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
98738  sqlite3_free(p->aiRowEst);
98739 #endif
98740  sqlite3DbFree(db, p);
98741 }
98742 
98743 /*
98744 ** For the index called zIdxName which is found in the database iDb,
98745 ** unlike that index from its Table then remove the index from
98746 ** the index hash table and free all memory structures associated
98747 ** with the index.
98748 */
98749 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
98750  Index *pIndex;
98751  Hash *pHash;
98752 
98753  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98754  pHash = &db->aDb[iDb].pSchema->idxHash;
98755  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
98756  if( ALWAYS(pIndex) ){
98757  if( pIndex->pTable->pIndex==pIndex ){
98758  pIndex->pTable->pIndex = pIndex->pNext;
98759  }else{
98760  Index *p;
98761  /* Justification of ALWAYS(); The index must be on the list of
98762  ** indices. */
98763  p = pIndex->pTable->pIndex;
98764  while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
98765  if( ALWAYS(p && p->pNext==pIndex) ){
98766  p->pNext = pIndex->pNext;
98767  }
98768  }
98769  freeIndex(db, pIndex);
98770  }
98771  db->flags |= SQLITE_InternChanges;
98772 }
98773 
98774 /*
98775 ** Look through the list of open database files in db->aDb[] and if
98776 ** any have been closed, remove them from the list. Reallocate the
98777 ** db->aDb[] structure to a smaller size, if possible.
98778 **
98779 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
98780 ** are never candidates for being collapsed.
98781 */
98783  int i, j;
98784  for(i=j=2; i<db->nDb; i++){
98785  struct Db *pDb = &db->aDb[i];
98786  if( pDb->pBt==0 ){
98787  sqlite3DbFree(db, pDb->zDbSName);
98788  pDb->zDbSName = 0;
98789  continue;
98790  }
98791  if( j<i ){
98792  db->aDb[j] = db->aDb[i];
98793  }
98794  j++;
98795  }
98796  db->nDb = j;
98797  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
98798  memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
98799  sqlite3DbFree(db, db->aDb);
98800  db->aDb = db->aDbStatic;
98801  }
98802 }
98803 
98804 /*
98805 ** Reset the schema for the database at index iDb. Also reset the
98806 ** TEMP schema.
98807 */
98809  Db *pDb;
98810  assert( iDb<db->nDb );
98811 
98812  /* Case 1: Reset the single schema identified by iDb */
98813  pDb = &db->aDb[iDb];
98814  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98815  assert( pDb->pSchema!=0 );
98817 
98818  /* If any database other than TEMP is reset, then also reset TEMP
98819  ** since TEMP might be holding triggers that reference tables in the
98820  ** other database.
98821  */
98822  if( iDb!=1 ){
98823  pDb = &db->aDb[1];
98824  assert( pDb->pSchema!=0 );
98826  }
98827  return;
98828 }
98829 
98830 /*
98831 ** Erase all schema information from all attached databases (including
98832 ** "main" and "temp") for a single database connection.
98833 */
98835  int i;
98837  for(i=0; i<db->nDb; i++){
98838  Db *pDb = &db->aDb[i];
98839  if( pDb->pSchema ){
98841  }
98842  }
98843  db->flags &= ~SQLITE_InternChanges;
98847 }
98848 
98849 /*
98850 ** This routine is called when a commit occurs.
98851 */
98853  db->flags &= ~SQLITE_InternChanges;
98854 }
98855 
98856 /*
98857 ** Delete memory allocated for the column names of a table or view (the
98858 ** Table.aCol[] array).
98859 */
98861  int i;
98862  Column *pCol;
98863  assert( pTable!=0 );
98864  if( (pCol = pTable->aCol)!=0 ){
98865  for(i=0; i<pTable->nCol; i++, pCol++){
98866  sqlite3DbFree(db, pCol->zName);
98867  sqlite3ExprDelete(db, pCol->pDflt);
98868  sqlite3DbFree(db, pCol->zColl);
98869  }
98870  sqlite3DbFree(db, pTable->aCol);
98871  }
98872 }
98873 
98874 /*
98875 ** Remove the memory data structures associated with the given
98876 ** Table. No changes are made to disk by this routine.
98877 **
98878 ** This routine just deletes the data structure. It does not unlink
98879 ** the table data structure from the hash table. But it does destroy
98880 ** memory structures of the indices and foreign keys associated with
98881 ** the table.
98882 **
98883 ** The db parameter is optional. It is needed if the Table object
98884 ** contains lookaside memory. (Table objects in the schema do not use
98885 ** lookaside memory, but some ephemeral Table objects do.) Or the
98886 ** db parameter can be used with db->pnBytesFreed to measure the memory
98887 ** used by the Table object.
98888 */
98889 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
98890  Index *pIndex, *pNext;
98891  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
98892 
98893  /* Record the number of outstanding lookaside allocations in schema Tables
98894  ** prior to doing any free() operations. Since schema Tables do not use
98895  ** lookaside, this number should not change. */
98896  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
98897  db->lookaside.nOut : 0 );
98898 
98899  /* Delete all indices associated with this table. */
98900  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
98901  pNext = pIndex->pNext;
98902  assert( pIndex->pSchema==pTable->pSchema
98903  || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
98904  if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
98905  char *zName = pIndex->zName;
98906  TESTONLY ( Index *pOld = ) sqlite3HashInsert(
98907  &pIndex->pSchema->idxHash, zName, 0
98908  );
98909  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
98910  assert( pOld==pIndex || pOld==0 );
98911  }
98912  freeIndex(db, pIndex);
98913  }
98914 
98915  /* Delete any foreign keys attached to this table. */
98916  sqlite3FkDelete(db, pTable);
98917 
98918  /* Delete the Table structure itself.
98919  */
98920  sqlite3DeleteColumnNames(db, pTable);
98921  sqlite3DbFree(db, pTable->zName);
98922  sqlite3DbFree(db, pTable->zColAff);
98923  sqlite3SelectDelete(db, pTable->pSelect);
98924  sqlite3ExprListDelete(db, pTable->pCheck);
98925 #ifndef SQLITE_OMIT_VIRTUALTABLE
98926  sqlite3VtabClear(db, pTable);
98927 #endif
98928  sqlite3DbFree(db, pTable);
98929 
98930  /* Verify that no lookaside memory was used by schema tables */
98931  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
98932 }
98934  /* Do not delete the table until the reference count reaches zero. */
98935  if( !pTable ) return;
98936  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
98937  deleteTable(db, pTable);
98938 }
98939 
98940 
98941 /*
98942 ** Unlink the given table from the hash tables and the delete the
98943 ** table structure with all its indices and foreign keys.
98944 */
98945 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
98946  Table *p;
98947  Db *pDb;
98948 
98949  assert( db!=0 );
98950  assert( iDb>=0 && iDb<db->nDb );
98951  assert( zTabName );
98952  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98953  testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
98954  pDb = &db->aDb[iDb];
98955  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
98956  sqlite3DeleteTable(db, p);
98957  db->flags |= SQLITE_InternChanges;
98958 }
98959 
98960 /*
98961 ** Given a token, return a string that consists of the text of that
98962 ** token. Space to hold the returned string
98963 ** is obtained from sqliteMalloc() and must be freed by the calling
98964 ** function.
98965 **
98966 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
98967 ** surround the body of the token are removed.
98968 **
98969 ** Tokens are often just pointers into the original SQL text and so
98970 ** are not \000 terminated and are not persistent. The returned string
98971 ** is \000 terminated and is persistent.
98972 */
98974  char *zName;
98975  if( pName ){
98976  zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
98977  sqlite3Dequote(zName);
98978  }else{
98979  zName = 0;
98980  }
98981  return zName;
98982 }
98983 
98984 /*
98985 ** Open the sqlite_master table stored in database number iDb for
98986 ** writing. The table is opened using cursor 0.
98987 */
98989  Vdbe *v = sqlite3GetVdbe(p);
98990  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
98992  if( p->nTab==0 ){
98993  p->nTab = 1;
98994  }
98995 }
98996 
98997 /*
98998 ** Parameter zName points to a nul-terminated buffer containing the name
98999 ** of a database ("main", "temp" or the name of an attached db). This
99000 ** function returns the index of the named database in db->aDb[], or
99001 ** -1 if the named db cannot be found.
99002 */
99003 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
99004  int i = -1; /* Database number */
99005  if( zName ){
99006  Db *pDb;
99007  for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
99008  if( 0==sqlite3StrICmp(pDb->zDbSName, zName) ) break;
99009  }
99010  }
99011  return i;
99012 }
99013 
99014 /*
99015 ** The token *pName contains the name of a database (either "main" or
99016 ** "temp" or the name of an attached db). This routine returns the
99017 ** index of the named database in db->aDb[], or -1 if the named db
99018 ** does not exist.
99019 */
99021  int i; /* Database number */
99022  char *zName; /* Name we are searching for */
99023  zName = sqlite3NameFromToken(db, pName);
99024  i = sqlite3FindDbName(db, zName);
99025  sqlite3DbFree(db, zName);
99026  return i;
99027 }
99028 
99029 /* The table or view or trigger name is passed to this routine via tokens
99030 ** pName1 and pName2. If the table name was fully qualified, for example:
99031 **
99032 ** CREATE TABLE xxx.yyy (...);
99033 **
99034 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
99035 ** the table name is not fully qualified, i.e.:
99036 **
99037 ** CREATE TABLE yyy(...);
99038 **
99039 ** Then pName1 is set to "yyy" and pName2 is "".
99040 **
99041 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
99042 ** pName2) that stores the unqualified table name. The index of the
99043 ** database "xxx" is returned.
99044 */
99046  Parse *pParse, /* Parsing and code generating context */
99047  Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
99048  Token *pName2, /* The "yyy" in the name "xxx.yyy" */
99049  Token **pUnqual /* Write the unqualified object name here */
99050 ){
99051  int iDb; /* Database holding the object */
99052  sqlite3 *db = pParse->db;
99053 
99054  assert( pName2!=0 );
99055  if( pName2->n>0 ){
99056  if( db->init.busy ) {
99057  sqlite3ErrorMsg(pParse, "corrupt database");
99058  return -1;
99059  }
99060  *pUnqual = pName2;
99061  iDb = sqlite3FindDb(db, pName1);
99062  if( iDb<0 ){
99063  sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
99064  return -1;
99065  }
99066  }else{
99067  assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0);
99068  iDb = db->init.iDb;
99069  *pUnqual = pName1;
99070  }
99071  return iDb;
99072 }
99073 
99074 /*
99075 ** This routine is used to check if the UTF-8 string zName is a legal
99076 ** unqualified name for a new schema object (table, index, view or
99077 ** trigger). All names are legal except those that begin with the string
99078 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
99079 ** is reserved for internal use.
99080 */
99081 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
99082  if( !pParse->db->init.busy && pParse->nested==0
99083  && (pParse->db->flags & SQLITE_WriteSchema)==0
99084  && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
99085  sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
99086  return SQLITE_ERROR;
99087  }
99088  return SQLITE_OK;
99089 }
99090 
99091 /*
99092 ** Return the PRIMARY KEY index of a table
99093 */
99095  Index *p;
99096  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
99097  return p;
99098 }
99099 
99100 /*
99101 ** Return the column of index pIdx that corresponds to table
99102 ** column iCol. Return -1 if not found.
99103 */
99105  int i;
99106  for(i=0; i<pIdx->nColumn; i++){
99107  if( iCol==pIdx->aiColumn[i] ) return i;
99108  }
99109  return -1;
99110 }
99111 
99112 /*
99113 ** Begin constructing a new table representation in memory. This is
99114 ** the first of several action routines that get called in response
99115 ** to a CREATE TABLE statement. In particular, this routine is called
99116 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
99117 ** flag is true if the table should be stored in the auxiliary database
99118 ** file instead of in the main database file. This is normally the case
99119 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
99120 ** CREATE and TABLE.
99121 **
99122 ** The new table record is initialized and put in pParse->pNewTable.
99123 ** As more of the CREATE TABLE statement is parsed, additional action
99124 ** routines will be called to add more information to this record.
99125 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
99126 ** is called to complete the construction of the new table record.
99127 */
99129  Parse *pParse, /* Parser context */
99130  Token *pName1, /* First part of the name of the table or view */
99131  Token *pName2, /* Second part of the name of the table or view */
99132  int isTemp, /* True if this is a TEMP table */
99133  int isView, /* True if this is a VIEW */
99134  int isVirtual, /* True if this is a VIRTUAL table */
99135  int noErr /* Do nothing if table already exists */
99136 ){
99137  Table *pTable;
99138  char *zName = 0; /* The name of the new table */
99139  sqlite3 *db = pParse->db;
99140  Vdbe *v;
99141  int iDb; /* Database number to create the table in */
99142  Token *pName; /* Unqualified name of the table to create */
99143 
99144  if( db->init.busy && db->init.newTnum==1 ){
99145  /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
99146  iDb = db->init.iDb;
99147  zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
99148  pName = pName1;
99149  }else{
99150  /* The common case */
99151  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99152  if( iDb<0 ) return;
99153  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
99154  /* If creating a temp table, the name may not be qualified. Unless
99155  ** the database name is "temp" anyway. */
99156  sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
99157  return;
99158  }
99159  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
99160  zName = sqlite3NameFromToken(db, pName);
99161  }
99162  pParse->sNameToken = *pName;
99163  if( zName==0 ) return;
99164  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99165  goto begin_table_error;
99166  }
99167  if( db->init.iDb==1 ) isTemp = 1;
99168 #ifndef SQLITE_OMIT_AUTHORIZATION
99169  assert( isTemp==0 || isTemp==1 );
99170  assert( isView==0 || isView==1 );
99171  {
99172  static const u8 aCode[] = {
99177  };
99178  char *zDb = db->aDb[iDb].zDbSName;
99179  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
99180  goto begin_table_error;
99181  }
99182  if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
99183  zName, 0, zDb) ){
99184  goto begin_table_error;
99185  }
99186  }
99187 #endif
99188 
99189  /* Make sure the new table name does not collide with an existing
99190  ** index or table name in the same database. Issue an error message if
99191  ** it does. The exception is if the statement being parsed was passed
99192  ** to an sqlite3_declare_vtab() call. In that case only the column names
99193  ** and types will be used, so there is no need to test for namespace
99194  ** collisions.
99195  */
99196  if( !IN_DECLARE_VTAB ){
99197  char *zDb = db->aDb[iDb].zDbSName;
99198  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99199  goto begin_table_error;
99200  }
99201  pTable = sqlite3FindTable(db, zName, zDb);
99202  if( pTable ){
99203  if( !noErr ){
99204  sqlite3ErrorMsg(pParse, "table %T already exists", pName);
99205  }else{
99206  assert( !db->init.busy || CORRUPT_DB );
99207  sqlite3CodeVerifySchema(pParse, iDb);
99208  }
99209  goto begin_table_error;
99210  }
99211  if( sqlite3FindIndex(db, zName, zDb)!=0 ){
99212  sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
99213  goto begin_table_error;
99214  }
99215  }
99216 
99217  pTable = sqlite3DbMallocZero(db, sizeof(Table));
99218  if( pTable==0 ){
99219  assert( db->mallocFailed );
99220  pParse->rc = SQLITE_NOMEM_BKPT;
99221  pParse->nErr++;
99222  goto begin_table_error;
99223  }
99224  pTable->zName = zName;
99225  pTable->iPKey = -1;
99226  pTable->pSchema = db->aDb[iDb].pSchema;
99227  pTable->nRef = 1;
99228  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
99229  assert( pParse->pNewTable==0 );
99230  pParse->pNewTable = pTable;
99231 
99232  /* If this is the magic sqlite_sequence table used by autoincrement,
99233  ** then record a pointer to this table in the main database structure
99234  ** so that INSERT can find the table easily.
99235  */
99236 #ifndef SQLITE_OMIT_AUTOINCREMENT
99237  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
99238  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99239  pTable->pSchema->pSeqTab = pTable;
99240  }
99241 #endif
99242 
99243  /* Begin generating the code that will insert the table record into
99244  ** the SQLITE_MASTER table. Note in particular that we must go ahead
99245  ** and allocate the record number for the table entry now. Before any
99246  ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
99247  ** indices to be created and the table record must come before the
99248  ** indices. Hence, the record number for the table must be allocated
99249  ** now.
99250  */
99251  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
99252  int addr1;
99253  int fileFormat;
99254  int reg1, reg2, reg3;
99255  /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
99256  static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
99257  sqlite3BeginWriteOperation(pParse, 1, iDb);
99258 
99259 #ifndef SQLITE_OMIT_VIRTUALTABLE
99260  if( isVirtual ){
99262  }
99263 #endif
99264 
99265  /* If the file format and encoding in the database have not been set,
99266  ** set them now.
99267  */
99268  reg1 = pParse->regRowid = ++pParse->nMem;
99269  reg2 = pParse->regRoot = ++pParse->nMem;
99270  reg3 = ++pParse->nMem;
99272  sqlite3VdbeUsesBtree(v, iDb);
99273  addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
99274  fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
99276  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
99278  sqlite3VdbeJumpHere(v, addr1);
99279 
99280  /* This just creates a place-holder record in the sqlite_master table.
99281  ** The record created does not contain anything yet. It will be replaced
99282  ** by the real entry in code generated at sqlite3EndTable().
99283  **
99284  ** The rowid for the new entry is left in register pParse->regRowid.
99285  ** The root page number of the new table is left in reg pParse->regRoot.
99286  ** The rowid and root page number values are needed by the code that
99287  ** sqlite3EndTable will generate.
99288  */
99289 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
99290  if( isView || isVirtual ){
99291  sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
99292  }else
99293 #endif
99294  {
99295  pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
99296  }
99297  sqlite3OpenMasterTable(pParse, iDb);
99298  sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
99299  sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
99300  sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
99303  }
99304 
99305  /* Normal (non-error) return. */
99306  return;
99307 
99308  /* If an error occurs, we jump here */
99309 begin_table_error:
99310  sqlite3DbFree(db, zName);
99311  return;
99312 }
99313 
99314 /* Set properties of a table column based on the (magical)
99315 ** name of the column.
99316 */
99317 #if SQLITE_ENABLE_HIDDEN_COLUMNS
99319  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
99320  pCol->colFlags |= COLFLAG_HIDDEN;
99321  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
99322  pTab->tabFlags |= TF_OOOHidden;
99323  }
99324 }
99325 #endif
99326 
99327 
99328 /*
99329 ** Add a new column to the table currently being constructed.
99330 **
99331 ** The parser calls this routine once for each column declaration
99332 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
99333 ** first to get things going. Then this routine is called for each
99334 ** column.
99335 */
99336 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
99337  Table *p;
99338  int i;
99339  char *z;
99340  char *zType;
99341  Column *pCol;
99342  sqlite3 *db = pParse->db;
99343  if( (p = pParse->pNewTable)==0 ) return;
99344 #if SQLITE_MAX_COLUMN
99345  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
99346  sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
99347  return;
99348  }
99349 #endif
99350  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
99351  if( z==0 ) return;
99352  memcpy(z, pName->z, pName->n);
99353  z[pName->n] = 0;
99354  sqlite3Dequote(z);
99355  for(i=0; i<p->nCol; i++){
99356  if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
99357  sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
99358  sqlite3DbFree(db, z);
99359  return;
99360  }
99361  }
99362  if( (p->nCol & 0x7)==0 ){
99363  Column *aNew;
99364  aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
99365  if( aNew==0 ){
99366  sqlite3DbFree(db, z);
99367  return;
99368  }
99369  p->aCol = aNew;
99370  }
99371  pCol = &p->aCol[p->nCol];
99372  memset(pCol, 0, sizeof(p->aCol[0]));
99373  pCol->zName = z;
99375 
99376  if( pType->n==0 ){
99377  /* If there is no type specified, columns have the default affinity
99378  ** 'BLOB'. */
99379  pCol->affinity = SQLITE_AFF_BLOB;
99380  pCol->szEst = 1;
99381  }else{
99382  zType = z + sqlite3Strlen30(z) + 1;
99383  memcpy(zType, pType->z, pType->n);
99384  zType[pType->n] = 0;
99385  sqlite3Dequote(zType);
99386  pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
99387  pCol->colFlags |= COLFLAG_HASTYPE;
99388  }
99389  p->nCol++;
99390  pParse->constraintName.n = 0;
99391 }
99392 
99393 /*
99394 ** This routine is called by the parser while in the middle of
99395 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
99396 ** been seen on a column. This routine sets the notNull flag on
99397 ** the column currently under construction.
99398 */
99399 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
99400  Table *p;
99401  p = pParse->pNewTable;
99402  if( p==0 || NEVER(p->nCol<1) ) return;
99403  p->aCol[p->nCol-1].notNull = (u8)onError;
99404 }
99405 
99406 /*
99407 ** Scan the column type name zType (length nType) and return the
99408 ** associated affinity type.
99409 **
99410 ** This routine does a case-independent search of zType for the
99411 ** substrings in the following table. If one of the substrings is
99412 ** found, the corresponding affinity is returned. If zType contains
99413 ** more than one of the substrings, entries toward the top of
99414 ** the table take priority. For example, if zType is 'BLOBINT',
99415 ** SQLITE_AFF_INTEGER is returned.
99416 **
99417 ** Substring | Affinity
99418 ** --------------------------------
99419 ** 'INT' | SQLITE_AFF_INTEGER
99420 ** 'CHAR' | SQLITE_AFF_TEXT
99421 ** 'CLOB' | SQLITE_AFF_TEXT
99422 ** 'TEXT' | SQLITE_AFF_TEXT
99423 ** 'BLOB' | SQLITE_AFF_BLOB
99424 ** 'REAL' | SQLITE_AFF_REAL
99425 ** 'FLOA' | SQLITE_AFF_REAL
99426 ** 'DOUB' | SQLITE_AFF_REAL
99427 **
99428 ** If none of the substrings in the above table are found,
99429 ** SQLITE_AFF_NUMERIC is returned.
99430 */
99431 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
99432  u32 h = 0;
99433  char aff = SQLITE_AFF_NUMERIC;
99434  const char *zChar = 0;
99435 
99436  assert( zIn!=0 );
99437  while( zIn[0] ){
99438  h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
99439  zIn++;
99440  if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
99441  aff = SQLITE_AFF_TEXT;
99442  zChar = zIn;
99443  }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
99444  aff = SQLITE_AFF_TEXT;
99445  }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
99446  aff = SQLITE_AFF_TEXT;
99447  }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
99448  && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
99449  aff = SQLITE_AFF_BLOB;
99450  if( zIn[0]=='(' ) zChar = zIn;
99451 #ifndef SQLITE_OMIT_FLOATING_POINT
99452  }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
99453  && aff==SQLITE_AFF_NUMERIC ){
99454  aff = SQLITE_AFF_REAL;
99455  }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
99456  && aff==SQLITE_AFF_NUMERIC ){
99457  aff = SQLITE_AFF_REAL;
99458  }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
99459  && aff==SQLITE_AFF_NUMERIC ){
99460  aff = SQLITE_AFF_REAL;
99461 #endif
99462  }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
99463  aff = SQLITE_AFF_INTEGER;
99464  break;
99465  }
99466  }
99467 
99468  /* If pszEst is not NULL, store an estimate of the field size. The
99469  ** estimate is scaled so that the size of an integer is 1. */
99470  if( pszEst ){
99471  *pszEst = 1; /* default size is approx 4 bytes */
99472  if( aff<SQLITE_AFF_NUMERIC ){
99473  if( zChar ){
99474  while( zChar[0] ){
99475  if( sqlite3Isdigit(zChar[0]) ){
99476  int v = 0;
99477  sqlite3GetInt32(zChar, &v);
99478  v = v/4 + 1;
99479  if( v>255 ) v = 255;
99480  *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
99481  break;
99482  }
99483  zChar++;
99484  }
99485  }else{
99486  *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
99487  }
99488  }
99489  }
99490  return aff;
99491 }
99492 
99493 /*
99494 ** The expression is the default value for the most recently added column
99495 ** of the table currently under construction.
99496 **
99497 ** Default value expressions must be constant. Raise an exception if this
99498 ** is not the case.
99499 **
99500 ** This routine is called by the parser while in the middle of
99501 ** parsing a CREATE TABLE statement.
99502 */
99504  Table *p;
99505  Column *pCol;
99506  sqlite3 *db = pParse->db;
99507  p = pParse->pNewTable;
99508  if( p!=0 ){
99509  pCol = &(p->aCol[p->nCol-1]);
99510  if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
99511  sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
99512  pCol->zName);
99513  }else{
99514  /* A copy of pExpr is used instead of the original, as pExpr contains
99515  ** tokens that point to volatile memory. The 'span' of the expression
99516  ** is required by pragma table_info.
99517  */
99518  Expr x;
99519  sqlite3ExprDelete(db, pCol->pDflt);
99520  memset(&x, 0, sizeof(x));
99521  x.op = TK_SPAN;
99522  x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
99523  (int)(pSpan->zEnd - pSpan->zStart));
99524  x.pLeft = pSpan->pExpr;
99525  x.flags = EP_Skip;
99526  pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
99527  sqlite3DbFree(db, x.u.zToken);
99528  }
99529  }
99530  sqlite3ExprDelete(db, pSpan->pExpr);
99531 }
99532 
99533 /*
99534 ** Backwards Compatibility Hack:
99535 **
99536 ** Historical versions of SQLite accepted strings as column names in
99537 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
99538 **
99539 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
99540 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
99541 **
99542 ** This is goofy. But to preserve backwards compatibility we continue to
99543 ** accept it. This routine does the necessary conversion. It converts
99544 ** the expression given in its argument from a TK_STRING into a TK_ID
99545 ** if the expression is just a TK_STRING with an optional COLLATE clause.
99546 ** If the epxression is anything other than TK_STRING, the expression is
99547 ** unchanged.
99548 */
99549 static void sqlite3StringToId(Expr *p){
99550  if( p->op==TK_STRING ){
99551  p->op = TK_ID;
99552  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
99553  p->pLeft->op = TK_ID;
99554  }
99555 }
99556 
99557 /*
99558 ** Designate the PRIMARY KEY for the table. pList is a list of names
99559 ** of columns that form the primary key. If pList is NULL, then the
99560 ** most recently added column of the table is the primary key.
99561 **
99562 ** A table can have at most one primary key. If the table already has
99563 ** a primary key (and this is the second primary key) then create an
99564 ** error.
99565 **
99566 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
99567 ** then we will try to use that column as the rowid. Set the Table.iPKey
99568 ** field of the table under construction to be the index of the
99569 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
99570 ** no INTEGER PRIMARY KEY.
99571 **
99572 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
99573 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
99574 */
99576  Parse *pParse, /* Parsing context */
99577  ExprList *pList, /* List of field names to be indexed */
99578  int onError, /* What to do with a uniqueness conflict */
99579  int autoInc, /* True if the AUTOINCREMENT keyword is present */
99580  int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
99581 ){
99582  Table *pTab = pParse->pNewTable;
99583  Column *pCol = 0;
99584  int iCol = -1, i;
99585  int nTerm;
99586  if( pTab==0 ) goto primary_key_exit;
99587  if( pTab->tabFlags & TF_HasPrimaryKey ){
99588  sqlite3ErrorMsg(pParse,
99589  "table \"%s\" has more than one primary key", pTab->zName);
99590  goto primary_key_exit;
99591  }
99592  pTab->tabFlags |= TF_HasPrimaryKey;
99593  if( pList==0 ){
99594  iCol = pTab->nCol - 1;
99595  pCol = &pTab->aCol[iCol];
99596  pCol->colFlags |= COLFLAG_PRIMKEY;
99597  nTerm = 1;
99598  }else{
99599  nTerm = pList->nExpr;
99600  for(i=0; i<nTerm; i++){
99601  Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
99602  assert( pCExpr!=0 );
99603  sqlite3StringToId(pCExpr);
99604  if( pCExpr->op==TK_ID ){
99605  const char *zCName = pCExpr->u.zToken;
99606  for(iCol=0; iCol<pTab->nCol; iCol++){
99607  if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
99608  pCol = &pTab->aCol[iCol];
99609  pCol->colFlags |= COLFLAG_PRIMKEY;
99610  break;
99611  }
99612  }
99613  }
99614  }
99615  }
99616  if( nTerm==1
99617  && pCol
99618  && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
99619  && sortOrder!=SQLITE_SO_DESC
99620  ){
99621  pTab->iPKey = iCol;
99622  pTab->keyConf = (u8)onError;
99623  assert( autoInc==0 || autoInc==1 );
99624  pTab->tabFlags |= autoInc*TF_Autoincrement;
99625  if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
99626  }else if( autoInc ){
99627 #ifndef SQLITE_OMIT_AUTOINCREMENT
99628  sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
99629  "INTEGER PRIMARY KEY");
99630 #endif
99631  }else{
99632  sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
99633  0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
99634  pList = 0;
99635  }
99636 
99637 primary_key_exit:
99638  sqlite3ExprListDelete(pParse->db, pList);
99639  return;
99640 }
99641 
99642 /*
99643 ** Add a new CHECK constraint to the table currently under construction.
99644 */
99646  Parse *pParse, /* Parsing context */
99647  Expr *pCheckExpr /* The check expression */
99648 ){
99649 #ifndef SQLITE_OMIT_CHECK
99650  Table *pTab = pParse->pNewTable;
99651  sqlite3 *db = pParse->db;
99652  if( pTab && !IN_DECLARE_VTAB
99653  && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
99654  ){
99655  pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
99656  if( pParse->constraintName.n ){
99657  sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
99658  }
99659  }else
99660 #endif
99661  {
99662  sqlite3ExprDelete(pParse->db, pCheckExpr);
99663  }
99664 }
99665 
99666 /*
99667 ** Set the collation function of the most recently parsed table column
99668 ** to the CollSeq given.
99669 */
99671  Table *p;
99672  int i;
99673  char *zColl; /* Dequoted name of collation sequence */
99674  sqlite3 *db;
99675 
99676  if( (p = pParse->pNewTable)==0 ) return;
99677  i = p->nCol-1;
99678  db = pParse->db;
99679  zColl = sqlite3NameFromToken(db, pToken);
99680  if( !zColl ) return;
99681 
99682  if( sqlite3LocateCollSeq(pParse, zColl) ){
99683  Index *pIdx;
99684  sqlite3DbFree(db, p->aCol[i].zColl);
99685  p->aCol[i].zColl = zColl;
99686 
99687  /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
99688  ** then an index may have been created on this column before the
99689  ** collation type was added. Correct this if it is the case.
99690  */
99691  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
99692  assert( pIdx->nKeyCol==1 );
99693  if( pIdx->aiColumn[0]==i ){
99694  pIdx->azColl[0] = p->aCol[i].zColl;
99695  }
99696  }
99697  }else{
99698  sqlite3DbFree(db, zColl);
99699  }
99700 }
99701 
99702 /*
99703 ** This function returns the collation sequence for database native text
99704 ** encoding identified by the string zName, length nName.
99705 **
99706 ** If the requested collation sequence is not available, or not available
99707 ** in the database native encoding, the collation factory is invoked to
99708 ** request it. If the collation factory does not supply such a sequence,
99709 ** and the sequence is available in another text encoding, then that is
99710 ** returned instead.
99711 **
99712 ** If no versions of the requested collations sequence are available, or
99713 ** another error occurs, NULL is returned and an error message written into
99714 ** pParse.
99715 **
99716 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
99717 ** invokes the collation factory if the named collation cannot be found
99718 ** and generates an error message.
99719 **
99720 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
99721 */
99722 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
99723  sqlite3 *db = pParse->db;
99724  u8 enc = ENC(db);
99725  u8 initbusy = db->init.busy;
99726  CollSeq *pColl;
99727 
99728  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
99729  if( !initbusy && (!pColl || !pColl->xCmp) ){
99730  pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
99731  }
99732 
99733  return pColl;
99734 }
99735 
99736 
99737 /*
99738 ** Generate code that will increment the schema cookie.
99739 **
99740 ** The schema cookie is used to determine when the schema for the
99741 ** database changes. After each schema change, the cookie value
99742 ** changes. When a process first reads the schema it records the
99743 ** cookie. Thereafter, whenever it goes to access the database,
99744 ** it checks the cookie to make sure the schema has not changed
99745 ** since it was last read.
99746 **
99747 ** This plan is not completely bullet-proof. It is possible for
99748 ** the schema to change multiple times and for the cookie to be
99749 ** set back to prior value. But schema changes are infrequent
99750 ** and the probability of hitting the same cookie value is only
99751 ** 1 chance in 2^32. So we're safe enough.
99752 **
99753 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
99754 ** the schema-version whenever the schema changes.
99755 */
99757  sqlite3 *db = pParse->db;
99758  Vdbe *v = pParse->pVdbe;
99759  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99761  db->aDb[iDb].pSchema->schema_cookie+1);
99762 }
99763 
99764 /*
99765 ** Measure the number of characters needed to output the given
99766 ** identifier. The number returned includes any quotes used
99767 ** but does not include the null terminator.
99768 **
99769 ** The estimate is conservative. It might be larger that what is
99770 ** really needed.
99771 */
99772 static int identLength(const char *z){
99773  int n;
99774  for(n=0; *z; n++, z++){
99775  if( *z=='"' ){ n++; }
99776  }
99777  return n + 2;
99778 }
99779 
99780 /*
99781 ** The first parameter is a pointer to an output buffer. The second
99782 ** parameter is a pointer to an integer that contains the offset at
99783 ** which to write into the output buffer. This function copies the
99784 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
99785 ** to the specified offset in the buffer and updates *pIdx to refer
99786 ** to the first byte after the last byte written before returning.
99787 **
99788 ** If the string zSignedIdent consists entirely of alpha-numeric
99789 ** characters, does not begin with a digit and is not an SQL keyword,
99790 ** then it is copied to the output buffer exactly as it is. Otherwise,
99791 ** it is quoted using double-quotes.
99792 */
99793 static void identPut(char *z, int *pIdx, char *zSignedIdent){
99794  unsigned char *zIdent = (unsigned char*)zSignedIdent;
99795  int i, j, needQuote;
99796  i = *pIdx;
99797 
99798  for(j=0; zIdent[j]; j++){
99799  if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
99800  }
99801  needQuote = sqlite3Isdigit(zIdent[0])
99802  || sqlite3KeywordCode(zIdent, j)!=TK_ID
99803  || zIdent[j]!=0
99804  || j==0;
99805 
99806  if( needQuote ) z[i++] = '"';
99807  for(j=0; zIdent[j]; j++){
99808  z[i++] = zIdent[j];
99809  if( zIdent[j]=='"' ) z[i++] = '"';
99810  }
99811  if( needQuote ) z[i++] = '"';
99812  z[i] = 0;
99813  *pIdx = i;
99814 }
99815 
99816 /*
99817 ** Generate a CREATE TABLE statement appropriate for the given
99818 ** table. Memory to hold the text of the statement is obtained
99819 ** from sqliteMalloc() and must be freed by the calling function.
99820 */
99821 static char *createTableStmt(sqlite3 *db, Table *p){
99822  int i, k, n;
99823  char *zStmt;
99824  char *zSep, *zSep2, *zEnd;
99825  Column *pCol;
99826  n = 0;
99827  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
99828  n += identLength(pCol->zName) + 5;
99829  }
99830  n += identLength(p->zName);
99831  if( n<50 ){
99832  zSep = "";
99833  zSep2 = ",";
99834  zEnd = ")";
99835  }else{
99836  zSep = "\n ";
99837  zSep2 = ",\n ";
99838  zEnd = "\n)";
99839  }
99840  n += 35 + 6*p->nCol;
99841  zStmt = sqlite3DbMallocRaw(0, n);
99842  if( zStmt==0 ){
99843  sqlite3OomFault(db);
99844  return 0;
99845  }
99846  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
99847  k = sqlite3Strlen30(zStmt);
99848  identPut(zStmt, &k, p->zName);
99849  zStmt[k++] = '(';
99850  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
99851  static const char * const azType[] = {
99852  /* SQLITE_AFF_BLOB */ "",
99853  /* SQLITE_AFF_TEXT */ " TEXT",
99854  /* SQLITE_AFF_NUMERIC */ " NUM",
99855  /* SQLITE_AFF_INTEGER */ " INT",
99856  /* SQLITE_AFF_REAL */ " REAL"
99857  };
99858  int len;
99859  const char *zType;
99860 
99861  sqlite3_snprintf(n-k, &zStmt[k], zSep);
99862  k += sqlite3Strlen30(&zStmt[k]);
99863  zSep = zSep2;
99864  identPut(zStmt, &k, pCol->zName);
99865  assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
99866  assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
99867  testcase( pCol->affinity==SQLITE_AFF_BLOB );
99868  testcase( pCol->affinity==SQLITE_AFF_TEXT );
99871  testcase( pCol->affinity==SQLITE_AFF_REAL );
99872 
99873  zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
99874  len = sqlite3Strlen30(zType);
99875  assert( pCol->affinity==SQLITE_AFF_BLOB
99876  || pCol->affinity==sqlite3AffinityType(zType, 0) );
99877  memcpy(&zStmt[k], zType, len);
99878  k += len;
99879  assert( k<=n );
99880  }
99881  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
99882  return zStmt;
99883 }
99884 
99885 /*
99886 ** Resize an Index object to hold N columns total. Return SQLITE_OK
99887 ** on success and SQLITE_NOMEM on an OOM error.
99888 */
99889 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
99890  char *zExtra;
99891  int nByte;
99892  if( pIdx->nColumn>=N ) return SQLITE_OK;
99893  assert( pIdx->isResized==0 );
99894  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
99895  zExtra = sqlite3DbMallocZero(db, nByte);
99896  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
99897  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
99898  pIdx->azColl = (const char**)zExtra;
99899  zExtra += sizeof(char*)*N;
99900  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
99901  pIdx->aiColumn = (i16*)zExtra;
99902  zExtra += sizeof(i16)*N;
99903  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
99904  pIdx->aSortOrder = (u8*)zExtra;
99905  pIdx->nColumn = N;
99906  pIdx->isResized = 1;
99907  return SQLITE_OK;
99908 }
99909 
99910 /*
99911 ** Estimate the total row width for a table.
99912 */
99913 static void estimateTableWidth(Table *pTab){
99914  unsigned wTable = 0;
99915  const Column *pTabCol;
99916  int i;
99917  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
99918  wTable += pTabCol->szEst;
99919  }
99920  if( pTab->iPKey<0 ) wTable++;
99921  pTab->szTabRow = sqlite3LogEst(wTable*4);
99922 }
99923 
99924 /*
99925 ** Estimate the average size of a row for an index.
99926 */
99927 static void estimateIndexWidth(Index *pIdx){
99928  unsigned wIndex = 0;
99929  int i;
99930  const Column *aCol = pIdx->pTable->aCol;
99931  for(i=0; i<pIdx->nColumn; i++){
99932  i16 x = pIdx->aiColumn[i];
99933  assert( x<pIdx->pTable->nCol );
99934  wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
99935  }
99936  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
99937 }
99938 
99939 /* Return true if value x is found any of the first nCol entries of aiCol[]
99940 */
99941 static int hasColumn(const i16 *aiCol, int nCol, int x){
99942  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
99943  return 0;
99944 }
99945 
99946 /*
99947 ** This routine runs at the end of parsing a CREATE TABLE statement that
99948 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
99949 ** internal schema data structures and the generated VDBE code so that they
99950 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
99951 ** Changes include:
99952 **
99953 ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
99954 ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is
99955 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
99956 ** data storage is a covering index btree.
99957 ** (3) Bypass the creation of the sqlite_master table entry
99958 ** for the PRIMARY KEY as the primary key index is now
99959 ** identified by the sqlite_master table entry of the table itself.
99960 ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
99961 ** schema to the rootpage from the main table.
99962 ** (5) Add all table columns to the PRIMARY KEY Index object
99963 ** so that the PRIMARY KEY is a covering index. The surplus
99964 ** columns are part of KeyInfo.nXField and are not used for
99965 ** sorting or lookup or uniqueness checks.
99966 ** (6) Replace the rowid tail on all automatically generated UNIQUE
99967 ** indices with the PRIMARY KEY columns.
99968 **
99969 ** For virtual tables, only (1) is performed.
99970 */
99971 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
99972  Index *pIdx;
99973  Index *pPk;
99974  int nPk;
99975  int i, j;
99976  sqlite3 *db = pParse->db;
99977  Vdbe *v = pParse->pVdbe;
99978 
99979  /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
99980  */
99981  if( !db->init.imposterTable ){
99982  for(i=0; i<pTab->nCol; i++){
99983  if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
99984  pTab->aCol[i].notNull = OE_Abort;
99985  }
99986  }
99987  }
99988 
99989  /* The remaining transformations only apply to b-tree tables, not to
99990  ** virtual tables */
99991  if( IN_DECLARE_VTAB ) return;
99992 
99993  /* Convert the OP_CreateTable opcode that would normally create the
99994  ** root-page for the table into an OP_CreateIndex opcode. The index
99995  ** created will become the PRIMARY KEY index.
99996  */
99997  if( pParse->addrCrTab ){
99998  assert( v );
100000  }
100001 
100002  /* Locate the PRIMARY KEY index. Or, if this table was originally
100003  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
100004  */
100005  if( pTab->iPKey>=0 ){
100006  ExprList *pList;
100007  Token ipkToken;
100008  sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
100009  pList = sqlite3ExprListAppend(pParse, 0,
100010  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
100011  if( pList==0 ) return;
100012  pList->a[0].sortOrder = pParse->iPkSortOrder;
100013  assert( pParse->pNewTable==pTab );
100014  sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
100016  if( db->mallocFailed ) return;
100017  pPk = sqlite3PrimaryKeyIndex(pTab);
100018  pTab->iPKey = -1;
100019  }else{
100020  pPk = sqlite3PrimaryKeyIndex(pTab);
100021 
100022  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
100023  ** table entry. This is only required if currently generating VDBE
100024  ** code for a CREATE TABLE (not when parsing one as part of reading
100025  ** a database schema). */
100026  if( v ){
100027  assert( db->init.busy==0 );
100029  }
100030 
100031  /*
100032  ** Remove all redundant columns from the PRIMARY KEY. For example, change
100033  ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
100034  ** code assumes the PRIMARY KEY contains no repeated columns.
100035  */
100036  for(i=j=1; i<pPk->nKeyCol; i++){
100037  if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
100038  pPk->nColumn--;
100039  }else{
100040  pPk->aiColumn[j++] = pPk->aiColumn[i];
100041  }
100042  }
100043  pPk->nKeyCol = j;
100044  }
100045  assert( pPk!=0 );
100046  pPk->isCovering = 1;
100047  if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
100048  nPk = pPk->nKeyCol;
100049 
100050  /* The root page of the PRIMARY KEY is the table root page */
100051  pPk->tnum = pTab->tnum;
100052 
100053  /* Update the in-memory representation of all UNIQUE indices by converting
100054  ** the final rowid column into one or more columns of the PRIMARY KEY.
100055  */
100056  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100057  int n;
100058  if( IsPrimaryKeyIndex(pIdx) ) continue;
100059  for(i=n=0; i<nPk; i++){
100060  if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
100061  }
100062  if( n==0 ){
100063  /* This index is a superset of the primary key */
100064  pIdx->nColumn = pIdx->nKeyCol;
100065  continue;
100066  }
100067  if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
100068  for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
100069  if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
100070  pIdx->aiColumn[j] = pPk->aiColumn[i];
100071  pIdx->azColl[j] = pPk->azColl[i];
100072  j++;
100073  }
100074  }
100075  assert( pIdx->nColumn>=pIdx->nKeyCol+n );
100076  assert( pIdx->nColumn>=j );
100077  }
100078 
100079  /* Add all table columns to the PRIMARY KEY index
100080  */
100081  if( nPk<pTab->nCol ){
100082  if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
100083  for(i=0, j=nPk; i<pTab->nCol; i++){
100084  if( !hasColumn(pPk->aiColumn, j, i) ){
100085  assert( j<pPk->nColumn );
100086  pPk->aiColumn[j] = i;
100087  pPk->azColl[j] = sqlite3StrBINARY;
100088  j++;
100089  }
100090  }
100091  assert( pPk->nColumn==j );
100092  assert( pTab->nCol==j );
100093  }else{
100094  pPk->nColumn = pTab->nCol;
100095  }
100096 }
100097 
100098 /*
100099 ** This routine is called to report the final ")" that terminates
100100 ** a CREATE TABLE statement.
100101 **
100102 ** The table structure that other action routines have been building
100103 ** is added to the internal hash tables, assuming no errors have
100104 ** occurred.
100105 **
100106 ** An entry for the table is made in the master table on disk, unless
100107 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
100108 ** it means we are reading the sqlite_master table because we just
100109 ** connected to the database or because the sqlite_master table has
100110 ** recently changed, so the entry for this table already exists in
100111 ** the sqlite_master table. We do not want to create it again.
100112 **
100113 ** If the pSelect argument is not NULL, it means that this routine
100114 ** was called to create a table generated from a
100115 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
100116 ** the new table will match the result set of the SELECT.
100117 */
100119  Parse *pParse, /* Parse context */
100120  Token *pCons, /* The ',' token after the last column defn. */
100121  Token *pEnd, /* The ')' before options in the CREATE TABLE */
100122  u8 tabOpts, /* Extra table options. Usually 0. */
100123  Select *pSelect /* Select from a "CREATE ... AS SELECT" */
100124 ){
100125  Table *p; /* The new table */
100126  sqlite3 *db = pParse->db; /* The database connection */
100127  int iDb; /* Database in which the table lives */
100128  Index *pIdx; /* An implied index of the table */
100129 
100130  if( pEnd==0 && pSelect==0 ){
100131  return;
100132  }
100133  assert( !db->mallocFailed );
100134  p = pParse->pNewTable;
100135  if( p==0 ) return;
100136 
100137  assert( !db->init.busy || !pSelect );
100138 
100139  /* If the db->init.busy is 1 it means we are reading the SQL off the
100140  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
100141  ** So do not write to the disk again. Extract the root page number
100142  ** for the table from the db->init.newTnum field. (The page number
100143  ** should have been put there by the sqliteOpenCb routine.)
100144  **
100145  ** If the root page number is 1, that means this is the sqlite_master
100146  ** table itself. So mark it read-only.
100147  */
100148  if( db->init.busy ){
100149  p->tnum = db->init.newTnum;
100150  if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
100151  }
100152 
100153  /* Special processing for WITHOUT ROWID Tables */
100154  if( tabOpts & TF_WithoutRowid ){
100155  if( (p->tabFlags & TF_Autoincrement) ){
100156  sqlite3ErrorMsg(pParse,
100157  "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
100158  return;
100159  }
100160  if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
100161  sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
100162  }else{
100163  p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
100164  convertToWithoutRowidTable(pParse, p);
100165  }
100166  }
100167 
100168  iDb = sqlite3SchemaToIndex(db, p->pSchema);
100169 
100170 #ifndef SQLITE_OMIT_CHECK
100171  /* Resolve names in all CHECK constraint expressions.
100172  */
100173  if( p->pCheck ){
100174  sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
100175  }
100176 #endif /* !defined(SQLITE_OMIT_CHECK) */
100177 
100178  /* Estimate the average row size for the table and for all implied indices */
100179  estimateTableWidth(p);
100180  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
100181  estimateIndexWidth(pIdx);
100182  }
100183 
100184  /* If not initializing, then create a record for the new table
100185  ** in the SQLITE_MASTER table of the database.
100186  **
100187  ** If this is a TEMPORARY table, write the entry into the auxiliary
100188  ** file instead of into the main database file.
100189  */
100190  if( !db->init.busy ){
100191  int n;
100192  Vdbe *v;
100193  char *zType; /* "view" or "table" */
100194  char *zType2; /* "VIEW" or "TABLE" */
100195  char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
100196 
100197  v = sqlite3GetVdbe(pParse);
100198  if( NEVER(v==0) ) return;
100199 
100200  sqlite3VdbeAddOp1(v, OP_Close, 0);
100201 
100202  /*
100203  ** Initialize zType for the new view or table.
100204  */
100205  if( p->pSelect==0 ){
100206  /* A regular table */
100207  zType = "table";
100208  zType2 = "TABLE";
100209 #ifndef SQLITE_OMIT_VIEW
100210  }else{
100211  /* A view */
100212  zType = "view";
100213  zType2 = "VIEW";
100214 #endif
100215  }
100216 
100217  /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
100218  ** statement to populate the new table. The root-page number for the
100219  ** new table is in register pParse->regRoot.
100220  **
100221  ** Once the SELECT has been coded by sqlite3Select(), it is in a
100222  ** suitable state to query for the column names and types to be used
100223  ** by the new table.
100224  **
100225  ** A shared-cache write-lock is not required to write to the new table,
100226  ** as a schema-lock must have already been obtained to create it. Since
100227  ** a schema-lock excludes all other database users, the write-lock would
100228  ** be redundant.
100229  */
100230  if( pSelect ){
100231  SelectDest dest; /* Where the SELECT should store results */
100232  int regYield; /* Register holding co-routine entry-point */
100233  int addrTop; /* Top of the co-routine */
100234  int regRec; /* A record to be insert into the new table */
100235  int regRowid; /* Rowid of the next row to insert */
100236  int addrInsLoop; /* Top of the loop for inserting rows */
100237  Table *pSelTab; /* A table that describes the SELECT results */
100238 
100239  regYield = ++pParse->nMem;
100240  regRec = ++pParse->nMem;
100241  regRowid = ++pParse->nMem;
100242  assert(pParse->nTab==1);
100243  sqlite3MayAbort(pParse);
100244  sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
100246  pParse->nTab = 2;
100247  addrTop = sqlite3VdbeCurrentAddr(v) + 1;
100248  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
100249  sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
100250  sqlite3Select(pParse, pSelect, &dest);
100251  sqlite3VdbeEndCoroutine(v, regYield);
100252  sqlite3VdbeJumpHere(v, addrTop - 1);
100253  if( pParse->nErr ) return;
100254  pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
100255  if( pSelTab==0 ) return;
100256  assert( p->aCol==0 );
100257  p->nCol = pSelTab->nCol;
100258  p->aCol = pSelTab->aCol;
100259  pSelTab->nCol = 0;
100260  pSelTab->aCol = 0;
100261  sqlite3DeleteTable(db, pSelTab);
100262  addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
100263  VdbeCoverage(v);
100264  sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
100265  sqlite3TableAffinity(v, p, 0);
100266  sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
100267  sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
100268  sqlite3VdbeGoto(v, addrInsLoop);
100269  sqlite3VdbeJumpHere(v, addrInsLoop);
100270  sqlite3VdbeAddOp1(v, OP_Close, 1);
100271  }
100272 
100273  /* Compute the complete text of the CREATE statement */
100274  if( pSelect ){
100275  zStmt = createTableStmt(db, p);
100276  }else{
100277  Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
100278  n = (int)(pEnd2->z - pParse->sNameToken.z);
100279  if( pEnd2->z[0]!=';' ) n += pEnd2->n;
100280  zStmt = sqlite3MPrintf(db,
100281  "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
100282  );
100283  }
100284 
100285  /* A slot for the record has already been allocated in the
100286  ** SQLITE_MASTER table. We just need to update that slot with all
100287  ** the information we've collected.
100288  */
100289  sqlite3NestedParse(pParse,
100290  "UPDATE %Q.%s "
100291  "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
100292  "WHERE rowid=#%d",
100293  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
100294  zType,
100295  p->zName,
100296  p->zName,
100297  pParse->regRoot,
100298  zStmt,
100299  pParse->regRowid
100300  );
100301  sqlite3DbFree(db, zStmt);
100302  sqlite3ChangeCookie(pParse, iDb);
100303 
100304 #ifndef SQLITE_OMIT_AUTOINCREMENT
100305  /* Check to see if we need to create an sqlite_sequence table for
100306  ** keeping track of autoincrement keys.
100307  */
100308  if( (p->tabFlags & TF_Autoincrement)!=0 ){
100309  Db *pDb = &db->aDb[iDb];
100310  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100311  if( pDb->pSchema->pSeqTab==0 ){
100312  sqlite3NestedParse(pParse,
100313  "CREATE TABLE %Q.sqlite_sequence(name,seq)",
100314  pDb->zDbSName
100315  );
100316  }
100317  }
100318 #endif
100319 
100320  /* Reparse everything to update our internal data structures */
100322  sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
100323  }
100324 
100325 
100326  /* Add the table to the in-memory representation of the database.
100327  */
100328  if( db->init.busy ){
100329  Table *pOld;
100330  Schema *pSchema = p->pSchema;
100331  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100332  pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
100333  if( pOld ){
100334  assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
100335  sqlite3OomFault(db);
100336  return;
100337  }
100338  pParse->pNewTable = 0;
100339  db->flags |= SQLITE_InternChanges;
100340 
100341 #ifndef SQLITE_OMIT_ALTERTABLE
100342  if( !p->pSelect ){
100343  const char *zName = (const char *)pParse->sNameToken.z;
100344  int nName;
100345  assert( !pSelect && pCons && pEnd );
100346  if( pCons->z==0 ){
100347  pCons = pEnd;
100348  }
100349  nName = (int)((const char *)pCons->z - zName);
100350  p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
100351  }
100352 #endif
100353  }
100354 }
100355 
100356 #ifndef SQLITE_OMIT_VIEW
100357 /*
100358 ** The parser calls this routine in order to create a new VIEW
100359 */
100361  Parse *pParse, /* The parsing context */
100362  Token *pBegin, /* The CREATE token that begins the statement */
100363  Token *pName1, /* The token that holds the name of the view */
100364  Token *pName2, /* The token that holds the name of the view */
100365  ExprList *pCNames, /* Optional list of view column names */
100366  Select *pSelect, /* A SELECT statement that will become the new view */
100367  int isTemp, /* TRUE for a TEMPORARY view */
100368  int noErr /* Suppress error messages if VIEW already exists */
100369 ){
100370  Table *p;
100371  int n;
100372  const char *z;
100373  Token sEnd;
100374  DbFixer sFix;
100375  Token *pName = 0;
100376  int iDb;
100377  sqlite3 *db = pParse->db;
100378 
100379  if( pParse->nVar>0 ){
100380  sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
100381  goto create_view_fail;
100382  }
100383  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
100384  p = pParse->pNewTable;
100385  if( p==0 || pParse->nErr ) goto create_view_fail;
100386  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
100387  iDb = sqlite3SchemaToIndex(db, p->pSchema);
100388  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
100389  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
100390 
100391  /* Make a copy of the entire SELECT statement that defines the view.
100392  ** This will force all the Expr.token.z values to be dynamically
100393  ** allocated rather than point to the input string - which means that
100394  ** they will persist after the current sqlite3_exec() call returns.
100395  */
100396  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
100397  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
100398  if( db->mallocFailed ) goto create_view_fail;
100399 
100400  /* Locate the end of the CREATE VIEW statement. Make sEnd point to
100401  ** the end.
100402  */
100403  sEnd = pParse->sLastToken;
100404  assert( sEnd.z[0]!=0 );
100405  if( sEnd.z[0]!=';' ){
100406  sEnd.z += sEnd.n;
100407  }
100408  sEnd.n = 0;
100409  n = (int)(sEnd.z - pBegin->z);
100410  assert( n>0 );
100411  z = pBegin->z;
100412  while( sqlite3Isspace(z[n-1]) ){ n--; }
100413  sEnd.z = &z[n-1];
100414  sEnd.n = 1;
100415 
100416  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
100417  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
100418 
100419 create_view_fail:
100420  sqlite3SelectDelete(db, pSelect);
100421  sqlite3ExprListDelete(db, pCNames);
100422  return;
100423 }
100424 #endif /* SQLITE_OMIT_VIEW */
100425 
100426 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
100427 /*
100428 ** The Table structure pTable is really a VIEW. Fill in the names of
100429 ** the columns of the view in the pTable structure. Return the number
100430 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
100431 */
100433  Table *pSelTab; /* A fake table from which we get the result set */
100434  Select *pSel; /* Copy of the SELECT that implements the view */
100435  int nErr = 0; /* Number of errors encountered */
100436  int n; /* Temporarily holds the number of cursors assigned */
100437  sqlite3 *db = pParse->db; /* Database connection for malloc errors */
100438 #ifndef SQLITE_OMIT_AUTHORIZATION
100439  sqlite3_xauth xAuth; /* Saved xAuth pointer */
100440 #endif
100441 
100442  assert( pTable );
100443 
100444 #ifndef SQLITE_OMIT_VIRTUALTABLE
100445  if( sqlite3VtabCallConnect(pParse, pTable) ){
100446  return SQLITE_ERROR;
100447  }
100448  if( IsVirtual(pTable) ) return 0;
100449 #endif
100450 
100451 #ifndef SQLITE_OMIT_VIEW
100452  /* A positive nCol means the columns names for this view are
100453  ** already known.
100454  */
100455  if( pTable->nCol>0 ) return 0;
100456 
100457  /* A negative nCol is a special marker meaning that we are currently
100458  ** trying to compute the column names. If we enter this routine with
100459  ** a negative nCol, it means two or more views form a loop, like this:
100460  **
100461  ** CREATE VIEW one AS SELECT * FROM two;
100462  ** CREATE VIEW two AS SELECT * FROM one;
100463  **
100464  ** Actually, the error above is now caught prior to reaching this point.
100465  ** But the following test is still important as it does come up
100466  ** in the following:
100467  **
100468  ** CREATE TABLE main.ex1(a);
100469  ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
100470  ** SELECT * FROM temp.ex1;
100471  */
100472  if( pTable->nCol<0 ){
100473  sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
100474  return 1;
100475  }
100476  assert( pTable->nCol>=0 );
100477 
100478  /* If we get this far, it means we need to compute the table names.
100479  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
100480  ** "*" elements in the results set of the view and will assign cursors
100481  ** to the elements of the FROM clause. But we do not want these changes
100482  ** to be permanent. So the computation is done on a copy of the SELECT
100483  ** statement that defines the view.
100484  */
100485  assert( pTable->pSelect );
100486  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
100487  if( pSel ){
100488  n = pParse->nTab;
100489  sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
100490  pTable->nCol = -1;
100491  db->lookaside.bDisable++;
100492 #ifndef SQLITE_OMIT_AUTHORIZATION
100493  xAuth = db->xAuth;
100494  db->xAuth = 0;
100495  pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
100496  db->xAuth = xAuth;
100497 #else
100498  pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
100499 #endif
100500  pParse->nTab = n;
100501  if( pTable->pCheck ){
100502  /* CREATE VIEW name(arglist) AS ...
100503  ** The names of the columns in the table are taken from
100504  ** arglist which is stored in pTable->pCheck. The pCheck field
100505  ** normally holds CHECK constraints on an ordinary table, but for
100506  ** a VIEW it holds the list of column names.
100507  */
100508  sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
100509  &pTable->nCol, &pTable->aCol);
100510  if( db->mallocFailed==0
100511  && pParse->nErr==0
100512  && pTable->nCol==pSel->pEList->nExpr
100513  ){
100514  sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
100515  }
100516  }else if( pSelTab ){
100517  /* CREATE VIEW name AS... without an argument list. Construct
100518  ** the column names from the SELECT statement that defines the view.
100519  */
100520  assert( pTable->aCol==0 );
100521  pTable->nCol = pSelTab->nCol;
100522  pTable->aCol = pSelTab->aCol;
100523  pSelTab->nCol = 0;
100524  pSelTab->aCol = 0;
100525  assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
100526  }else{
100527  pTable->nCol = 0;
100528  nErr++;
100529  }
100530  sqlite3DeleteTable(db, pSelTab);
100531  sqlite3SelectDelete(db, pSel);
100532  db->lookaside.bDisable--;
100533  } else {
100534  nErr++;
100535  }
100536  pTable->pSchema->schemaFlags |= DB_UnresetViews;
100537 #endif /* SQLITE_OMIT_VIEW */
100538  return nErr;
100539 }
100540 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
100541 
100542 #ifndef SQLITE_OMIT_VIEW
100543 /*
100544 ** Clear the column names from every VIEW in database idx.
100545 */
100546 static void sqliteViewResetAll(sqlite3 *db, int idx){
100547  HashElem *i;
100548  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
100549  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
100550  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
100551  Table *pTab = sqliteHashData(i);
100552  if( pTab->pSelect ){
100553  sqlite3DeleteColumnNames(db, pTab);
100554  pTab->aCol = 0;
100555  pTab->nCol = 0;
100556  }
100557  }
100558  DbClearProperty(db, idx, DB_UnresetViews);
100559 }
100560 #else
100561 # define sqliteViewResetAll(A,B)
100562 #endif /* SQLITE_OMIT_VIEW */
100563 
100564 /*
100565 ** This function is called by the VDBE to adjust the internal schema
100566 ** used by SQLite when the btree layer moves a table root page. The
100567 ** root-page of a table or index in database iDb has changed from iFrom
100568 ** to iTo.
100569 **
100570 ** Ticket #1728: The symbol table might still contain information
100571 ** on tables and/or indices that are the process of being deleted.
100572 ** If you are unlucky, one of those deleted indices or tables might
100573 ** have the same rootpage number as the real table or index that is
100574 ** being moved. So we cannot stop searching after the first match
100575 ** because the first match might be for one of the deleted indices
100576 ** or tables and not the table/index that is actually being moved.
100577 ** We must continue looping until all tables and indices with
100578 ** rootpage==iFrom have been converted to have a rootpage of iTo
100579 ** in order to be certain that we got the right one.
100580 */
100581 #ifndef SQLITE_OMIT_AUTOVACUUM
100582 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
100583  HashElem *pElem;
100584  Hash *pHash;
100585  Db *pDb;
100586 
100587  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100588  pDb = &db->aDb[iDb];
100589  pHash = &pDb->pSchema->tblHash;
100590  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
100591  Table *pTab = sqliteHashData(pElem);
100592  if( pTab->tnum==iFrom ){
100593  pTab->tnum = iTo;
100594  }
100595  }
100596  pHash = &pDb->pSchema->idxHash;
100597  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
100598  Index *pIdx = sqliteHashData(pElem);
100599  if( pIdx->tnum==iFrom ){
100600  pIdx->tnum = iTo;
100601  }
100602  }
100603 }
100604 #endif
100605 
100606 /*
100607 ** Write code to erase the table with root-page iTable from database iDb.
100608 ** Also write code to modify the sqlite_master table and internal schema
100609 ** if a root-page of another table is moved by the btree-layer whilst
100610 ** erasing iTable (this can happen with an auto-vacuum database).
100611 */
100612 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
100613  Vdbe *v = sqlite3GetVdbe(pParse);
100614  int r1 = sqlite3GetTempReg(pParse);
100615  assert( iTable>1 );
100616  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
100617  sqlite3MayAbort(pParse);
100618 #ifndef SQLITE_OMIT_AUTOVACUUM
100619  /* OP_Destroy stores an in integer r1. If this integer
100620  ** is non-zero, then it is the root page number of a table moved to
100621  ** location iTable. The following code modifies the sqlite_master table to
100622  ** reflect this.
100623  **
100624  ** The "#NNN" in the SQL is a special constant that means whatever value
100625  ** is in register NNN. See grammar rules associated with the TK_REGISTER
100626  ** token for additional information.
100627  */
100628  sqlite3NestedParse(pParse,
100629  "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
100630  pParse->db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), iTable, r1, r1);
100631 #endif
100632  sqlite3ReleaseTempReg(pParse, r1);
100633 }
100634 
100635 /*
100636 ** Write VDBE code to erase table pTab and all associated indices on disk.
100637 ** Code to update the sqlite_master tables and internal schema definitions
100638 ** in case a root-page belonging to another table is moved by the btree layer
100639 ** is also added (this can happen with an auto-vacuum database).
100640 */
100641 static void destroyTable(Parse *pParse, Table *pTab){
100642 #ifdef SQLITE_OMIT_AUTOVACUUM
100643  Index *pIdx;
100644  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100645  destroyRootPage(pParse, pTab->tnum, iDb);
100646  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100647  destroyRootPage(pParse, pIdx->tnum, iDb);
100648  }
100649 #else
100650  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
100651  ** is not defined), then it is important to call OP_Destroy on the
100652  ** table and index root-pages in order, starting with the numerically
100653  ** largest root-page number. This guarantees that none of the root-pages
100654  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
100655  ** following were coded:
100656  **
100657  ** OP_Destroy 4 0
100658  ** ...
100659  ** OP_Destroy 5 0
100660  **
100661  ** and root page 5 happened to be the largest root-page number in the
100662  ** database, then root page 5 would be moved to page 4 by the
100663  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
100664  ** a free-list page.
100665  */
100666  int iTab = pTab->tnum;
100667  int iDestroyed = 0;
100668 
100669  while( 1 ){
100670  Index *pIdx;
100671  int iLargest = 0;
100672 
100673  if( iDestroyed==0 || iTab<iDestroyed ){
100674  iLargest = iTab;
100675  }
100676  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100677  int iIdx = pIdx->tnum;
100678  assert( pIdx->pSchema==pTab->pSchema );
100679  if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
100680  iLargest = iIdx;
100681  }
100682  }
100683  if( iLargest==0 ){
100684  return;
100685  }else{
100686  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100687  assert( iDb>=0 && iDb<pParse->db->nDb );
100688  destroyRootPage(pParse, iLargest, iDb);
100689  iDestroyed = iLargest;
100690  }
100691  }
100692 #endif
100693 }
100694 
100695 /*
100696 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
100697 ** after a DROP INDEX or DROP TABLE command.
100698 */
100700  Parse *pParse, /* The parsing context */
100701  int iDb, /* The database number */
100702  const char *zType, /* "idx" or "tbl" */
100703  const char *zName /* Name of index or table */
100704 ){
100705  int i;
100706  const char *zDbName = pParse->db->aDb[iDb].zDbSName;
100707  for(i=1; i<=4; i++){
100708  char zTab[24];
100709  sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
100710  if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
100711  sqlite3NestedParse(pParse,
100712  "DELETE FROM %Q.%s WHERE %s=%Q",
100713  zDbName, zTab, zType, zName
100714  );
100715  }
100716  }
100717 }
100718 
100719 /*
100720 ** Generate code to drop a table.
100721 */
100722 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
100723  Vdbe *v;
100724  sqlite3 *db = pParse->db;
100725  Trigger *pTrigger;
100726  Db *pDb = &db->aDb[iDb];
100727 
100728  v = sqlite3GetVdbe(pParse);
100729  assert( v!=0 );
100730  sqlite3BeginWriteOperation(pParse, 1, iDb);
100731 
100732 #ifndef SQLITE_OMIT_VIRTUALTABLE
100733  if( IsVirtual(pTab) ){
100735  }
100736 #endif
100737 
100738  /* Drop all triggers associated with the table being dropped. Code
100739  ** is generated to remove entries from sqlite_master and/or
100740  ** sqlite_temp_master if required.
100741  */
100742  pTrigger = sqlite3TriggerList(pParse, pTab);
100743  while( pTrigger ){
100744  assert( pTrigger->pSchema==pTab->pSchema ||
100745  pTrigger->pSchema==db->aDb[1].pSchema );
100746  sqlite3DropTriggerPtr(pParse, pTrigger);
100747  pTrigger = pTrigger->pNext;
100748  }
100749 
100750 #ifndef SQLITE_OMIT_AUTOINCREMENT
100751  /* Remove any entries of the sqlite_sequence table associated with
100752  ** the table being dropped. This is done before the table is dropped
100753  ** at the btree level, in case the sqlite_sequence table needs to
100754  ** move as a result of the drop (can happen in auto-vacuum mode).
100755  */
100756  if( pTab->tabFlags & TF_Autoincrement ){
100757  sqlite3NestedParse(pParse,
100758  "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
100759  pDb->zDbSName, pTab->zName
100760  );
100761  }
100762 #endif
100763 
100764  /* Drop all SQLITE_MASTER table and index entries that refer to the
100765  ** table. The program name loops through the master table and deletes
100766  ** every row that refers to a table of the same name as the one being
100767  ** dropped. Triggers are handled separately because a trigger can be
100768  ** created in the temp database that refers to a table in another
100769  ** database.
100770  */
100771  sqlite3NestedParse(pParse,
100772  "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
100773  pDb->zDbSName, SCHEMA_TABLE(iDb), pTab->zName);
100774  if( !isView && !IsVirtual(pTab) ){
100775  destroyTable(pParse, pTab);
100776  }
100777 
100778  /* Remove the table entry from SQLite's internal schema and modify
100779  ** the schema cookie.
100780  */
100781  if( IsVirtual(pTab) ){
100782  sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
100783  }
100784  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
100785  sqlite3ChangeCookie(pParse, iDb);
100786  sqliteViewResetAll(db, iDb);
100787 }
100788 
100789 /*
100790 ** This routine is called to do the work of a DROP TABLE statement.
100791 ** pName is the name of the table to be dropped.
100792 */
100793 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
100794  Table *pTab;
100795  Vdbe *v;
100796  sqlite3 *db = pParse->db;
100797  int iDb;
100798 
100799  if( db->mallocFailed ){
100800  goto exit_drop_table;
100801  }
100802  assert( pParse->nErr==0 );
100803  assert( pName->nSrc==1 );
100804  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
100805  if( noErr ) db->suppressErr++;
100806  assert( isView==0 || isView==LOCATE_VIEW );
100807  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
100808  if( noErr ) db->suppressErr--;
100809 
100810  if( pTab==0 ){
100811  if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
100812  goto exit_drop_table;
100813  }
100814  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100815  assert( iDb>=0 && iDb<db->nDb );
100816 
100817  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
100818  ** it is initialized.
100819  */
100820  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
100821  goto exit_drop_table;
100822  }
100823 #ifndef SQLITE_OMIT_AUTHORIZATION
100824  {
100825  int code;
100826  const char *zTab = SCHEMA_TABLE(iDb);
100827  const char *zDb = db->aDb[iDb].zDbSName;
100828  const char *zArg2 = 0;
100829  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
100830  goto exit_drop_table;
100831  }
100832  if( isView ){
100833  if( !OMIT_TEMPDB && iDb==1 ){
100834  code = SQLITE_DROP_TEMP_VIEW;
100835  }else{
100836  code = SQLITE_DROP_VIEW;
100837  }
100838 #ifndef SQLITE_OMIT_VIRTUALTABLE
100839  }else if( IsVirtual(pTab) ){
100840  code = SQLITE_DROP_VTABLE;
100841  zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
100842 #endif
100843  }else{
100844  if( !OMIT_TEMPDB && iDb==1 ){
100845  code = SQLITE_DROP_TEMP_TABLE;
100846  }else{
100847  code = SQLITE_DROP_TABLE;
100848  }
100849  }
100850  if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
100851  goto exit_drop_table;
100852  }
100853  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
100854  goto exit_drop_table;
100855  }
100856  }
100857 #endif
100858  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
100859  && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
100860  sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
100861  goto exit_drop_table;
100862  }
100863 
100864 #ifndef SQLITE_OMIT_VIEW
100865  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
100866  ** on a table.
100867  */
100868  if( isView && pTab->pSelect==0 ){
100869  sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
100870  goto exit_drop_table;
100871  }
100872  if( !isView && pTab->pSelect ){
100873  sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
100874  goto exit_drop_table;
100875  }
100876 #endif
100877 
100878  /* Generate code to remove the table from the master table
100879  ** on disk.
100880  */
100881  v = sqlite3GetVdbe(pParse);
100882  if( v ){
100883  sqlite3BeginWriteOperation(pParse, 1, iDb);
100884  sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
100885  sqlite3FkDropTable(pParse, pName, pTab);
100886  sqlite3CodeDropTable(pParse, pTab, iDb, isView);
100887  }
100888 
100889 exit_drop_table:
100890  sqlite3SrcListDelete(db, pName);
100891 }
100892 
100893 /*
100894 ** This routine is called to create a new foreign key on the table
100895 ** currently under construction. pFromCol determines which columns
100896 ** in the current table point to the foreign key. If pFromCol==0 then
100897 ** connect the key to the last column inserted. pTo is the name of
100898 ** the table referred to (a.k.a the "parent" table). pToCol is a list
100899 ** of tables in the parent pTo table. flags contains all
100900 ** information about the conflict resolution algorithms specified
100901 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
100902 **
100903 ** An FKey structure is created and added to the table currently
100904 ** under construction in the pParse->pNewTable field.
100905 **
100906 ** The foreign key is set for IMMEDIATE processing. A subsequent call
100907 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
100908 */
100910  Parse *pParse, /* Parsing context */
100911  ExprList *pFromCol, /* Columns in this table that point to other table */
100912  Token *pTo, /* Name of the other table */
100913  ExprList *pToCol, /* Columns in the other table */
100914  int flags /* Conflict resolution algorithms. */
100915 ){
100916  sqlite3 *db = pParse->db;
100917 #ifndef SQLITE_OMIT_FOREIGN_KEY
100918  FKey *pFKey = 0;
100919  FKey *pNextTo;
100920  Table *p = pParse->pNewTable;
100921  int nByte;
100922  int i;
100923  int nCol;
100924  char *z;
100925 
100926  assert( pTo!=0 );
100927  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
100928  if( pFromCol==0 ){
100929  int iCol = p->nCol-1;
100930  if( NEVER(iCol<0) ) goto fk_end;
100931  if( pToCol && pToCol->nExpr!=1 ){
100932  sqlite3ErrorMsg(pParse, "foreign key on %s"
100933  " should reference only one column of table %T",
100934  p->aCol[iCol].zName, pTo);
100935  goto fk_end;
100936  }
100937  nCol = 1;
100938  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
100939  sqlite3ErrorMsg(pParse,
100940  "number of columns in foreign key does not match the number of "
100941  "columns in the referenced table");
100942  goto fk_end;
100943  }else{
100944  nCol = pFromCol->nExpr;
100945  }
100946  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
100947  if( pToCol ){
100948  for(i=0; i<pToCol->nExpr; i++){
100949  nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
100950  }
100951  }
100952  pFKey = sqlite3DbMallocZero(db, nByte );
100953  if( pFKey==0 ){
100954  goto fk_end;
100955  }
100956  pFKey->pFrom = p;
100957  pFKey->pNextFrom = p->pFKey;
100958  z = (char*)&pFKey->aCol[nCol];
100959  pFKey->zTo = z;
100960  memcpy(z, pTo->z, pTo->n);
100961  z[pTo->n] = 0;
100962  sqlite3Dequote(z);
100963  z += pTo->n+1;
100964  pFKey->nCol = nCol;
100965  if( pFromCol==0 ){
100966  pFKey->aCol[0].iFrom = p->nCol-1;
100967  }else{
100968  for(i=0; i<nCol; i++){
100969  int j;
100970  for(j=0; j<p->nCol; j++){
100971  if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
100972  pFKey->aCol[i].iFrom = j;
100973  break;
100974  }
100975  }
100976  if( j>=p->nCol ){
100977  sqlite3ErrorMsg(pParse,
100978  "unknown column \"%s\" in foreign key definition",
100979  pFromCol->a[i].zName);
100980  goto fk_end;
100981  }
100982  }
100983  }
100984  if( pToCol ){
100985  for(i=0; i<nCol; i++){
100986  int n = sqlite3Strlen30(pToCol->a[i].zName);
100987  pFKey->aCol[i].zCol = z;
100988  memcpy(z, pToCol->a[i].zName, n);
100989  z[n] = 0;
100990  z += n+1;
100991  }
100992  }
100993  pFKey->isDeferred = 0;
100994  pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
100995  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
100996 
100997  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
100998  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
100999  pFKey->zTo, (void *)pFKey
101000  );
101001  if( pNextTo==pFKey ){
101002  sqlite3OomFault(db);
101003  goto fk_end;
101004  }
101005  if( pNextTo ){
101006  assert( pNextTo->pPrevTo==0 );
101007  pFKey->pNextTo = pNextTo;
101008  pNextTo->pPrevTo = pFKey;
101009  }
101010 
101011  /* Link the foreign key to the table as the last step.
101012  */
101013  p->pFKey = pFKey;
101014  pFKey = 0;
101015 
101016 fk_end:
101017  sqlite3DbFree(db, pFKey);
101018 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
101019  sqlite3ExprListDelete(db, pFromCol);
101020  sqlite3ExprListDelete(db, pToCol);
101021 }
101022 
101023 /*
101024 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
101025 ** clause is seen as part of a foreign key definition. The isDeferred
101026 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
101027 ** The behavior of the most recently created foreign key is adjusted
101028 ** accordingly.
101029 */
101030 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
101031 #ifndef SQLITE_OMIT_FOREIGN_KEY
101032  Table *pTab;
101033  FKey *pFKey;
101034  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
101035  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
101036  pFKey->isDeferred = (u8)isDeferred;
101037 #endif
101038 }
101039 
101040 /*
101041 ** Generate code that will erase and refill index *pIdx. This is
101042 ** used to initialize a newly created index or to recompute the
101043 ** content of an index in response to a REINDEX command.
101044 **
101045 ** if memRootPage is not negative, it means that the index is newly
101046 ** created. The register specified by memRootPage contains the
101047 ** root page number of the index. If memRootPage is negative, then
101048 ** the index already exists and must be cleared before being refilled and
101049 ** the root page number of the index is taken from pIndex->tnum.
101050 */
101051 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
101052  Table *pTab = pIndex->pTable; /* The table that is indexed */
101053  int iTab = pParse->nTab++; /* Btree cursor used for pTab */
101054  int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
101055  int iSorter; /* Cursor opened by OpenSorter (if in use) */
101056  int addr1; /* Address of top of loop */
101057  int addr2; /* Address to jump to for next iteration */
101058  int tnum; /* Root page of index */
101059  int iPartIdxLabel; /* Jump to this label to skip a row */
101060  Vdbe *v; /* Generate code into this virtual machine */
101061  KeyInfo *pKey; /* KeyInfo for index */
101062  int regRecord; /* Register holding assembled index record */
101063  sqlite3 *db = pParse->db; /* The database connection */
101064  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
101065 
101066 #ifndef SQLITE_OMIT_AUTHORIZATION
101067  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
101068  db->aDb[iDb].zDbSName ) ){
101069  return;
101070  }
101071 #endif
101072 
101073  /* Require a write-lock on the table to perform this operation */
101074  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
101075 
101076  v = sqlite3GetVdbe(pParse);
101077  if( v==0 ) return;
101078  if( memRootPage>=0 ){
101079  tnum = memRootPage;
101080  }else{
101081  tnum = pIndex->tnum;
101082  }
101083  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
101084  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
101085 
101086  /* Open the sorter cursor if we are to use one. */
101087  iSorter = pParse->nTab++;
101088  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
101089  sqlite3KeyInfoRef(pKey), P4_KEYINFO);
101090 
101091  /* Open the table. Loop through all rows of the table, inserting index
101092  ** records into the sorter. */
101093  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
101094  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
101095  regRecord = sqlite3GetTempReg(pParse);
101096 
101097  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
101098  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
101099  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
101100  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
101101  sqlite3VdbeJumpHere(v, addr1);
101102  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
101103  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
101104  (char *)pKey, P4_KEYINFO);
101105  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
101106 
101107  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
101108  if( IsUniqueIndex(pIndex) ){
101109  int j2 = sqlite3VdbeCurrentAddr(v) + 3;
101110  sqlite3VdbeGoto(v, j2);
101111  addr2 = sqlite3VdbeCurrentAddr(v);
101112  sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
101113  pIndex->nKeyCol); VdbeCoverage(v);
101114  sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
101115  }else{
101116  addr2 = sqlite3VdbeCurrentAddr(v);
101117  }
101118  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
101119  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
101120  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
101122  sqlite3ReleaseTempReg(pParse, regRecord);
101123  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
101124  sqlite3VdbeJumpHere(v, addr1);
101125 
101126  sqlite3VdbeAddOp1(v, OP_Close, iTab);
101127  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
101128  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
101129 }
101130 
101131 /*
101132 ** Allocate heap space to hold an Index object with nCol columns.
101133 **
101134 ** Increase the allocation size to provide an extra nExtra bytes
101135 ** of 8-byte aligned space after the Index object and return a
101136 ** pointer to this extra space in *ppExtra.
101137 */
101139  sqlite3 *db, /* Database connection */
101140  i16 nCol, /* Total number of columns in the index */
101141  int nExtra, /* Number of bytes of extra space to alloc */
101142  char **ppExtra /* Pointer to the "extra" space */
101143 ){
101144  Index *p; /* Allocated index object */
101145  int nByte; /* Bytes of space for Index object + arrays */
101146 
101147  nByte = ROUND8(sizeof(Index)) + /* Index structure */
101148  ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
101149  ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
101150  sizeof(i16)*nCol + /* Index.aiColumn */
101151  sizeof(u8)*nCol); /* Index.aSortOrder */
101152  p = sqlite3DbMallocZero(db, nByte + nExtra);
101153  if( p ){
101154  char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
101155  p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
101156  p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
101157  p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
101158  p->aSortOrder = (u8*)pExtra;
101159  p->nColumn = nCol;
101160  p->nKeyCol = nCol - 1;
101161  *ppExtra = ((char*)p) + nByte;
101162  }
101163  return p;
101164 }
101165 
101166 /*
101167 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
101168 ** and pTblList is the name of the table that is to be indexed. Both will
101169 ** be NULL for a primary key or an index that is created to satisfy a
101170 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
101171 ** as the table to be indexed. pParse->pNewTable is a table that is
101172 ** currently being constructed by a CREATE TABLE statement.
101173 **
101174 ** pList is a list of columns to be indexed. pList will be NULL if this
101175 ** is a primary key or unique-constraint on the most recent column added
101176 ** to the table currently under construction.
101177 */
101179  Parse *pParse, /* All information about this parse */
101180  Token *pName1, /* First part of index name. May be NULL */
101181  Token *pName2, /* Second part of index name. May be NULL */
101182  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
101183  ExprList *pList, /* A list of columns to be indexed */
101184  int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
101185  Token *pStart, /* The CREATE token that begins this statement */
101186  Expr *pPIWhere, /* WHERE clause for partial indices */
101187  int sortOrder, /* Sort order of primary key when pList==NULL */
101188  int ifNotExist, /* Omit error if index already exists */
101189  u8 idxType /* The index type */
101190 ){
101191  Table *pTab = 0; /* Table to be indexed */
101192  Index *pIndex = 0; /* The index to be created */
101193  char *zName = 0; /* Name of the index */
101194  int nName; /* Number of characters in zName */
101195  int i, j;
101196  DbFixer sFix; /* For assigning database names to pTable */
101197  int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
101198  sqlite3 *db = pParse->db;
101199  Db *pDb; /* The specific table containing the indexed database */
101200  int iDb; /* Index of the database that is being written */
101201  Token *pName = 0; /* Unqualified name of the index to create */
101202  struct ExprList_item *pListItem; /* For looping over pList */
101203  int nExtra = 0; /* Space allocated for zExtra[] */
101204  int nExtraCol; /* Number of extra columns needed */
101205  char *zExtra = 0; /* Extra space after the Index object */
101206  Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
101207 
101208  if( db->mallocFailed || pParse->nErr>0 ){
101209  goto exit_create_index;
101210  }
101211  if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
101212  goto exit_create_index;
101213  }
101214  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101215  goto exit_create_index;
101216  }
101217 
101218  /*
101219  ** Find the table that is to be indexed. Return early if not found.
101220  */
101221  if( pTblName!=0 ){
101222 
101223  /* Use the two-part index name to determine the database
101224  ** to search for the table. 'Fix' the table name to this db
101225  ** before looking up the table.
101226  */
101227  assert( pName1 && pName2 );
101228  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101229  if( iDb<0 ) goto exit_create_index;
101230  assert( pName && pName->z );
101231 
101232 #ifndef SQLITE_OMIT_TEMPDB
101233  /* If the index name was unqualified, check if the table
101234  ** is a temp table. If so, set the database to 1. Do not do this
101235  ** if initialising a database schema.
101236  */
101237  if( !db->init.busy ){
101238  pTab = sqlite3SrcListLookup(pParse, pTblName);
101239  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
101240  iDb = 1;
101241  }
101242  }
101243 #endif
101244 
101245  sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
101246  if( sqlite3FixSrcList(&sFix, pTblName) ){
101247  /* Because the parser constructs pTblName from a single identifier,
101248  ** sqlite3FixSrcList can never fail. */
101249  assert(0);
101250  }
101251  pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
101252  assert( db->mallocFailed==0 || pTab==0 );
101253  if( pTab==0 ) goto exit_create_index;
101254  if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
101255  sqlite3ErrorMsg(pParse,
101256  "cannot create a TEMP index on non-TEMP table \"%s\"",
101257  pTab->zName);
101258  goto exit_create_index;
101259  }
101260  if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
101261  }else{
101262  assert( pName==0 );
101263  assert( pStart==0 );
101264  pTab = pParse->pNewTable;
101265  if( !pTab ) goto exit_create_index;
101266  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101267  }
101268  pDb = &db->aDb[iDb];
101269 
101270  assert( pTab!=0 );
101271  assert( pParse->nErr==0 );
101272  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
101273  && db->init.busy==0
101274 #if SQLITE_USER_AUTHENTICATION
101275  && sqlite3UserAuthTable(pTab->zName)==0
101276 #endif
101277  && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
101278  sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
101279  goto exit_create_index;
101280  }
101281 #ifndef SQLITE_OMIT_VIEW
101282  if( pTab->pSelect ){
101283  sqlite3ErrorMsg(pParse, "views may not be indexed");
101284  goto exit_create_index;
101285  }
101286 #endif
101287 #ifndef SQLITE_OMIT_VIRTUALTABLE
101288  if( IsVirtual(pTab) ){
101289  sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
101290  goto exit_create_index;
101291  }
101292 #endif
101293 
101294  /*
101295  ** Find the name of the index. Make sure there is not already another
101296  ** index or table with the same name.
101297  **
101298  ** Exception: If we are reading the names of permanent indices from the
101299  ** sqlite_master table (because some other process changed the schema) and
101300  ** one of the index names collides with the name of a temporary table or
101301  ** index, then we will continue to process this index.
101302  **
101303  ** If pName==0 it means that we are
101304  ** dealing with a primary key or UNIQUE constraint. We have to invent our
101305  ** own name.
101306  */
101307  if( pName ){
101308  zName = sqlite3NameFromToken(db, pName);
101309  if( zName==0 ) goto exit_create_index;
101310  assert( pName->z!=0 );
101311  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101312  goto exit_create_index;
101313  }
101314  if( !db->init.busy ){
101315  if( sqlite3FindTable(db, zName, 0)!=0 ){
101316  sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
101317  goto exit_create_index;
101318  }
101319  }
101320  if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
101321  if( !ifNotExist ){
101322  sqlite3ErrorMsg(pParse, "index %s already exists", zName);
101323  }else{
101324  assert( !db->init.busy );
101325  sqlite3CodeVerifySchema(pParse, iDb);
101326  }
101327  goto exit_create_index;
101328  }
101329  }else{
101330  int n;
101331  Index *pLoop;
101332  for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
101333  zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
101334  if( zName==0 ){
101335  goto exit_create_index;
101336  }
101337 
101338  /* Automatic index names generated from within sqlite3_declare_vtab()
101339  ** must have names that are distinct from normal automatic index names.
101340  ** The following statement converts "sqlite3_autoindex..." into
101341  ** "sqlite3_butoindex..." in order to make the names distinct.
101342  ** The "vtab_err.test" test demonstrates the need of this statement. */
101343  if( IN_DECLARE_VTAB ) zName[7]++;
101344  }
101345 
101346  /* Check for authorization to create an index.
101347  */
101348 #ifndef SQLITE_OMIT_AUTHORIZATION
101349  {
101350  const char *zDb = pDb->zDbSName;
101351  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
101352  goto exit_create_index;
101353  }
101354  i = SQLITE_CREATE_INDEX;
101355  if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
101356  if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
101357  goto exit_create_index;
101358  }
101359  }
101360 #endif
101361 
101362  /* If pList==0, it means this routine was called to make a primary
101363  ** key out of the last column added to the table under construction.
101364  ** So create a fake list to simulate this.
101365  */
101366  if( pList==0 ){
101367  Token prevCol;
101368  sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
101369  pList = sqlite3ExprListAppend(pParse, 0,
101370  sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
101371  if( pList==0 ) goto exit_create_index;
101372  assert( pList->nExpr==1 );
101373  sqlite3ExprListSetSortOrder(pList, sortOrder);
101374  }else{
101375  sqlite3ExprListCheckLength(pParse, pList, "index");
101376  }
101377 
101378  /* Figure out how many bytes of space are required to store explicitly
101379  ** specified collation sequence names.
101380  */
101381  for(i=0; i<pList->nExpr; i++){
101382  Expr *pExpr = pList->a[i].pExpr;
101383  assert( pExpr!=0 );
101384  if( pExpr->op==TK_COLLATE ){
101385  nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
101386  }
101387  }
101388 
101389  /*
101390  ** Allocate the index structure.
101391  */
101392  nName = sqlite3Strlen30(zName);
101393  nExtraCol = pPk ? pPk->nKeyCol : 1;
101394  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
101395  nName + nExtra + 1, &zExtra);
101396  if( db->mallocFailed ){
101397  goto exit_create_index;
101398  }
101399  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
101400  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
101401  pIndex->zName = zExtra;
101402  zExtra += nName + 1;
101403  memcpy(pIndex->zName, zName, nName+1);
101404  pIndex->pTable = pTab;
101405  pIndex->onError = (u8)onError;
101406  pIndex->uniqNotNull = onError!=OE_None;
101407  pIndex->idxType = idxType;
101408  pIndex->pSchema = db->aDb[iDb].pSchema;
101409  pIndex->nKeyCol = pList->nExpr;
101410  if( pPIWhere ){
101411  sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
101412  pIndex->pPartIdxWhere = pPIWhere;
101413  pPIWhere = 0;
101414  }
101415  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101416 
101417  /* Check to see if we should honor DESC requests on index columns
101418  */
101419  if( pDb->pSchema->file_format>=4 ){
101420  sortOrderMask = -1; /* Honor DESC */
101421  }else{
101422  sortOrderMask = 0; /* Ignore DESC */
101423  }
101424 
101425  /* Analyze the list of expressions that form the terms of the index and
101426  ** report any errors. In the common case where the expression is exactly
101427  ** a table column, store that column in aiColumn[]. For general expressions,
101428  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
101429  **
101430  ** TODO: Issue a warning if two or more columns of the index are identical.
101431  ** TODO: Issue a warning if the table primary key is used as part of the
101432  ** index key.
101433  */
101434  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
101435  Expr *pCExpr; /* The i-th index expression */
101436  int requestedSortOrder; /* ASC or DESC on the i-th expression */
101437  const char *zColl; /* Collation sequence name */
101438 
101439  sqlite3StringToId(pListItem->pExpr);
101440  sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
101441  if( pParse->nErr ) goto exit_create_index;
101442  pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
101443  if( pCExpr->op!=TK_COLUMN ){
101444  if( pTab==pParse->pNewTable ){
101445  sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
101446  "UNIQUE constraints");
101447  goto exit_create_index;
101448  }
101449  if( pIndex->aColExpr==0 ){
101450  ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
101451  pIndex->aColExpr = pCopy;
101452  if( !db->mallocFailed ){
101453  assert( pCopy!=0 );
101454  pListItem = &pCopy->a[i];
101455  }
101456  }
101457  j = XN_EXPR;
101458  pIndex->aiColumn[i] = XN_EXPR;
101459  pIndex->uniqNotNull = 0;
101460  }else{
101461  j = pCExpr->iColumn;
101462  assert( j<=0x7fff );
101463  if( j<0 ){
101464  j = pTab->iPKey;
101465  }else if( pTab->aCol[j].notNull==0 ){
101466  pIndex->uniqNotNull = 0;
101467  }
101468  pIndex->aiColumn[i] = (i16)j;
101469  }
101470  zColl = 0;
101471  if( pListItem->pExpr->op==TK_COLLATE ){
101472  int nColl;
101473  zColl = pListItem->pExpr->u.zToken;
101474  nColl = sqlite3Strlen30(zColl) + 1;
101475  assert( nExtra>=nColl );
101476  memcpy(zExtra, zColl, nColl);
101477  zColl = zExtra;
101478  zExtra += nColl;
101479  nExtra -= nColl;
101480  }else if( j>=0 ){
101481  zColl = pTab->aCol[j].zColl;
101482  }
101483  if( !zColl ) zColl = sqlite3StrBINARY;
101484  if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
101485  goto exit_create_index;
101486  }
101487  pIndex->azColl[i] = zColl;
101488  requestedSortOrder = pListItem->sortOrder & sortOrderMask;
101489  pIndex->aSortOrder[i] = (u8)requestedSortOrder;
101490  }
101491 
101492  /* Append the table key to the end of the index. For WITHOUT ROWID
101493  ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
101494  ** normal tables (when pPk==0) this will be the rowid.
101495  */
101496  if( pPk ){
101497  for(j=0; j<pPk->nKeyCol; j++){
101498  int x = pPk->aiColumn[j];
101499  assert( x>=0 );
101500  if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
101501  pIndex->nColumn--;
101502  }else{
101503  pIndex->aiColumn[i] = x;
101504  pIndex->azColl[i] = pPk->azColl[j];
101505  pIndex->aSortOrder[i] = pPk->aSortOrder[j];
101506  i++;
101507  }
101508  }
101509  assert( i==pIndex->nColumn );
101510  }else{
101511  pIndex->aiColumn[i] = XN_ROWID;
101512  pIndex->azColl[i] = sqlite3StrBINARY;
101513  }
101514  sqlite3DefaultRowEst(pIndex);
101515  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
101516 
101517  /* If this index contains every column of its table, then mark
101518  ** it as a covering index */
101519  assert( HasRowid(pTab)
101520  || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
101521  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
101522  pIndex->isCovering = 1;
101523  for(j=0; j<pTab->nCol; j++){
101524  if( j==pTab->iPKey ) continue;
101525  if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
101526  pIndex->isCovering = 0;
101527  break;
101528  }
101529  }
101530 
101531  if( pTab==pParse->pNewTable ){
101532  /* This routine has been called to create an automatic index as a
101533  ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
101534  ** a PRIMARY KEY or UNIQUE clause following the column definitions.
101535  ** i.e. one of:
101536  **
101537  ** CREATE TABLE t(x PRIMARY KEY, y);
101538  ** CREATE TABLE t(x, y, UNIQUE(x, y));
101539  **
101540  ** Either way, check to see if the table already has such an index. If
101541  ** so, don't bother creating this one. This only applies to
101542  ** automatically created indices. Users can do as they wish with
101543  ** explicit indices.
101544  **
101545  ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
101546  ** (and thus suppressing the second one) even if they have different
101547  ** sort orders.
101548  **
101549  ** If there are different collating sequences or if the columns of
101550  ** the constraint occur in different orders, then the constraints are
101551  ** considered distinct and both result in separate indices.
101552  */
101553  Index *pIdx;
101554  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101555  int k;
101556  assert( IsUniqueIndex(pIdx) );
101557  assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
101558  assert( IsUniqueIndex(pIndex) );
101559 
101560  if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
101561  for(k=0; k<pIdx->nKeyCol; k++){
101562  const char *z1;
101563  const char *z2;
101564  assert( pIdx->aiColumn[k]>=0 );
101565  if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
101566  z1 = pIdx->azColl[k];
101567  z2 = pIndex->azColl[k];
101568  if( sqlite3StrICmp(z1, z2) ) break;
101569  }
101570  if( k==pIdx->nKeyCol ){
101571  if( pIdx->onError!=pIndex->onError ){
101572  /* This constraint creates the same index as a previous
101573  ** constraint specified somewhere in the CREATE TABLE statement.
101574  ** However the ON CONFLICT clauses are different. If both this
101575  ** constraint and the previous equivalent constraint have explicit
101576  ** ON CONFLICT clauses this is an error. Otherwise, use the
101577  ** explicitly specified behavior for the index.
101578  */
101579  if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
101580  sqlite3ErrorMsg(pParse,
101581  "conflicting ON CONFLICT clauses specified", 0);
101582  }
101583  if( pIdx->onError==OE_Default ){
101584  pIdx->onError = pIndex->onError;
101585  }
101586  }
101587  if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
101588  goto exit_create_index;
101589  }
101590  }
101591  }
101592 
101593  /* Link the new Index structure to its table and to the other
101594  ** in-memory database structures.
101595  */
101596  assert( pParse->nErr==0 );
101597  if( db->init.busy ){
101598  Index *p;
101599  assert( !IN_DECLARE_VTAB );
101600  assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
101601  p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
101602  pIndex->zName, pIndex);
101603  if( p ){
101604  assert( p==pIndex ); /* Malloc must have failed */
101605  sqlite3OomFault(db);
101606  goto exit_create_index;
101607  }
101608  db->flags |= SQLITE_InternChanges;
101609  if( pTblName!=0 ){
101610  pIndex->tnum = db->init.newTnum;
101611  }
101612  }
101613 
101614  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
101615  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
101616  ** emit code to allocate the index rootpage on disk and make an entry for
101617  ** the index in the sqlite_master table and populate the index with
101618  ** content. But, do not do this if we are simply reading the sqlite_master
101619  ** table to parse the schema, or if this index is the PRIMARY KEY index
101620  ** of a WITHOUT ROWID table.
101621  **
101622  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
101623  ** or UNIQUE index in a CREATE TABLE statement. Since the table
101624  ** has just been created, it contains no data and the index initialization
101625  ** step can be skipped.
101626  */
101627  else if( HasRowid(pTab) || pTblName!=0 ){
101628  Vdbe *v;
101629  char *zStmt;
101630  int iMem = ++pParse->nMem;
101631 
101632  v = sqlite3GetVdbe(pParse);
101633  if( v==0 ) goto exit_create_index;
101634 
101635  sqlite3BeginWriteOperation(pParse, 1, iDb);
101636 
101637  /* Create the rootpage for the index using CreateIndex. But before
101638  ** doing so, code a Noop instruction and store its address in
101639  ** Index.tnum. This is required in case this index is actually a
101640  ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
101641  ** that case the convertToWithoutRowidTable() routine will replace
101642  ** the Noop with a Goto to jump over the VDBE code generated below. */
101643  pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
101644  sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
101645 
101646  /* Gather the complete text of the CREATE INDEX statement into
101647  ** the zStmt variable
101648  */
101649  if( pStart ){
101650  int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
101651  if( pName->z[n-1]==';' ) n--;
101652  /* A named index with an explicit CREATE INDEX statement */
101653  zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
101654  onError==OE_None ? "" : " UNIQUE", n, pName->z);
101655  }else{
101656  /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
101657  /* zStmt = sqlite3MPrintf(""); */
101658  zStmt = 0;
101659  }
101660 
101661  /* Add an entry in sqlite_master for this index
101662  */
101663  sqlite3NestedParse(pParse,
101664  "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
101665  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
101666  pIndex->zName,
101667  pTab->zName,
101668  iMem,
101669  zStmt
101670  );
101671  sqlite3DbFree(db, zStmt);
101672 
101673  /* Fill the index with data and reparse the schema. Code an OP_Expire
101674  ** to invalidate all pre-compiled statements.
101675  */
101676  if( pTblName ){
101677  sqlite3RefillIndex(pParse, pIndex, iMem);
101678  sqlite3ChangeCookie(pParse, iDb);
101680  sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
101682  }
101683 
101684  sqlite3VdbeJumpHere(v, pIndex->tnum);
101685  }
101686 
101687  /* When adding an index to the list of indices for a table, make
101688  ** sure all indices labeled OE_Replace come after all those labeled
101689  ** OE_Ignore. This is necessary for the correct constraint check
101690  ** processing (in sqlite3GenerateConstraintChecks()) as part of
101691  ** UPDATE and INSERT statements.
101692  */
101693  if( db->init.busy || pTblName==0 ){
101694  if( onError!=OE_Replace || pTab->pIndex==0
101695  || pTab->pIndex->onError==OE_Replace){
101696  pIndex->pNext = pTab->pIndex;
101697  pTab->pIndex = pIndex;
101698  }else{
101699  Index *pOther = pTab->pIndex;
101700  while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
101701  pOther = pOther->pNext;
101702  }
101703  pIndex->pNext = pOther->pNext;
101704  pOther->pNext = pIndex;
101705  }
101706  pIndex = 0;
101707  }
101708 
101709  /* Clean up before exiting */
101710 exit_create_index:
101711  if( pIndex ) freeIndex(db, pIndex);
101712  sqlite3ExprDelete(db, pPIWhere);
101713  sqlite3ExprListDelete(db, pList);
101714  sqlite3SrcListDelete(db, pTblName);
101715  sqlite3DbFree(db, zName);
101716 }
101717 
101718 /*
101719 ** Fill the Index.aiRowEst[] array with default information - information
101720 ** to be used when we have not run the ANALYZE command.
101721 **
101722 ** aiRowEst[0] is supposed to contain the number of elements in the index.
101723 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
101724 ** number of rows in the table that match any particular value of the
101725 ** first column of the index. aiRowEst[2] is an estimate of the number
101726 ** of rows that match any particular combination of the first 2 columns
101727 ** of the index. And so forth. It must always be the case that
101728 *
101729 ** aiRowEst[N]<=aiRowEst[N-1]
101730 ** aiRowEst[N]>=1
101731 **
101732 ** Apart from that, we have little to go on besides intuition as to
101733 ** how aiRowEst[] should be initialized. The numbers generated here
101734 ** are based on typical values found in actual indices.
101735 */
101737  /* 10, 9, 8, 7, 6 */
101738  LogEst aVal[] = { 33, 32, 30, 28, 26 };
101739  LogEst *a = pIdx->aiRowLogEst;
101740  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
101741  int i;
101742 
101743  /* Set the first entry (number of rows in the index) to the estimated
101744  ** number of rows in the table, or half the number of rows in the table
101745  ** for a partial index. But do not let the estimate drop below 10. */
101746  a[0] = pIdx->pTable->nRowLogEst;
101747  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
101748  if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
101749 
101750  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
101751  ** 6 and each subsequent value (if any) is 5. */
101752  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
101753  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
101754  a[i] = 23; assert( 23==sqlite3LogEst(5) );
101755  }
101756 
101757  assert( 0==sqlite3LogEst(1) );
101758  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
101759 }
101760 
101761 /*
101762 ** This routine will drop an existing named index. This routine
101763 ** implements the DROP INDEX statement.
101764 */
101765 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
101766  Index *pIndex;
101767  Vdbe *v;
101768  sqlite3 *db = pParse->db;
101769  int iDb;
101770 
101771  assert( pParse->nErr==0 ); /* Never called with prior errors */
101772  if( db->mallocFailed ){
101773  goto exit_drop_index;
101774  }
101775  assert( pName->nSrc==1 );
101776  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101777  goto exit_drop_index;
101778  }
101779  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
101780  if( pIndex==0 ){
101781  if( !ifExists ){
101782  sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
101783  }else{
101784  sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
101785  }
101786  pParse->checkSchema = 1;
101787  goto exit_drop_index;
101788  }
101789  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
101790  sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
101791  "or PRIMARY KEY constraint cannot be dropped", 0);
101792  goto exit_drop_index;
101793  }
101794  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
101795 #ifndef SQLITE_OMIT_AUTHORIZATION
101796  {
101797  int code = SQLITE_DROP_INDEX;
101798  Table *pTab = pIndex->pTable;
101799  const char *zDb = db->aDb[iDb].zDbSName;
101800  const char *zTab = SCHEMA_TABLE(iDb);
101801  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
101802  goto exit_drop_index;
101803  }
101804  if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
101805  if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
101806  goto exit_drop_index;
101807  }
101808  }
101809 #endif
101810 
101811  /* Generate code to remove the index and from the master table */
101812  v = sqlite3GetVdbe(pParse);
101813  if( v ){
101814  sqlite3BeginWriteOperation(pParse, 1, iDb);
101815  sqlite3NestedParse(pParse,
101816  "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
101817  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pIndex->zName
101818  );
101819  sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
101820  sqlite3ChangeCookie(pParse, iDb);
101821  destroyRootPage(pParse, pIndex->tnum, iDb);
101822  sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
101823  }
101824 
101825 exit_drop_index:
101826  sqlite3SrcListDelete(db, pName);
101827 }
101828 
101829 /*
101830 ** pArray is a pointer to an array of objects. Each object in the
101831 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
101832 ** to extend the array so that there is space for a new object at the end.
101833 **
101834 ** When this function is called, *pnEntry contains the current size of
101835 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
101836 ** in total).
101837 **
101838 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
101839 ** space allocated for the new object is zeroed, *pnEntry updated to
101840 ** reflect the new size of the array and a pointer to the new allocation
101841 ** returned. *pIdx is set to the index of the new array entry in this case.
101842 **
101843 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
101844 ** unchanged and a copy of pArray returned.
101845 */
101847  sqlite3 *db, /* Connection to notify of malloc failures */
101848  void *pArray, /* Array of objects. Might be reallocated */
101849  int szEntry, /* Size of each object in the array */
101850  int *pnEntry, /* Number of objects currently in use */
101851  int *pIdx /* Write the index of a new slot here */
101852 ){
101853  char *z;
101854  int n = *pnEntry;
101855  if( (n & (n-1))==0 ){
101856  int sz = (n==0) ? 1 : 2*n;
101857  void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
101858  if( pNew==0 ){
101859  *pIdx = -1;
101860  return pArray;
101861  }
101862  pArray = pNew;
101863  }
101864  z = (char*)pArray;
101865  memset(&z[n * szEntry], 0, szEntry);
101866  *pIdx = n;
101867  ++*pnEntry;
101868  return pArray;
101869 }
101870 
101871 /*
101872 ** Append a new element to the given IdList. Create a new IdList if
101873 ** need be.
101874 **
101875 ** A new IdList is returned, or NULL if malloc() fails.
101876 */
101878  int i;
101879  if( pList==0 ){
101880  pList = sqlite3DbMallocZero(db, sizeof(IdList) );
101881  if( pList==0 ) return 0;
101882  }
101883  pList->a = sqlite3ArrayAllocate(
101884  db,
101885  pList->a,
101886  sizeof(pList->a[0]),
101887  &pList->nId,
101888  &i
101889  );
101890  if( i<0 ){
101891  sqlite3IdListDelete(db, pList);
101892  return 0;
101893  }
101894  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
101895  return pList;
101896 }
101897 
101898 /*
101899 ** Delete an IdList.
101900 */
101902  int i;
101903  if( pList==0 ) return;
101904  for(i=0; i<pList->nId; i++){
101905  sqlite3DbFree(db, pList->a[i].zName);
101906  }
101907  sqlite3DbFree(db, pList->a);
101908  sqlite3DbFree(db, pList);
101909 }
101910 
101911 /*
101912 ** Return the index in pList of the identifier named zId. Return -1
101913 ** if not found.
101914 */
101915 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
101916  int i;
101917  if( pList==0 ) return -1;
101918  for(i=0; i<pList->nId; i++){
101919  if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
101920  }
101921  return -1;
101922 }
101923 
101924 /*
101925 ** Expand the space allocated for the given SrcList object by
101926 ** creating nExtra new slots beginning at iStart. iStart is zero based.
101927 ** New slots are zeroed.
101928 **
101929 ** For example, suppose a SrcList initially contains two entries: A,B.
101930 ** To append 3 new entries onto the end, do this:
101931 **
101932 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
101933 **
101934 ** After the call above it would contain: A, B, nil, nil, nil.
101935 ** If the iStart argument had been 1 instead of 2, then the result
101936 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
101937 ** the iStart value would be 0. The result then would
101938 ** be: nil, nil, nil, A, B.
101939 **
101940 ** If a memory allocation fails the SrcList is unchanged. The
101941 ** db->mallocFailed flag will be set to true.
101942 */
101944  sqlite3 *db, /* Database connection to notify of OOM errors */
101945  SrcList *pSrc, /* The SrcList to be enlarged */
101946  int nExtra, /* Number of new slots to add to pSrc->a[] */
101947  int iStart /* Index in pSrc->a[] of first new slot */
101948 ){
101949  int i;
101950 
101951  /* Sanity checking on calling parameters */
101952  assert( iStart>=0 );
101953  assert( nExtra>=1 );
101954  assert( pSrc!=0 );
101955  assert( iStart<=pSrc->nSrc );
101956 
101957  /* Allocate additional space if needed */
101958  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
101959  SrcList *pNew;
101960  int nAlloc = pSrc->nSrc+nExtra;
101961  int nGot;
101962  pNew = sqlite3DbRealloc(db, pSrc,
101963  sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
101964  if( pNew==0 ){
101965  assert( db->mallocFailed );
101966  return pSrc;
101967  }
101968  pSrc = pNew;
101969  nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
101970  pSrc->nAlloc = nGot;
101971  }
101972 
101973  /* Move existing slots that come after the newly inserted slots
101974  ** out of the way */
101975  for(i=pSrc->nSrc-1; i>=iStart; i--){
101976  pSrc->a[i+nExtra] = pSrc->a[i];
101977  }
101978  pSrc->nSrc += nExtra;
101979 
101980  /* Zero the newly allocated slots */
101981  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
101982  for(i=iStart; i<iStart+nExtra; i++){
101983  pSrc->a[i].iCursor = -1;
101984  }
101985 
101986  /* Return a pointer to the enlarged SrcList */
101987  return pSrc;
101988 }
101989 
101990 
101991 /*
101992 ** Append a new table name to the given SrcList. Create a new SrcList if
101993 ** need be. A new entry is created in the SrcList even if pTable is NULL.
101994 **
101995 ** A SrcList is returned, or NULL if there is an OOM error. The returned
101996 ** SrcList might be the same as the SrcList that was input or it might be
101997 ** a new one. If an OOM error does occurs, then the prior value of pList
101998 ** that is input to this routine is automatically freed.
101999 **
102000 ** If pDatabase is not null, it means that the table has an optional
102001 ** database name prefix. Like this: "database.table". The pDatabase
102002 ** points to the table name and the pTable points to the database name.
102003 ** The SrcList.a[].zName field is filled with the table name which might
102004 ** come from pTable (if pDatabase is NULL) or from pDatabase.
102005 ** SrcList.a[].zDatabase is filled with the database name from pTable,
102006 ** or with NULL if no database is specified.
102007 **
102008 ** In other words, if call like this:
102009 **
102010 ** sqlite3SrcListAppend(D,A,B,0);
102011 **
102012 ** Then B is a table name and the database name is unspecified. If called
102013 ** like this:
102014 **
102015 ** sqlite3SrcListAppend(D,A,B,C);
102016 **
102017 ** Then C is the table name and B is the database name. If C is defined
102018 ** then so is B. In other words, we never have a case where:
102019 **
102020 ** sqlite3SrcListAppend(D,A,0,C);
102021 **
102022 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
102023 ** before being added to the SrcList.
102024 */
102026  sqlite3 *db, /* Connection to notify of malloc failures */
102027  SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
102028  Token *pTable, /* Table to append */
102029  Token *pDatabase /* Database of the table */
102030 ){
102031  struct SrcList_item *pItem;
102032  assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
102033  assert( db!=0 );
102034  if( pList==0 ){
102035  pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
102036  if( pList==0 ) return 0;
102037  pList->nAlloc = 1;
102038  pList->nSrc = 0;
102039  }
102040  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
102041  if( db->mallocFailed ){
102042  sqlite3SrcListDelete(db, pList);
102043  return 0;
102044  }
102045  pItem = &pList->a[pList->nSrc-1];
102046  if( pDatabase && pDatabase->z==0 ){
102047  pDatabase = 0;
102048  }
102049  if( pDatabase ){
102050  Token *pTemp = pDatabase;
102051  pDatabase = pTable;
102052  pTable = pTemp;
102053  }
102054  pItem->zName = sqlite3NameFromToken(db, pTable);
102055  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
102056  return pList;
102057 }
102058 
102059 /*
102060 ** Assign VdbeCursor index numbers to all tables in a SrcList
102061 */
102063  int i;
102064  struct SrcList_item *pItem;
102065  assert(pList || pParse->db->mallocFailed );
102066  if( pList ){
102067  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
102068  if( pItem->iCursor>=0 ) break;
102069  pItem->iCursor = pParse->nTab++;
102070  if( pItem->pSelect ){
102071  sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
102072  }
102073  }
102074  }
102075 }
102076 
102077 /*
102078 ** Delete an entire SrcList including all its substructure.
102079 */
102081  int i;
102082  struct SrcList_item *pItem;
102083  if( pList==0 ) return;
102084  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
102085  sqlite3DbFree(db, pItem->zDatabase);
102086  sqlite3DbFree(db, pItem->zName);
102087  sqlite3DbFree(db, pItem->zAlias);
102088  if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
102089  if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
102090  sqlite3DeleteTable(db, pItem->pTab);
102091  sqlite3SelectDelete(db, pItem->pSelect);
102092  sqlite3ExprDelete(db, pItem->pOn);
102093  sqlite3IdListDelete(db, pItem->pUsing);
102094  }
102095  sqlite3DbFree(db, pList);
102096 }
102097 
102098 /*
102099 ** This routine is called by the parser to add a new term to the
102100 ** end of a growing FROM clause. The "p" parameter is the part of
102101 ** the FROM clause that has already been constructed. "p" is NULL
102102 ** if this is the first term of the FROM clause. pTable and pDatabase
102103 ** are the name of the table and database named in the FROM clause term.
102104 ** pDatabase is NULL if the database name qualifier is missing - the
102105 ** usual case. If the term has an alias, then pAlias points to the
102106 ** alias token. If the term is a subquery, then pSubquery is the
102107 ** SELECT statement that the subquery encodes. The pTable and
102108 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
102109 ** parameters are the content of the ON and USING clauses.
102110 **
102111 ** Return a new SrcList which encodes is the FROM with the new
102112 ** term added.
102113 */
102115  Parse *pParse, /* Parsing context */
102116  SrcList *p, /* The left part of the FROM clause already seen */
102117  Token *pTable, /* Name of the table to add to the FROM clause */
102118  Token *pDatabase, /* Name of the database containing pTable */
102119  Token *pAlias, /* The right-hand side of the AS subexpression */
102120  Select *pSubquery, /* A subquery used in place of a table name */
102121  Expr *pOn, /* The ON clause of a join */
102122  IdList *pUsing /* The USING clause of a join */
102123 ){
102124  struct SrcList_item *pItem;
102125  sqlite3 *db = pParse->db;
102126  if( !p && (pOn || pUsing) ){
102127  sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
102128  (pOn ? "ON" : "USING")
102129  );
102130  goto append_from_error;
102131  }
102132  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
102133  if( p==0 || NEVER(p->nSrc==0) ){
102134  goto append_from_error;
102135  }
102136  pItem = &p->a[p->nSrc-1];
102137  assert( pAlias!=0 );
102138  if( pAlias->n ){
102139  pItem->zAlias = sqlite3NameFromToken(db, pAlias);
102140  }
102141  pItem->pSelect = pSubquery;
102142  pItem->pOn = pOn;
102143  pItem->pUsing = pUsing;
102144  return p;
102145 
102146  append_from_error:
102147  assert( p==0 );
102148  sqlite3ExprDelete(db, pOn);
102149  sqlite3IdListDelete(db, pUsing);
102150  sqlite3SelectDelete(db, pSubquery);
102151  return 0;
102152 }
102153 
102154 /*
102155 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
102156 ** element of the source-list passed as the second argument.
102157 */
102159  assert( pIndexedBy!=0 );
102160  if( p && ALWAYS(p->nSrc>0) ){
102161  struct SrcList_item *pItem = &p->a[p->nSrc-1];
102162  assert( pItem->fg.notIndexed==0 );
102163  assert( pItem->fg.isIndexedBy==0 );
102164  assert( pItem->fg.isTabFunc==0 );
102165  if( pIndexedBy->n==1 && !pIndexedBy->z ){
102166  /* A "NOT INDEXED" clause was supplied. See parse.y
102167  ** construct "indexed_opt" for details. */
102168  pItem->fg.notIndexed = 1;
102169  }else{
102170  pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
102171  pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
102172  }
102173  }
102174 }
102175 
102176 /*
102177 ** Add the list of function arguments to the SrcList entry for a
102178 ** table-valued-function.
102179 */
102181  if( p ){
102182  struct SrcList_item *pItem = &p->a[p->nSrc-1];
102183  assert( pItem->fg.notIndexed==0 );
102184  assert( pItem->fg.isIndexedBy==0 );
102185  assert( pItem->fg.isTabFunc==0 );
102186  pItem->u1.pFuncArg = pList;
102187  pItem->fg.isTabFunc = 1;
102188  }else{
102189  sqlite3ExprListDelete(pParse->db, pList);
102190  }
102191 }
102192 
102193 /*
102194 ** When building up a FROM clause in the parser, the join operator
102195 ** is initially attached to the left operand. But the code generator
102196 ** expects the join operator to be on the right operand. This routine
102197 ** Shifts all join operators from left to right for an entire FROM
102198 ** clause.
102199 **
102200 ** Example: Suppose the join is like this:
102201 **
102202 ** A natural cross join B
102203 **
102204 ** The operator is "natural cross join". The A and B operands are stored
102205 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
102206 ** operator with A. This routine shifts that operator over to B.
102207 */
102209  if( p ){
102210  int i;
102211  for(i=p->nSrc-1; i>0; i--){
102212  p->a[i].fg.jointype = p->a[i-1].fg.jointype;
102213  }
102214  p->a[0].fg.jointype = 0;
102215  }
102216 }
102217 
102218 /*
102219 ** Generate VDBE code for a BEGIN statement.
102220 */
102222  sqlite3 *db;
102223  Vdbe *v;
102224  int i;
102225 
102226  assert( pParse!=0 );
102227  db = pParse->db;
102228  assert( db!=0 );
102229  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
102230  return;
102231  }
102232  v = sqlite3GetVdbe(pParse);
102233  if( !v ) return;
102234  if( type!=TK_DEFERRED ){
102235  for(i=0; i<db->nDb; i++){
102236  sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
102237  sqlite3VdbeUsesBtree(v, i);
102238  }
102239  }
102241 }
102242 
102243 /*
102244 ** Generate VDBE code for a COMMIT statement.
102245 */
102247  Vdbe *v;
102248 
102249  assert( pParse!=0 );
102250  assert( pParse->db!=0 );
102251  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
102252  return;
102253  }
102254  v = sqlite3GetVdbe(pParse);
102255  if( v ){
102257  }
102258 }
102259 
102260 /*
102261 ** Generate VDBE code for a ROLLBACK statement.
102262 */
102264  Vdbe *v;
102265 
102266  assert( pParse!=0 );
102267  assert( pParse->db!=0 );
102268  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
102269  return;
102270  }
102271  v = sqlite3GetVdbe(pParse);
102272  if( v ){
102273  sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
102274  }
102275 }
102276 
102277 /*
102278 ** This function is called by the parser when it parses a command to create,
102279 ** release or rollback an SQL savepoint.
102280 */
102281 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
102282  char *zName = sqlite3NameFromToken(pParse->db, pName);
102283  if( zName ){
102284  Vdbe *v = sqlite3GetVdbe(pParse);
102285 #ifndef SQLITE_OMIT_AUTHORIZATION
102286  static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
102287  assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
102288 #endif
102289  if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
102290  sqlite3DbFree(pParse->db, zName);
102291  return;
102292  }
102293  sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
102294  }
102295 }
102296 
102297 /*
102298 ** Make sure the TEMP database is open and available for use. Return
102299 ** the number of errors. Leave any error messages in the pParse structure.
102300 */
102302  sqlite3 *db = pParse->db;
102303  if( db->aDb[1].pBt==0 && !pParse->explain ){
102304  int rc;
102305  Btree *pBt;
102306  static const int flags =
102312 
102313  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
102314  if( rc!=SQLITE_OK ){
102315  sqlite3ErrorMsg(pParse, "unable to open a temporary database "
102316  "file for storing temporary tables");
102317  pParse->rc = rc;
102318  return 1;
102319  }
102320  db->aDb[1].pBt = pBt;
102321  assert( db->aDb[1].pSchema );
102322  if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
102323  sqlite3OomFault(db);
102324  return 1;
102325  }
102326  }
102327  return 0;
102328 }
102329 
102330 /*
102331 ** Record the fact that the schema cookie will need to be verified
102332 ** for database iDb. The code to actually verify the schema cookie
102333 ** will occur at the end of the top-level VDBE and will be generated
102334 ** later, by sqlite3FinishCoding().
102335 */
102337  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102338 
102339  assert( iDb>=0 && iDb<pParse->db->nDb );
102340  assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
102341  assert( iDb<SQLITE_MAX_ATTACHED+2 );
102342  assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
102343  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
102344  DbMaskSet(pToplevel->cookieMask, iDb);
102345  if( !OMIT_TEMPDB && iDb==1 ){
102346  sqlite3OpenTempDatabase(pToplevel);
102347  }
102348  }
102349 }
102350 
102351 /*
102352 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
102353 ** attached database. Otherwise, invoke it for the database named zDb only.
102354 */
102355 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
102356  sqlite3 *db = pParse->db;
102357  int i;
102358  for(i=0; i<db->nDb; i++){
102359  Db *pDb = &db->aDb[i];
102360  if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
102361  sqlite3CodeVerifySchema(pParse, i);
102362  }
102363  }
102364 }
102365 
102366 /*
102367 ** Generate VDBE code that prepares for doing an operation that
102368 ** might change the database.
102369 **
102370 ** This routine starts a new transaction if we are not already within
102371 ** a transaction. If we are already within a transaction, then a checkpoint
102372 ** is set if the setStatement parameter is true. A checkpoint should
102373 ** be set for operations that might fail (due to a constraint) part of
102374 ** the way through and which will need to undo some writes without having to
102375 ** rollback the whole transaction. For operations where all constraints
102376 ** can be checked before any changes are made to the database, it is never
102377 ** necessary to undo a write and the checkpoint should not be set.
102378 */
102379 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
102380  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102381  sqlite3CodeVerifySchema(pParse, iDb);
102382  DbMaskSet(pToplevel->writeMask, iDb);
102383  pToplevel->isMultiWrite |= setStatement;
102384 }
102385 
102386 /*
102387 ** Indicate that the statement currently under construction might write
102388 ** more than one entry (example: deleting one row then inserting another,
102389 ** inserting multiple rows in a table, or inserting a row and index entries.)
102390 ** If an abort occurs after some of these writes have completed, then it will
102391 ** be necessary to undo the completed writes.
102392 */
102394  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102395  pToplevel->isMultiWrite = 1;
102396 }
102397 
102398 /*
102399 ** The code generator calls this routine if is discovers that it is
102400 ** possible to abort a statement prior to completion. In order to
102401 ** perform this abort without corrupting the database, we need to make
102402 ** sure that the statement is protected by a statement transaction.
102403 **
102404 ** Technically, we only need to set the mayAbort flag if the
102405 ** isMultiWrite flag was previously set. There is a time dependency
102406 ** such that the abort must occur after the multiwrite. This makes
102407 ** some statements involving the REPLACE conflict resolution algorithm
102408 ** go a little faster. But taking advantage of this time dependency
102409 ** makes it more difficult to prove that the code is correct (in
102410 ** particular, it prevents us from writing an effective
102411 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
102412 ** to take the safe route and skip the optimization.
102413 */
102415  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102416  pToplevel->mayAbort = 1;
102417 }
102418 
102419 /*
102420 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
102421 ** error. The onError parameter determines which (if any) of the statement
102422 ** and/or current transaction is rolled back.
102423 */
102425  Parse *pParse, /* Parsing context */
102426  int errCode, /* extended error code */
102427  int onError, /* Constraint type */
102428  char *p4, /* Error message */
102429  i8 p4type, /* P4_STATIC or P4_TRANSIENT */
102430  u8 p5Errmsg /* P5_ErrMsg type */
102431 ){
102432  Vdbe *v = sqlite3GetVdbe(pParse);
102433  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
102434  if( onError==OE_Abort ){
102435  sqlite3MayAbort(pParse);
102436  }
102437  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
102438  sqlite3VdbeChangeP5(v, p5Errmsg);
102439 }
102440 
102441 /*
102442 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
102443 */
102445  Parse *pParse, /* Parsing context */
102446  int onError, /* Constraint type */
102447  Index *pIdx /* The index that triggers the constraint */
102448 ){
102449  char *zErr;
102450  int j;
102451  StrAccum errMsg;
102452  Table *pTab = pIdx->pTable;
102453 
102454  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
102455  if( pIdx->aColExpr ){
102456  sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
102457  }else{
102458  for(j=0; j<pIdx->nKeyCol; j++){
102459  char *zCol;
102460  assert( pIdx->aiColumn[j]>=0 );
102461  zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
102462  if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
102463  sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
102464  }
102465  }
102466  zErr = sqlite3StrAccumFinish(&errMsg);
102467  sqlite3HaltConstraint(pParse,
102470  onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
102471 }
102472 
102473 
102474 /*
102475 ** Code an OP_Halt due to non-unique rowid.
102476 */
102478  Parse *pParse, /* Parsing context */
102479  int onError, /* Conflict resolution algorithm */
102480  Table *pTab /* The table with the non-unique rowid */
102481 ){
102482  char *zMsg;
102483  int rc;
102484  if( pTab->iPKey>=0 ){
102485  zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
102486  pTab->aCol[pTab->iPKey].zName);
102488  }else{
102489  zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
102491  }
102492  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
102494 }
102495 
102496 /*
102497 ** Check to see if pIndex uses the collating sequence pColl. Return
102498 ** true if it does and false if it does not.
102499 */
102500 #ifndef SQLITE_OMIT_REINDEX
102501 static int collationMatch(const char *zColl, Index *pIndex){
102502  int i;
102503  assert( zColl!=0 );
102504  for(i=0; i<pIndex->nColumn; i++){
102505  const char *z = pIndex->azColl[i];
102506  assert( z!=0 || pIndex->aiColumn[i]<0 );
102507  if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
102508  return 1;
102509  }
102510  }
102511  return 0;
102512 }
102513 #endif
102514 
102515 /*
102516 ** Recompute all indices of pTab that use the collating sequence pColl.
102517 ** If pColl==0 then recompute all indices of pTab.
102518 */
102519 #ifndef SQLITE_OMIT_REINDEX
102520 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
102521  Index *pIndex; /* An index associated with pTab */
102522 
102523  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
102524  if( zColl==0 || collationMatch(zColl, pIndex) ){
102525  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102526  sqlite3BeginWriteOperation(pParse, 0, iDb);
102527  sqlite3RefillIndex(pParse, pIndex, -1);
102528  }
102529  }
102530 }
102531 #endif
102532 
102533 /*
102534 ** Recompute all indices of all tables in all databases where the
102535 ** indices use the collating sequence pColl. If pColl==0 then recompute
102536 ** all indices everywhere.
102537 */
102538 #ifndef SQLITE_OMIT_REINDEX
102539 static void reindexDatabases(Parse *pParse, char const *zColl){
102540  Db *pDb; /* A single database */
102541  int iDb; /* The database index number */
102542  sqlite3 *db = pParse->db; /* The database connection */
102543  HashElem *k; /* For looping over tables in pDb */
102544  Table *pTab; /* A table in the database */
102545 
102546  assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
102547  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
102548  assert( pDb!=0 );
102549  for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
102550  pTab = (Table*)sqliteHashData(k);
102551  reindexTable(pParse, pTab, zColl);
102552  }
102553  }
102554 }
102555 #endif
102556 
102557 /*
102558 ** Generate code for the REINDEX command.
102559 **
102560 ** REINDEX -- 1
102561 ** REINDEX <collation> -- 2
102562 ** REINDEX ?<database>.?<tablename> -- 3
102563 ** REINDEX ?<database>.?<indexname> -- 4
102564 **
102565 ** Form 1 causes all indices in all attached databases to be rebuilt.
102566 ** Form 2 rebuilds all indices in all databases that use the named
102567 ** collating function. Forms 3 and 4 rebuild the named index or all
102568 ** indices associated with the named table.
102569 */
102570 #ifndef SQLITE_OMIT_REINDEX
102571 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
102572  CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
102573  char *z; /* Name of a table or index */
102574  const char *zDb; /* Name of the database */
102575  Table *pTab; /* A table in the database */
102576  Index *pIndex; /* An index associated with pTab */
102577  int iDb; /* The database index number */
102578  sqlite3 *db = pParse->db; /* The database connection */
102579  Token *pObjName; /* Name of the table or index to be reindexed */
102580 
102581  /* Read the database schema. If an error occurs, leave an error message
102582  ** and code in pParse and return NULL. */
102583  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
102584  return;
102585  }
102586 
102587  if( pName1==0 ){
102588  reindexDatabases(pParse, 0);
102589  return;
102590  }else if( NEVER(pName2==0) || pName2->z==0 ){
102591  char *zColl;
102592  assert( pName1->z );
102593  zColl = sqlite3NameFromToken(pParse->db, pName1);
102594  if( !zColl ) return;
102595  pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
102596  if( pColl ){
102597  reindexDatabases(pParse, zColl);
102598  sqlite3DbFree(db, zColl);
102599  return;
102600  }
102601  sqlite3DbFree(db, zColl);
102602  }
102603  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
102604  if( iDb<0 ) return;
102605  z = sqlite3NameFromToken(db, pObjName);
102606  if( z==0 ) return;
102607  zDb = db->aDb[iDb].zDbSName;
102608  pTab = sqlite3FindTable(db, z, zDb);
102609  if( pTab ){
102610  reindexTable(pParse, pTab, 0);
102611  sqlite3DbFree(db, z);
102612  return;
102613  }
102614  pIndex = sqlite3FindIndex(db, z, zDb);
102615  sqlite3DbFree(db, z);
102616  if( pIndex ){
102617  sqlite3BeginWriteOperation(pParse, 0, iDb);
102618  sqlite3RefillIndex(pParse, pIndex, -1);
102619  return;
102620  }
102621  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
102622 }
102623 #endif
102624 
102625 /*
102626 ** Return a KeyInfo structure that is appropriate for the given Index.
102627 **
102628 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
102629 ** when it has finished using it.
102630 */
102632  int i;
102633  int nCol = pIdx->nColumn;
102634  int nKey = pIdx->nKeyCol;
102635  KeyInfo *pKey;
102636  if( pParse->nErr ) return 0;
102637  if( pIdx->uniqNotNull ){
102638  pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
102639  }else{
102640  pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
102641  }
102642  if( pKey ){
102643  assert( sqlite3KeyInfoIsWriteable(pKey) );
102644  for(i=0; i<nCol; i++){
102645  const char *zColl = pIdx->azColl[i];
102646  pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
102647  sqlite3LocateCollSeq(pParse, zColl);
102648  pKey->aSortOrder[i] = pIdx->aSortOrder[i];
102649  }
102650  if( pParse->nErr ){
102651  sqlite3KeyInfoUnref(pKey);
102652  pKey = 0;
102653  }
102654  }
102655  return pKey;
102656 }
102657 
102658 #ifndef SQLITE_OMIT_CTE
102659 /*
102660 ** This routine is invoked once per CTE by the parser while parsing a
102661 ** WITH clause.
102662 */
102664  Parse *pParse, /* Parsing context */
102665  With *pWith, /* Existing WITH clause, or NULL */
102666  Token *pName, /* Name of the common-table */
102667  ExprList *pArglist, /* Optional column name list for the table */
102668  Select *pQuery /* Query used to initialize the table */
102669 ){
102670  sqlite3 *db = pParse->db;
102671  With *pNew;
102672  char *zName;
102673 
102674  /* Check that the CTE name is unique within this WITH clause. If
102675  ** not, store an error in the Parse structure. */
102676  zName = sqlite3NameFromToken(pParse->db, pName);
102677  if( zName && pWith ){
102678  int i;
102679  for(i=0; i<pWith->nCte; i++){
102680  if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
102681  sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
102682  }
102683  }
102684  }
102685 
102686  if( pWith ){
102687  int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
102688  pNew = sqlite3DbRealloc(db, pWith, nByte);
102689  }else{
102690  pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
102691  }
102692  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
102693 
102694  if( db->mallocFailed ){
102695  sqlite3ExprListDelete(db, pArglist);
102696  sqlite3SelectDelete(db, pQuery);
102697  sqlite3DbFree(db, zName);
102698  pNew = pWith;
102699  }else{
102700  pNew->a[pNew->nCte].pSelect = pQuery;
102701  pNew->a[pNew->nCte].pCols = pArglist;
102702  pNew->a[pNew->nCte].zName = zName;
102703  pNew->a[pNew->nCte].zCteErr = 0;
102704  pNew->nCte++;
102705  }
102706 
102707  return pNew;
102708 }
102709 
102710 /*
102711 ** Free the contents of the With object passed as the second argument.
102712 */
102714  if( pWith ){
102715  int i;
102716  for(i=0; i<pWith->nCte; i++){
102717  struct Cte *pCte = &pWith->a[i];
102718  sqlite3ExprListDelete(db, pCte->pCols);
102719  sqlite3SelectDelete(db, pCte->pSelect);
102720  sqlite3DbFree(db, pCte->zName);
102721  }
102722  sqlite3DbFree(db, pWith);
102723  }
102724 }
102725 #endif /* !defined(SQLITE_OMIT_CTE) */
102726 
102727 /************** End of build.c ***********************************************/
102728 /************** Begin file callback.c ****************************************/
102729 /*
102730 ** 2005 May 23
102731 **
102732 ** The author disclaims copyright to this source code. In place of
102733 ** a legal notice, here is a blessing:
102734 **
102735 ** May you do good and not evil.
102736 ** May you find forgiveness for yourself and forgive others.
102737 ** May you share freely, never taking more than you give.
102738 **
102739 *************************************************************************
102740 **
102741 ** This file contains functions used to access the internal hash tables
102742 ** of user defined functions and collation sequences.
102743 */
102744 
102745 /* #include "sqliteInt.h" */
102746 
102747 /*
102748 ** Invoke the 'collation needed' callback to request a collation sequence
102749 ** in the encoding enc of name zName, length nName.
102750 */
102751 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
102752  assert( !db->xCollNeeded || !db->xCollNeeded16 );
102753  if( db->xCollNeeded ){
102754  char *zExternal = sqlite3DbStrDup(db, zName);
102755  if( !zExternal ) return;
102756  db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
102757  sqlite3DbFree(db, zExternal);
102758  }
102759 #ifndef SQLITE_OMIT_UTF16
102760  if( db->xCollNeeded16 ){
102761  char const *zExternal;
102762  sqlite3_value *pTmp = sqlite3ValueNew(db);
102763  sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
102764  zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
102765  if( zExternal ){
102766  db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
102767  }
102768  sqlite3ValueFree(pTmp);
102769  }
102770 #endif
102771 }
102772 
102773 /*
102774 ** This routine is called if the collation factory fails to deliver a
102775 ** collation function in the best encoding but there may be other versions
102776 ** of this collation function (for other text encodings) available. Use one
102777 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
102778 ** possible.
102779 */
102780 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
102781  CollSeq *pColl2;
102782  char *z = pColl->zName;
102783  int i;
102784  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
102785  for(i=0; i<3; i++){
102786  pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
102787  if( pColl2->xCmp!=0 ){
102788  memcpy(pColl, pColl2, sizeof(CollSeq));
102789  pColl->xDel = 0; /* Do not copy the destructor */
102790  return SQLITE_OK;
102791  }
102792  }
102793  return SQLITE_ERROR;
102794 }
102795 
102796 /*
102797 ** This function is responsible for invoking the collation factory callback
102798 ** or substituting a collation sequence of a different encoding when the
102799 ** requested collation sequence is not available in the desired encoding.
102800 **
102801 ** If it is not NULL, then pColl must point to the database native encoding
102802 ** collation sequence with name zName, length nName.
102803 **
102804 ** The return value is either the collation sequence to be used in database
102805 ** db for collation type name zName, length nName, or NULL, if no collation
102806 ** sequence can be found. If no collation is found, leave an error message.
102807 **
102808 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
102809 */
102811  Parse *pParse, /* Parsing context */
102812  u8 enc, /* The desired encoding for the collating sequence */
102813  CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
102814  const char *zName /* Collating sequence name */
102815 ){
102816  CollSeq *p;
102817  sqlite3 *db = pParse->db;
102818 
102819  p = pColl;
102820  if( !p ){
102821  p = sqlite3FindCollSeq(db, enc, zName, 0);
102822  }
102823  if( !p || !p->xCmp ){
102824  /* No collation sequence of this type for this encoding is registered.
102825  ** Call the collation factory to see if it can supply us with one.
102826  */
102827  callCollNeeded(db, enc, zName);
102828  p = sqlite3FindCollSeq(db, enc, zName, 0);
102829  }
102830  if( p && !p->xCmp && synthCollSeq(db, p) ){
102831  p = 0;
102832  }
102833  assert( !p || p->xCmp );
102834  if( p==0 ){
102835  sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
102836  }
102837  return p;
102838 }
102839 
102840 /*
102841 ** This routine is called on a collation sequence before it is used to
102842 ** check that it is defined. An undefined collation sequence exists when
102843 ** a database is loaded that contains references to collation sequences
102844 ** that have not been defined by sqlite3_create_collation() etc.
102845 **
102846 ** If required, this routine calls the 'collation needed' callback to
102847 ** request a definition of the collating sequence. If this doesn't work,
102848 ** an equivalent collating sequence that uses a text encoding different
102849 ** from the main database is substituted, if one is available.
102850 */
102852  if( pColl ){
102853  const char *zName = pColl->zName;
102854  sqlite3 *db = pParse->db;
102855  CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
102856  if( !p ){
102857  return SQLITE_ERROR;
102858  }
102859  assert( p==pColl );
102860  }
102861  return SQLITE_OK;
102862 }
102863 
102864 
102865 
102866 /*
102867 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
102868 ** specified by zName and nName is not found and parameter 'create' is
102869 ** true, then create a new entry. Otherwise return NULL.
102870 **
102871 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
102872 ** array of three CollSeq structures. The first is the collation sequence
102873 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
102874 **
102875 ** Stored immediately after the three collation sequences is a copy of
102876 ** the collation sequence name. A pointer to this string is stored in
102877 ** each collation sequence structure.
102878 */
102880  sqlite3 *db, /* Database connection */
102881  const char *zName, /* Name of the collating sequence */
102882  int create /* Create a new entry if true */
102883 ){
102884  CollSeq *pColl;
102885  pColl = sqlite3HashFind(&db->aCollSeq, zName);
102886 
102887  if( 0==pColl && create ){
102888  int nName = sqlite3Strlen30(zName);
102889  pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
102890  if( pColl ){
102891  CollSeq *pDel = 0;
102892  pColl[0].zName = (char*)&pColl[3];
102893  pColl[0].enc = SQLITE_UTF8;
102894  pColl[1].zName = (char*)&pColl[3];
102895  pColl[1].enc = SQLITE_UTF16LE;
102896  pColl[2].zName = (char*)&pColl[3];
102897  pColl[2].enc = SQLITE_UTF16BE;
102898  memcpy(pColl[0].zName, zName, nName);
102899  pColl[0].zName[nName] = 0;
102900  pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
102901 
102902  /* If a malloc() failure occurred in sqlite3HashInsert(), it will
102903  ** return the pColl pointer to be deleted (because it wasn't added
102904  ** to the hash table).
102905  */
102906  assert( pDel==0 || pDel==pColl );
102907  if( pDel!=0 ){
102908  sqlite3OomFault(db);
102909  sqlite3DbFree(db, pDel);
102910  pColl = 0;
102911  }
102912  }
102913  }
102914  return pColl;
102915 }
102916 
102917 /*
102918 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
102919 ** Return the CollSeq* pointer for the collation sequence named zName
102920 ** for the encoding 'enc' from the database 'db'.
102921 **
102922 ** If the entry specified is not found and 'create' is true, then create a
102923 ** new entry. Otherwise return NULL.
102924 **
102925 ** A separate function sqlite3LocateCollSeq() is a wrapper around
102926 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
102927 ** if necessary and generates an error message if the collating sequence
102928 ** cannot be found.
102929 **
102930 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
102931 */
102933  sqlite3 *db,
102934  u8 enc,
102935  const char *zName,
102936  int create
102937 ){
102938  CollSeq *pColl;
102939  if( zName ){
102940  pColl = findCollSeqEntry(db, zName, create);
102941  }else{
102942  pColl = db->pDfltColl;
102943  }
102944  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
102945  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
102946  if( pColl ) pColl += enc-1;
102947  return pColl;
102948 }
102949 
102950 /* During the search for the best function definition, this procedure
102951 ** is called to test how well the function passed as the first argument
102952 ** matches the request for a function with nArg arguments in a system
102953 ** that uses encoding enc. The value returned indicates how well the
102954 ** request is matched. A higher value indicates a better match.
102955 **
102956 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
102957 ** is also -1. In other words, we are searching for a function that
102958 ** takes a variable number of arguments.
102959 **
102960 ** If nArg is -2 that means that we are searching for any function
102961 ** regardless of the number of arguments it uses, so return a positive
102962 ** match score for any
102963 **
102964 ** The returned value is always between 0 and 6, as follows:
102965 **
102966 ** 0: Not a match.
102967 ** 1: UTF8/16 conversion required and function takes any number of arguments.
102968 ** 2: UTF16 byte order change required and function takes any number of args.
102969 ** 3: encoding matches and function takes any number of arguments
102970 ** 4: UTF8/16 conversion required - argument count matches exactly
102971 ** 5: UTF16 byte order conversion required - argument count matches exactly
102972 ** 6: Perfect match: encoding and argument count match exactly.
102973 **
102974 ** If nArg==(-2) then any function with a non-null xSFunc is
102975 ** a perfect match and any function with xSFunc NULL is
102976 ** a non-match.
102977 */
102978 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
102979 static int matchQuality(
102980  FuncDef *p, /* The function we are evaluating for match quality */
102981  int nArg, /* Desired number of arguments. (-1)==any */
102982  u8 enc /* Desired text encoding */
102983 ){
102984  int match;
102985 
102986  /* nArg of -2 is a special case */
102987  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
102988 
102989  /* Wrong number of arguments means "no match" */
102990  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
102991 
102992  /* Give a better score to a function with a specific number of arguments
102993  ** than to function that accepts any number of arguments. */
102994  if( p->nArg==nArg ){
102995  match = 4;
102996  }else{
102997  match = 1;
102998  }
102999 
103000  /* Bonus points if the text encoding matches */
103001  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
103002  match += 2; /* Exact encoding match */
103003  }else if( (enc & p->funcFlags & 2)!=0 ){
103004  match += 1; /* Both are UTF16, but with different byte orders */
103005  }
103006 
103007  return match;
103008 }
103009 
103010 /*
103011 ** Search a FuncDefHash for a function with the given name. Return
103012 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
103013 */
103015  int h, /* Hash of the name */
103016  const char *zFunc /* Name of function */
103017 ){
103018  FuncDef *p;
103019  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
103020  if( sqlite3StrICmp(p->zName, zFunc)==0 ){
103021  return p;
103022  }
103023  }
103024  return 0;
103025 }
103026 
103027 /*
103028 ** Insert a new FuncDef into a FuncDefHash hash table.
103029 */
103031  FuncDef *aDef, /* List of global functions to be inserted */
103032  int nDef /* Length of the apDef[] list */
103033 ){
103034  int i;
103035  for(i=0; i<nDef; i++){
103036  FuncDef *pOther;
103037  const char *zName = aDef[i].zName;
103038  int nName = sqlite3Strlen30(zName);
103039  int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
103040  pOther = functionSearch(h, zName);
103041  if( pOther ){
103042  assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
103043  aDef[i].pNext = pOther->pNext;
103044  pOther->pNext = &aDef[i];
103045  }else{
103046  aDef[i].pNext = 0;
103047  aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
103048  sqlite3BuiltinFunctions.a[h] = &aDef[i];
103049  }
103050  }
103051 }
103052 
103053 
103054 
103055 /*
103056 ** Locate a user function given a name, a number of arguments and a flag
103057 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
103058 ** pointer to the FuncDef structure that defines that function, or return
103059 ** NULL if the function does not exist.
103060 **
103061 ** If the createFlag argument is true, then a new (blank) FuncDef
103062 ** structure is created and liked into the "db" structure if a
103063 ** no matching function previously existed.
103064 **
103065 ** If nArg is -2, then the first valid function found is returned. A
103066 ** function is valid if xSFunc is non-zero. The nArg==(-2)
103067 ** case is used to see if zName is a valid function name for some number
103068 ** of arguments. If nArg is -2, then createFlag must be 0.
103069 **
103070 ** If createFlag is false, then a function with the required name and
103071 ** number of arguments may be returned even if the eTextRep flag does not
103072 ** match that requested.
103073 */
103075  sqlite3 *db, /* An open database */
103076  const char *zName, /* Name of the function. zero-terminated */
103077  int nArg, /* Number of arguments. -1 means any number */
103078  u8 enc, /* Preferred text encoding */
103079  u8 createFlag /* Create new entry if true and does not otherwise exist */
103080 ){
103081  FuncDef *p; /* Iterator variable */
103082  FuncDef *pBest = 0; /* Best match found so far */
103083  int bestScore = 0; /* Score of best match */
103084  int h; /* Hash value */
103085  int nName; /* Length of the name */
103086 
103087  assert( nArg>=(-2) );
103088  assert( nArg>=(-1) || createFlag==0 );
103089  nName = sqlite3Strlen30(zName);
103090 
103091  /* First search for a match amongst the application-defined functions.
103092  */
103093  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
103094  while( p ){
103095  int score = matchQuality(p, nArg, enc);
103096  if( score>bestScore ){
103097  pBest = p;
103098  bestScore = score;
103099  }
103100  p = p->pNext;
103101  }
103102 
103103  /* If no match is found, search the built-in functions.
103104  **
103105  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
103106  ** functions even if a prior app-defined function was found. And give
103107  ** priority to built-in functions.
103108  **
103109  ** Except, if createFlag is true, that means that we are trying to
103110  ** install a new function. Whatever FuncDef structure is returned it will
103111  ** have fields overwritten with new information appropriate for the
103112  ** new function. But the FuncDefs for built-in functions are read-only.
103113  ** So we must not search for built-ins when creating a new function.
103114  */
103115  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
103116  bestScore = 0;
103117  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
103118  p = functionSearch(h, zName);
103119  while( p ){
103120  int score = matchQuality(p, nArg, enc);
103121  if( score>bestScore ){
103122  pBest = p;
103123  bestScore = score;
103124  }
103125  p = p->pNext;
103126  }
103127  }
103128 
103129  /* If the createFlag parameter is true and the search did not reveal an
103130  ** exact match for the name, number of arguments and encoding, then add a
103131  ** new entry to the hash table and return it.
103132  */
103133  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
103134  (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
103135  FuncDef *pOther;
103136  pBest->zName = (const char*)&pBest[1];
103137  pBest->nArg = (u16)nArg;
103138  pBest->funcFlags = enc;
103139  memcpy((char*)&pBest[1], zName, nName+1);
103140  pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
103141  if( pOther==pBest ){
103142  sqlite3DbFree(db, pBest);
103143  sqlite3OomFault(db);
103144  return 0;
103145  }else{
103146  pBest->pNext = pOther;
103147  }
103148  }
103149 
103150  if( pBest && (pBest->xSFunc || createFlag) ){
103151  return pBest;
103152  }
103153  return 0;
103154 }
103155 
103156 /*
103157 ** Free all resources held by the schema structure. The void* argument points
103158 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
103159 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
103160 ** of the schema hash tables).
103161 **
103162 ** The Schema.cache_size variable is not cleared.
103163 */
103165  Hash temp1;
103166  Hash temp2;
103167  HashElem *pElem;
103168  Schema *pSchema = (Schema *)p;
103169 
103170  temp1 = pSchema->tblHash;
103171  temp2 = pSchema->trigHash;
103172  sqlite3HashInit(&pSchema->trigHash);
103173  sqlite3HashClear(&pSchema->idxHash);
103174  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
103176  }
103177  sqlite3HashClear(&temp2);
103178  sqlite3HashInit(&pSchema->tblHash);
103179  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
103180  Table *pTab = sqliteHashData(pElem);
103181  sqlite3DeleteTable(0, pTab);
103182  }
103183  sqlite3HashClear(&temp1);
103184  sqlite3HashClear(&pSchema->fkeyHash);
103185  pSchema->pSeqTab = 0;
103186  if( pSchema->schemaFlags & DB_SchemaLoaded ){
103187  pSchema->iGeneration++;
103188  pSchema->schemaFlags &= ~DB_SchemaLoaded;
103189  }
103190 }
103191 
103192 /*
103193 ** Find and return the schema associated with a BTree. Create
103194 ** a new one if necessary.
103195 */
103197  Schema * p;
103198  if( pBt ){
103199  p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
103200  }else{
103201  p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
103202  }
103203  if( !p ){
103204  sqlite3OomFault(db);
103205  }else if ( 0==p->file_format ){
103206  sqlite3HashInit(&p->tblHash);
103207  sqlite3HashInit(&p->idxHash);
103208  sqlite3HashInit(&p->trigHash);
103209  sqlite3HashInit(&p->fkeyHash);
103210  p->enc = SQLITE_UTF8;
103211  }
103212  return p;
103213 }
103214 
103215 /************** End of callback.c ********************************************/
103216 /************** Begin file delete.c ******************************************/
103217 /*
103218 ** 2001 September 15
103219 **
103220 ** The author disclaims copyright to this source code. In place of
103221 ** a legal notice, here is a blessing:
103222 **
103223 ** May you do good and not evil.
103224 ** May you find forgiveness for yourself and forgive others.
103225 ** May you share freely, never taking more than you give.
103226 **
103227 *************************************************************************
103228 ** This file contains C code routines that are called by the parser
103229 ** in order to generate code for DELETE FROM statements.
103230 */
103231 /* #include "sqliteInt.h" */
103232 
103233 /*
103234 ** While a SrcList can in general represent multiple tables and subqueries
103235 ** (as in the FROM clause of a SELECT statement) in this case it contains
103236 ** the name of a single table, as one might find in an INSERT, DELETE,
103237 ** or UPDATE statement. Look up that table in the symbol table and
103238 ** return a pointer. Set an error message and return NULL if the table
103239 ** name is not found or if any other error occurs.
103240 **
103241 ** The following fields are initialized appropriate in pSrc:
103242 **
103243 ** pSrc->a[0].pTab Pointer to the Table object
103244 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
103245 **
103246 */
103248  struct SrcList_item *pItem = pSrc->a;
103249  Table *pTab;
103250  assert( pItem && pSrc->nSrc==1 );
103251  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
103252  sqlite3DeleteTable(pParse->db, pItem->pTab);
103253  pItem->pTab = pTab;
103254  if( pTab ){
103255  pTab->nRef++;
103256  }
103257  if( sqlite3IndexedByLookup(pParse, pItem) ){
103258  pTab = 0;
103259  }
103260  return pTab;
103261 }
103262 
103263 /*
103264 ** Check to make sure the given table is writable. If it is not
103265 ** writable, generate an error message and return 1. If it is
103266 ** writable return 0;
103267 */
103268 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
103269  /* A table is not writable under the following circumstances:
103270  **
103271  ** 1) It is a virtual table and no implementation of the xUpdate method
103272  ** has been provided, or
103273  ** 2) It is a system table (i.e. sqlite_master), this call is not
103274  ** part of a nested parse and writable_schema pragma has not
103275  ** been specified.
103276  **
103277  ** In either case leave an error message in pParse and return non-zero.
103278  */
103279  if( ( IsVirtual(pTab)
103280  && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
103281  || ( (pTab->tabFlags & TF_Readonly)!=0
103282  && (pParse->db->flags & SQLITE_WriteSchema)==0
103283  && pParse->nested==0 )
103284  ){
103285  sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
103286  return 1;
103287  }
103288 
103289 #ifndef SQLITE_OMIT_VIEW
103290  if( !viewOk && pTab->pSelect ){
103291  sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
103292  return 1;
103293  }
103294 #endif
103295  return 0;
103296 }
103297 
103298 
103299 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
103300 /*
103301 ** Evaluate a view and store its result in an ephemeral table. The
103302 ** pWhere argument is an optional WHERE clause that restricts the
103303 ** set of rows in the view that are to be added to the ephemeral table.
103304 */
103306  Parse *pParse, /* Parsing context */
103307  Table *pView, /* View definition */
103308  Expr *pWhere, /* Optional WHERE clause to be added */
103309  int iCur /* Cursor number for ephemeral table */
103310 ){
103311  SelectDest dest;
103312  Select *pSel;
103313  SrcList *pFrom;
103314  sqlite3 *db = pParse->db;
103315  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
103316  pWhere = sqlite3ExprDup(db, pWhere, 0);
103317  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
103318  if( pFrom ){
103319  assert( pFrom->nSrc==1 );
103320  pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
103321  pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
103322  assert( pFrom->a[0].pOn==0 );
103323  assert( pFrom->a[0].pUsing==0 );
103324  }
103325  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
103326  SF_IncludeHidden, 0, 0);
103327  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
103328  sqlite3Select(pParse, pSel, &dest);
103329  sqlite3SelectDelete(db, pSel);
103330 }
103331 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
103332 
103333 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
103334 /*
103335 ** Generate an expression tree to implement the WHERE, ORDER BY,
103336 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
103337 **
103338 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
103339 ** \__________________________/
103340 ** pLimitWhere (pInClause)
103341 */
103342 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
103343  Parse *pParse, /* The parser context */
103344  SrcList *pSrc, /* the FROM clause -- which tables to scan */
103345  Expr *pWhere, /* The WHERE clause. May be null */
103346  ExprList *pOrderBy, /* The ORDER BY clause. May be null */
103347  Expr *pLimit, /* The LIMIT clause. May be null */
103348  Expr *pOffset, /* The OFFSET clause. May be null */
103349  char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
103350 ){
103351  Expr *pWhereRowid = NULL; /* WHERE rowid .. */
103352  Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
103353  Expr *pSelectRowid = NULL; /* SELECT rowid ... */
103354  ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
103355  SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
103356  Select *pSelect = NULL; /* Complete SELECT tree */
103357 
103358  /* Check that there isn't an ORDER BY without a LIMIT clause.
103359  */
103360  if( pOrderBy && (pLimit == 0) ) {
103361  sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
103362  goto limit_where_cleanup;
103363  }
103364 
103365  /* We only need to generate a select expression if there
103366  ** is a limit/offset term to enforce.
103367  */
103368  if( pLimit == 0 ) {
103369  /* if pLimit is null, pOffset will always be null as well. */
103370  assert( pOffset == 0 );
103371  return pWhere;
103372  }
103373 
103374  /* Generate a select expression tree to enforce the limit/offset
103375  ** term for the DELETE or UPDATE statement. For example:
103376  ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
103377  ** becomes:
103378  ** DELETE FROM table_a WHERE rowid IN (
103379  ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
103380  ** );
103381  */
103382 
103383  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
103384  if( pSelectRowid == 0 ) goto limit_where_cleanup;
103385  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
103386  if( pEList == 0 ) goto limit_where_cleanup;
103387 
103388  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
103389  ** and the SELECT subtree. */
103390  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
103391  if( pSelectSrc == 0 ) {
103392  sqlite3ExprListDelete(pParse->db, pEList);
103393  goto limit_where_cleanup;
103394  }
103395 
103396  /* generate the SELECT expression tree. */
103397  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
103398  pOrderBy,0,pLimit,pOffset);
103399  if( pSelect == 0 ) return 0;
103400 
103401  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
103402  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
103403  pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
103404  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
103405  return pInClause;
103406 
103407 limit_where_cleanup:
103408  sqlite3ExprDelete(pParse->db, pWhere);
103409  sqlite3ExprListDelete(pParse->db, pOrderBy);
103410  sqlite3ExprDelete(pParse->db, pLimit);
103411  sqlite3ExprDelete(pParse->db, pOffset);
103412  return 0;
103413 }
103414 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
103415  /* && !defined(SQLITE_OMIT_SUBQUERY) */
103416 
103417 /*
103418 ** Generate code for a DELETE FROM statement.
103419 **
103420 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
103421 ** \________/ \________________/
103422 ** pTabList pWhere
103423 */
103425  Parse *pParse, /* The parser context */
103426  SrcList *pTabList, /* The table from which we should delete things */
103427  Expr *pWhere /* The WHERE clause. May be null */
103428 ){
103429  Vdbe *v; /* The virtual database engine */
103430  Table *pTab; /* The table from which records will be deleted */
103431  int i; /* Loop counter */
103432  WhereInfo *pWInfo; /* Information about the WHERE clause */
103433  Index *pIdx; /* For looping over indices of the table */
103434  int iTabCur; /* Cursor number for the table */
103435  int iDataCur = 0; /* VDBE cursor for the canonical data source */
103436  int iIdxCur = 0; /* Cursor number of the first index */
103437  int nIdx; /* Number of indices */
103438  sqlite3 *db; /* Main database structure */
103439  AuthContext sContext; /* Authorization context */
103440  NameContext sNC; /* Name context to resolve expressions in */
103441  int iDb; /* Database number */
103442  int memCnt = -1; /* Memory cell used for change counting */
103443  int rcauth; /* Value returned by authorization callback */
103444  int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
103445  int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
103446  u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
103447  Index *pPk; /* The PRIMARY KEY index on the table */
103448  int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
103449  i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
103450  int iKey; /* Memory cell holding key of row to be deleted */
103451  i16 nKey; /* Number of memory cells in the row key */
103452  int iEphCur = 0; /* Ephemeral table holding all primary key values */
103453  int iRowSet = 0; /* Register for rowset of rows to delete */
103454  int addrBypass = 0; /* Address of jump over the delete logic */
103455  int addrLoop = 0; /* Top of the delete loop */
103456  int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
103457  int bComplex; /* True if there are triggers or FKs or
103458  ** subqueries in the WHERE clause */
103459 
103460 #ifndef SQLITE_OMIT_TRIGGER
103461  int isView; /* True if attempting to delete from a view */
103462  Trigger *pTrigger; /* List of table triggers, if required */
103463 #endif
103464 
103465  memset(&sContext, 0, sizeof(sContext));
103466  db = pParse->db;
103467  if( pParse->nErr || db->mallocFailed ){
103468  goto delete_from_cleanup;
103469  }
103470  assert( pTabList->nSrc==1 );
103471 
103472  /* Locate the table which we want to delete. This table has to be
103473  ** put in an SrcList structure because some of the subroutines we
103474  ** will be calling are designed to work with multiple tables and expect
103475  ** an SrcList* parameter instead of just a Table* parameter.
103476  */
103477  pTab = sqlite3SrcListLookup(pParse, pTabList);
103478  if( pTab==0 ) goto delete_from_cleanup;
103479 
103480  /* Figure out if we have any triggers and if the table being
103481  ** deleted from is a view
103482  */
103483 #ifndef SQLITE_OMIT_TRIGGER
103484  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
103485  isView = pTab->pSelect!=0;
103486  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
103487 #else
103488 # define pTrigger 0
103489 # define isView 0
103490 #endif
103491 #ifdef SQLITE_OMIT_VIEW
103492 # undef isView
103493 # define isView 0
103494 #endif
103495 
103496  /* If pTab is really a view, make sure it has been initialized.
103497  */
103498  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
103499  goto delete_from_cleanup;
103500  }
103501 
103502  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
103503  goto delete_from_cleanup;
103504  }
103505  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103506  assert( iDb<db->nDb );
103507  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
103508  db->aDb[iDb].zDbSName);
103509  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
103510  if( rcauth==SQLITE_DENY ){
103511  goto delete_from_cleanup;
103512  }
103513  assert(!isView || pTrigger);
103514 
103515  /* Assign cursor numbers to the table and all its indices.
103516  */
103517  assert( pTabList->nSrc==1 );
103518  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
103519  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
103520  pParse->nTab++;
103521  }
103522 
103523  /* Start the view context
103524  */
103525  if( isView ){
103526  sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
103527  }
103528 
103529  /* Begin generating code.
103530  */
103531  v = sqlite3GetVdbe(pParse);
103532  if( v==0 ){
103533  goto delete_from_cleanup;
103534  }
103535  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
103536  sqlite3BeginWriteOperation(pParse, 1, iDb);
103537 
103538  /* If we are trying to delete from a view, realize that view into
103539  ** an ephemeral table.
103540  */
103541 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
103542  if( isView ){
103543  sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
103544  iDataCur = iIdxCur = iTabCur;
103545  }
103546 #endif
103547 
103548  /* Resolve the column names in the WHERE clause.
103549  */
103550  memset(&sNC, 0, sizeof(sNC));
103551  sNC.pParse = pParse;
103552  sNC.pSrcList = pTabList;
103553  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
103554  goto delete_from_cleanup;
103555  }
103556 
103557  /* Initialize the counter of the number of rows deleted, if
103558  ** we are counting rows.
103559  */
103560  if( db->flags & SQLITE_CountRows ){
103561  memCnt = ++pParse->nMem;
103562  sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
103563  }
103564 
103565 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
103566  /* Special case: A DELETE without a WHERE clause deletes everything.
103567  ** It is easier just to erase the whole table. Prior to version 3.6.5,
103568  ** this optimization caused the row change count (the value returned by
103569  ** API function sqlite3_count_changes) to be set incorrectly. */
103570  if( rcauth==SQLITE_OK
103571  && pWhere==0
103572  && !bComplex
103573  && !IsVirtual(pTab)
103574 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
103575  && db->xPreUpdateCallback==0
103576 #endif
103577  ){
103578  assert( !isView );
103579  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
103580  if( HasRowid(pTab) ){
103581  sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
103582  pTab->zName, P4_STATIC);
103583  }
103584  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103585  assert( pIdx->pSchema==pTab->pSchema );
103586  sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
103587  }
103588  }else
103589 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
103590  {
103592  if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
103593  wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
103594  if( HasRowid(pTab) ){
103595  /* For a rowid table, initialize the RowSet to an empty set */
103596  pPk = 0;
103597  nPk = 1;
103598  iRowSet = ++pParse->nMem;
103599  sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
103600  }else{
103601  /* For a WITHOUT ROWID table, create an ephemeral table used to
103602  ** hold all primary keys for rows to be deleted. */
103603  pPk = sqlite3PrimaryKeyIndex(pTab);
103604  assert( pPk!=0 );
103605  nPk = pPk->nKeyCol;
103606  iPk = pParse->nMem+1;
103607  pParse->nMem += nPk;
103608  iEphCur = pParse->nTab++;
103609  addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
103610  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
103611  }
103612 
103613  /* Construct a query to find the rowid or primary key for every row
103614  ** to be deleted, based on the WHERE clause. Set variable eOnePass
103615  ** to indicate the strategy used to implement this delete:
103616  **
103617  ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
103618  ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
103619  ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
103620  */
103621  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
103622  if( pWInfo==0 ) goto delete_from_cleanup;
103623  eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
103624  assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
103625  assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
103626 
103627  /* Keep track of the number of rows to be deleted */
103628  if( db->flags & SQLITE_CountRows ){
103629  sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
103630  }
103631 
103632  /* Extract the rowid or primary key for the current row */
103633  if( pPk ){
103634  for(i=0; i<nPk; i++){
103635  assert( pPk->aiColumn[i]>=0 );
103636  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
103637  pPk->aiColumn[i], iPk+i);
103638  }
103639  iKey = iPk;
103640  }else{
103641  iKey = pParse->nMem + 1;
103642  iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
103643  if( iKey>pParse->nMem ) pParse->nMem = iKey;
103644  }
103645 
103646  if( eOnePass!=ONEPASS_OFF ){
103647  /* For ONEPASS, no need to store the rowid/primary-key. There is only
103648  ** one, so just keep it in its register(s) and fall through to the
103649  ** delete code. */
103650  nKey = nPk; /* OP_Found will use an unpacked key */
103651  aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
103652  if( aToOpen==0 ){
103653  sqlite3WhereEnd(pWInfo);
103654  goto delete_from_cleanup;
103655  }
103656  memset(aToOpen, 1, nIdx+1);
103657  aToOpen[nIdx+1] = 0;
103658  if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
103659  if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
103660  if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
103661  }else{
103662  if( pPk ){
103663  /* Add the PK key for this row to the temporary table */
103664  iKey = ++pParse->nMem;
103665  nKey = 0; /* Zero tells OP_Found to use a composite key */
103666  sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
103667  sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
103668  sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
103669  }else{
103670  /* Add the rowid of the row to be deleted to the RowSet */
103671  nKey = 1; /* OP_Seek always uses a single rowid */
103672  sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
103673  }
103674  }
103675 
103676  /* If this DELETE cannot use the ONEPASS strategy, this is the
103677  ** end of the WHERE loop */
103678  if( eOnePass!=ONEPASS_OFF ){
103679  addrBypass = sqlite3VdbeMakeLabel(v);
103680  }else{
103681  sqlite3WhereEnd(pWInfo);
103682  }
103683 
103684  /* Unless this is a view, open cursors for the table we are
103685  ** deleting from and all its indices. If this is a view, then the
103686  ** only effect this statement has is to fire the INSTEAD OF
103687  ** triggers.
103688  */
103689  if( !isView ){
103690  int iAddrOnce = 0;
103691  if( eOnePass==ONEPASS_MULTI ){
103692  iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
103693  }
103694  testcase( IsVirtual(pTab) );
103696  iTabCur, aToOpen, &iDataCur, &iIdxCur);
103697  assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
103698  assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
103699  if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
103700  }
103701 
103702  /* Set up a loop over the rowids/primary-keys that were found in the
103703  ** where-clause loop above.
103704  */
103705  if( eOnePass!=ONEPASS_OFF ){
103706  assert( nKey==nPk ); /* OP_Found will use an unpacked key */
103707  if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
103708  assert( pPk!=0 || pTab->pSelect!=0 );
103709  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
103710  VdbeCoverage(v);
103711  }
103712  }else if( pPk ){
103713  addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
103714  sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
103715  assert( nKey==0 ); /* OP_Found will use a composite key */
103716  }else{
103717  addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
103718  VdbeCoverage(v);
103719  assert( nKey==1 );
103720  }
103721 
103722  /* Delete the row */
103723 #ifndef SQLITE_OMIT_VIRTUALTABLE
103724  if( IsVirtual(pTab) ){
103725  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
103726  sqlite3VtabMakeWritable(pParse, pTab);
103727  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
103729  assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
103730  sqlite3MayAbort(pParse);
103731  if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
103732  pParse->isMultiWrite = 0;
103733  }
103734  }else
103735 #endif
103736  {
103737  int count = (pParse->nested==0); /* True to count changes */
103738  int iIdxNoSeek = -1;
103739  if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
103740  iIdxNoSeek = aiCurOnePass[1];
103741  }
103742  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
103743  iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
103744  }
103745 
103746  /* End of the loop over all rowids/primary-keys. */
103747  if( eOnePass!=ONEPASS_OFF ){
103748  sqlite3VdbeResolveLabel(v, addrBypass);
103749  sqlite3WhereEnd(pWInfo);
103750  }else if( pPk ){
103751  sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
103752  sqlite3VdbeJumpHere(v, addrLoop);
103753  }else{
103754  sqlite3VdbeGoto(v, addrLoop);
103755  sqlite3VdbeJumpHere(v, addrLoop);
103756  }
103757 
103758  /* Close the cursors open on the table and its indexes. */
103759  if( !isView && !IsVirtual(pTab) ){
103760  if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
103761  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
103762  sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
103763  }
103764  }
103765  } /* End non-truncate path */
103766 
103767  /* Update the sqlite_sequence table by storing the content of the
103768  ** maximum rowid counter values recorded while inserting into
103769  ** autoincrement tables.
103770  */
103771  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
103772  sqlite3AutoincrementEnd(pParse);
103773  }
103774 
103775  /* Return the number of rows that were deleted. If this routine is
103776  ** generating code because of a call to sqlite3NestedParse(), do not
103777  ** invoke the callback function.
103778  */
103779  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
103780  sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
103781  sqlite3VdbeSetNumCols(v, 1);
103782  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
103783  }
103784 
103785 delete_from_cleanup:
103786  sqlite3AuthContextPop(&sContext);
103787  sqlite3SrcListDelete(db, pTabList);
103788  sqlite3ExprDelete(db, pWhere);
103789  sqlite3DbFree(db, aToOpen);
103790  return;
103791 }
103792 /* Make sure "isView" and other macros defined above are undefined. Otherwise
103793 ** they may interfere with compilation of other functions in this file
103794 ** (or in another file, if this file becomes part of the amalgamation). */
103795 #ifdef isView
103796  #undef isView
103797 #endif
103798 #ifdef pTrigger
103799  #undef pTrigger
103800 #endif
103801 
103802 /*
103803 ** This routine generates VDBE code that causes a single row of a
103804 ** single table to be deleted. Both the original table entry and
103805 ** all indices are removed.
103806 **
103807 ** Preconditions:
103808 **
103809 ** 1. iDataCur is an open cursor on the btree that is the canonical data
103810 ** store for the table. (This will be either the table itself,
103811 ** in the case of a rowid table, or the PRIMARY KEY index in the case
103812 ** of a WITHOUT ROWID table.)
103813 **
103814 ** 2. Read/write cursors for all indices of pTab must be open as
103815 ** cursor number iIdxCur+i for the i-th index.
103816 **
103817 ** 3. The primary key for the row to be deleted must be stored in a
103818 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
103819 ** that a search record formed from OP_MakeRecord is contained in the
103820 ** single memory location iPk.
103821 **
103822 ** eMode:
103823 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
103824 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
103825 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
103826 ** then this function must seek iDataCur to the entry identified by iPk
103827 ** and nPk before reading from it.
103828 **
103829 ** If eMode is ONEPASS_MULTI, then this call is being made as part
103830 ** of a ONEPASS delete that affects multiple rows. In this case, if
103831 ** iIdxNoSeek is a valid cursor number (>=0), then its position should
103832 ** be preserved following the delete operation. Or, if iIdxNoSeek is not
103833 ** a valid cursor number, the position of iDataCur should be preserved
103834 ** instead.
103835 **
103836 ** iIdxNoSeek:
103837 ** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
103838 ** index cursor (from within array of cursors starting at iIdxCur) that
103839 ** already points to the index entry to be deleted.
103840 */
103842  Parse *pParse, /* Parsing context */
103843  Table *pTab, /* Table containing the row to be deleted */
103844  Trigger *pTrigger, /* List of triggers to (potentially) fire */
103845  int iDataCur, /* Cursor from which column data is extracted */
103846  int iIdxCur, /* First index cursor */
103847  int iPk, /* First memory cell containing the PRIMARY KEY */
103848  i16 nPk, /* Number of PRIMARY KEY memory cells */
103849  u8 count, /* If non-zero, increment the row change counter */
103850  u8 onconf, /* Default ON CONFLICT policy for triggers */
103851  u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
103852  int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
103853 ){
103854  Vdbe *v = pParse->pVdbe; /* Vdbe */
103855  int iOld = 0; /* First register in OLD.* array */
103856  int iLabel; /* Label resolved to end of generated code */
103857  u8 opSeek; /* Seek opcode */
103858 
103859  /* Vdbe is guaranteed to have been allocated by this stage. */
103860  assert( v );
103861  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
103862  iDataCur, iIdxCur, iPk, (int)nPk));
103863 
103864  /* Seek cursor iCur to the row to delete. If this row no longer exists
103865  ** (this can happen if a trigger program has already deleted it), do
103866  ** not attempt to delete it or fire any DELETE triggers. */
103867  iLabel = sqlite3VdbeMakeLabel(v);
103868  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
103869  if( eMode==ONEPASS_OFF ){
103870  sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
103871  VdbeCoverageIf(v, opSeek==OP_NotExists);
103872  VdbeCoverageIf(v, opSeek==OP_NotFound);
103873  }
103874 
103875  /* If there are any triggers to fire, allocate a range of registers to
103876  ** use for the old.* references in the triggers. */
103877  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
103878  u32 mask; /* Mask of OLD.* columns in use */
103879  int iCol; /* Iterator used while populating OLD.* */
103880  int addrStart; /* Start of BEFORE trigger programs */
103881 
103882  /* TODO: Could use temporary registers here. Also could attempt to
103883  ** avoid copying the contents of the rowid register. */
103884  mask = sqlite3TriggerColmask(
103885  pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
103886  );
103887  mask |= sqlite3FkOldmask(pParse, pTab);
103888  iOld = pParse->nMem+1;
103889  pParse->nMem += (1 + pTab->nCol);
103890 
103891  /* Populate the OLD.* pseudo-table register array. These values will be
103892  ** used by any BEFORE and AFTER triggers that exist. */
103893  sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
103894  for(iCol=0; iCol<pTab->nCol; iCol++){
103895  testcase( mask!=0xffffffff && iCol==31 );
103896  testcase( mask!=0xffffffff && iCol==32 );
103897  if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
103898  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
103899  }
103900  }
103901 
103902  /* Invoke BEFORE DELETE trigger programs. */
103903  addrStart = sqlite3VdbeCurrentAddr(v);
103904  sqlite3CodeRowTrigger(pParse, pTrigger,
103905  TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
103906  );
103907 
103908  /* If any BEFORE triggers were coded, then seek the cursor to the
103909  ** row to be deleted again. It may be that the BEFORE triggers moved
103910  ** the cursor or of already deleted the row that the cursor was
103911  ** pointing to.
103912  */
103913  if( addrStart<sqlite3VdbeCurrentAddr(v) ){
103914  sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
103915  VdbeCoverageIf(v, opSeek==OP_NotExists);
103916  VdbeCoverageIf(v, opSeek==OP_NotFound);
103917  }
103918 
103919  /* Do FK processing. This call checks that any FK constraints that
103920  ** refer to this table (i.e. constraints attached to other tables)
103921  ** are not violated by deleting this row. */
103922  sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
103923  }
103924 
103925  /* Delete the index and table entries. Skip this step if pTab is really
103926  ** a view (in which case the only effect of the DELETE statement is to
103927  ** fire the INSTEAD OF triggers).
103928  **
103929  ** If variable 'count' is non-zero, then this OP_Delete instruction should
103930  ** invoke the update-hook. The pre-update-hook, on the other hand should
103931  ** be invoked unless table pTab is a system table. The difference is that
103932  ** the update-hook is not invoked for rows removed by REPLACE, but the
103933  ** pre-update-hook is.
103934  */
103935  if( pTab->pSelect==0 ){
103936  u8 p5 = 0;
103937  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
103938  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
103939  sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
103940  if( eMode!=ONEPASS_OFF ){
103942  }
103943  if( iIdxNoSeek>=0 ){
103944  sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
103945  }
103946  if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
103947  sqlite3VdbeChangeP5(v, p5);
103948  }
103949 
103950  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
103951  ** handle rows (possibly in other tables) that refer via a foreign key
103952  ** to the row just deleted. */
103953  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
103954 
103955  /* Invoke AFTER DELETE trigger programs. */
103956  sqlite3CodeRowTrigger(pParse, pTrigger,
103957  TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
103958  );
103959 
103960  /* Jump here if the row had already been deleted before any BEFORE
103961  ** trigger programs were invoked. Or if a trigger program throws a
103962  ** RAISE(IGNORE) exception. */
103963  sqlite3VdbeResolveLabel(v, iLabel);
103964  VdbeModuleComment((v, "END: GenRowDel()"));
103965 }
103966 
103967 /*
103968 ** This routine generates VDBE code that causes the deletion of all
103969 ** index entries associated with a single row of a single table, pTab
103970 **
103971 ** Preconditions:
103972 **
103973 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
103974 ** btree for the table pTab. (This will be either the table itself
103975 ** for rowid tables or to the primary key index for WITHOUT ROWID
103976 ** tables.)
103977 **
103978 ** 2. Read/write cursors for all indices of pTab must be open as
103979 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
103980 ** index is the 0-th index.)
103981 **
103982 ** 3. The "iDataCur" cursor must be already be positioned on the row
103983 ** that is to be deleted.
103984 */
103986  Parse *pParse, /* Parsing and code generating context */
103987  Table *pTab, /* Table containing the row to be deleted */
103988  int iDataCur, /* Cursor of table holding data. */
103989  int iIdxCur, /* First index cursor */
103990  int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
103991  int iIdxNoSeek /* Do not delete from this cursor */
103992 ){
103993  int i; /* Index loop counter */
103994  int r1 = -1; /* Register holding an index key */
103995  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
103996  Index *pIdx; /* Current index */
103997  Index *pPrior = 0; /* Prior index */
103998  Vdbe *v; /* The prepared statement under construction */
103999  Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
104000 
104001  v = pParse->pVdbe;
104002  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
104003  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
104004  assert( iIdxCur+i!=iDataCur || pPk==pIdx );
104005  if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
104006  if( pIdx==pPk ) continue;
104007  if( iIdxCur+i==iIdxNoSeek ) continue;
104008  VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
104009  r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
104010  &iPartIdxLabel, pPrior, r1);
104011  sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
104012  pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
104013  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
104014  pPrior = pIdx;
104015  }
104016 }
104017 
104018 /*
104019 ** Generate code that will assemble an index key and stores it in register
104020 ** regOut. The key with be for index pIdx which is an index on pTab.
104021 ** iCur is the index of a cursor open on the pTab table and pointing to
104022 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
104023 ** iCur must be the cursor of the PRIMARY KEY index.
104024 **
104025 ** Return a register number which is the first in a block of
104026 ** registers that holds the elements of the index key. The
104027 ** block of registers has already been deallocated by the time
104028 ** this routine returns.
104029 **
104030 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
104031 ** to that label if pIdx is a partial index that should be skipped.
104032 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
104033 ** A partial index should be skipped if its WHERE clause evaluates
104034 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
104035 ** will be set to zero which is an empty label that is ignored by
104036 ** sqlite3ResolvePartIdxLabel().
104037 **
104038 ** The pPrior and regPrior parameters are used to implement a cache to
104039 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
104040 ** a pointer to a different index for which an index key has just been
104041 ** computed into register regPrior. If the current pIdx index is generating
104042 ** its key into the same sequence of registers and if pPrior and pIdx share
104043 ** a column in common, then the register corresponding to that column already
104044 ** holds the correct value and the loading of that register is skipped.
104045 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
104046 ** on a table with multiple indices, and especially with the ROWID or
104047 ** PRIMARY KEY columns of the index.
104048 */
104050  Parse *pParse, /* Parsing context */
104051  Index *pIdx, /* The index for which to generate a key */
104052  int iDataCur, /* Cursor number from which to take column data */
104053  int regOut, /* Put the new key into this register if not 0 */
104054  int prefixOnly, /* Compute only a unique prefix of the key */
104055  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
104056  Index *pPrior, /* Previously generated index key */
104057  int regPrior /* Register holding previous generated key */
104058 ){
104059  Vdbe *v = pParse->pVdbe;
104060  int j;
104061  int regBase;
104062  int nCol;
104063 
104064  if( piPartIdxLabel ){
104065  if( pIdx->pPartIdxWhere ){
104066  *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
104067  pParse->iSelfTab = iDataCur;
104068  sqlite3ExprCachePush(pParse);
104069  sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
104071  }else{
104072  *piPartIdxLabel = 0;
104073  }
104074  }
104075  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
104076  regBase = sqlite3GetTempRange(pParse, nCol);
104077  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
104078  for(j=0; j<nCol; j++){
104079  if( pPrior
104080  && pPrior->aiColumn[j]==pIdx->aiColumn[j]
104081  && pPrior->aiColumn[j]!=XN_EXPR
104082  ){
104083  /* This column was already computed by the previous index */
104084  continue;
104085  }
104086  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
104087  /* If the column affinity is REAL but the number is an integer, then it
104088  ** might be stored in the table as an integer (using a compact
104089  ** representation) then converted to REAL by an OP_RealAffinity opcode.
104090  ** But we are getting ready to store this value back into an index, where
104091  ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
104092  ** opcode if it is present */
104094  }
104095  if( regOut ){
104096  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
104097  }
104098  sqlite3ReleaseTempRange(pParse, regBase, nCol);
104099  return regBase;
104100 }
104101 
104102 /*
104103 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
104104 ** because it was a partial index, then this routine should be called to
104105 ** resolve that label.
104106 */
104108  if( iLabel ){
104109  sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
104110  sqlite3ExprCachePop(pParse);
104111  }
104112 }
104113 
104114 /************** End of delete.c **********************************************/
104115 /************** Begin file func.c ********************************************/
104116 /*
104117 ** 2002 February 23
104118 **
104119 ** The author disclaims copyright to this source code. In place of
104120 ** a legal notice, here is a blessing:
104121 **
104122 ** May you do good and not evil.
104123 ** May you find forgiveness for yourself and forgive others.
104124 ** May you share freely, never taking more than you give.
104125 **
104126 *************************************************************************
104127 ** This file contains the C-language implementations for many of the SQL
104128 ** functions of SQLite. (Some function, and in particular the date and
104129 ** time functions, are implemented separately.)
104130 */
104131 /* #include "sqliteInt.h" */
104132 /* #include <stdlib.h> */
104133 /* #include <assert.h> */
104134 /* #include "vdbeInt.h" */
104135 
104136 /*
104137 ** Return the collating function associated with a function.
104138 */
104140  VdbeOp *pOp;
104141  assert( context->pVdbe!=0 );
104142  pOp = &context->pVdbe->aOp[context->iOp-1];
104143  assert( pOp->opcode==OP_CollSeq );
104144  assert( pOp->p4type==P4_COLLSEQ );
104145  return pOp->p4.pColl;
104146 }
104147 
104148 /*
104149 ** Indicate that the accumulator load should be skipped on this
104150 ** iteration of the aggregate loop.
104151 */
104153  context->skipFlag = 1;
104154 }
104155 
104156 /*
104157 ** Implementation of the non-aggregate min() and max() functions
104158 */
104159 static void minmaxFunc(
104160  sqlite3_context *context,
104161  int argc,
104162  sqlite3_value **argv
104163 ){
104164  int i;
104165  int mask; /* 0 for min() or 0xffffffff for max() */
104166  int iBest;
104167  CollSeq *pColl;
104168 
104169  assert( argc>1 );
104170  mask = sqlite3_user_data(context)==0 ? 0 : -1;
104171  pColl = sqlite3GetFuncCollSeq(context);
104172  assert( pColl );
104173  assert( mask==-1 || mask==0 );
104174  iBest = 0;
104175  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104176  for(i=1; i<argc; i++){
104177  if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
104178  if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
104179  testcase( mask==0 );
104180  iBest = i;
104181  }
104182  }
104183  sqlite3_result_value(context, argv[iBest]);
104184 }
104185 
104186 /*
104187 ** Return the type of the argument.
104188 */
104189 static void typeofFunc(
104190  sqlite3_context *context,
104191  int NotUsed,
104192  sqlite3_value **argv
104193 ){
104194  const char *z = 0;
104195  UNUSED_PARAMETER(NotUsed);
104196  switch( sqlite3_value_type(argv[0]) ){
104197  case SQLITE_INTEGER: z = "integer"; break;
104198  case SQLITE_TEXT: z = "text"; break;
104199  case SQLITE_FLOAT: z = "real"; break;
104200  case SQLITE_BLOB: z = "blob"; break;
104201  default: z = "null"; break;
104202  }
104203  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
104204 }
104205 
104206 
104207 /*
104208 ** Implementation of the length() function
104209 */
104210 static void lengthFunc(
104211  sqlite3_context *context,
104212  int argc,
104213  sqlite3_value **argv
104214 ){
104215  int len;
104216 
104217  assert( argc==1 );
104218  UNUSED_PARAMETER(argc);
104219  switch( sqlite3_value_type(argv[0]) ){
104220  case SQLITE_BLOB:
104221  case SQLITE_INTEGER:
104222  case SQLITE_FLOAT: {
104223  sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
104224  break;
104225  }
104226  case SQLITE_TEXT: {
104227  const unsigned char *z = sqlite3_value_text(argv[0]);
104228  if( z==0 ) return;
104229  len = 0;
104230  while( *z ){
104231  len++;
104232  SQLITE_SKIP_UTF8(z);
104233  }
104234  sqlite3_result_int(context, len);
104235  break;
104236  }
104237  default: {
104238  sqlite3_result_null(context);
104239  break;
104240  }
104241  }
104242 }
104243 
104244 /*
104245 ** Implementation of the abs() function.
104246 **
104247 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
104248 ** the numeric argument X.
104249 */
104250 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104251  assert( argc==1 );
104252  UNUSED_PARAMETER(argc);
104253  switch( sqlite3_value_type(argv[0]) ){
104254  case SQLITE_INTEGER: {
104255  i64 iVal = sqlite3_value_int64(argv[0]);
104256  if( iVal<0 ){
104257  if( iVal==SMALLEST_INT64 ){
104258  /* IMP: R-31676-45509 If X is the integer -9223372036854775808
104259  ** then abs(X) throws an integer overflow error since there is no
104260  ** equivalent positive 64-bit two complement value. */
104261  sqlite3_result_error(context, "integer overflow", -1);
104262  return;
104263  }
104264  iVal = -iVal;
104265  }
104266  sqlite3_result_int64(context, iVal);
104267  break;
104268  }
104269  case SQLITE_NULL: {
104270  /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
104271  sqlite3_result_null(context);
104272  break;
104273  }
104274  default: {
104275  /* Because sqlite3_value_double() returns 0.0 if the argument is not
104276  ** something that can be converted into a number, we have:
104277  ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
104278  ** that cannot be converted to a numeric value.
104279  */
104280  double rVal = sqlite3_value_double(argv[0]);
104281  if( rVal<0 ) rVal = -rVal;
104282  sqlite3_result_double(context, rVal);
104283  break;
104284  }
104285  }
104286 }
104287 
104288 /*
104289 ** Implementation of the instr() function.
104290 **
104291 ** instr(haystack,needle) finds the first occurrence of needle
104292 ** in haystack and returns the number of previous characters plus 1,
104293 ** or 0 if needle does not occur within haystack.
104294 **
104295 ** If both haystack and needle are BLOBs, then the result is one more than
104296 ** the number of bytes in haystack prior to the first occurrence of needle,
104297 ** or 0 if needle never occurs in haystack.
104298 */
104299 static void instrFunc(
104300  sqlite3_context *context,
104301  int argc,
104302  sqlite3_value **argv
104303 ){
104304  const unsigned char *zHaystack;
104305  const unsigned char *zNeedle;
104306  int nHaystack;
104307  int nNeedle;
104308  int typeHaystack, typeNeedle;
104309  int N = 1;
104310  int isText;
104311 
104312  UNUSED_PARAMETER(argc);
104313  typeHaystack = sqlite3_value_type(argv[0]);
104314  typeNeedle = sqlite3_value_type(argv[1]);
104315  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
104316  nHaystack = sqlite3_value_bytes(argv[0]);
104317  nNeedle = sqlite3_value_bytes(argv[1]);
104318  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
104319  zHaystack = sqlite3_value_blob(argv[0]);
104320  zNeedle = sqlite3_value_blob(argv[1]);
104321  isText = 0;
104322  }else{
104323  zHaystack = sqlite3_value_text(argv[0]);
104324  zNeedle = sqlite3_value_text(argv[1]);
104325  isText = 1;
104326  if( zNeedle==0 ) return;
104327  assert( zHaystack );
104328  }
104329  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
104330  N++;
104331  do{
104332  nHaystack--;
104333  zHaystack++;
104334  }while( isText && (zHaystack[0]&0xc0)==0x80 );
104335  }
104336  if( nNeedle>nHaystack ) N = 0;
104337  sqlite3_result_int(context, N);
104338 }
104339 
104340 /*
104341 ** Implementation of the printf() function.
104342 */
104343 static void printfFunc(
104344  sqlite3_context *context,
104345  int argc,
104346  sqlite3_value **argv
104347 ){
104348  PrintfArguments x;
104349  StrAccum str;
104350  const char *zFormat;
104351  int n;
104352  sqlite3 *db = sqlite3_context_db_handle(context);
104353 
104354  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
104355  x.nArg = argc-1;
104356  x.nUsed = 0;
104357  x.apArg = argv+1;
104358  sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
104360  sqlite3XPrintf(&str, zFormat, &x);
104361  n = str.nChar;
104362  sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
104363  SQLITE_DYNAMIC);
104364  }
104365 }
104366 
104367 /*
104368 ** Implementation of the substr() function.
104369 **
104370 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
104371 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
104372 ** of x. If x is text, then we actually count UTF-8 characters.
104373 ** If x is a blob, then we count bytes.
104374 **
104375 ** If p1 is negative, then we begin abs(p1) from the end of x[].
104376 **
104377 ** If p2 is negative, return the p2 characters preceding p1.
104378 */
104379 static void substrFunc(
104380  sqlite3_context *context,
104381  int argc,
104382  sqlite3_value **argv
104383 ){
104384  const unsigned char *z;
104385  const unsigned char *z2;
104386  int len;
104387  int p0type;
104388  i64 p1, p2;
104389  int negP2 = 0;
104390 
104391  assert( argc==3 || argc==2 );
104392  if( sqlite3_value_type(argv[1])==SQLITE_NULL
104393  || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
104394  ){
104395  return;
104396  }
104397  p0type = sqlite3_value_type(argv[0]);
104398  p1 = sqlite3_value_int(argv[1]);
104399  if( p0type==SQLITE_BLOB ){
104400  len = sqlite3_value_bytes(argv[0]);
104401  z = sqlite3_value_blob(argv[0]);
104402  if( z==0 ) return;
104403  assert( len==sqlite3_value_bytes(argv[0]) );
104404  }else{
104405  z = sqlite3_value_text(argv[0]);
104406  if( z==0 ) return;
104407  len = 0;
104408  if( p1<0 ){
104409  for(z2=z; *z2; len++){
104410  SQLITE_SKIP_UTF8(z2);
104411  }
104412  }
104413  }
104414 #ifdef SQLITE_SUBSTR_COMPATIBILITY
104415  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
104416  ** as substr(X,1,N) - it returns the first N characters of X. This
104417  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
104418  ** from 2009-02-02 for compatibility of applications that exploited the
104419  ** old buggy behavior. */
104420  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
104421 #endif
104422  if( argc==3 ){
104423  p2 = sqlite3_value_int(argv[2]);
104424  if( p2<0 ){
104425  p2 = -p2;
104426  negP2 = 1;
104427  }
104428  }else{
104430  }
104431  if( p1<0 ){
104432  p1 += len;
104433  if( p1<0 ){
104434  p2 += p1;
104435  if( p2<0 ) p2 = 0;
104436  p1 = 0;
104437  }
104438  }else if( p1>0 ){
104439  p1--;
104440  }else if( p2>0 ){
104441  p2--;
104442  }
104443  if( negP2 ){
104444  p1 -= p2;
104445  if( p1<0 ){
104446  p2 += p1;
104447  p1 = 0;
104448  }
104449  }
104450  assert( p1>=0 && p2>=0 );
104451  if( p0type!=SQLITE_BLOB ){
104452  while( *z && p1 ){
104453  SQLITE_SKIP_UTF8(z);
104454  p1--;
104455  }
104456  for(z2=z; *z2 && p2; p2--){
104457  SQLITE_SKIP_UTF8(z2);
104458  }
104459  sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
104460  SQLITE_UTF8);
104461  }else{
104462  if( p1+p2>len ){
104463  p2 = len-p1;
104464  if( p2<0 ) p2 = 0;
104465  }
104466  sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
104467  }
104468 }
104469 
104470 /*
104471 ** Implementation of the round() function
104472 */
104473 #ifndef SQLITE_OMIT_FLOATING_POINT
104474 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104475  int n = 0;
104476  double r;
104477  char *zBuf;
104478  assert( argc==1 || argc==2 );
104479  if( argc==2 ){
104480  if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
104481  n = sqlite3_value_int(argv[1]);
104482  if( n>30 ) n = 30;
104483  if( n<0 ) n = 0;
104484  }
104485  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104486  r = sqlite3_value_double(argv[0]);
104487  /* If Y==0 and X will fit in a 64-bit int,
104488  ** handle the rounding directly,
104489  ** otherwise use printf.
104490  */
104491  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
104492  r = (double)((sqlite_int64)(r+0.5));
104493  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
104494  r = -(double)((sqlite_int64)((-r)+0.5));
104495  }else{
104496  zBuf = sqlite3_mprintf("%.*f",n,r);
104497  if( zBuf==0 ){
104498  sqlite3_result_error_nomem(context);
104499  return;
104500  }
104501  sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
104502  sqlite3_free(zBuf);
104503  }
104504  sqlite3_result_double(context, r);
104505 }
104506 #endif
104507 
104508 /*
104509 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
104510 ** allocation fails, call sqlite3_result_error_nomem() to notify
104511 ** the database handle that malloc() has failed and return NULL.
104512 ** If nByte is larger than the maximum string or blob length, then
104513 ** raise an SQLITE_TOOBIG exception and return NULL.
104514 */
104515 static void *contextMalloc(sqlite3_context *context, i64 nByte){
104516  char *z;
104517  sqlite3 *db = sqlite3_context_db_handle(context);
104518  assert( nByte>0 );
104519  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
104520  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
104521  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
104522  sqlite3_result_error_toobig(context);
104523  z = 0;
104524  }else{
104525  z = sqlite3Malloc(nByte);
104526  if( !z ){
104527  sqlite3_result_error_nomem(context);
104528  }
104529  }
104530  return z;
104531 }
104532 
104533 /*
104534 ** Implementation of the upper() and lower() SQL functions.
104535 */
104536 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104537  char *z1;
104538  const char *z2;
104539  int i, n;
104540  UNUSED_PARAMETER(argc);
104541  z2 = (char*)sqlite3_value_text(argv[0]);
104542  n = sqlite3_value_bytes(argv[0]);
104543  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
104544  assert( z2==(char*)sqlite3_value_text(argv[0]) );
104545  if( z2 ){
104546  z1 = contextMalloc(context, ((i64)n)+1);
104547  if( z1 ){
104548  for(i=0; i<n; i++){
104549  z1[i] = (char)sqlite3Toupper(z2[i]);
104550  }
104551  sqlite3_result_text(context, z1, n, sqlite3_free);
104552  }
104553  }
104554 }
104555 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104556  char *z1;
104557  const char *z2;
104558  int i, n;
104559  UNUSED_PARAMETER(argc);
104560  z2 = (char*)sqlite3_value_text(argv[0]);
104561  n = sqlite3_value_bytes(argv[0]);
104562  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
104563  assert( z2==(char*)sqlite3_value_text(argv[0]) );
104564  if( z2 ){
104565  z1 = contextMalloc(context, ((i64)n)+1);
104566  if( z1 ){
104567  for(i=0; i<n; i++){
104568  z1[i] = sqlite3Tolower(z2[i]);
104569  }
104570  sqlite3_result_text(context, z1, n, sqlite3_free);
104571  }
104572  }
104573 }
104574 
104575 /*
104576 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
104577 ** as VDBE code so that unused argument values do not have to be computed.
104578 ** However, we still need some kind of function implementation for this
104579 ** routines in the function table. The noopFunc macro provides this.
104580 ** noopFunc will never be called so it doesn't matter what the implementation
104581 ** is. We might as well use the "version()" function as a substitute.
104582 */
104583 #define noopFunc versionFunc /* Substitute function - never called */
104584 
104585 /*
104586 ** Implementation of random(). Return a random integer.
104587 */
104588 static void randomFunc(
104589  sqlite3_context *context,
104590  int NotUsed,
104591  sqlite3_value **NotUsed2
104592 ){
104593  sqlite_int64 r;
104594  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104595  sqlite3_randomness(sizeof(r), &r);
104596  if( r<0 ){
104597  /* We need to prevent a random number of 0x8000000000000000
104598  ** (or -9223372036854775808) since when you do abs() of that
104599  ** number of you get the same value back again. To do this
104600  ** in a way that is testable, mask the sign bit off of negative
104601  ** values, resulting in a positive value. Then take the
104602  ** 2s complement of that positive value. The end result can
104603  ** therefore be no less than -9223372036854775807.
104604  */
104605  r = -(r & LARGEST_INT64);
104606  }
104607  sqlite3_result_int64(context, r);
104608 }
104609 
104610 /*
104611 ** Implementation of randomblob(N). Return a random blob
104612 ** that is N bytes long.
104613 */
104614 static void randomBlob(
104615  sqlite3_context *context,
104616  int argc,
104617  sqlite3_value **argv
104618 ){
104619  int n;
104620  unsigned char *p;
104621  assert( argc==1 );
104622  UNUSED_PARAMETER(argc);
104623  n = sqlite3_value_int(argv[0]);
104624  if( n<1 ){
104625  n = 1;
104626  }
104627  p = contextMalloc(context, n);
104628  if( p ){
104629  sqlite3_randomness(n, p);
104630  sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
104631  }
104632 }
104633 
104634 /*
104635 ** Implementation of the last_insert_rowid() SQL function. The return
104636 ** value is the same as the sqlite3_last_insert_rowid() API function.
104637 */
104639  sqlite3_context *context,
104640  int NotUsed,
104641  sqlite3_value **NotUsed2
104642 ){
104643  sqlite3 *db = sqlite3_context_db_handle(context);
104644  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104645  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
104646  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
104647  ** function. */
104649 }
104650 
104651 /*
104652 ** Implementation of the changes() SQL function.
104653 **
104654 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
104655 ** around the sqlite3_changes() C/C++ function and hence follows the same
104656 ** rules for counting changes.
104657 */
104658 static void changes(
104659  sqlite3_context *context,
104660  int NotUsed,
104661  sqlite3_value **NotUsed2
104662 ){
104663  sqlite3 *db = sqlite3_context_db_handle(context);
104664  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104665  sqlite3_result_int(context, sqlite3_changes(db));
104666 }
104667 
104668 /*
104669 ** Implementation of the total_changes() SQL function. The return value is
104670 ** the same as the sqlite3_total_changes() API function.
104671 */
104672 static void total_changes(
104673  sqlite3_context *context,
104674  int NotUsed,
104675  sqlite3_value **NotUsed2
104676 ){
104677  sqlite3 *db = sqlite3_context_db_handle(context);
104678  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104679  /* IMP: R-52756-41993 This function is a wrapper around the
104680  ** sqlite3_total_changes() C/C++ interface. */
104682 }
104683 
104684 /*
104685 ** A structure defining how to do GLOB-style comparisons.
104686 */
104688  u8 matchAll; /* "*" or "%" */
104689  u8 matchOne; /* "?" or "_" */
104690  u8 matchSet; /* "[" or 0 */
104691  u8 noCase; /* true to ignore case differences */
104692 };
104693 
104694 /*
104695 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
104696 ** character is exactly one byte in size. Also, provde the Utf8Read()
104697 ** macro for fast reading of the next character in the common case where
104698 ** the next character is ASCII.
104699 */
104700 #if defined(SQLITE_EBCDIC)
104701 # define sqlite3Utf8Read(A) (*((*A)++))
104702 # define Utf8Read(A) (*(A++))
104703 #else
104704 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
104705 #endif
104706 
104707 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
104708 /* The correct SQL-92 behavior is for the LIKE operator to ignore
104709 ** case. Thus 'a' LIKE 'A' would be true. */
104710 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
104711 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
104712 ** is case sensitive causing 'a' LIKE 'A' to be false */
104713 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
104714 
104715 /*
104716 ** Compare two UTF-8 strings for equality where the first string can
104717 ** potentially be a "glob" or "like" expression. Return true (1) if they
104718 ** are the same and false (0) if they are different.
104719 **
104720 ** Globbing rules:
104721 **
104722 ** '*' Matches any sequence of zero or more characters.
104723 **
104724 ** '?' Matches exactly one character.
104725 **
104726 ** [...] Matches one character from the enclosed list of
104727 ** characters.
104728 **
104729 ** [^...] Matches one character not in the enclosed list.
104730 **
104731 ** With the [...] and [^...] matching, a ']' character can be included
104732 ** in the list by making it the first character after '[' or '^'. A
104733 ** range of characters can be specified using '-'. Example:
104734 ** "[a-z]" matches any single lower-case letter. To match a '-', make
104735 ** it the last character in the list.
104736 **
104737 ** Like matching rules:
104738 **
104739 ** '%' Matches any sequence of zero or more characters
104740 **
104741 *** '_' Matches any one character
104742 **
104743 ** Ec Where E is the "esc" character and c is any other
104744 ** character, including '%', '_', and esc, match exactly c.
104745 **
104746 ** The comments within this routine usually assume glob matching.
104747 **
104748 ** This routine is usually quick, but can be N**2 in the worst case.
104749 */
104750 static int patternCompare(
104751  const u8 *zPattern, /* The glob pattern */
104752  const u8 *zString, /* The string to compare against the glob */
104753  const struct compareInfo *pInfo, /* Information about how to do the compare */
104754  u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
104755 ){
104756  u32 c, c2; /* Next pattern and input string chars */
104757  u32 matchOne = pInfo->matchOne; /* "?" or "_" */
104758  u32 matchAll = pInfo->matchAll; /* "*" or "%" */
104759  u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
104760  const u8 *zEscaped = 0; /* One past the last escaped input char */
104761 
104762  while( (c = Utf8Read(zPattern))!=0 ){
104763  if( c==matchAll ){ /* Match "*" */
104764  /* Skip over multiple "*" characters in the pattern. If there
104765  ** are also "?" characters, skip those as well, but consume a
104766  ** single character of the input string for each "?" skipped */
104767  while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
104768  if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
104769  return 0;
104770  }
104771  }
104772  if( c==0 ){
104773  return 1; /* "*" at the end of the pattern matches */
104774  }else if( c==matchOther ){
104775  if( pInfo->matchSet==0 ){
104776  c = sqlite3Utf8Read(&zPattern);
104777  if( c==0 ) return 0;
104778  }else{
104779  /* "[...]" immediately follows the "*". We have to do a slow
104780  ** recursive search in this case, but it is an unusual case. */
104781  assert( matchOther<0x80 ); /* '[' is a single-byte character */
104782  while( *zString
104783  && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){
104784  SQLITE_SKIP_UTF8(zString);
104785  }
104786  return *zString!=0;
104787  }
104788  }
104789 
104790  /* At this point variable c contains the first character of the
104791  ** pattern string past the "*". Search in the input string for the
104792  ** first matching character and recursively contine the match from
104793  ** that point.
104794  **
104795  ** For a case-insensitive search, set variable cx to be the same as
104796  ** c but in the other case and search the input string for either
104797  ** c or cx.
104798  */
104799  if( c<=0x80 ){
104800  u32 cx;
104801  if( noCase ){
104802  cx = sqlite3Toupper(c);
104803  c = sqlite3Tolower(c);
104804  }else{
104805  cx = c;
104806  }
104807  while( (c2 = *(zString++))!=0 ){
104808  if( c2!=c && c2!=cx ) continue;
104809  if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
104810  }
104811  }else{
104812  while( (c2 = Utf8Read(zString))!=0 ){
104813  if( c2!=c ) continue;
104814  if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
104815  }
104816  }
104817  return 0;
104818  }
104819  if( c==matchOther ){
104820  if( pInfo->matchSet==0 ){
104821  c = sqlite3Utf8Read(&zPattern);
104822  if( c==0 ) return 0;
104823  zEscaped = zPattern;
104824  }else{
104825  u32 prior_c = 0;
104826  int seen = 0;
104827  int invert = 0;
104828  c = sqlite3Utf8Read(&zString);
104829  if( c==0 ) return 0;
104830  c2 = sqlite3Utf8Read(&zPattern);
104831  if( c2=='^' ){
104832  invert = 1;
104833  c2 = sqlite3Utf8Read(&zPattern);
104834  }
104835  if( c2==']' ){
104836  if( c==']' ) seen = 1;
104837  c2 = sqlite3Utf8Read(&zPattern);
104838  }
104839  while( c2 && c2!=']' ){
104840  if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
104841  c2 = sqlite3Utf8Read(&zPattern);
104842  if( c>=prior_c && c<=c2 ) seen = 1;
104843  prior_c = 0;
104844  }else{
104845  if( c==c2 ){
104846  seen = 1;
104847  }
104848  prior_c = c2;
104849  }
104850  c2 = sqlite3Utf8Read(&zPattern);
104851  }
104852  if( c2==0 || (seen ^ invert)==0 ){
104853  return 0;
104854  }
104855  continue;
104856  }
104857  }
104858  c2 = Utf8Read(zString);
104859  if( c==c2 ) continue;
104860  if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
104861  continue;
104862  }
104863  if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
104864  return 0;
104865  }
104866  return *zString==0;
104867 }
104868 
104869 /*
104870 ** The sqlite3_strglob() interface.
104871 */
104872 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
104873  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0;
104874 }
104875 
104876 /*
104877 ** The sqlite3_strlike() interface.
104878 */
104879 SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
104880  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
104881 }
104882 
104883 /*
104884 ** Count the number of times that the LIKE operator (or GLOB which is
104885 ** just a variation of LIKE) gets called. This is used for testing
104886 ** only.
104887 */
104888 #ifdef SQLITE_TEST
104889 SQLITE_API int sqlite3_like_count = 0;
104890 #endif
104891 
104892 
104893 /*
104894 ** Implementation of the like() SQL function. This function implements
104895 ** the build-in LIKE operator. The first argument to the function is the
104896 ** pattern and the second argument is the string. So, the SQL statements:
104897 **
104898 ** A LIKE B
104899 **
104900 ** is implemented as like(B,A).
104901 **
104902 ** This same function (with a different compareInfo structure) computes
104903 ** the GLOB operator.
104904 */
104905 static void likeFunc(
104906  sqlite3_context *context,
104907  int argc,
104908  sqlite3_value **argv
104909 ){
104910  const unsigned char *zA, *zB;
104911  u32 escape;
104912  int nPat;
104913  sqlite3 *db = sqlite3_context_db_handle(context);
104914  struct compareInfo *pInfo = sqlite3_user_data(context);
104915 
104916 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
104917  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
104918  || sqlite3_value_type(argv[1])==SQLITE_BLOB
104919  ){
104920 #ifdef SQLITE_TEST
104921  sqlite3_like_count++;
104922 #endif
104923  sqlite3_result_int(context, 0);
104924  return;
104925  }
104926 #endif
104927  zB = sqlite3_value_text(argv[0]);
104928  zA = sqlite3_value_text(argv[1]);
104929 
104930  /* Limit the length of the LIKE or GLOB pattern to avoid problems
104931  ** of deep recursion and N*N behavior in patternCompare().
104932  */
104933  nPat = sqlite3_value_bytes(argv[0]);
104936  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
104937  sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
104938  return;
104939  }
104940  assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
104941 
104942  if( argc==3 ){
104943  /* The escape character string must consist of a single UTF-8 character.
104944  ** Otherwise, return an error.
104945  */
104946  const unsigned char *zEsc = sqlite3_value_text(argv[2]);
104947  if( zEsc==0 ) return;
104948  if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
104949  sqlite3_result_error(context,
104950  "ESCAPE expression must be a single character", -1);
104951  return;
104952  }
104953  escape = sqlite3Utf8Read(&zEsc);
104954  }else{
104955  escape = pInfo->matchSet;
104956  }
104957  if( zA && zB ){
104958 #ifdef SQLITE_TEST
104959  sqlite3_like_count++;
104960 #endif
104961  sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
104962  }
104963 }
104964 
104965 /*
104966 ** Implementation of the NULLIF(x,y) function. The result is the first
104967 ** argument if the arguments are different. The result is NULL if the
104968 ** arguments are equal to each other.
104969 */
104970 static void nullifFunc(
104971  sqlite3_context *context,
104972  int NotUsed,
104973  sqlite3_value **argv
104974 ){
104975  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104976  UNUSED_PARAMETER(NotUsed);
104977  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
104978  sqlite3_result_value(context, argv[0]);
104979  }
104980 }
104981 
104982 /*
104983 ** Implementation of the sqlite_version() function. The result is the version
104984 ** of the SQLite library that is running.
104985 */
104986 static void versionFunc(
104987  sqlite3_context *context,
104988  int NotUsed,
104989  sqlite3_value **NotUsed2
104990 ){
104991  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104992  /* IMP: R-48699-48617 This function is an SQL wrapper around the
104993  ** sqlite3_libversion() C-interface. */
104995 }
104996 
104997 /*
104998 ** Implementation of the sqlite_source_id() function. The result is a string
104999 ** that identifies the particular version of the source code used to build
105000 ** SQLite.
105001 */
105002 static void sourceidFunc(
105003  sqlite3_context *context,
105004  int NotUsed,
105005  sqlite3_value **NotUsed2
105006 ){
105007  UNUSED_PARAMETER2(NotUsed, NotUsed2);
105008  /* IMP: R-24470-31136 This function is an SQL wrapper around the
105009  ** sqlite3_sourceid() C interface. */
105011 }
105012 
105013 /*
105014 ** Implementation of the sqlite_log() function. This is a wrapper around
105015 ** sqlite3_log(). The return value is NULL. The function exists purely for
105016 ** its side-effects.
105017 */
105018 static void errlogFunc(
105019  sqlite3_context *context,
105020  int argc,
105021  sqlite3_value **argv
105022 ){
105023  UNUSED_PARAMETER(argc);
105024  UNUSED_PARAMETER(context);
105025  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
105026 }
105027 
105028 /*
105029 ** Implementation of the sqlite_compileoption_used() function.
105030 ** The result is an integer that identifies if the compiler option
105031 ** was used to build SQLite.
105032 */
105033 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
105035  sqlite3_context *context,
105036  int argc,
105037  sqlite3_value **argv
105038 ){
105039  const char *zOptName;
105040  assert( argc==1 );
105041  UNUSED_PARAMETER(argc);
105042  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
105043  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
105044  ** function.
105045  */
105046  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
105047  sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
105048  }
105049 }
105050 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
105051 
105052 /*
105053 ** Implementation of the sqlite_compileoption_get() function.
105054 ** The result is a string that identifies the compiler options
105055 ** used to build SQLite.
105056 */
105057 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
105059  sqlite3_context *context,
105060  int argc,
105061  sqlite3_value **argv
105062 ){
105063  int n;
105064  assert( argc==1 );
105065  UNUSED_PARAMETER(argc);
105066  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
105067  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
105068  */
105069  n = sqlite3_value_int(argv[0]);
105071 }
105072 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
105073 
105074 /* Array for converting from half-bytes (nybbles) into ASCII hex
105075 ** digits. */
105076 static const char hexdigits[] = {
105077  '0', '1', '2', '3', '4', '5', '6', '7',
105078  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
105079 };
105080 
105081 /*
105082 ** Implementation of the QUOTE() function. This function takes a single
105083 ** argument. If the argument is numeric, the return value is the same as
105084 ** the argument. If the argument is NULL, the return value is the string
105085 ** "NULL". Otherwise, the argument is enclosed in single quotes with
105086 ** single-quote escapes.
105087 */
105088 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
105089  assert( argc==1 );
105090  UNUSED_PARAMETER(argc);
105091  switch( sqlite3_value_type(argv[0]) ){
105092  case SQLITE_FLOAT: {
105093  double r1, r2;
105094  char zBuf[50];
105095  r1 = sqlite3_value_double(argv[0]);
105096  sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
105097  sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
105098  if( r1!=r2 ){
105099  sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
105100  }
105101  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
105102  break;
105103  }
105104  case SQLITE_INTEGER: {
105105  sqlite3_result_value(context, argv[0]);
105106  break;
105107  }
105108  case SQLITE_BLOB: {
105109  char *zText = 0;
105110  char const *zBlob = sqlite3_value_blob(argv[0]);
105111  int nBlob = sqlite3_value_bytes(argv[0]);
105112  assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
105113  zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
105114  if( zText ){
105115  int i;
105116  for(i=0; i<nBlob; i++){
105117  zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
105118  zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
105119  }
105120  zText[(nBlob*2)+2] = '\'';
105121  zText[(nBlob*2)+3] = '\0';
105122  zText[0] = 'X';
105123  zText[1] = '\'';
105124  sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
105125  sqlite3_free(zText);
105126  }
105127  break;
105128  }
105129  case SQLITE_TEXT: {
105130  int i,j;
105131  u64 n;
105132  const unsigned char *zArg = sqlite3_value_text(argv[0]);
105133  char *z;
105134 
105135  if( zArg==0 ) return;
105136  for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
105137  z = contextMalloc(context, ((i64)i)+((i64)n)+3);
105138  if( z ){
105139  z[0] = '\'';
105140  for(i=0, j=1; zArg[i]; i++){
105141  z[j++] = zArg[i];
105142  if( zArg[i]=='\'' ){
105143  z[j++] = '\'';
105144  }
105145  }
105146  z[j++] = '\'';
105147  z[j] = 0;
105148  sqlite3_result_text(context, z, j, sqlite3_free);
105149  }
105150  break;
105151  }
105152  default: {
105153  assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
105154  sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
105155  break;
105156  }
105157  }
105158 }
105159 
105160 /*
105161 ** The unicode() function. Return the integer unicode code-point value
105162 ** for the first character of the input string.
105163 */
105164 static void unicodeFunc(
105165  sqlite3_context *context,
105166  int argc,
105167  sqlite3_value **argv
105168 ){
105169  const unsigned char *z = sqlite3_value_text(argv[0]);
105170  (void)argc;
105171  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
105172 }
105173 
105174 /*
105175 ** The char() function takes zero or more arguments, each of which is
105176 ** an integer. It constructs a string where each character of the string
105177 ** is the unicode character for the corresponding integer argument.
105178 */
105179 static void charFunc(
105180  sqlite3_context *context,
105181  int argc,
105182  sqlite3_value **argv
105183 ){
105184  unsigned char *z, *zOut;
105185  int i;
105186  zOut = z = sqlite3_malloc64( argc*4+1 );
105187  if( z==0 ){
105188  sqlite3_result_error_nomem(context);
105189  return;
105190  }
105191  for(i=0; i<argc; i++){
105192  sqlite3_int64 x;
105193  unsigned c;
105194  x = sqlite3_value_int64(argv[i]);
105195  if( x<0 || x>0x10ffff ) x = 0xfffd;
105196  c = (unsigned)(x & 0x1fffff);
105197  if( c<0x00080 ){
105198  *zOut++ = (u8)(c&0xFF);
105199  }else if( c<0x00800 ){
105200  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
105201  *zOut++ = 0x80 + (u8)(c & 0x3F);
105202  }else if( c<0x10000 ){
105203  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
105204  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
105205  *zOut++ = 0x80 + (u8)(c & 0x3F);
105206  }else{
105207  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
105208  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
105209  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
105210  *zOut++ = 0x80 + (u8)(c & 0x3F);
105211  } \
105212  }
105213  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
105214 }
105215 
105216 /*
105217 ** The hex() function. Interpret the argument as a blob. Return
105218 ** a hexadecimal rendering as text.
105219 */
105220 static void hexFunc(
105221  sqlite3_context *context,
105222  int argc,
105223  sqlite3_value **argv
105224 ){
105225  int i, n;
105226  const unsigned char *pBlob;
105227  char *zHex, *z;
105228  assert( argc==1 );
105229  UNUSED_PARAMETER(argc);
105230  pBlob = sqlite3_value_blob(argv[0]);
105231  n = sqlite3_value_bytes(argv[0]);
105232  assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
105233  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
105234  if( zHex ){
105235  for(i=0; i<n; i++, pBlob++){
105236  unsigned char c = *pBlob;
105237  *(z++) = hexdigits[(c>>4)&0xf];
105238  *(z++) = hexdigits[c&0xf];
105239  }
105240  *z = 0;
105241  sqlite3_result_text(context, zHex, n*2, sqlite3_free);
105242  }
105243 }
105244 
105245 /*
105246 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
105247 */
105248 static void zeroblobFunc(
105249  sqlite3_context *context,
105250  int argc,
105251  sqlite3_value **argv
105252 ){
105253  i64 n;
105254  int rc;
105255  assert( argc==1 );
105256  UNUSED_PARAMETER(argc);
105257  n = sqlite3_value_int64(argv[0]);
105258  if( n<0 ) n = 0;
105259  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
105260  if( rc ){
105261  sqlite3_result_error_code(context, rc);
105262  }
105263 }
105264 
105265 /*
105266 ** The replace() function. Three arguments are all strings: call
105267 ** them A, B, and C. The result is also a string which is derived
105268 ** from A by replacing every occurrence of B with C. The match
105269 ** must be exact. Collating sequences are not used.
105270 */
105271 static void replaceFunc(
105272  sqlite3_context *context,
105273  int argc,
105274  sqlite3_value **argv
105275 ){
105276  const unsigned char *zStr; /* The input string A */
105277  const unsigned char *zPattern; /* The pattern string B */
105278  const unsigned char *zRep; /* The replacement string C */
105279  unsigned char *zOut; /* The output */
105280  int nStr; /* Size of zStr */
105281  int nPattern; /* Size of zPattern */
105282  int nRep; /* Size of zRep */
105283  i64 nOut; /* Maximum size of zOut */
105284  int loopLimit; /* Last zStr[] that might match zPattern[] */
105285  int i, j; /* Loop counters */
105286 
105287  assert( argc==3 );
105288  UNUSED_PARAMETER(argc);
105289  zStr = sqlite3_value_text(argv[0]);
105290  if( zStr==0 ) return;
105291  nStr = sqlite3_value_bytes(argv[0]);
105292  assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
105293  zPattern = sqlite3_value_text(argv[1]);
105294  if( zPattern==0 ){
105295  assert( sqlite3_value_type(argv[1])==SQLITE_NULL
105296  || sqlite3_context_db_handle(context)->mallocFailed );
105297  return;
105298  }
105299  if( zPattern[0]==0 ){
105300  assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
105301  sqlite3_result_value(context, argv[0]);
105302  return;
105303  }
105304  nPattern = sqlite3_value_bytes(argv[1]);
105305  assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
105306  zRep = sqlite3_value_text(argv[2]);
105307  if( zRep==0 ) return;
105308  nRep = sqlite3_value_bytes(argv[2]);
105309  assert( zRep==sqlite3_value_text(argv[2]) );
105310  nOut = nStr + 1;
105311  assert( nOut<SQLITE_MAX_LENGTH );
105312  zOut = contextMalloc(context, (i64)nOut);
105313  if( zOut==0 ){
105314  return;
105315  }
105316  loopLimit = nStr - nPattern;
105317  for(i=j=0; i<=loopLimit; i++){
105318  if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
105319  zOut[j++] = zStr[i];
105320  }else{
105321  u8 *zOld;
105322  sqlite3 *db = sqlite3_context_db_handle(context);
105323  nOut += nRep - nPattern;
105324  testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
105325  testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
105326  if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
105327  sqlite3_result_error_toobig(context);
105328  sqlite3_free(zOut);
105329  return;
105330  }
105331  zOld = zOut;
105332  zOut = sqlite3_realloc64(zOut, (int)nOut);
105333  if( zOut==0 ){
105334  sqlite3_result_error_nomem(context);
105335  sqlite3_free(zOld);
105336  return;
105337  }
105338  memcpy(&zOut[j], zRep, nRep);
105339  j += nRep;
105340  i += nPattern-1;
105341  }
105342  }
105343  assert( j+nStr-i+1==nOut );
105344  memcpy(&zOut[j], &zStr[i], nStr-i);
105345  j += nStr - i;
105346  assert( j<=nOut );
105347  zOut[j] = 0;
105348  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
105349 }
105350 
105351 /*
105352 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
105353 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
105354 */
105355 static void trimFunc(
105356  sqlite3_context *context,
105357  int argc,
105358  sqlite3_value **argv
105359 ){
105360  const unsigned char *zIn; /* Input string */
105361  const unsigned char *zCharSet; /* Set of characters to trim */
105362  int nIn; /* Number of bytes in input */
105363  int flags; /* 1: trimleft 2: trimright 3: trim */
105364  int i; /* Loop counter */
105365  unsigned char *aLen = 0; /* Length of each character in zCharSet */
105366  unsigned char **azChar = 0; /* Individual characters in zCharSet */
105367  int nChar; /* Number of characters in zCharSet */
105368 
105369  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
105370  return;
105371  }
105372  zIn = sqlite3_value_text(argv[0]);
105373  if( zIn==0 ) return;
105374  nIn = sqlite3_value_bytes(argv[0]);
105375  assert( zIn==sqlite3_value_text(argv[0]) );
105376  if( argc==1 ){
105377  static const unsigned char lenOne[] = { 1 };
105378  static unsigned char * const azOne[] = { (u8*)" " };
105379  nChar = 1;
105380  aLen = (u8*)lenOne;
105381  azChar = (unsigned char **)azOne;
105382  zCharSet = 0;
105383  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
105384  return;
105385  }else{
105386  const unsigned char *z;
105387  for(z=zCharSet, nChar=0; *z; nChar++){
105388  SQLITE_SKIP_UTF8(z);
105389  }
105390  if( nChar>0 ){
105391  azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
105392  if( azChar==0 ){
105393  return;
105394  }
105395  aLen = (unsigned char*)&azChar[nChar];
105396  for(z=zCharSet, nChar=0; *z; nChar++){
105397  azChar[nChar] = (unsigned char *)z;
105398  SQLITE_SKIP_UTF8(z);
105399  aLen[nChar] = (u8)(z - azChar[nChar]);
105400  }
105401  }
105402  }
105403  if( nChar>0 ){
105404  flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
105405  if( flags & 1 ){
105406  while( nIn>0 ){
105407  int len = 0;
105408  for(i=0; i<nChar; i++){
105409  len = aLen[i];
105410  if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
105411  }
105412  if( i>=nChar ) break;
105413  zIn += len;
105414  nIn -= len;
105415  }
105416  }
105417  if( flags & 2 ){
105418  while( nIn>0 ){
105419  int len = 0;
105420  for(i=0; i<nChar; i++){
105421  len = aLen[i];
105422  if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
105423  }
105424  if( i>=nChar ) break;
105425  nIn -= len;
105426  }
105427  }
105428  if( zCharSet ){
105429  sqlite3_free(azChar);
105430  }
105431  }
105432  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
105433 }
105434 
105435 
105436 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105437 /*
105438 ** The "unknown" function is automatically substituted in place of
105439 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
105440 ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
105441 ** When the "sqlite3" command-line shell is built using this functionality,
105442 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
105443 ** involving application-defined functions to be examined in a generic
105444 ** sqlite3 shell.
105445 */
105446 static void unknownFunc(
105447  sqlite3_context *context,
105448  int argc,
105449  sqlite3_value **argv
105450 ){
105451  /* no-op */
105452 }
105453 #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
105454 
105455 
105456 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
105457 ** is only available if the SQLITE_SOUNDEX compile-time option is used
105458 ** when SQLite is built.
105459 */
105460 #ifdef SQLITE_SOUNDEX
105461 /*
105462 ** Compute the soundex encoding of a word.
105463 **
105464 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
105465 ** soundex encoding of the string X.
105466 */
105467 static void soundexFunc(
105468  sqlite3_context *context,
105469  int argc,
105470  sqlite3_value **argv
105471 ){
105472  char zResult[8];
105473  const u8 *zIn;
105474  int i, j;
105475  static const unsigned char iCode[] = {
105476  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105477  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105478  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105479  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
105480  0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
105481  1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
105482  0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
105483  1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
105484  };
105485  assert( argc==1 );
105486  zIn = (u8*)sqlite3_value_text(argv[0]);
105487  if( zIn==0 ) zIn = (u8*)"";
105488  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
105489  if( zIn[i] ){
105490  u8 prevcode = iCode[zIn[i]&0x7f];
105491  zResult[0] = sqlite3Toupper(zIn[i]);
105492  for(j=1; j<4 && zIn[i]; i++){
105493  int code = iCode[zIn[i]&0x7f];
105494  if( code>0 ){
105495  if( code!=prevcode ){
105496  prevcode = code;
105497  zResult[j++] = code + '0';
105498  }
105499  }else{
105500  prevcode = 0;
105501  }
105502  }
105503  while( j<4 ){
105504  zResult[j++] = '0';
105505  }
105506  zResult[j] = 0;
105507  sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
105508  }else{
105509  /* IMP: R-64894-50321 The string "?000" is returned if the argument
105510  ** is NULL or contains no ASCII alphabetic characters. */
105511  sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
105512  }
105513 }
105514 #endif /* SQLITE_SOUNDEX */
105515 
105516 #ifndef SQLITE_OMIT_LOAD_EXTENSION
105517 /*
105518 ** A function that loads a shared-library extension then returns NULL.
105519 */
105520 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
105521  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
105522  const char *zProc;
105523  sqlite3 *db = sqlite3_context_db_handle(context);
105524  char *zErrMsg = 0;
105525 
105526  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
105527  ** flag is set. See the sqlite3_enable_load_extension() API.
105528  */
105529  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
105530  sqlite3_result_error(context, "not authorized", -1);
105531  return;
105532  }
105533 
105534  if( argc==2 ){
105535  zProc = (const char *)sqlite3_value_text(argv[1]);
105536  }else{
105537  zProc = 0;
105538  }
105539  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
105540  sqlite3_result_error(context, zErrMsg, -1);
105541  sqlite3_free(zErrMsg);
105542  }
105543 }
105544 #endif
105545 
105546 
105547 /*
105548 ** An instance of the following structure holds the context of a
105549 ** sum() or avg() aggregate computation.
105550 */
105551 typedef struct SumCtx SumCtx;
105552 struct SumCtx {
105553  double rSum; /* Floating point sum */
105554  i64 iSum; /* Integer sum */
105555  i64 cnt; /* Number of elements summed */
105556  u8 overflow; /* True if integer overflow seen */
105557  u8 approx; /* True if non-integer value was input to the sum */
105558 };
105559 
105560 /*
105561 ** Routines used to compute the sum, average, and total.
105562 **
105563 ** The SUM() function follows the (broken) SQL standard which means
105564 ** that it returns NULL if it sums over no inputs. TOTAL returns
105565 ** 0.0 in that case. In addition, TOTAL always returns a float where
105566 ** SUM might return an integer if it never encounters a floating point
105567 ** value. TOTAL never fails, but SUM might through an exception if
105568 ** it overflows an integer.
105569 */
105570 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
105571  SumCtx *p;
105572  int type;
105573  assert( argc==1 );
105574  UNUSED_PARAMETER(argc);
105575  p = sqlite3_aggregate_context(context, sizeof(*p));
105576  type = sqlite3_value_numeric_type(argv[0]);
105577  if( p && type!=SQLITE_NULL ){
105578  p->cnt++;
105579  if( type==SQLITE_INTEGER ){
105580  i64 v = sqlite3_value_int64(argv[0]);
105581  p->rSum += v;
105582  if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
105583  p->overflow = 1;
105584  }
105585  }else{
105586  p->rSum += sqlite3_value_double(argv[0]);
105587  p->approx = 1;
105588  }
105589  }
105590 }
105591 static void sumFinalize(sqlite3_context *context){
105592  SumCtx *p;
105593  p = sqlite3_aggregate_context(context, 0);
105594  if( p && p->cnt>0 ){
105595  if( p->overflow ){
105596  sqlite3_result_error(context,"integer overflow",-1);
105597  }else if( p->approx ){
105598  sqlite3_result_double(context, p->rSum);
105599  }else{
105600  sqlite3_result_int64(context, p->iSum);
105601  }
105602  }
105603 }
105604 static void avgFinalize(sqlite3_context *context){
105605  SumCtx *p;
105606  p = sqlite3_aggregate_context(context, 0);
105607  if( p && p->cnt>0 ){
105608  sqlite3_result_double(context, p->rSum/(double)p->cnt);
105609  }
105610 }
105611 static void totalFinalize(sqlite3_context *context){
105612  SumCtx *p;
105613  p = sqlite3_aggregate_context(context, 0);
105614  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
105615  sqlite3_result_double(context, p ? p->rSum : (double)0);
105616 }
105617 
105618 /*
105619 ** The following structure keeps track of state information for the
105620 ** count() aggregate function.
105621 */
105622 typedef struct CountCtx CountCtx;
105623 struct CountCtx {
105624  i64 n;
105625 };
105626 
105627 /*
105628 ** Routines to implement the count() aggregate function.
105629 */
105630 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
105631  CountCtx *p;
105632  p = sqlite3_aggregate_context(context, sizeof(*p));
105633  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
105634  p->n++;
105635  }
105636 
105637 #ifndef SQLITE_OMIT_DEPRECATED
105638  /* The sqlite3_aggregate_count() function is deprecated. But just to make
105639  ** sure it still operates correctly, verify that its count agrees with our
105640  ** internal count when using count(*) and when the total count can be
105641  ** expressed as a 32-bit integer. */
105642  assert( argc==1 || p==0 || p->n>0x7fffffff
105643  || p->n==sqlite3_aggregate_count(context) );
105644 #endif
105645 }
105646 static void countFinalize(sqlite3_context *context){
105647  CountCtx *p;
105648  p = sqlite3_aggregate_context(context, 0);
105649  sqlite3_result_int64(context, p ? p->n : 0);
105650 }
105651 
105652 /*
105653 ** Routines to implement min() and max() aggregate functions.
105654 */
105655 static void minmaxStep(
105656  sqlite3_context *context,
105657  int NotUsed,
105658  sqlite3_value **argv
105659 ){
105660  Mem *pArg = (Mem *)argv[0];
105661  Mem *pBest;
105662  UNUSED_PARAMETER(NotUsed);
105663 
105664  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
105665  if( !pBest ) return;
105666 
105667  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
105668  if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
105669  }else if( pBest->flags ){
105670  int max;
105671  int cmp;
105672  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
105673  /* This step function is used for both the min() and max() aggregates,
105674  ** the only difference between the two being that the sense of the
105675  ** comparison is inverted. For the max() aggregate, the
105676  ** sqlite3_user_data() function returns (void *)-1. For min() it
105677  ** returns (void *)db, where db is the sqlite3* database pointer.
105678  ** Therefore the next statement sets variable 'max' to 1 for the max()
105679  ** aggregate, or 0 for min().
105680  */
105681  max = sqlite3_user_data(context)!=0;
105682  cmp = sqlite3MemCompare(pBest, pArg, pColl);
105683  if( (max && cmp<0) || (!max && cmp>0) ){
105684  sqlite3VdbeMemCopy(pBest, pArg);
105685  }else{
105686  sqlite3SkipAccumulatorLoad(context);
105687  }
105688  }else{
105689  pBest->db = sqlite3_context_db_handle(context);
105690  sqlite3VdbeMemCopy(pBest, pArg);
105691  }
105692 }
105693 static void minMaxFinalize(sqlite3_context *context){
105694  sqlite3_value *pRes;
105695  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
105696  if( pRes ){
105697  if( pRes->flags ){
105698  sqlite3_result_value(context, pRes);
105699  }
105700  sqlite3VdbeMemRelease(pRes);
105701  }
105702 }
105703 
105704 /*
105705 ** group_concat(EXPR, ?SEPARATOR?)
105706 */
105707 static void groupConcatStep(
105708  sqlite3_context *context,
105709  int argc,
105710  sqlite3_value **argv
105711 ){
105712  const char *zVal;
105713  StrAccum *pAccum;
105714  const char *zSep;
105715  int nVal, nSep;
105716  assert( argc==1 || argc==2 );
105717  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
105718  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
105719 
105720  if( pAccum ){
105721  sqlite3 *db = sqlite3_context_db_handle(context);
105722  int firstTerm = pAccum->mxAlloc==0;
105723  pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
105724  if( !firstTerm ){
105725  if( argc==2 ){
105726  zSep = (char*)sqlite3_value_text(argv[1]);
105727  nSep = sqlite3_value_bytes(argv[1]);
105728  }else{
105729  zSep = ",";
105730  nSep = 1;
105731  }
105732  if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
105733  }
105734  zVal = (char*)sqlite3_value_text(argv[0]);
105735  nVal = sqlite3_value_bytes(argv[0]);
105736  if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
105737  }
105738 }
105740  StrAccum *pAccum;
105741  pAccum = sqlite3_aggregate_context(context, 0);
105742  if( pAccum ){
105743  if( pAccum->accError==STRACCUM_TOOBIG ){
105744  sqlite3_result_error_toobig(context);
105745  }else if( pAccum->accError==STRACCUM_NOMEM ){
105746  sqlite3_result_error_nomem(context);
105747  }else{
105748  sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
105749  sqlite3_free);
105750  }
105751  }
105752 }
105753 
105754 /*
105755 ** This routine does per-connection function registration. Most
105756 ** of the built-in functions above are part of the global function set.
105757 ** This routine only deals with those that are not global.
105758 */
105760  int rc = sqlite3_overload_function(db, "MATCH", 2);
105761  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
105762  if( rc==SQLITE_NOMEM ){
105763  sqlite3OomFault(db);
105764  }
105765 }
105766 
105767 /*
105768 ** Set the LIKEOPT flag on the 2-argument function with the given name.
105769 */
105770 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
105771  FuncDef *pDef;
105772  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
105773  if( ALWAYS(pDef) ){
105774  pDef->funcFlags |= flagVal;
105775  }
105776 }
105777 
105778 /*
105779 ** Register the built-in LIKE and GLOB functions. The caseSensitive
105780 ** parameter determines whether or not the LIKE operator is case
105781 ** sensitive. GLOB is always case sensitive.
105782 */
105784  struct compareInfo *pInfo;
105785  if( caseSensitive ){
105786  pInfo = (struct compareInfo*)&likeInfoAlt;
105787  }else{
105788  pInfo = (struct compareInfo*)&likeInfoNorm;
105789  }
105790  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
105791  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
105792  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
105793  (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
105795  setLikeOptFlag(db, "like",
105796  caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
105797 }
105798 
105799 /*
105800 ** pExpr points to an expression which implements a function. If
105801 ** it is appropriate to apply the LIKE optimization to that function
105802 ** then set aWc[0] through aWc[2] to the wildcard characters and
105803 ** return TRUE. If the function is not a LIKE-style function then
105804 ** return FALSE.
105805 **
105806 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
105807 ** the function (default for LIKE). If the function makes the distinction
105808 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
105809 ** false.
105810 */
105811 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
105812  FuncDef *pDef;
105813  if( pExpr->op!=TK_FUNCTION
105814  || !pExpr->x.pList
105815  || pExpr->x.pList->nExpr!=2
105816  ){
105817  return 0;
105818  }
105819  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
105820  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
105821  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
105822  return 0;
105823  }
105824 
105825  /* The memcpy() statement assumes that the wildcard characters are
105826  ** the first three statements in the compareInfo structure. The
105827  ** asserts() that follow verify that assumption
105828  */
105829  memcpy(aWc, pDef->pUserData, 3);
105830  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
105831  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
105832  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
105833  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
105834  return 1;
105835 }
105836 
105837 /*
105838 ** All of the FuncDef structures in the aBuiltinFunc[] array above
105839 ** to the global function hash table. This occurs at start-time (as
105840 ** a consequence of calling sqlite3_initialize()).
105841 **
105842 ** After this routine runs
105843 */
105845  /*
105846  ** The following array holds FuncDef structures for all of the functions
105847  ** defined in this file.
105848  **
105849  ** The array cannot be constant since changes are made to the
105850  ** FuncDef.pHash elements at start-time. The elements of this array
105851  ** are read-only after initialization is complete.
105852  **
105853  ** For peak efficiency, put the most frequently used function last.
105854  */
105855  static FuncDef aBuiltinFunc[] = {
105856 #ifdef SQLITE_SOUNDEX
105857  FUNCTION(soundex, 1, 0, 0, soundexFunc ),
105858 #endif
105859 #ifndef SQLITE_OMIT_LOAD_EXTENSION
105860  VFUNCTION(load_extension, 1, 0, 0, loadExt ),
105861  VFUNCTION(load_extension, 2, 0, 0, loadExt ),
105862 #endif
105863 #if SQLITE_USER_AUTHENTICATION
105864  FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
105865 #endif
105866 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
105867  DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
105868  DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
105869 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
105871  FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
105873  FUNCTION(ltrim, 1, 1, 0, trimFunc ),
105874  FUNCTION(ltrim, 2, 1, 0, trimFunc ),
105875  FUNCTION(rtrim, 1, 2, 0, trimFunc ),
105876  FUNCTION(rtrim, 2, 2, 0, trimFunc ),
105877  FUNCTION(trim, 1, 3, 0, trimFunc ),
105878  FUNCTION(trim, 2, 3, 0, trimFunc ),
105879  FUNCTION(min, -1, 0, 1, minmaxFunc ),
105880  FUNCTION(min, 0, 0, 1, 0 ),
105882  SQLITE_FUNC_MINMAX ),
105883  FUNCTION(max, -1, 1, 1, minmaxFunc ),
105884  FUNCTION(max, 0, 1, 1, 0 ),
105885  AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
105886  SQLITE_FUNC_MINMAX ),
105887  FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
105888  FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
105889  FUNCTION(instr, 2, 0, 0, instrFunc ),
105890  FUNCTION(printf, -1, 0, 0, printfFunc ),
105891  FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
105892  FUNCTION(char, -1, 0, 0, charFunc ),
105893  FUNCTION(abs, 1, 0, 0, absFunc ),
105894 #ifndef SQLITE_OMIT_FLOATING_POINT
105895  FUNCTION(round, 1, 0, 0, roundFunc ),
105896  FUNCTION(round, 2, 0, 0, roundFunc ),
105897 #endif
105898  FUNCTION(upper, 1, 0, 0, upperFunc ),
105899  FUNCTION(lower, 1, 0, 0, lowerFunc ),
105900  FUNCTION(hex, 1, 0, 0, hexFunc ),
105901  FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
105902  VFUNCTION(random, 0, 0, 0, randomFunc ),
105903  VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
105904  FUNCTION(nullif, 2, 0, 1, nullifFunc ),
105905  DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
105906  DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
105907  FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
105908  FUNCTION(quote, 1, 0, 0, quoteFunc ),
105910  VFUNCTION(changes, 0, 0, 0, changes ),
105911  VFUNCTION(total_changes, 0, 0, 0, total_changes ),
105912  FUNCTION(replace, 3, 0, 0, replaceFunc ),
105913  FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
105914  FUNCTION(substr, 2, 0, 0, substrFunc ),
105915  FUNCTION(substr, 3, 0, 0, substrFunc ),
105916  AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
105917  AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
105918  AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
105919  AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
105920  SQLITE_FUNC_COUNT ),
105921  AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
105922  AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
105923  AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
105924 
105925  LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105926 #ifdef SQLITE_CASE_SENSITIVE_LIKE
105927  LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105928  LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105929 #else
105930  LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
105931  LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
105932 #endif
105933 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105934  FUNCTION(unknown, -1, 0, 0, unknownFunc ),
105935 #endif
105936  FUNCTION(coalesce, 1, 0, 0, 0 ),
105937  FUNCTION(coalesce, 0, 0, 0, 0 ),
105938  FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
105939  };
105940 #ifndef SQLITE_OMIT_ALTERTABLE
105942 #endif
105943 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
105944  sqlite3AnalyzeFunctions();
105945 #endif
105947  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
105948 
105949 #if 0 /* Enable to print out how the built-in functions are hashed */
105950  {
105951  int i;
105952  FuncDef *p;
105953  for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
105954  printf("FUNC-HASH %02d:", i);
105955  for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
105956  int n = sqlite3Strlen30(p->zName);
105957  int h = p->zName[0] + n;
105958  printf(" %s(%d)", p->zName, h);
105959  }
105960  printf("\n");
105961  }
105962  }
105963 #endif
105964 }
105965 
105966 /************** End of func.c ************************************************/
105967 /************** Begin file fkey.c ********************************************/
105968 /*
105969 **
105970 ** The author disclaims copyright to this source code. In place of
105971 ** a legal notice, here is a blessing:
105972 **
105973 ** May you do good and not evil.
105974 ** May you find forgiveness for yourself and forgive others.
105975 ** May you share freely, never taking more than you give.
105976 **
105977 *************************************************************************
105978 ** This file contains code used by the compiler to add foreign key
105979 ** support to compiled SQL statements.
105980 */
105981 /* #include "sqliteInt.h" */
105982 
105983 #ifndef SQLITE_OMIT_FOREIGN_KEY
105984 #ifndef SQLITE_OMIT_TRIGGER
105985 
105986 /*
105987 ** Deferred and Immediate FKs
105988 ** --------------------------
105989 **
105990 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
105991 ** If an immediate foreign key constraint is violated,
105992 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
105993 ** statement transaction rolled back. If a
105994 ** deferred foreign key constraint is violated, no action is taken
105995 ** immediately. However if the application attempts to commit the
105996 ** transaction before fixing the constraint violation, the attempt fails.
105997 **
105998 ** Deferred constraints are implemented using a simple counter associated
105999 ** with the database handle. The counter is set to zero each time a
106000 ** database transaction is opened. Each time a statement is executed
106001 ** that causes a foreign key violation, the counter is incremented. Each
106002 ** time a statement is executed that removes an existing violation from
106003 ** the database, the counter is decremented. When the transaction is
106004 ** committed, the commit fails if the current value of the counter is
106005 ** greater than zero. This scheme has two big drawbacks:
106006 **
106007 ** * When a commit fails due to a deferred foreign key constraint,
106008 ** there is no way to tell which foreign constraint is not satisfied,
106009 ** or which row it is not satisfied for.
106010 **
106011 ** * If the database contains foreign key violations when the
106012 ** transaction is opened, this may cause the mechanism to malfunction.
106013 **
106014 ** Despite these problems, this approach is adopted as it seems simpler
106015 ** than the alternatives.
106016 **
106017 ** INSERT operations:
106018 **
106019 ** I.1) For each FK for which the table is the child table, search
106020 ** the parent table for a match. If none is found increment the
106021 ** constraint counter.
106022 **
106023 ** I.2) For each FK for which the table is the parent table,
106024 ** search the child table for rows that correspond to the new
106025 ** row in the parent table. Decrement the counter for each row
106026 ** found (as the constraint is now satisfied).
106027 **
106028 ** DELETE operations:
106029 **
106030 ** D.1) For each FK for which the table is the child table,
106031 ** search the parent table for a row that corresponds to the
106032 ** deleted row in the child table. If such a row is not found,
106033 ** decrement the counter.
106034 **
106035 ** D.2) For each FK for which the table is the parent table, search
106036 ** the child table for rows that correspond to the deleted row
106037 ** in the parent table. For each found increment the counter.
106038 **
106039 ** UPDATE operations:
106040 **
106041 ** An UPDATE command requires that all 4 steps above are taken, but only
106042 ** for FK constraints for which the affected columns are actually
106043 ** modified (values must be compared at runtime).
106044 **
106045 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
106046 ** This simplifies the implementation a bit.
106047 **
106048 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
106049 ** resolution is considered to delete rows before the new row is inserted.
106050 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
106051 ** is thrown, even if the FK constraint would be satisfied after the new
106052 ** row is inserted.
106053 **
106054 ** Immediate constraints are usually handled similarly. The only difference
106055 ** is that the counter used is stored as part of each individual statement
106056 ** object (struct Vdbe). If, after the statement has run, its immediate
106057 ** constraint counter is greater than zero,
106058 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
106059 ** and the statement transaction is rolled back. An exception is an INSERT
106060 ** statement that inserts a single row only (no triggers). In this case,
106061 ** instead of using a counter, an exception is thrown immediately if the
106062 ** INSERT violates a foreign key constraint. This is necessary as such
106063 ** an INSERT does not open a statement transaction.
106064 **
106065 ** TODO: How should dropping a table be handled? How should renaming a
106066 ** table be handled?
106067 **
106068 **
106069 ** Query API Notes
106070 ** ---------------
106071 **
106072 ** Before coding an UPDATE or DELETE row operation, the code-generator
106073 ** for those two operations needs to know whether or not the operation
106074 ** requires any FK processing and, if so, which columns of the original
106075 ** row are required by the FK processing VDBE code (i.e. if FKs were
106076 ** implemented using triggers, which of the old.* columns would be
106077 ** accessed). No information is required by the code-generator before
106078 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
106079 ** generation code to query for this information are:
106080 **
106081 ** sqlite3FkRequired() - Test to see if FK processing is required.
106082 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
106083 **
106084 **
106085 ** Externally accessible module functions
106086 ** --------------------------------------
106087 **
106088 ** sqlite3FkCheck() - Check for foreign key violations.
106089 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
106090 ** sqlite3FkDelete() - Delete an FKey structure.
106091 */
106092 
106093 /*
106094 ** VDBE Calling Convention
106095 ** -----------------------
106096 **
106097 ** Example:
106098 **
106099 ** For the following INSERT statement:
106100 **
106101 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
106102 ** INSERT INTO t1 VALUES(1, 2, 3.1);
106103 **
106104 ** Register (x): 2 (type integer)
106105 ** Register (x+1): 1 (type integer)
106106 ** Register (x+2): NULL (type NULL)
106107 ** Register (x+3): 3.1 (type real)
106108 */
106109 
106110 /*
106111 ** A foreign key constraint requires that the key columns in the parent
106112 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
106113 ** Given that pParent is the parent table for foreign key constraint pFKey,
106114 ** search the schema for a unique index on the parent key columns.
106115 **
106116 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
106117 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
106118 ** is set to point to the unique index.
106119 **
106120 ** If the parent key consists of a single column (the foreign key constraint
106121 ** is not a composite foreign key), output variable *paiCol is set to NULL.
106122 ** Otherwise, it is set to point to an allocated array of size N, where
106123 ** N is the number of columns in the parent key. The first element of the
106124 ** array is the index of the child table column that is mapped by the FK
106125 ** constraint to the parent table column stored in the left-most column
106126 ** of index *ppIdx. The second element of the array is the index of the
106127 ** child table column that corresponds to the second left-most column of
106128 ** *ppIdx, and so on.
106129 **
106130 ** If the required index cannot be found, either because:
106131 **
106132 ** 1) The named parent key columns do not exist, or
106133 **
106134 ** 2) The named parent key columns do exist, but are not subject to a
106135 ** UNIQUE or PRIMARY KEY constraint, or
106136 **
106137 ** 3) No parent key columns were provided explicitly as part of the
106138 ** foreign key definition, and the parent table does not have a
106139 ** PRIMARY KEY, or
106140 **
106141 ** 4) No parent key columns were provided explicitly as part of the
106142 ** foreign key definition, and the PRIMARY KEY of the parent table
106143 ** consists of a different number of columns to the child key in
106144 ** the child table.
106145 **
106146 ** then non-zero is returned, and a "foreign key mismatch" error loaded
106147 ** into pParse. If an OOM error occurs, non-zero is returned and the
106148 ** pParse->db->mallocFailed flag is set.
106149 */
106151  Parse *pParse, /* Parse context to store any error in */
106152  Table *pParent, /* Parent table of FK constraint pFKey */
106153  FKey *pFKey, /* Foreign key to find index for */
106154  Index **ppIdx, /* OUT: Unique index on parent table */
106155  int **paiCol /* OUT: Map of index columns in pFKey */
106156 ){
106157  Index *pIdx = 0; /* Value to return via *ppIdx */
106158  int *aiCol = 0; /* Value to return via *paiCol */
106159  int nCol = pFKey->nCol; /* Number of columns in parent key */
106160  char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
106161 
106162  /* The caller is responsible for zeroing output parameters. */
106163  assert( ppIdx && *ppIdx==0 );
106164  assert( !paiCol || *paiCol==0 );
106165  assert( pParse );
106166 
106167  /* If this is a non-composite (single column) foreign key, check if it
106168  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
106169  ** and *paiCol set to zero and return early.
106170  **
106171  ** Otherwise, for a composite foreign key (more than one column), allocate
106172  ** space for the aiCol array (returned via output parameter *paiCol).
106173  ** Non-composite foreign keys do not require the aiCol array.
106174  */
106175  if( nCol==1 ){
106176  /* The FK maps to the IPK if any of the following are true:
106177  **
106178  ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
106179  ** mapped to the primary key of table pParent, or
106180  ** 2) The FK is explicitly mapped to a column declared as INTEGER
106181  ** PRIMARY KEY.
106182  */
106183  if( pParent->iPKey>=0 ){
106184  if( !zKey ) return 0;
106185  if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
106186  }
106187  }else if( paiCol ){
106188  assert( nCol>1 );
106189  aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
106190  if( !aiCol ) return 1;
106191  *paiCol = aiCol;
106192  }
106193 
106194  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
106195  if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
106196  /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
106197  ** of columns. If each indexed column corresponds to a foreign key
106198  ** column of pFKey, then this index is a winner. */
106199 
106200  if( zKey==0 ){
106201  /* If zKey is NULL, then this foreign key is implicitly mapped to
106202  ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
106203  ** identified by the test. */
106204  if( IsPrimaryKeyIndex(pIdx) ){
106205  if( aiCol ){
106206  int i;
106207  for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
106208  }
106209  break;
106210  }
106211  }else{
106212  /* If zKey is non-NULL, then this foreign key was declared to
106213  ** map to an explicit list of columns in table pParent. Check if this
106214  ** index matches those columns. Also, check that the index uses
106215  ** the default collation sequences for each column. */
106216  int i, j;
106217  for(i=0; i<nCol; i++){
106218  i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
106219  const char *zDfltColl; /* Def. collation for column */
106220  char *zIdxCol; /* Name of indexed column */
106221 
106222  if( iCol<0 ) break; /* No foreign keys against expression indexes */
106223 
106224  /* If the index uses a collation sequence that is different from
106225  ** the default collation sequence for the column, this index is
106226  ** unusable. Bail out early in this case. */
106227  zDfltColl = pParent->aCol[iCol].zColl;
106228  if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
106229  if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
106230 
106231  zIdxCol = pParent->aCol[iCol].zName;
106232  for(j=0; j<nCol; j++){
106233  if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
106234  if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
106235  break;
106236  }
106237  }
106238  if( j==nCol ) break;
106239  }
106240  if( i==nCol ) break; /* pIdx is usable */
106241  }
106242  }
106243  }
106244 
106245  if( !pIdx ){
106246  if( !pParse->disableTriggers ){
106247  sqlite3ErrorMsg(pParse,
106248  "foreign key mismatch - \"%w\" referencing \"%w\"",
106249  pFKey->pFrom->zName, pFKey->zTo);
106250  }
106251  sqlite3DbFree(pParse->db, aiCol);
106252  return 1;
106253  }
106254 
106255  *ppIdx = pIdx;
106256  return 0;
106257 }
106258 
106259 /*
106260 ** This function is called when a row is inserted into or deleted from the
106261 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
106262 ** on the child table of pFKey, this function is invoked twice for each row
106263 ** affected - once to "delete" the old row, and then again to "insert" the
106264 ** new row.
106265 **
106266 ** Each time it is called, this function generates VDBE code to locate the
106267 ** row in the parent table that corresponds to the row being inserted into
106268 ** or deleted from the child table. If the parent row can be found, no
106269 ** special action is taken. Otherwise, if the parent row can *not* be
106270 ** found in the parent table:
106271 **
106272 ** Operation | FK type | Action taken
106273 ** --------------------------------------------------------------------------
106274 ** INSERT immediate Increment the "immediate constraint counter".
106275 **
106276 ** DELETE immediate Decrement the "immediate constraint counter".
106277 **
106278 ** INSERT deferred Increment the "deferred constraint counter".
106279 **
106280 ** DELETE deferred Decrement the "deferred constraint counter".
106281 **
106282 ** These operations are identified in the comment at the top of this file
106283 ** (fkey.c) as "I.1" and "D.1".
106284 */
106285 static void fkLookupParent(
106286  Parse *pParse, /* Parse context */
106287  int iDb, /* Index of database housing pTab */
106288  Table *pTab, /* Parent table of FK pFKey */
106289  Index *pIdx, /* Unique index on parent key columns in pTab */
106290  FKey *pFKey, /* Foreign key constraint */
106291  int *aiCol, /* Map from parent key columns to child table columns */
106292  int regData, /* Address of array containing child table row */
106293  int nIncr, /* Increment constraint counter by this */
106294  int isIgnore /* If true, pretend pTab contains all NULL values */
106295 ){
106296  int i; /* Iterator variable */
106297  Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
106298  int iCur = pParse->nTab - 1; /* Cursor number to use */
106299  int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
106300 
106301  /* If nIncr is less than zero, then check at runtime if there are any
106302  ** outstanding constraints to resolve. If there are not, there is no need
106303  ** to check if deleting this row resolves any outstanding violations.
106304  **
106305  ** Check if any of the key columns in the child table row are NULL. If
106306  ** any are, then the constraint is considered satisfied. No need to
106307  ** search for a matching row in the parent table. */
106308  if( nIncr<0 ){
106309  sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
106310  VdbeCoverage(v);
106311  }
106312  for(i=0; i<pFKey->nCol; i++){
106313  int iReg = aiCol[i] + regData + 1;
106314  sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
106315  }
106316 
106317  if( isIgnore==0 ){
106318  if( pIdx==0 ){
106319  /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
106320  ** column of the parent table (table pTab). */
106321  int iMustBeInt; /* Address of MustBeInt instruction */
106322  int regTemp = sqlite3GetTempReg(pParse);
106323 
106324  /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
106325  ** apply the affinity of the parent key). If this fails, then there
106326  ** is no matching parent key. Before using MustBeInt, make a copy of
106327  ** the value. Otherwise, the value inserted into the child key column
106328  ** will have INTEGER affinity applied to it, which may not be correct. */
106329  sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
106330  iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
106331  VdbeCoverage(v);
106332 
106333  /* If the parent table is the same as the child table, and we are about
106334  ** to increment the constraint-counter (i.e. this is an INSERT operation),
106335  ** then check if the row being inserted matches itself. If so, do not
106336  ** increment the constraint-counter. */
106337  if( pTab==pFKey->pFrom && nIncr==1 ){
106338  sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
106340  }
106341 
106342  sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
106343  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
106344  sqlite3VdbeGoto(v, iOk);
106346  sqlite3VdbeJumpHere(v, iMustBeInt);
106347  sqlite3ReleaseTempReg(pParse, regTemp);
106348  }else{
106349  int nCol = pFKey->nCol;
106350  int regTemp = sqlite3GetTempRange(pParse, nCol);
106351  int regRec = sqlite3GetTempReg(pParse);
106352 
106353  sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
106354  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
106355  for(i=0; i<nCol; i++){
106356  sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
106357  }
106358 
106359  /* If the parent table is the same as the child table, and we are about
106360  ** to increment the constraint-counter (i.e. this is an INSERT operation),
106361  ** then check if the row being inserted matches itself. If so, do not
106362  ** increment the constraint-counter.
106363  **
106364  ** If any of the parent-key values are NULL, then the row cannot match
106365  ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
106366  ** of the parent-key values are NULL (at this point it is known that
106367  ** none of the child key values are).
106368  */
106369  if( pTab==pFKey->pFrom && nIncr==1 ){
106370  int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
106371  for(i=0; i<nCol; i++){
106372  int iChild = aiCol[i]+1+regData;
106373  int iParent = pIdx->aiColumn[i]+1+regData;
106374  assert( pIdx->aiColumn[i]>=0 );
106375  assert( aiCol[i]!=pTab->iPKey );
106376  if( pIdx->aiColumn[i]==pTab->iPKey ){
106377  /* The parent key is a composite key that includes the IPK column */
106378  iParent = regData;
106379  }
106380  sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
106382  }
106383  sqlite3VdbeGoto(v, iOk);
106384  }
106385 
106386  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
106387  sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
106388  sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
106389 
106390  sqlite3ReleaseTempReg(pParse, regRec);
106391  sqlite3ReleaseTempRange(pParse, regTemp, nCol);
106392  }
106393  }
106394 
106395  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
106396  && !pParse->pToplevel
106397  && !pParse->isMultiWrite
106398  ){
106399  /* Special case: If this is an INSERT statement that will insert exactly
106400  ** one row into the table, raise a constraint immediately instead of
106401  ** incrementing a counter. This is necessary as the VM code is being
106402  ** generated for will not open a statement transaction. */
106403  assert( nIncr==1 );
106406  }else{
106407  if( nIncr>0 && pFKey->isDeferred==0 ){
106408  sqlite3MayAbort(pParse);
106409  }
106410  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
106411  }
106412 
106413  sqlite3VdbeResolveLabel(v, iOk);
106414  sqlite3VdbeAddOp1(v, OP_Close, iCur);
106415 }
106416 
106417 
106418 /*
106419 ** Return an Expr object that refers to a memory register corresponding
106420 ** to column iCol of table pTab.
106421 **
106422 ** regBase is the first of an array of register that contains the data
106423 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
106424 ** column. regBase+2 holds the second column, and so forth.
106425 */
106427  Parse *pParse, /* Parsing and code generating context */
106428  Table *pTab, /* The table whose content is at r[regBase]... */
106429  int regBase, /* Contents of table pTab */
106430  i16 iCol /* Which column of pTab is desired */
106431 ){
106432  Expr *pExpr;
106433  Column *pCol;
106434  const char *zColl;
106435  sqlite3 *db = pParse->db;
106436 
106437  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
106438  if( pExpr ){
106439  if( iCol>=0 && iCol!=pTab->iPKey ){
106440  pCol = &pTab->aCol[iCol];
106441  pExpr->iTable = regBase + iCol + 1;
106442  pExpr->affinity = pCol->affinity;
106443  zColl = pCol->zColl;
106444  if( zColl==0 ) zColl = db->pDfltColl->zName;
106445  pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
106446  }else{
106447  pExpr->iTable = regBase;
106448  pExpr->affinity = SQLITE_AFF_INTEGER;
106449  }
106450  }
106451  return pExpr;
106452 }
106453 
106454 /*
106455 ** Return an Expr object that refers to column iCol of table pTab which
106456 ** has cursor iCur.
106457 */
106459  sqlite3 *db, /* The database connection */
106460  Table *pTab, /* The table whose column is desired */
106461  int iCursor, /* The open cursor on the table */
106462  i16 iCol /* The column that is wanted */
106463 ){
106464  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
106465  if( pExpr ){
106466  pExpr->pTab = pTab;
106467  pExpr->iTable = iCursor;
106468  pExpr->iColumn = iCol;
106469  }
106470  return pExpr;
106471 }
106472 
106473 /*
106474 ** This function is called to generate code executed when a row is deleted
106475 ** from the parent table of foreign key constraint pFKey and, if pFKey is
106476 ** deferred, when a row is inserted into the same table. When generating
106477 ** code for an SQL UPDATE operation, this function may be called twice -
106478 ** once to "delete" the old row and once to "insert" the new row.
106479 **
106480 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
106481 ** the number of FK violations in the db) or +1 when deleting one (as this
106482 ** may increase the number of FK constraint problems).
106483 **
106484 ** The code generated by this function scans through the rows in the child
106485 ** table that correspond to the parent table row being deleted or inserted.
106486 ** For each child row found, one of the following actions is taken:
106487 **
106488 ** Operation | FK type | Action taken
106489 ** --------------------------------------------------------------------------
106490 ** DELETE immediate Increment the "immediate constraint counter".
106491 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
106492 ** throw a "FOREIGN KEY constraint failed" exception.
106493 **
106494 ** INSERT immediate Decrement the "immediate constraint counter".
106495 **
106496 ** DELETE deferred Increment the "deferred constraint counter".
106497 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
106498 ** throw a "FOREIGN KEY constraint failed" exception.
106499 **
106500 ** INSERT deferred Decrement the "deferred constraint counter".
106501 **
106502 ** These operations are identified in the comment at the top of this file
106503 ** (fkey.c) as "I.2" and "D.2".
106504 */
106505 static void fkScanChildren(
106506  Parse *pParse, /* Parse context */
106507  SrcList *pSrc, /* The child table to be scanned */
106508  Table *pTab, /* The parent table */
106509  Index *pIdx, /* Index on parent covering the foreign key */
106510  FKey *pFKey, /* The foreign key linking pSrc to pTab */
106511  int *aiCol, /* Map from pIdx cols to child table cols */
106512  int regData, /* Parent row data starts here */
106513  int nIncr /* Amount to increment deferred counter by */
106514 ){
106515  sqlite3 *db = pParse->db; /* Database handle */
106516  int i; /* Iterator variable */
106517  Expr *pWhere = 0; /* WHERE clause to scan with */
106518  NameContext sNameContext; /* Context used to resolve WHERE clause */
106519  WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
106520  int iFkIfZero = 0; /* Address of OP_FkIfZero */
106521  Vdbe *v = sqlite3GetVdbe(pParse);
106522 
106523  assert( pIdx==0 || pIdx->pTable==pTab );
106524  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
106525  assert( pIdx!=0 || pFKey->nCol==1 );
106526  assert( pIdx!=0 || HasRowid(pTab) );
106527 
106528  if( nIncr<0 ){
106529  iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
106530  VdbeCoverage(v);
106531  }
106532 
106533  /* Create an Expr object representing an SQL expression like:
106534  **
106535  ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
106536  **
106537  ** The collation sequence used for the comparison should be that of
106538  ** the parent key columns. The affinity of the parent key column should
106539  ** be applied to each child key value before the comparison takes place.
106540  */
106541  for(i=0; i<pFKey->nCol; i++){
106542  Expr *pLeft; /* Value from parent table row */
106543  Expr *pRight; /* Column ref to child table */
106544  Expr *pEq; /* Expression (pLeft = pRight) */
106545  i16 iCol; /* Index of column in child table */
106546  const char *zCol; /* Name of column in child table */
106547 
106548  iCol = pIdx ? pIdx->aiColumn[i] : -1;
106549  pLeft = exprTableRegister(pParse, pTab, regData, iCol);
106550  iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
106551  assert( iCol>=0 );
106552  zCol = pFKey->pFrom->aCol[iCol].zName;
106553  pRight = sqlite3Expr(db, TK_ID, zCol);
106554  pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
106555  pWhere = sqlite3ExprAnd(db, pWhere, pEq);
106556  }
106557 
106558  /* If the child table is the same as the parent table, then add terms
106559  ** to the WHERE clause that prevent this entry from being scanned.
106560  ** The added WHERE clause terms are like this:
106561  **
106562  ** $current_rowid!=rowid
106563  ** NOT( $current_a==a AND $current_b==b AND ... )
106564  **
106565  ** The first form is used for rowid tables. The second form is used
106566  ** for WITHOUT ROWID tables. In the second form, the primary key is
106567  ** (a,b,...)
106568  */
106569  if( pTab==pFKey->pFrom && nIncr>0 ){
106570  Expr *pNe; /* Expression (pLeft != pRight) */
106571  Expr *pLeft; /* Value from parent table row */
106572  Expr *pRight; /* Column ref to child table */
106573  if( HasRowid(pTab) ){
106574  pLeft = exprTableRegister(pParse, pTab, regData, -1);
106575  pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
106576  pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
106577  }else{
106578  Expr *pEq, *pAll = 0;
106579  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
106580  assert( pIdx!=0 );
106581  for(i=0; i<pPk->nKeyCol; i++){
106582  i16 iCol = pIdx->aiColumn[i];
106583  assert( iCol>=0 );
106584  pLeft = exprTableRegister(pParse, pTab, regData, iCol);
106585  pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
106586  pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
106587  pAll = sqlite3ExprAnd(db, pAll, pEq);
106588  }
106589  pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
106590  }
106591  pWhere = sqlite3ExprAnd(db, pWhere, pNe);
106592  }
106593 
106594  /* Resolve the references in the WHERE clause. */
106595  memset(&sNameContext, 0, sizeof(NameContext));
106596  sNameContext.pSrcList = pSrc;
106597  sNameContext.pParse = pParse;
106598  sqlite3ResolveExprNames(&sNameContext, pWhere);
106599 
106600  /* Create VDBE to loop through the entries in pSrc that match the WHERE
106601  ** clause. For each row found, increment either the deferred or immediate
106602  ** foreign key constraint counter. */
106603  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
106604  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
106605  if( pWInfo ){
106606  sqlite3WhereEnd(pWInfo);
106607  }
106608 
106609  /* Clean up the WHERE clause constructed above. */
106610  sqlite3ExprDelete(db, pWhere);
106611  if( iFkIfZero ){
106612  sqlite3VdbeJumpHere(v, iFkIfZero);
106613  }
106614 }
106615 
106616 /*
106617 ** This function returns a linked list of FKey objects (connected by
106618 ** FKey.pNextTo) holding all children of table pTab. For example,
106619 ** given the following schema:
106620 **
106621 ** CREATE TABLE t1(a PRIMARY KEY);
106622 ** CREATE TABLE t2(b REFERENCES t1(a);
106623 **
106624 ** Calling this function with table "t1" as an argument returns a pointer
106625 ** to the FKey structure representing the foreign key constraint on table
106626 ** "t2". Calling this function with "t2" as the argument would return a
106627 ** NULL pointer (as there are no FK constraints for which t2 is the parent
106628 ** table).
106629 */
106631  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
106632 }
106633 
106634 /*
106635 ** The second argument is a Trigger structure allocated by the
106636 ** fkActionTrigger() routine. This function deletes the Trigger structure
106637 ** and all of its sub-components.
106638 **
106639 ** The Trigger structure or any of its sub-components may be allocated from
106640 ** the lookaside buffer belonging to database handle dbMem.
106641 */
106642 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
106643  if( p ){
106644  TriggerStep *pStep = p->step_list;
106645  sqlite3ExprDelete(dbMem, pStep->pWhere);
106646  sqlite3ExprListDelete(dbMem, pStep->pExprList);
106647  sqlite3SelectDelete(dbMem, pStep->pSelect);
106648  sqlite3ExprDelete(dbMem, p->pWhen);
106649  sqlite3DbFree(dbMem, p);
106650  }
106651 }
106652 
106653 /*
106654 ** This function is called to generate code that runs when table pTab is
106655 ** being dropped from the database. The SrcList passed as the second argument
106656 ** to this function contains a single entry guaranteed to resolve to
106657 ** table pTab.
106658 **
106659 ** Normally, no code is required. However, if either
106660 **
106661 ** (a) The table is the parent table of a FK constraint, or
106662 ** (b) The table is the child table of a deferred FK constraint and it is
106663 ** determined at runtime that there are outstanding deferred FK
106664 ** constraint violations in the database,
106665 **
106666 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
106667 ** the table from the database. Triggers are disabled while running this
106668 ** DELETE, but foreign key actions are not.
106669 */
106671  sqlite3 *db = pParse->db;
106672  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
106673  int iSkip = 0;
106674  Vdbe *v = sqlite3GetVdbe(pParse);
106675 
106676  assert( v ); /* VDBE has already been allocated */
106677  if( sqlite3FkReferences(pTab)==0 ){
106678  /* Search for a deferred foreign key constraint for which this table
106679  ** is the child table. If one cannot be found, return without
106680  ** generating any VDBE code. If one can be found, then jump over
106681  ** the entire DELETE if there are no outstanding deferred constraints
106682  ** when this statement is run. */
106683  FKey *p;
106684  for(p=pTab->pFKey; p; p=p->pNextFrom){
106685  if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
106686  }
106687  if( !p ) return;
106688  iSkip = sqlite3VdbeMakeLabel(v);
106689  sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
106690  }
106691 
106692  pParse->disableTriggers = 1;
106693  sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
106694  pParse->disableTriggers = 0;
106695 
106696  /* If the DELETE has generated immediate foreign key constraint
106697  ** violations, halt the VDBE and return an error at this point, before
106698  ** any modifications to the schema are made. This is because statement
106699  ** transactions are not able to rollback schema changes.
106700  **
106701  ** If the SQLITE_DeferFKs flag is set, then this is not required, as
106702  ** the statement transaction will not be rolled back even if FK
106703  ** constraints are violated.
106704  */
106705  if( (db->flags & SQLITE_DeferFKs)==0 ){
106707  VdbeCoverage(v);
106710  }
106711 
106712  if( iSkip ){
106713  sqlite3VdbeResolveLabel(v, iSkip);
106714  }
106715  }
106716 }
106717 
106718 
106719 /*
106720 ** The second argument points to an FKey object representing a foreign key
106721 ** for which pTab is the child table. An UPDATE statement against pTab
106722 ** is currently being processed. For each column of the table that is
106723 ** actually updated, the corresponding element in the aChange[] array
106724 ** is zero or greater (if a column is unmodified the corresponding element
106725 ** is set to -1). If the rowid column is modified by the UPDATE statement
106726 ** the bChngRowid argument is non-zero.
106727 **
106728 ** This function returns true if any of the columns that are part of the
106729 ** child key for FK constraint *p are modified.
106730 */
106732  Table *pTab, /* Table being updated */
106733  FKey *p, /* Foreign key for which pTab is the child */
106734  int *aChange, /* Array indicating modified columns */
106735  int bChngRowid /* True if rowid is modified by this update */
106736 ){
106737  int i;
106738  for(i=0; i<p->nCol; i++){
106739  int iChildKey = p->aCol[i].iFrom;
106740  if( aChange[iChildKey]>=0 ) return 1;
106741  if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
106742  }
106743  return 0;
106744 }
106745 
106746 /*
106747 ** The second argument points to an FKey object representing a foreign key
106748 ** for which pTab is the parent table. An UPDATE statement against pTab
106749 ** is currently being processed. For each column of the table that is
106750 ** actually updated, the corresponding element in the aChange[] array
106751 ** is zero or greater (if a column is unmodified the corresponding element
106752 ** is set to -1). If the rowid column is modified by the UPDATE statement
106753 ** the bChngRowid argument is non-zero.
106754 **
106755 ** This function returns true if any of the columns that are part of the
106756 ** parent key for FK constraint *p are modified.
106757 */
106759  Table *pTab,
106760  FKey *p,
106761  int *aChange,
106762  int bChngRowid
106763 ){
106764  int i;
106765  for(i=0; i<p->nCol; i++){
106766  char *zKey = p->aCol[i].zCol;
106767  int iKey;
106768  for(iKey=0; iKey<pTab->nCol; iKey++){
106769  if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
106770  Column *pCol = &pTab->aCol[iKey];
106771  if( zKey ){
106772  if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
106773  }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
106774  return 1;
106775  }
106776  }
106777  }
106778  }
106779  return 0;
106780 }
106781 
106782 /*
106783 ** Return true if the parser passed as the first argument is being
106784 ** used to code a trigger that is really a "SET NULL" action belonging
106785 ** to trigger pFKey.
106786 */
106787 static int isSetNullAction(Parse *pParse, FKey *pFKey){
106788  Parse *pTop = sqlite3ParseToplevel(pParse);
106789  if( pTop->pTriggerPrg ){
106790  Trigger *p = pTop->pTriggerPrg->pTrigger;
106791  if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
106792  || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
106793  ){
106794  return 1;
106795  }
106796  }
106797  return 0;
106798 }
106799 
106800 /*
106801 ** This function is called when inserting, deleting or updating a row of
106802 ** table pTab to generate VDBE code to perform foreign key constraint
106803 ** processing for the operation.
106804 **
106805 ** For a DELETE operation, parameter regOld is passed the index of the
106806 ** first register in an array of (pTab->nCol+1) registers containing the
106807 ** rowid of the row being deleted, followed by each of the column values
106808 ** of the row being deleted, from left to right. Parameter regNew is passed
106809 ** zero in this case.
106810 **
106811 ** For an INSERT operation, regOld is passed zero and regNew is passed the
106812 ** first register of an array of (pTab->nCol+1) registers containing the new
106813 ** row data.
106814 **
106815 ** For an UPDATE operation, this function is called twice. Once before
106816 ** the original record is deleted from the table using the calling convention
106817 ** described for DELETE. Then again after the original record is deleted
106818 ** but before the new record is inserted using the INSERT convention.
106819 */
106821  Parse *pParse, /* Parse context */
106822  Table *pTab, /* Row is being deleted from this table */
106823  int regOld, /* Previous row data is stored here */
106824  int regNew, /* New row data is stored here */
106825  int *aChange, /* Array indicating UPDATEd columns (or 0) */
106826  int bChngRowid /* True if rowid is UPDATEd */
106827 ){
106828  sqlite3 *db = pParse->db; /* Database handle */
106829  FKey *pFKey; /* Used to iterate through FKs */
106830  int iDb; /* Index of database containing pTab */
106831  const char *zDb; /* Name of database containing pTab */
106832  int isIgnoreErrors = pParse->disableTriggers;
106833 
106834  /* Exactly one of regOld and regNew should be non-zero. */
106835  assert( (regOld==0)!=(regNew==0) );
106836 
106837  /* If foreign-keys are disabled, this function is a no-op. */
106838  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
106839 
106840  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
106841  zDb = db->aDb[iDb].zDbSName;
106842 
106843  /* Loop through all the foreign key constraints for which pTab is the
106844  ** child table (the table that the foreign key definition is part of). */
106845  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
106846  Table *pTo; /* Parent table of foreign key pFKey */
106847  Index *pIdx = 0; /* Index on key columns in pTo */
106848  int *aiFree = 0;
106849  int *aiCol;
106850  int iCol;
106851  int i;
106852  int bIgnore = 0;
106853 
106854  if( aChange
106855  && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
106856  && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
106857  ){
106858  continue;
106859  }
106860 
106861  /* Find the parent table of this foreign key. Also find a unique index
106862  ** on the parent key columns in the parent table. If either of these
106863  ** schema items cannot be located, set an error in pParse and return
106864  ** early. */
106865  if( pParse->disableTriggers ){
106866  pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
106867  }else{
106868  pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
106869  }
106870  if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
106871  assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
106872  if( !isIgnoreErrors || db->mallocFailed ) return;
106873  if( pTo==0 ){
106874  /* If isIgnoreErrors is true, then a table is being dropped. In this
106875  ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
106876  ** before actually dropping it in order to check FK constraints.
106877  ** If the parent table of an FK constraint on the current table is
106878  ** missing, behave as if it is empty. i.e. decrement the relevant
106879  ** FK counter for each row of the current table with non-NULL keys.
106880  */
106881  Vdbe *v = sqlite3GetVdbe(pParse);
106882  int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
106883  for(i=0; i<pFKey->nCol; i++){
106884  int iReg = pFKey->aCol[i].iFrom + regOld + 1;
106885  sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
106886  }
106887  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
106888  }
106889  continue;
106890  }
106891  assert( pFKey->nCol==1 || (aiFree && pIdx) );
106892 
106893  if( aiFree ){
106894  aiCol = aiFree;
106895  }else{
106896  iCol = pFKey->aCol[0].iFrom;
106897  aiCol = &iCol;
106898  }
106899  for(i=0; i<pFKey->nCol; i++){
106900  if( aiCol[i]==pTab->iPKey ){
106901  aiCol[i] = -1;
106902  }
106903  assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
106904 #ifndef SQLITE_OMIT_AUTHORIZATION
106905  /* Request permission to read the parent key columns. If the
106906  ** authorization callback returns SQLITE_IGNORE, behave as if any
106907  ** values read from the parent table are NULL. */
106908  if( db->xAuth ){
106909  int rcauth;
106910  char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
106911  rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
106912  bIgnore = (rcauth==SQLITE_IGNORE);
106913  }
106914 #endif
106915  }
106916 
106917  /* Take a shared-cache advisory read-lock on the parent table. Allocate
106918  ** a cursor to use to search the unique index on the parent key columns
106919  ** in the parent table. */
106920  sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
106921  pParse->nTab++;
106922 
106923  if( regOld!=0 ){
106924  /* A row is being removed from the child table. Search for the parent.
106925  ** If the parent does not exist, removing the child row resolves an
106926  ** outstanding foreign key constraint violation. */
106927  fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
106928  }
106929  if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
106930  /* A row is being added to the child table. If a parent row cannot
106931  ** be found, adding the child row has violated the FK constraint.
106932  **
106933  ** If this operation is being performed as part of a trigger program
106934  ** that is actually a "SET NULL" action belonging to this very
106935  ** foreign key, then omit this scan altogether. As all child key
106936  ** values are guaranteed to be NULL, it is not possible for adding
106937  ** this row to cause an FK violation. */
106938  fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
106939  }
106940 
106941  sqlite3DbFree(db, aiFree);
106942  }
106943 
106944  /* Loop through all the foreign key constraints that refer to this table.
106945  ** (the "child" constraints) */
106946  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106947  Index *pIdx = 0; /* Foreign key index for pFKey */
106948  SrcList *pSrc;
106949  int *aiCol = 0;
106950 
106951  if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
106952  continue;
106953  }
106954 
106955  if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
106956  && !pParse->pToplevel && !pParse->isMultiWrite
106957  ){
106958  assert( regOld==0 && regNew!=0 );
106959  /* Inserting a single row into a parent table cannot cause (or fix)
106960  ** an immediate foreign key violation. So do nothing in this case. */
106961  continue;
106962  }
106963 
106964  if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
106965  if( !isIgnoreErrors || db->mallocFailed ) return;
106966  continue;
106967  }
106968  assert( aiCol || pFKey->nCol==1 );
106969 
106970  /* Create a SrcList structure containing the child table. We need the
106971  ** child table as a SrcList for sqlite3WhereBegin() */
106972  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
106973  if( pSrc ){
106974  struct SrcList_item *pItem = pSrc->a;
106975  pItem->pTab = pFKey->pFrom;
106976  pItem->zName = pFKey->pFrom->zName;
106977  pItem->pTab->nRef++;
106978  pItem->iCursor = pParse->nTab++;
106979 
106980  if( regNew!=0 ){
106981  fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
106982  }
106983  if( regOld!=0 ){
106984  int eAction = pFKey->aAction[aChange!=0];
106985  fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
106986  /* If this is a deferred FK constraint, or a CASCADE or SET NULL
106987  ** action applies, then any foreign key violations caused by
106988  ** removing the parent key will be rectified by the action trigger.
106989  ** So do not set the "may-abort" flag in this case.
106990  **
106991  ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
106992  ** may-abort flag will eventually be set on this statement anyway
106993  ** (when this function is called as part of processing the UPDATE
106994  ** within the action trigger).
106995  **
106996  ** Note 2: At first glance it may seem like SQLite could simply omit
106997  ** all OP_FkCounter related scans when either CASCADE or SET NULL
106998  ** applies. The trouble starts if the CASCADE or SET NULL action
106999  ** trigger causes other triggers or action rules attached to the
107000  ** child table to fire. In these cases the fk constraint counters
107001  ** might be set incorrectly if any OP_FkCounter related scans are
107002  ** omitted. */
107003  if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
107004  sqlite3MayAbort(pParse);
107005  }
107006  }
107007  pItem->zName = 0;
107008  sqlite3SrcListDelete(db, pSrc);
107009  }
107010  sqlite3DbFree(db, aiCol);
107011  }
107012 }
107013 
107014 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
107015 
107016 /*
107017 ** This function is called before generating code to update or delete a
107018 ** row contained in table pTab.
107019 */
107021  Parse *pParse, /* Parse context */
107022  Table *pTab /* Table being modified */
107023 ){
107024  u32 mask = 0;
107025  if( pParse->db->flags&SQLITE_ForeignKeys ){
107026  FKey *p;
107027  int i;
107028  for(p=pTab->pFKey; p; p=p->pNextFrom){
107029  for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
107030  }
107031  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
107032  Index *pIdx = 0;
107033  sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
107034  if( pIdx ){
107035  for(i=0; i<pIdx->nKeyCol; i++){
107036  assert( pIdx->aiColumn[i]>=0 );
107037  mask |= COLUMN_MASK(pIdx->aiColumn[i]);
107038  }
107039  }
107040  }
107041  }
107042  return mask;
107043 }
107044 
107045 
107046 /*
107047 ** This function is called before generating code to update or delete a
107048 ** row contained in table pTab. If the operation is a DELETE, then
107049 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
107050 ** to an array of size N, where N is the number of columns in table pTab.
107051 ** If the i'th column is not modified by the UPDATE, then the corresponding
107052 ** entry in the aChange[] array is set to -1. If the column is modified,
107053 ** the value is 0 or greater. Parameter chngRowid is set to true if the
107054 ** UPDATE statement modifies the rowid fields of the table.
107055 **
107056 ** If any foreign key processing will be required, this function returns
107057 ** true. If there is no foreign key related processing, this function
107058 ** returns false.
107059 */
107061  Parse *pParse, /* Parse context */
107062  Table *pTab, /* Table being modified */
107063  int *aChange, /* Non-NULL for UPDATE operations */
107064  int chngRowid /* True for UPDATE that affects rowid */
107065 ){
107066  if( pParse->db->flags&SQLITE_ForeignKeys ){
107067  if( !aChange ){
107068  /* A DELETE operation. Foreign key processing is required if the
107069  ** table in question is either the child or parent table for any
107070  ** foreign key constraint. */
107071  return (sqlite3FkReferences(pTab) || pTab->pFKey);
107072  }else{
107073  /* This is an UPDATE. Foreign key processing is only required if the
107074  ** operation modifies one or more child or parent key columns. */
107075  FKey *p;
107076 
107077  /* Check if any child key columns are being modified. */
107078  for(p=pTab->pFKey; p; p=p->pNextFrom){
107079  if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
107080  }
107081 
107082  /* Check if any parent key columns are being modified. */
107083  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
107084  if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
107085  }
107086  }
107087  }
107088  return 0;
107089 }
107090 
107091 /*
107092 ** This function is called when an UPDATE or DELETE operation is being
107093 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
107094 ** If the current operation is an UPDATE, then the pChanges parameter is
107095 ** passed a pointer to the list of columns being modified. If it is a
107096 ** DELETE, pChanges is passed a NULL pointer.
107097 **
107098 ** It returns a pointer to a Trigger structure containing a trigger
107099 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
107100 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
107101 ** returned (these actions require no special handling by the triggers
107102 ** sub-system, code for them is created by fkScanChildren()).
107103 **
107104 ** For example, if pFKey is the foreign key and pTab is table "p" in
107105 ** the following schema:
107106 **
107107 ** CREATE TABLE p(pk PRIMARY KEY);
107108 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
107109 **
107110 ** then the returned trigger structure is equivalent to:
107111 **
107112 ** CREATE TRIGGER ... DELETE ON p BEGIN
107113 ** DELETE FROM c WHERE ck = old.pk;
107114 ** END;
107115 **
107116 ** The returned pointer is cached as part of the foreign key object. It
107117 ** is eventually freed along with the rest of the foreign key object by
107118 ** sqlite3FkDelete().
107119 */
107121  Parse *pParse, /* Parse context */
107122  Table *pTab, /* Table being updated or deleted from */
107123  FKey *pFKey, /* Foreign key to get action for */
107124  ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
107125 ){
107126  sqlite3 *db = pParse->db; /* Database handle */
107127  int action; /* One of OE_None, OE_Cascade etc. */
107128  Trigger *pTrigger; /* Trigger definition to return */
107129  int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
107130 
107131  action = pFKey->aAction[iAction];
107132  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
107133  return 0;
107134  }
107135  pTrigger = pFKey->apTrigger[iAction];
107136 
107137  if( action!=OE_None && !pTrigger ){
107138  char const *zFrom; /* Name of child table */
107139  int nFrom; /* Length in bytes of zFrom */
107140  Index *pIdx = 0; /* Parent key index for this FK */
107141  int *aiCol = 0; /* child table cols -> parent key cols */
107142  TriggerStep *pStep = 0; /* First (only) step of trigger program */
107143  Expr *pWhere = 0; /* WHERE clause of trigger step */
107144  ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
107145  Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
107146  int i; /* Iterator variable */
107147  Expr *pWhen = 0; /* WHEN clause for the trigger */
107148 
107149  if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
107150  assert( aiCol || pFKey->nCol==1 );
107151 
107152  for(i=0; i<pFKey->nCol; i++){
107153  Token tOld = { "old", 3 }; /* Literal "old" token */
107154  Token tNew = { "new", 3 }; /* Literal "new" token */
107155  Token tFromCol; /* Name of column in child table */
107156  Token tToCol; /* Name of column in parent table */
107157  int iFromCol; /* Idx of column in child table */
107158  Expr *pEq; /* tFromCol = OLD.tToCol */
107159 
107160  iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
107161  assert( iFromCol>=0 );
107162  assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
107163  assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
107164  sqlite3TokenInit(&tToCol,
107165  pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
107166  sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
107167 
107168  /* Create the expression "OLD.zToCol = zFromCol". It is important
107169  ** that the "OLD.zToCol" term is on the LHS of the = operator, so
107170  ** that the affinity and collation sequence associated with the
107171  ** parent table are used for the comparison. */
107172  pEq = sqlite3PExpr(pParse, TK_EQ,
107173  sqlite3PExpr(pParse, TK_DOT,
107174  sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
107175  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
107176  , 0),
107177  sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
107178  , 0);
107179  pWhere = sqlite3ExprAnd(db, pWhere, pEq);
107180 
107181  /* For ON UPDATE, construct the next term of the WHEN clause.
107182  ** The final WHEN clause will be like this:
107183  **
107184  ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
107185  */
107186  if( pChanges ){
107187  pEq = sqlite3PExpr(pParse, TK_IS,
107188  sqlite3PExpr(pParse, TK_DOT,
107189  sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
107190  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
107191  0),
107192  sqlite3PExpr(pParse, TK_DOT,
107193  sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
107194  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
107195  0),
107196  0);
107197  pWhen = sqlite3ExprAnd(db, pWhen, pEq);
107198  }
107199 
107200  if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
107201  Expr *pNew;
107202  if( action==OE_Cascade ){
107203  pNew = sqlite3PExpr(pParse, TK_DOT,
107204  sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
107205  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
107206  , 0);
107207  }else if( action==OE_SetDflt ){
107208  Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
107209  if( pDflt ){
107210  pNew = sqlite3ExprDup(db, pDflt, 0);
107211  }else{
107212  pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
107213  }
107214  }else{
107215  pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
107216  }
107217  pList = sqlite3ExprListAppend(pParse, pList, pNew);
107218  sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
107219  }
107220  }
107221  sqlite3DbFree(db, aiCol);
107222 
107223  zFrom = pFKey->pFrom->zName;
107224  nFrom = sqlite3Strlen30(zFrom);
107225 
107226  if( action==OE_Restrict ){
107227  Token tFrom;
107228  Expr *pRaise;
107229 
107230  tFrom.z = zFrom;
107231  tFrom.n = nFrom;
107232  pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
107233  if( pRaise ){
107234  pRaise->affinity = OE_Abort;
107235  }
107236  pSelect = sqlite3SelectNew(pParse,
107237  sqlite3ExprListAppend(pParse, 0, pRaise),
107238  sqlite3SrcListAppend(db, 0, &tFrom, 0),
107239  pWhere,
107240  0, 0, 0, 0, 0, 0
107241  );
107242  pWhere = 0;
107243  }
107244 
107245  /* Disable lookaside memory allocation */
107246  db->lookaside.bDisable++;
107247 
107248  pTrigger = (Trigger *)sqlite3DbMallocZero(db,
107249  sizeof(Trigger) + /* struct Trigger */
107250  sizeof(TriggerStep) + /* Single step in trigger program */
107251  nFrom + 1 /* Space for pStep->zTarget */
107252  );
107253  if( pTrigger ){
107254  pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
107255  pStep->zTarget = (char *)&pStep[1];
107256  memcpy((char *)pStep->zTarget, zFrom, nFrom);
107257 
107258  pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
107259  pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
107260  pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
107261  if( pWhen ){
107262  pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
107263  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
107264  }
107265  }
107266 
107267  /* Re-enable the lookaside buffer, if it was disabled earlier. */
107268  db->lookaside.bDisable--;
107269 
107270  sqlite3ExprDelete(db, pWhere);
107271  sqlite3ExprDelete(db, pWhen);
107272  sqlite3ExprListDelete(db, pList);
107273  sqlite3SelectDelete(db, pSelect);
107274  if( db->mallocFailed==1 ){
107275  fkTriggerDelete(db, pTrigger);
107276  return 0;
107277  }
107278  assert( pStep!=0 );
107279 
107280  switch( action ){
107281  case OE_Restrict:
107282  pStep->op = TK_SELECT;
107283  break;
107284  case OE_Cascade:
107285  if( !pChanges ){
107286  pStep->op = TK_DELETE;
107287  break;
107288  }
107289  default:
107290  pStep->op = TK_UPDATE;
107291  }
107292  pStep->pTrig = pTrigger;
107293  pTrigger->pSchema = pTab->pSchema;
107294  pTrigger->pTabSchema = pTab->pSchema;
107295  pFKey->apTrigger[iAction] = pTrigger;
107296  pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
107297  }
107298 
107299  return pTrigger;
107300 }
107301 
107302 /*
107303 ** This function is called when deleting or updating a row to implement
107304 ** any required CASCADE, SET NULL or SET DEFAULT actions.
107305 */
107307  Parse *pParse, /* Parse context */
107308  Table *pTab, /* Table being updated or deleted from */
107309  ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
107310  int regOld, /* Address of array containing old row */
107311  int *aChange, /* Array indicating UPDATEd columns (or 0) */
107312  int bChngRowid /* True if rowid is UPDATEd */
107313 ){
107314  /* If foreign-key support is enabled, iterate through all FKs that
107315  ** refer to table pTab. If there is an action associated with the FK
107316  ** for this operation (either update or delete), invoke the associated
107317  ** trigger sub-program. */
107318  if( pParse->db->flags&SQLITE_ForeignKeys ){
107319  FKey *pFKey; /* Iterator variable */
107320  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
107321  if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
107322  Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
107323  if( pAct ){
107324  sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
107325  }
107326  }
107327  }
107328  }
107329 }
107330 
107331 #endif /* ifndef SQLITE_OMIT_TRIGGER */
107332 
107333 /*
107334 ** Free all memory associated with foreign key definitions attached to
107335 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
107336 ** hash table.
107337 */
107339  FKey *pFKey; /* Iterator variable */
107340  FKey *pNext; /* Copy of pFKey->pNextFrom */
107341 
107342  assert( db==0 || IsVirtual(pTab)
107343  || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
107344  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
107345 
107346  /* Remove the FK from the fkeyHash hash table. */
107347  if( !db || db->pnBytesFreed==0 ){
107348  if( pFKey->pPrevTo ){
107349  pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
107350  }else{
107351  void *p = (void *)pFKey->pNextTo;
107352  const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
107353  sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
107354  }
107355  if( pFKey->pNextTo ){
107356  pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
107357  }
107358  }
107359 
107360  /* EV: R-30323-21917 Each foreign key constraint in SQLite is
107361  ** classified as either immediate or deferred.
107362  */
107363  assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
107364 
107365  /* Delete any triggers created to implement actions for this FK. */
107366 #ifndef SQLITE_OMIT_TRIGGER
107367  fkTriggerDelete(db, pFKey->apTrigger[0]);
107368  fkTriggerDelete(db, pFKey->apTrigger[1]);
107369 #endif
107370 
107371  pNext = pFKey->pNextFrom;
107372  sqlite3DbFree(db, pFKey);
107373  }
107374 }
107375 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
107376 
107377 /************** End of fkey.c ************************************************/
107378 /************** Begin file insert.c ******************************************/
107379 /*
107380 ** 2001 September 15
107381 **
107382 ** The author disclaims copyright to this source code. In place of
107383 ** a legal notice, here is a blessing:
107384 **
107385 ** May you do good and not evil.
107386 ** May you find forgiveness for yourself and forgive others.
107387 ** May you share freely, never taking more than you give.
107388 **
107389 *************************************************************************
107390 ** This file contains C code routines that are called by the parser
107391 ** to handle INSERT statements in SQLite.
107392 */
107393 /* #include "sqliteInt.h" */
107394 
107395 /*
107396 ** Generate code that will
107397 **
107398 ** (1) acquire a lock for table pTab then
107399 ** (2) open pTab as cursor iCur.
107400 **
107401 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
107402 ** for that table that is actually opened.
107403 */
107405  Parse *pParse, /* Generate code into this VDBE */
107406  int iCur, /* The cursor number of the table */
107407  int iDb, /* The database index in sqlite3.aDb[] */
107408  Table *pTab, /* The table to be opened */
107409  int opcode /* OP_OpenRead or OP_OpenWrite */
107410 ){
107411  Vdbe *v;
107412  assert( !IsVirtual(pTab) );
107413  v = sqlite3GetVdbe(pParse);
107414  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
107415  sqlite3TableLock(pParse, iDb, pTab->tnum,
107416  (opcode==OP_OpenWrite)?1:0, pTab->zName);
107417  if( HasRowid(pTab) ){
107418  sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
107419  VdbeComment((v, "%s", pTab->zName));
107420  }else{
107421  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
107422  assert( pPk!=0 );
107423  assert( pPk->tnum==pTab->tnum );
107424  sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
107425  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
107426  VdbeComment((v, "%s", pTab->zName));
107427  }
107428 }
107429 
107430 /*
107431 ** Return a pointer to the column affinity string associated with index
107432 ** pIdx. A column affinity string has one character for each column in
107433 ** the table, according to the affinity of the column:
107434 **
107435 ** Character Column affinity
107436 ** ------------------------------
107437 ** 'A' BLOB
107438 ** 'B' TEXT
107439 ** 'C' NUMERIC
107440 ** 'D' INTEGER
107441 ** 'F' REAL
107442 **
107443 ** An extra 'D' is appended to the end of the string to cover the
107444 ** rowid that appears as the last column in every index.
107445 **
107446 ** Memory for the buffer containing the column index affinity string
107447 ** is managed along with the rest of the Index structure. It will be
107448 ** released when sqlite3DeleteIndex() is called.
107449 */
107451  if( !pIdx->zColAff ){
107452  /* The first time a column affinity string for a particular index is
107453  ** required, it is allocated and populated here. It is then stored as
107454  ** a member of the Index structure for subsequent use.
107455  **
107456  ** The column affinity string will eventually be deleted by
107457  ** sqliteDeleteIndex() when the Index structure itself is cleaned
107458  ** up.
107459  */
107460  int n;
107461  Table *pTab = pIdx->pTable;
107462  pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
107463  if( !pIdx->zColAff ){
107464  sqlite3OomFault(db);
107465  return 0;
107466  }
107467  for(n=0; n<pIdx->nColumn; n++){
107468  i16 x = pIdx->aiColumn[n];
107469  if( x>=0 ){
107470  pIdx->zColAff[n] = pTab->aCol[x].affinity;
107471  }else if( x==XN_ROWID ){
107472  pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
107473  }else{
107474  char aff;
107475  assert( x==XN_EXPR );
107476  assert( pIdx->aColExpr!=0 );
107477  aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
107478  if( aff==0 ) aff = SQLITE_AFF_BLOB;
107479  pIdx->zColAff[n] = aff;
107480  }
107481  }
107482  pIdx->zColAff[n] = 0;
107483  }
107484 
107485  return pIdx->zColAff;
107486 }
107487 
107488 /*
107489 ** Compute the affinity string for table pTab, if it has not already been
107490 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
107491 **
107492 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
107493 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
107494 ** for register iReg and following. Or if affinities exists and iReg==0,
107495 ** then just set the P4 operand of the previous opcode (which should be
107496 ** an OP_MakeRecord) to the affinity string.
107497 **
107498 ** A column affinity string has one character per column:
107499 **
107500 ** Character Column affinity
107501 ** ------------------------------
107502 ** 'A' BLOB
107503 ** 'B' TEXT
107504 ** 'C' NUMERIC
107505 ** 'D' INTEGER
107506 ** 'E' REAL
107507 */
107509  int i;
107510  char *zColAff = pTab->zColAff;
107511  if( zColAff==0 ){
107512  sqlite3 *db = sqlite3VdbeDb(v);
107513  zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
107514  if( !zColAff ){
107515  sqlite3OomFault(db);
107516  return;
107517  }
107518 
107519  for(i=0; i<pTab->nCol; i++){
107520  zColAff[i] = pTab->aCol[i].affinity;
107521  }
107522  do{
107523  zColAff[i--] = 0;
107524  }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
107525  pTab->zColAff = zColAff;
107526  }
107527  i = sqlite3Strlen30(zColAff);
107528  if( i ){
107529  if( iReg ){
107530  sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
107531  }else{
107532  sqlite3VdbeChangeP4(v, -1, zColAff, i);
107533  }
107534  }
107535 }
107536 
107537 /*
107538 ** Return non-zero if the table pTab in database iDb or any of its indices
107539 ** have been opened at any point in the VDBE program. This is used to see if
107540 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
107541 ** run without using a temporary table for the results of the SELECT.
107542 */
107543 static int readsTable(Parse *p, int iDb, Table *pTab){
107544  Vdbe *v = sqlite3GetVdbe(p);
107545  int i;
107546  int iEnd = sqlite3VdbeCurrentAddr(v);
107547 #ifndef SQLITE_OMIT_VIRTUALTABLE
107548  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
107549 #endif
107550 
107551  for(i=1; i<iEnd; i++){
107552  VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
107553  assert( pOp!=0 );
107554  if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
107555  Index *pIndex;
107556  int tnum = pOp->p2;
107557  if( tnum==pTab->tnum ){
107558  return 1;
107559  }
107560  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
107561  if( tnum==pIndex->tnum ){
107562  return 1;
107563  }
107564  }
107565  }
107566 #ifndef SQLITE_OMIT_VIRTUALTABLE
107567  if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
107568  assert( pOp->p4.pVtab!=0 );
107569  assert( pOp->p4type==P4_VTAB );
107570  return 1;
107571  }
107572 #endif
107573  }
107574  return 0;
107575 }
107576 
107577 #ifndef SQLITE_OMIT_AUTOINCREMENT
107578 /*
107579 ** Locate or create an AutoincInfo structure associated with table pTab
107580 ** which is in database iDb. Return the register number for the register
107581 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
107582 ** table. (Also return zero when doing a VACUUM since we do not want to
107583 ** update the AUTOINCREMENT counters during a VACUUM.)
107584 **
107585 ** There is at most one AutoincInfo structure per table even if the
107586 ** same table is autoincremented multiple times due to inserts within
107587 ** triggers. A new AutoincInfo structure is created if this is the
107588 ** first use of table pTab. On 2nd and subsequent uses, the original
107589 ** AutoincInfo structure is used.
107590 **
107591 ** Three memory locations are allocated:
107592 **
107593 ** (1) Register to hold the name of the pTab table.
107594 ** (2) Register to hold the maximum ROWID of pTab.
107595 ** (3) Register to hold the rowid in sqlite_sequence of pTab
107596 **
107597 ** The 2nd register is the one that is returned. That is all the
107598 ** insert routine needs to know about.
107599 */
107600 static int autoIncBegin(
107601  Parse *pParse, /* Parsing context */
107602  int iDb, /* Index of the database holding pTab */
107603  Table *pTab /* The table we are writing to */
107604 ){
107605  int memId = 0; /* Register holding maximum rowid */
107606  if( (pTab->tabFlags & TF_Autoincrement)!=0
107607  && (pParse->db->flags & SQLITE_Vacuum)==0
107608  ){
107609  Parse *pToplevel = sqlite3ParseToplevel(pParse);
107610  AutoincInfo *pInfo;
107611 
107612  pInfo = pToplevel->pAinc;
107613  while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
107614  if( pInfo==0 ){
107615  pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
107616  if( pInfo==0 ) return 0;
107617  pInfo->pNext = pToplevel->pAinc;
107618  pToplevel->pAinc = pInfo;
107619  pInfo->pTab = pTab;
107620  pInfo->iDb = iDb;
107621  pToplevel->nMem++; /* Register to hold name of table */
107622  pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
107623  pToplevel->nMem++; /* Rowid in sqlite_sequence */
107624  }
107625  memId = pInfo->regCtr;
107626  }
107627  return memId;
107628 }
107629 
107630 /*
107631 ** This routine generates code that will initialize all of the
107632 ** register used by the autoincrement tracker.
107633 */
107635  AutoincInfo *p; /* Information about an AUTOINCREMENT */
107636  sqlite3 *db = pParse->db; /* The database connection */
107637  Db *pDb; /* Database only autoinc table */
107638  int memId; /* Register holding max rowid */
107639  Vdbe *v = pParse->pVdbe; /* VDBE under construction */
107640 
107641  /* This routine is never called during trigger-generation. It is
107642  ** only called from the top-level */
107643  assert( pParse->pTriggerTab==0 );
107644  assert( sqlite3IsToplevel(pParse) );
107645 
107646  assert( v ); /* We failed long ago if this is not so */
107647  for(p = pParse->pAinc; p; p = p->pNext){
107648  static const int iLn = VDBE_OFFSET_LINENO(2);
107649  static const VdbeOpList autoInc[] = {
107650  /* 0 */ {OP_Null, 0, 0, 0},
107651  /* 1 */ {OP_Rewind, 0, 9, 0},
107652  /* 2 */ {OP_Column, 0, 0, 0},
107653  /* 3 */ {OP_Ne, 0, 7, 0},
107654  /* 4 */ {OP_Rowid, 0, 0, 0},
107655  /* 5 */ {OP_Column, 0, 1, 0},
107656  /* 6 */ {OP_Goto, 0, 9, 0},
107657  /* 7 */ {OP_Next, 0, 2, 0},
107658  /* 8 */ {OP_Integer, 0, 0, 0},
107659  /* 9 */ {OP_Close, 0, 0, 0}
107660  };
107661  VdbeOp *aOp;
107662  pDb = &db->aDb[p->iDb];
107663  memId = p->regCtr;
107664  assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
107665  sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
107666  sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
107667  aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
107668  if( aOp==0 ) break;
107669  aOp[0].p2 = memId;
107670  aOp[0].p3 = memId+1;
107671  aOp[2].p3 = memId;
107672  aOp[3].p1 = memId-1;
107673  aOp[3].p3 = memId;
107674  aOp[3].p5 = SQLITE_JUMPIFNULL;
107675  aOp[4].p2 = memId+1;
107676  aOp[5].p3 = memId;
107677  aOp[8].p2 = memId;
107678  }
107679 }
107680 
107681 /*
107682 ** Update the maximum rowid for an autoincrement calculation.
107683 **
107684 ** This routine should be called when the regRowid register holds a
107685 ** new rowid that is about to be inserted. If that new rowid is
107686 ** larger than the maximum rowid in the memId memory cell, then the
107687 ** memory cell is updated.
107688 */
107689 static void autoIncStep(Parse *pParse, int memId, int regRowid){
107690  if( memId>0 ){
107691  sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
107692  }
107693 }
107694 
107695 /*
107696 ** This routine generates the code needed to write autoincrement
107697 ** maximum rowid values back into the sqlite_sequence register.
107698 ** Every statement that might do an INSERT into an autoincrement
107699 ** table (either directly or through triggers) needs to call this
107700 ** routine just before the "exit" code.
107701 */
107703  AutoincInfo *p;
107704  Vdbe *v = pParse->pVdbe;
107705  sqlite3 *db = pParse->db;
107706 
107707  assert( v );
107708  for(p = pParse->pAinc; p; p = p->pNext){
107709  static const int iLn = VDBE_OFFSET_LINENO(2);
107710  static const VdbeOpList autoIncEnd[] = {
107711  /* 0 */ {OP_NotNull, 0, 2, 0},
107712  /* 1 */ {OP_NewRowid, 0, 0, 0},
107713  /* 2 */ {OP_MakeRecord, 0, 2, 0},
107714  /* 3 */ {OP_Insert, 0, 0, 0},
107715  /* 4 */ {OP_Close, 0, 0, 0}
107716  };
107717  VdbeOp *aOp;
107718  Db *pDb = &db->aDb[p->iDb];
107719  int iRec;
107720  int memId = p->regCtr;
107721 
107722  iRec = sqlite3GetTempReg(pParse);
107723  assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
107724  sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
107725  aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
107726  if( aOp==0 ) break;
107727  aOp[0].p1 = memId+1;
107728  aOp[1].p2 = memId+1;
107729  aOp[2].p1 = memId-1;
107730  aOp[2].p3 = iRec;
107731  aOp[3].p2 = iRec;
107732  aOp[3].p3 = memId+1;
107733  aOp[3].p5 = OPFLAG_APPEND;
107734  sqlite3ReleaseTempReg(pParse, iRec);
107735  }
107736 }
107738  if( pParse->pAinc ) autoIncrementEnd(pParse);
107739 }
107740 #else
107741 /*
107742 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
107743 ** above are all no-ops
107744 */
107745 # define autoIncBegin(A,B,C) (0)
107746 # define autoIncStep(A,B,C)
107747 #endif /* SQLITE_OMIT_AUTOINCREMENT */
107748 
107749 
107750 /* Forward declaration */
107751 static int xferOptimization(
107752  Parse *pParse, /* Parser context */
107753  Table *pDest, /* The table we are inserting into */
107754  Select *pSelect, /* A SELECT statement to use as the data source */
107755  int onError, /* How to handle constraint errors */
107756  int iDbDest /* The database of pDest */
107757 );
107758 
107759 /*
107760 ** This routine is called to handle SQL of the following forms:
107761 **
107762 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
107763 ** insert into TABLE (IDLIST) select
107764 ** insert into TABLE (IDLIST) default values
107765 **
107766 ** The IDLIST following the table name is always optional. If omitted,
107767 ** then a list of all (non-hidden) columns for the table is substituted.
107768 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
107769 ** is omitted.
107770 **
107771 ** For the pSelect parameter holds the values to be inserted for the
107772 ** first two forms shown above. A VALUES clause is really just short-hand
107773 ** for a SELECT statement that omits the FROM clause and everything else
107774 ** that follows. If the pSelect parameter is NULL, that means that the
107775 ** DEFAULT VALUES form of the INSERT statement is intended.
107776 **
107777 ** The code generated follows one of four templates. For a simple
107778 ** insert with data coming from a single-row VALUES clause, the code executes
107779 ** once straight down through. Pseudo-code follows (we call this
107780 ** the "1st template"):
107781 **
107782 ** open write cursor to <table> and its indices
107783 ** put VALUES clause expressions into registers
107784 ** write the resulting record into <table>
107785 ** cleanup
107786 **
107787 ** The three remaining templates assume the statement is of the form
107788 **
107789 ** INSERT INTO <table> SELECT ...
107790 **
107791 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
107792 ** in other words if the SELECT pulls all columns from a single table
107793 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
107794 ** if <table2> and <table1> are distinct tables but have identical
107795 ** schemas, including all the same indices, then a special optimization
107796 ** is invoked that copies raw records from <table2> over to <table1>.
107797 ** See the xferOptimization() function for the implementation of this
107798 ** template. This is the 2nd template.
107799 **
107800 ** open a write cursor to <table>
107801 ** open read cursor on <table2>
107802 ** transfer all records in <table2> over to <table>
107803 ** close cursors
107804 ** foreach index on <table>
107805 ** open a write cursor on the <table> index
107806 ** open a read cursor on the corresponding <table2> index
107807 ** transfer all records from the read to the write cursors
107808 ** close cursors
107809 ** end foreach
107810 **
107811 ** The 3rd template is for when the second template does not apply
107812 ** and the SELECT clause does not read from <table> at any time.
107813 ** The generated code follows this template:
107814 **
107815 ** X <- A
107816 ** goto B
107817 ** A: setup for the SELECT
107818 ** loop over the rows in the SELECT
107819 ** load values into registers R..R+n
107820 ** yield X
107821 ** end loop
107822 ** cleanup after the SELECT
107823 ** end-coroutine X
107824 ** B: open write cursor to <table> and its indices
107825 ** C: yield X, at EOF goto D
107826 ** insert the select result into <table> from R..R+n
107827 ** goto C
107828 ** D: cleanup
107829 **
107830 ** The 4th template is used if the insert statement takes its
107831 ** values from a SELECT but the data is being inserted into a table
107832 ** that is also read as part of the SELECT. In the third form,
107833 ** we have to use an intermediate table to store the results of
107834 ** the select. The template is like this:
107835 **
107836 ** X <- A
107837 ** goto B
107838 ** A: setup for the SELECT
107839 ** loop over the tables in the SELECT
107840 ** load value into register R..R+n
107841 ** yield X
107842 ** end loop
107843 ** cleanup after the SELECT
107844 ** end co-routine R
107845 ** B: open temp table
107846 ** L: yield X, at EOF goto M
107847 ** insert row from R..R+n into temp table
107848 ** goto L
107849 ** M: open write cursor to <table> and its indices
107850 ** rewind temp table
107851 ** C: loop over rows of intermediate table
107852 ** transfer values form intermediate table into <table>
107853 ** end loop
107854 ** D: cleanup
107855 */
107857  Parse *pParse, /* Parser context */
107858  SrcList *pTabList, /* Name of table into which we are inserting */
107859  Select *pSelect, /* A SELECT statement to use as the data source */
107860  IdList *pColumn, /* Column names corresponding to IDLIST. */
107861  int onError /* How to handle constraint errors */
107862 ){
107863  sqlite3 *db; /* The main database structure */
107864  Table *pTab; /* The table to insert into. aka TABLE */
107865  char *zTab; /* Name of the table into which we are inserting */
107866  int i, j, idx; /* Loop counters */
107867  Vdbe *v; /* Generate code into this virtual machine */
107868  Index *pIdx; /* For looping over indices of the table */
107869  int nColumn; /* Number of columns in the data */
107870  int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
107871  int iDataCur = 0; /* VDBE cursor that is the main data repository */
107872  int iIdxCur = 0; /* First index cursor */
107873  int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
107874  int endOfLoop; /* Label for the end of the insertion loop */
107875  int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
107876  int addrInsTop = 0; /* Jump to label "D" */
107877  int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
107878  SelectDest dest; /* Destination for SELECT on rhs of INSERT */
107879  int iDb; /* Index of database holding TABLE */
107880  u8 useTempTable = 0; /* Store SELECT results in intermediate table */
107881  u8 appendFlag = 0; /* True if the insert is likely to be an append */
107882  u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
107883  u8 bIdListInOrder; /* True if IDLIST is in table order */
107884  ExprList *pList = 0; /* List of VALUES() to be inserted */
107885 
107886  /* Register allocations */
107887  int regFromSelect = 0;/* Base register for data coming from SELECT */
107888  int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
107889  int regRowCount = 0; /* Memory cell used for the row counter */
107890  int regIns; /* Block of regs holding rowid+data being inserted */
107891  int regRowid; /* registers holding insert rowid */
107892  int regData; /* register holding first column to insert */
107893  int *aRegIdx = 0; /* One register allocated to each index */
107894 
107895 #ifndef SQLITE_OMIT_TRIGGER
107896  int isView; /* True if attempting to insert into a view */
107897  Trigger *pTrigger; /* List of triggers on pTab, if required */
107898  int tmask; /* Mask of trigger times */
107899 #endif
107900 
107901  db = pParse->db;
107902  memset(&dest, 0, sizeof(dest));
107903  if( pParse->nErr || db->mallocFailed ){
107904  goto insert_cleanup;
107905  }
107906 
107907  /* If the Select object is really just a simple VALUES() list with a
107908  ** single row (the common case) then keep that one row of values
107909  ** and discard the other (unused) parts of the pSelect object
107910  */
107911  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
107912  pList = pSelect->pEList;
107913  pSelect->pEList = 0;
107914  sqlite3SelectDelete(db, pSelect);
107915  pSelect = 0;
107916  }
107917 
107918  /* Locate the table into which we will be inserting new information.
107919  */
107920  assert( pTabList->nSrc==1 );
107921  zTab = pTabList->a[0].zName;
107922  if( NEVER(zTab==0) ) goto insert_cleanup;
107923  pTab = sqlite3SrcListLookup(pParse, pTabList);
107924  if( pTab==0 ){
107925  goto insert_cleanup;
107926  }
107927  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107928  assert( iDb<db->nDb );
107929  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
107930  db->aDb[iDb].zDbSName) ){
107931  goto insert_cleanup;
107932  }
107933  withoutRowid = !HasRowid(pTab);
107934 
107935  /* Figure out if we have any triggers and if the table being
107936  ** inserted into is a view
107937  */
107938 #ifndef SQLITE_OMIT_TRIGGER
107939  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
107940  isView = pTab->pSelect!=0;
107941 #else
107942 # define pTrigger 0
107943 # define tmask 0
107944 # define isView 0
107945 #endif
107946 #ifdef SQLITE_OMIT_VIEW
107947 # undef isView
107948 # define isView 0
107949 #endif
107950  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
107951 
107952  /* If pTab is really a view, make sure it has been initialized.
107953  ** ViewGetColumnNames() is a no-op if pTab is not a view.
107954  */
107955  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
107956  goto insert_cleanup;
107957  }
107958 
107959  /* Cannot insert into a read-only table.
107960  */
107961  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
107962  goto insert_cleanup;
107963  }
107964 
107965  /* Allocate a VDBE
107966  */
107967  v = sqlite3GetVdbe(pParse);
107968  if( v==0 ) goto insert_cleanup;
107969  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
107970  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
107971 
107972 #ifndef SQLITE_OMIT_XFER_OPT
107973  /* If the statement is of the form
107974  **
107975  ** INSERT INTO <table1> SELECT * FROM <table2>;
107976  **
107977  ** Then special optimizations can be applied that make the transfer
107978  ** very fast and which reduce fragmentation of indices.
107979  **
107980  ** This is the 2nd template.
107981  */
107982  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
107983  assert( !pTrigger );
107984  assert( pList==0 );
107985  goto insert_end;
107986  }
107987 #endif /* SQLITE_OMIT_XFER_OPT */
107988 
107989  /* If this is an AUTOINCREMENT table, look up the sequence number in the
107990  ** sqlite_sequence table and store it in memory cell regAutoinc.
107991  */
107992  regAutoinc = autoIncBegin(pParse, iDb, pTab);
107993 
107994  /* Allocate registers for holding the rowid of the new row,
107995  ** the content of the new row, and the assembled row record.
107996  */
107997  regRowid = regIns = pParse->nMem+1;
107998  pParse->nMem += pTab->nCol + 1;
107999  if( IsVirtual(pTab) ){
108000  regRowid++;
108001  pParse->nMem++;
108002  }
108003  regData = regRowid+1;
108004 
108005  /* If the INSERT statement included an IDLIST term, then make sure
108006  ** all elements of the IDLIST really are columns of the table and
108007  ** remember the column indices.
108008  **
108009  ** If the table has an INTEGER PRIMARY KEY column and that column
108010  ** is named in the IDLIST, then record in the ipkColumn variable
108011  ** the index into IDLIST of the primary key column. ipkColumn is
108012  ** the index of the primary key as it appears in IDLIST, not as
108013  ** is appears in the original table. (The index of the INTEGER
108014  ** PRIMARY KEY in the original table is pTab->iPKey.)
108015  */
108016  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
108017  if( pColumn ){
108018  for(i=0; i<pColumn->nId; i++){
108019  pColumn->a[i].idx = -1;
108020  }
108021  for(i=0; i<pColumn->nId; i++){
108022  for(j=0; j<pTab->nCol; j++){
108023  if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
108024  pColumn->a[i].idx = j;
108025  if( i!=j ) bIdListInOrder = 0;
108026  if( j==pTab->iPKey ){
108027  ipkColumn = i; assert( !withoutRowid );
108028  }
108029  break;
108030  }
108031  }
108032  if( j>=pTab->nCol ){
108033  if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
108034  ipkColumn = i;
108035  bIdListInOrder = 0;
108036  }else{
108037  sqlite3ErrorMsg(pParse, "table %S has no column named %s",
108038  pTabList, 0, pColumn->a[i].zName);
108039  pParse->checkSchema = 1;
108040  goto insert_cleanup;
108041  }
108042  }
108043  }
108044  }
108045 
108046  /* Figure out how many columns of data are supplied. If the data
108047  ** is coming from a SELECT statement, then generate a co-routine that
108048  ** produces a single row of the SELECT on each invocation. The
108049  ** co-routine is the common header to the 3rd and 4th templates.
108050  */
108051  if( pSelect ){
108052  /* Data is coming from a SELECT or from a multi-row VALUES clause.
108053  ** Generate a co-routine to run the SELECT. */
108054  int regYield; /* Register holding co-routine entry-point */
108055  int addrTop; /* Top of the co-routine */
108056  int rc; /* Result code */
108057 
108058  regYield = ++pParse->nMem;
108059  addrTop = sqlite3VdbeCurrentAddr(v) + 1;
108060  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
108061  sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
108062  dest.iSdst = bIdListInOrder ? regData : 0;
108063  dest.nSdst = pTab->nCol;
108064  rc = sqlite3Select(pParse, pSelect, &dest);
108065  regFromSelect = dest.iSdst;
108066  if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
108067  sqlite3VdbeEndCoroutine(v, regYield);
108068  sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
108069  assert( pSelect->pEList );
108070  nColumn = pSelect->pEList->nExpr;
108071 
108072  /* Set useTempTable to TRUE if the result of the SELECT statement
108073  ** should be written into a temporary table (template 4). Set to
108074  ** FALSE if each output row of the SELECT can be written directly into
108075  ** the destination table (template 3).
108076  **
108077  ** A temp table must be used if the table being updated is also one
108078  ** of the tables being read by the SELECT statement. Also use a
108079  ** temp table in the case of row triggers.
108080  */
108081  if( pTrigger || readsTable(pParse, iDb, pTab) ){
108082  useTempTable = 1;
108083  }
108084 
108085  if( useTempTable ){
108086  /* Invoke the coroutine to extract information from the SELECT
108087  ** and add it to a transient table srcTab. The code generated
108088  ** here is from the 4th template:
108089  **
108090  ** B: open temp table
108091  ** L: yield X, goto M at EOF
108092  ** insert row from R..R+n into temp table
108093  ** goto L
108094  ** M: ...
108095  */
108096  int regRec; /* Register to hold packed record */
108097  int regTempRowid; /* Register to hold temp table ROWID */
108098  int addrL; /* Label "L" */
108099 
108100  srcTab = pParse->nTab++;
108101  regRec = sqlite3GetTempReg(pParse);
108102  regTempRowid = sqlite3GetTempReg(pParse);
108103  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
108104  addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
108105  sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
108106  sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
108107  sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
108108  sqlite3VdbeGoto(v, addrL);
108109  sqlite3VdbeJumpHere(v, addrL);
108110  sqlite3ReleaseTempReg(pParse, regRec);
108111  sqlite3ReleaseTempReg(pParse, regTempRowid);
108112  }
108113  }else{
108114  /* This is the case if the data for the INSERT is coming from a
108115  ** single-row VALUES clause
108116  */
108117  NameContext sNC;
108118  memset(&sNC, 0, sizeof(sNC));
108119  sNC.pParse = pParse;
108120  srcTab = -1;
108121  assert( useTempTable==0 );
108122  if( pList ){
108123  nColumn = pList->nExpr;
108124  if( sqlite3ResolveExprListNames(&sNC, pList) ){
108125  goto insert_cleanup;
108126  }
108127  }else{
108128  nColumn = 0;
108129  }
108130  }
108131 
108132  /* If there is no IDLIST term but the table has an integer primary
108133  ** key, the set the ipkColumn variable to the integer primary key
108134  ** column index in the original table definition.
108135  */
108136  if( pColumn==0 && nColumn>0 ){
108137  ipkColumn = pTab->iPKey;
108138  }
108139 
108140  /* Make sure the number of columns in the source data matches the number
108141  ** of columns to be inserted into the table.
108142  */
108143  for(i=0; i<pTab->nCol; i++){
108144  nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
108145  }
108146  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
108147  sqlite3ErrorMsg(pParse,
108148  "table %S has %d columns but %d values were supplied",
108149  pTabList, 0, pTab->nCol-nHidden, nColumn);
108150  goto insert_cleanup;
108151  }
108152  if( pColumn!=0 && nColumn!=pColumn->nId ){
108153  sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
108154  goto insert_cleanup;
108155  }
108156 
108157  /* Initialize the count of rows to be inserted
108158  */
108159  if( db->flags & SQLITE_CountRows ){
108160  regRowCount = ++pParse->nMem;
108161  sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
108162  }
108163 
108164  /* If this is not a view, open the table and and all indices */
108165  if( !isView ){
108166  int nIdx;
108167  nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
108168  &iDataCur, &iIdxCur);
108169  aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
108170  if( aRegIdx==0 ){
108171  goto insert_cleanup;
108172  }
108173  for(i=0; i<nIdx; i++){
108174  aRegIdx[i] = ++pParse->nMem;
108175  }
108176  }
108177 
108178  /* This is the top of the main insertion loop */
108179  if( useTempTable ){
108180  /* This block codes the top of loop only. The complete loop is the
108181  ** following pseudocode (template 4):
108182  **
108183  ** rewind temp table, if empty goto D
108184  ** C: loop over rows of intermediate table
108185  ** transfer values form intermediate table into <table>
108186  ** end loop
108187  ** D: ...
108188  */
108189  addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
108190  addrCont = sqlite3VdbeCurrentAddr(v);
108191  }else if( pSelect ){
108192  /* This block codes the top of loop only. The complete loop is the
108193  ** following pseudocode (template 3):
108194  **
108195  ** C: yield X, at EOF goto D
108196  ** insert the select result into <table> from R..R+n
108197  ** goto C
108198  ** D: ...
108199  */
108200  addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
108201  VdbeCoverage(v);
108202  }
108203 
108204  /* Run the BEFORE and INSTEAD OF triggers, if there are any
108205  */
108206  endOfLoop = sqlite3VdbeMakeLabel(v);
108207  if( tmask & TRIGGER_BEFORE ){
108208  int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
108209 
108210  /* build the NEW.* reference row. Note that if there is an INTEGER
108211  ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
108212  ** translated into a unique ID for the row. But on a BEFORE trigger,
108213  ** we do not know what the unique ID will be (because the insert has
108214  ** not happened yet) so we substitute a rowid of -1
108215  */
108216  if( ipkColumn<0 ){
108217  sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
108218  }else{
108219  int addr1;
108220  assert( !withoutRowid );
108221  if( useTempTable ){
108222  sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
108223  }else{
108224  assert( pSelect==0 ); /* Otherwise useTempTable is true */
108225  sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
108226  }
108227  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
108228  sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
108229  sqlite3VdbeJumpHere(v, addr1);
108230  sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
108231  }
108232 
108233  /* Cannot have triggers on a virtual table. If it were possible,
108234  ** this block would have to account for hidden column.
108235  */
108236  assert( !IsVirtual(pTab) );
108237 
108238  /* Create the new column data
108239  */
108240  for(i=j=0; i<pTab->nCol; i++){
108241  if( pColumn ){
108242  for(j=0; j<pColumn->nId; j++){
108243  if( pColumn->a[j].idx==i ) break;
108244  }
108245  }
108246  if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
108247  || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
108248  sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
108249  }else if( useTempTable ){
108250  sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
108251  }else{
108252  assert( pSelect==0 ); /* Otherwise useTempTable is true */
108253  sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
108254  }
108255  if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
108256  }
108257 
108258  /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
108259  ** do not attempt any conversions before assembling the record.
108260  ** If this is a real table, attempt conversions as required by the
108261  ** table column affinities.
108262  */
108263  if( !isView ){
108264  sqlite3TableAffinity(v, pTab, regCols+1);
108265  }
108266 
108267  /* Fire BEFORE or INSTEAD OF triggers */
108268  sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
108269  pTab, regCols-pTab->nCol-1, onError, endOfLoop);
108270 
108271  sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
108272  }
108273 
108274  /* Compute the content of the next row to insert into a range of
108275  ** registers beginning at regIns.
108276  */
108277  if( !isView ){
108278  if( IsVirtual(pTab) ){
108279  /* The row that the VUpdate opcode will delete: none */
108280  sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
108281  }
108282  if( ipkColumn>=0 ){
108283  if( useTempTable ){
108284  sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
108285  }else if( pSelect ){
108286  sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
108287  }else{
108288  VdbeOp *pOp;
108289  sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
108290  pOp = sqlite3VdbeGetOp(v, -1);
108291  if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
108292  appendFlag = 1;
108293  pOp->opcode = OP_NewRowid;
108294  pOp->p1 = iDataCur;
108295  pOp->p2 = regRowid;
108296  pOp->p3 = regAutoinc;
108297  }
108298  }
108299  /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
108300  ** to generate a unique primary key value.
108301  */
108302  if( !appendFlag ){
108303  int addr1;
108304  if( !IsVirtual(pTab) ){
108305  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
108306  sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
108307  sqlite3VdbeJumpHere(v, addr1);
108308  }else{
108309  addr1 = sqlite3VdbeCurrentAddr(v);
108310  sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
108311  }
108312  sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
108313  }
108314  }else if( IsVirtual(pTab) || withoutRowid ){
108315  sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
108316  }else{
108317  sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
108318  appendFlag = 1;
108319  }
108320  autoIncStep(pParse, regAutoinc, regRowid);
108321 
108322  /* Compute data for all columns of the new entry, beginning
108323  ** with the first column.
108324  */
108325  nHidden = 0;
108326  for(i=0; i<pTab->nCol; i++){
108327  int iRegStore = regRowid+1+i;
108328  if( i==pTab->iPKey ){
108329  /* The value of the INTEGER PRIMARY KEY column is always a NULL.
108330  ** Whenever this column is read, the rowid will be substituted
108331  ** in its place. Hence, fill this column with a NULL to avoid
108332  ** taking up data space with information that will never be used.
108333  ** As there may be shallow copies of this value, make it a soft-NULL */
108334  sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
108335  continue;
108336  }
108337  if( pColumn==0 ){
108338  if( IsHiddenColumn(&pTab->aCol[i]) ){
108339  j = -1;
108340  nHidden++;
108341  }else{
108342  j = i - nHidden;
108343  }
108344  }else{
108345  for(j=0; j<pColumn->nId; j++){
108346  if( pColumn->a[j].idx==i ) break;
108347  }
108348  }
108349  if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
108350  sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
108351  }else if( useTempTable ){
108352  sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
108353  }else if( pSelect ){
108354  if( regFromSelect!=regData ){
108355  sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
108356  }
108357  }else{
108358  sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
108359  }
108360  }
108361 
108362  /* Generate code to check constraints and generate index keys and
108363  ** do the insertion.
108364  */
108365 #ifndef SQLITE_OMIT_VIRTUALTABLE
108366  if( IsVirtual(pTab) ){
108367  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
108368  sqlite3VtabMakeWritable(pParse, pTab);
108369  sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
108370  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
108371  sqlite3MayAbort(pParse);
108372  }else
108373 #endif
108374  {
108375  int isReplace; /* Set to true if constraints may cause a replace */
108376  sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
108377  regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
108378  );
108379  sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
108380  sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
108381  regIns, aRegIdx, 0, appendFlag, isReplace==0);
108382  }
108383  }
108384 
108385  /* Update the count of rows that are inserted
108386  */
108387  if( (db->flags & SQLITE_CountRows)!=0 ){
108388  sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
108389  }
108390 
108391  if( pTrigger ){
108392  /* Code AFTER triggers */
108393  sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
108394  pTab, regData-2-pTab->nCol, onError, endOfLoop);
108395  }
108396 
108397  /* The bottom of the main insertion loop, if the data source
108398  ** is a SELECT statement.
108399  */
108400  sqlite3VdbeResolveLabel(v, endOfLoop);
108401  if( useTempTable ){
108402  sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
108403  sqlite3VdbeJumpHere(v, addrInsTop);
108404  sqlite3VdbeAddOp1(v, OP_Close, srcTab);
108405  }else if( pSelect ){
108406  sqlite3VdbeGoto(v, addrCont);
108407  sqlite3VdbeJumpHere(v, addrInsTop);
108408  }
108409 
108410  if( !IsVirtual(pTab) && !isView ){
108411  /* Close all tables opened */
108412  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
108413  for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
108414  sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
108415  }
108416  }
108417 
108418 insert_end:
108419  /* Update the sqlite_sequence table by storing the content of the
108420  ** maximum rowid counter values recorded while inserting into
108421  ** autoincrement tables.
108422  */
108423  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
108424  sqlite3AutoincrementEnd(pParse);
108425  }
108426 
108427  /*
108428  ** Return the number of rows inserted. If this routine is
108429  ** generating code because of a call to sqlite3NestedParse(), do not
108430  ** invoke the callback function.
108431  */
108432  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
108433  sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
108434  sqlite3VdbeSetNumCols(v, 1);
108435  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
108436  }
108437 
108438 insert_cleanup:
108439  sqlite3SrcListDelete(db, pTabList);
108440  sqlite3ExprListDelete(db, pList);
108441  sqlite3SelectDelete(db, pSelect);
108442  sqlite3IdListDelete(db, pColumn);
108443  sqlite3DbFree(db, aRegIdx);
108444 }
108445 
108446 /* Make sure "isView" and other macros defined above are undefined. Otherwise
108447 ** they may interfere with compilation of other functions in this file
108448 ** (or in another file, if this file becomes part of the amalgamation). */
108449 #ifdef isView
108450  #undef isView
108451 #endif
108452 #ifdef pTrigger
108453  #undef pTrigger
108454 #endif
108455 #ifdef tmask
108456  #undef tmask
108457 #endif
108458 
108459 /*
108460 ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
108461 */
108462 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
108463 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
108464 
108465 /* This is the Walker callback from checkConstraintUnchanged(). Set
108466 ** bit 0x01 of pWalker->eCode if
108467 ** pWalker->eCode to 0 if this expression node references any of the
108468 ** columns that are being modifed by an UPDATE statement.
108469 */
108470 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
108471  if( pExpr->op==TK_COLUMN ){
108472  assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
108473  if( pExpr->iColumn>=0 ){
108474  if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
108475  pWalker->eCode |= CKCNSTRNT_COLUMN;
108476  }
108477  }else{
108478  pWalker->eCode |= CKCNSTRNT_ROWID;
108479  }
108480  }
108481  return WRC_Continue;
108482 }
108483 
108484 /*
108485 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
108486 ** only columns that are modified by the UPDATE are those for which
108487 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
108488 **
108489 ** Return true if CHECK constraint pExpr does not use any of the
108490 ** changing columns (or the rowid if it is changing). In other words,
108491 ** return true if this CHECK constraint can be skipped when validating
108492 ** the new row in the UPDATE statement.
108493 */
108494 static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
108495  Walker w;
108496  memset(&w, 0, sizeof(w));
108497  w.eCode = 0;
108499  w.u.aiCol = aiChng;
108500  sqlite3WalkExpr(&w, pExpr);
108501  if( !chngRowid ){
108502  testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
108503  w.eCode &= ~CKCNSTRNT_ROWID;
108504  }
108505  testcase( w.eCode==0 );
108509  return !w.eCode;
108510 }
108511 
108512 /*
108513 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
108514 ** on table pTab.
108515 **
108516 ** The regNewData parameter is the first register in a range that contains
108517 ** the data to be inserted or the data after the update. There will be
108518 ** pTab->nCol+1 registers in this range. The first register (the one
108519 ** that regNewData points to) will contain the new rowid, or NULL in the
108520 ** case of a WITHOUT ROWID table. The second register in the range will
108521 ** contain the content of the first table column. The third register will
108522 ** contain the content of the second table column. And so forth.
108523 **
108524 ** The regOldData parameter is similar to regNewData except that it contains
108525 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
108526 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
108527 ** checking regOldData for zero.
108528 **
108529 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
108530 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
108531 ** might be modified by the UPDATE. If pkChng is false, then the key of
108532 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
108533 **
108534 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
108535 ** was explicitly specified as part of the INSERT statement. If pkChng
108536 ** is zero, it means that the either rowid is computed automatically or
108537 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
108538 ** pkChng will only be true if the INSERT statement provides an integer
108539 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
108540 **
108541 ** The code generated by this routine will store new index entries into
108542 ** registers identified by aRegIdx[]. No index entry is created for
108543 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
108544 ** the same as the order of indices on the linked list of indices
108545 ** at pTab->pIndex.
108546 **
108547 ** The caller must have already opened writeable cursors on the main
108548 ** table and all applicable indices (that is to say, all indices for which
108549 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
108550 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
108551 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
108552 ** for the first index in the pTab->pIndex list. Cursors for other indices
108553 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
108554 **
108555 ** This routine also generates code to check constraints. NOT NULL,
108556 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
108557 ** then the appropriate action is performed. There are five possible
108558 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
108559 **
108560 ** Constraint type Action What Happens
108561 ** --------------- ---------- ----------------------------------------
108562 ** any ROLLBACK The current transaction is rolled back and
108563 ** sqlite3_step() returns immediately with a
108564 ** return code of SQLITE_CONSTRAINT.
108565 **
108566 ** any ABORT Back out changes from the current command
108567 ** only (do not do a complete rollback) then
108568 ** cause sqlite3_step() to return immediately
108569 ** with SQLITE_CONSTRAINT.
108570 **
108571 ** any FAIL Sqlite3_step() returns immediately with a
108572 ** return code of SQLITE_CONSTRAINT. The
108573 ** transaction is not rolled back and any
108574 ** changes to prior rows are retained.
108575 **
108576 ** any IGNORE The attempt in insert or update the current
108577 ** row is skipped, without throwing an error.
108578 ** Processing continues with the next row.
108579 ** (There is an immediate jump to ignoreDest.)
108580 **
108581 ** NOT NULL REPLACE The NULL value is replace by the default
108582 ** value for that column. If the default value
108583 ** is NULL, the action is the same as ABORT.
108584 **
108585 ** UNIQUE REPLACE The other row that conflicts with the row
108586 ** being inserted is removed.
108587 **
108588 ** CHECK REPLACE Illegal. The results in an exception.
108589 **
108590 ** Which action to take is determined by the overrideError parameter.
108591 ** Or if overrideError==OE_Default, then the pParse->onError parameter
108592 ** is used. Or if pParse->onError==OE_Default then the onError value
108593 ** for the constraint is used.
108594 */
108596  Parse *pParse, /* The parser context */
108597  Table *pTab, /* The table being inserted or updated */
108598  int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
108599  int iDataCur, /* Canonical data cursor (main table or PK index) */
108600  int iIdxCur, /* First index cursor */
108601  int regNewData, /* First register in a range holding values to insert */
108602  int regOldData, /* Previous content. 0 for INSERTs */
108603  u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
108604  u8 overrideError, /* Override onError to this if not OE_Default */
108605  int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
108606  int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
108607  int *aiChng /* column i is unchanged if aiChng[i]<0 */
108608 ){
108609  Vdbe *v; /* VDBE under constrution */
108610  Index *pIdx; /* Pointer to one of the indices */
108611  Index *pPk = 0; /* The PRIMARY KEY index */
108612  sqlite3 *db; /* Database connection */
108613  int i; /* loop counter */
108614  int ix; /* Index loop counter */
108615  int nCol; /* Number of columns */
108616  int onError; /* Conflict resolution strategy */
108617  int addr1; /* Address of jump instruction */
108618  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
108619  int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
108620  int ipkTop = 0; /* Top of the rowid change constraint check */
108621  int ipkBottom = 0; /* Bottom of the rowid change constraint check */
108622  u8 isUpdate; /* True if this is an UPDATE operation */
108623  u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
108624  int regRowid = -1; /* Register holding ROWID value */
108625 
108626  isUpdate = regOldData!=0;
108627  db = pParse->db;
108628  v = sqlite3GetVdbe(pParse);
108629  assert( v!=0 );
108630  assert( pTab->pSelect==0 ); /* This table is not a VIEW */
108631  nCol = pTab->nCol;
108632 
108633  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
108634  ** normal rowid tables. nPkField is the number of key fields in the
108635  ** pPk index or 1 for a rowid table. In other words, nPkField is the
108636  ** number of fields in the true primary key of the table. */
108637  if( HasRowid(pTab) ){
108638  pPk = 0;
108639  nPkField = 1;
108640  }else{
108641  pPk = sqlite3PrimaryKeyIndex(pTab);
108642  nPkField = pPk->nKeyCol;
108643  }
108644 
108645  /* Record that this module has started */
108646  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
108647  iDataCur, iIdxCur, regNewData, regOldData, pkChng));
108648 
108649  /* Test all NOT NULL constraints.
108650  */
108651  for(i=0; i<nCol; i++){
108652  if( i==pTab->iPKey ){
108653  continue; /* ROWID is never NULL */
108654  }
108655  if( aiChng && aiChng[i]<0 ){
108656  /* Don't bother checking for NOT NULL on columns that do not change */
108657  continue;
108658  }
108659  onError = pTab->aCol[i].notNull;
108660  if( onError==OE_None ) continue; /* This column is allowed to be NULL */
108661  if( overrideError!=OE_Default ){
108662  onError = overrideError;
108663  }else if( onError==OE_Default ){
108664  onError = OE_Abort;
108665  }
108666  if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
108667  onError = OE_Abort;
108668  }
108669  assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
108670  || onError==OE_Ignore || onError==OE_Replace );
108671  switch( onError ){
108672  case OE_Abort:
108673  sqlite3MayAbort(pParse);
108674  /* Fall through */
108675  case OE_Rollback:
108676  case OE_Fail: {
108677  char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
108678  pTab->aCol[i].zName);
108680  regNewData+1+i, zMsg, P4_DYNAMIC);
108682  VdbeCoverage(v);
108683  break;
108684  }
108685  case OE_Ignore: {
108686  sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
108687  VdbeCoverage(v);
108688  break;
108689  }
108690  default: {
108691  assert( onError==OE_Replace );
108692  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
108693  VdbeCoverage(v);
108694  sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
108695  sqlite3VdbeJumpHere(v, addr1);
108696  break;
108697  }
108698  }
108699  }
108700 
108701  /* Test all CHECK constraints
108702  */
108703 #ifndef SQLITE_OMIT_CHECK
108704  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
108705  ExprList *pCheck = pTab->pCheck;
108706  pParse->ckBase = regNewData+1;
108707  onError = overrideError!=OE_Default ? overrideError : OE_Abort;
108708  for(i=0; i<pCheck->nExpr; i++){
108709  int allOk;
108710  Expr *pExpr = pCheck->a[i].pExpr;
108711  if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
108712  allOk = sqlite3VdbeMakeLabel(v);
108713  sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
108714  if( onError==OE_Ignore ){
108715  sqlite3VdbeGoto(v, ignoreDest);
108716  }else{
108717  char *zName = pCheck->a[i].zName;
108718  if( zName==0 ) zName = pTab->zName;
108719  if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
108721  onError, zName, P4_TRANSIENT,
108723  }
108724  sqlite3VdbeResolveLabel(v, allOk);
108725  }
108726  }
108727 #endif /* !defined(SQLITE_OMIT_CHECK) */
108728 
108729  /* If rowid is changing, make sure the new rowid does not previously
108730  ** exist in the table.
108731  */
108732  if( pkChng && pPk==0 ){
108733  int addrRowidOk = sqlite3VdbeMakeLabel(v);
108734 
108735  /* Figure out what action to take in case of a rowid collision */
108736  onError = pTab->keyConf;
108737  if( overrideError!=OE_Default ){
108738  onError = overrideError;
108739  }else if( onError==OE_Default ){
108740  onError = OE_Abort;
108741  }
108742 
108743  if( isUpdate ){
108744  /* pkChng!=0 does not mean that the rowid has change, only that
108745  ** it might have changed. Skip the conflict logic below if the rowid
108746  ** is unchanged. */
108747  sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
108749  VdbeCoverage(v);
108750  }
108751 
108752  /* If the response to a rowid conflict is REPLACE but the response
108753  ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
108754  ** to defer the running of the rowid conflict checking until after
108755  ** the UNIQUE constraints have run.
108756  */
108757  if( onError==OE_Replace && overrideError!=OE_Replace ){
108758  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
108759  if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
108760  ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
108761  break;
108762  }
108763  }
108764  }
108765 
108766  /* Check to see if the new rowid already exists in the table. Skip
108767  ** the following conflict logic if it does not. */
108768  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
108769  VdbeCoverage(v);
108770 
108771  /* Generate code that deals with a rowid collision */
108772  switch( onError ){
108773  default: {
108774  onError = OE_Abort;
108775  /* Fall thru into the next case */
108776  }
108777  case OE_Rollback:
108778  case OE_Abort:
108779  case OE_Fail: {
108780  sqlite3RowidConstraint(pParse, onError, pTab);
108781  break;
108782  }
108783  case OE_Replace: {
108784  /* If there are DELETE triggers on this table and the
108785  ** recursive-triggers flag is set, call GenerateRowDelete() to
108786  ** remove the conflicting row from the table. This will fire
108787  ** the triggers and remove both the table and index b-tree entries.
108788  **
108789  ** Otherwise, if there are no triggers or the recursive-triggers
108790  ** flag is not set, but the table has one or more indexes, call
108791  ** GenerateRowIndexDelete(). This removes the index b-tree entries
108792  ** only. The table b-tree entry will be replaced by the new entry
108793  ** when it is inserted.
108794  **
108795  ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
108796  ** also invoke MultiWrite() to indicate that this VDBE may require
108797  ** statement rollback (if the statement is aborted after the delete
108798  ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
108799  ** but being more selective here allows statements like:
108800  **
108801  ** REPLACE INTO t(rowid) VALUES($newrowid)
108802  **
108803  ** to run without a statement journal if there are no indexes on the
108804  ** table.
108805  */
108806  Trigger *pTrigger = 0;
108807  if( db->flags&SQLITE_RecTriggers ){
108808  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
108809  }
108810  if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
108811  sqlite3MultiWrite(pParse);
108812  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
108813  regNewData, 1, 0, OE_Replace, 1, -1);
108814  }else{
108815 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
108816  if( HasRowid(pTab) ){
108817  /* This OP_Delete opcode fires the pre-update-hook only. It does
108818  ** not modify the b-tree. It is more efficient to let the coming
108819  ** OP_Insert replace the existing entry than it is to delete the
108820  ** existing entry and then insert a new one. */
108821  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
108822  sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
108823  }
108824 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
108825  if( pTab->pIndex ){
108826  sqlite3MultiWrite(pParse);
108827  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
108828  }
108829  }
108830  seenReplace = 1;
108831  break;
108832  }
108833  case OE_Ignore: {
108834  /*assert( seenReplace==0 );*/
108835  sqlite3VdbeGoto(v, ignoreDest);
108836  break;
108837  }
108838  }
108839  sqlite3VdbeResolveLabel(v, addrRowidOk);
108840  if( ipkTop ){
108841  ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
108842  sqlite3VdbeJumpHere(v, ipkTop);
108843  }
108844  }
108845 
108846  /* Test all UNIQUE constraints by creating entries for each UNIQUE
108847  ** index and making sure that duplicate entries do not already exist.
108848  ** Compute the revised record entries for indices as we go.
108849  **
108850  ** This loop also handles the case of the PRIMARY KEY index for a
108851  ** WITHOUT ROWID table.
108852  */
108853  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
108854  int regIdx; /* Range of registers hold conent for pIdx */
108855  int regR; /* Range of registers holding conflicting PK */
108856  int iThisCur; /* Cursor for this UNIQUE index */
108857  int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
108858 
108859  if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
108860  if( bAffinityDone==0 ){
108861  sqlite3TableAffinity(v, pTab, regNewData+1);
108862  bAffinityDone = 1;
108863  }
108864  iThisCur = iIdxCur+ix;
108865  addrUniqueOk = sqlite3VdbeMakeLabel(v);
108866 
108867  /* Skip partial indices for which the WHERE clause is not true */
108868  if( pIdx->pPartIdxWhere ){
108869  sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
108870  pParse->ckBase = regNewData+1;
108871  sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
108873  pParse->ckBase = 0;
108874  }
108875 
108876  /* Create a record for this index entry as it should appear after
108877  ** the insert or update. Store that record in the aRegIdx[ix] register
108878  */
108879  regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
108880  for(i=0; i<pIdx->nColumn; i++){
108881  int iField = pIdx->aiColumn[i];
108882  int x;
108883  if( iField==XN_EXPR ){
108884  pParse->ckBase = regNewData+1;
108885  sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
108886  pParse->ckBase = 0;
108887  VdbeComment((v, "%s column %d", pIdx->zName, i));
108888  }else{
108889  if( iField==XN_ROWID || iField==pTab->iPKey ){
108890  if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
108891  x = regNewData;
108892  regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
108893  }else{
108894  x = iField + regNewData + 1;
108895  }
108896  sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
108897  VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
108898  }
108899  }
108900  sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
108901  VdbeComment((v, "for %s", pIdx->zName));
108902  sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
108903 
108904  /* In an UPDATE operation, if this index is the PRIMARY KEY index
108905  ** of a WITHOUT ROWID table and there has been no change the
108906  ** primary key, then no collision is possible. The collision detection
108907  ** logic below can all be skipped. */
108908  if( isUpdate && pPk==pIdx && pkChng==0 ){
108909  sqlite3VdbeResolveLabel(v, addrUniqueOk);
108910  continue;
108911  }
108912 
108913  /* Find out what action to take in case there is a uniqueness conflict */
108914  onError = pIdx->onError;
108915  if( onError==OE_None ){
108916  sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
108917  sqlite3VdbeResolveLabel(v, addrUniqueOk);
108918  continue; /* pIdx is not a UNIQUE index */
108919  }
108920  if( overrideError!=OE_Default ){
108921  onError = overrideError;
108922  }else if( onError==OE_Default ){
108923  onError = OE_Abort;
108924  }
108925 
108926  /* Check to see if the new index entry will be unique */
108927  sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
108928  regIdx, pIdx->nKeyCol); VdbeCoverage(v);
108929 
108930  /* Generate code to handle collisions */
108931  regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
108932  if( isUpdate || onError==OE_Replace ){
108933  if( HasRowid(pTab) ){
108934  sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
108935  /* Conflict only if the rowid of the existing index entry
108936  ** is different from old-rowid */
108937  if( isUpdate ){
108938  sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
108940  VdbeCoverage(v);
108941  }
108942  }else{
108943  int x;
108944  /* Extract the PRIMARY KEY from the end of the index entry and
108945  ** store it in registers regR..regR+nPk-1 */
108946  if( pIdx!=pPk ){
108947  for(i=0; i<pPk->nKeyCol; i++){
108948  assert( pPk->aiColumn[i]>=0 );
108949  x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
108950  sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
108951  VdbeComment((v, "%s.%s", pTab->zName,
108952  pTab->aCol[pPk->aiColumn[i]].zName));
108953  }
108954  }
108955  if( isUpdate ){
108956  /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
108957  ** table, only conflict if the new PRIMARY KEY values are actually
108958  ** different from the old.
108959  **
108960  ** For a UNIQUE index, only conflict if the PRIMARY KEY values
108961  ** of the matched index row are different from the original PRIMARY
108962  ** KEY values of this row before the update. */
108963  int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
108964  int op = OP_Ne;
108965  int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
108966 
108967  for(i=0; i<pPk->nKeyCol; i++){
108968  char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
108969  x = pPk->aiColumn[i];
108970  assert( x>=0 );
108971  if( i==(pPk->nKeyCol-1) ){
108972  addrJump = addrUniqueOk;
108973  op = OP_Eq;
108974  }
108975  sqlite3VdbeAddOp4(v, op,
108976  regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
108977  );
108979  VdbeCoverageIf(v, op==OP_Eq);
108980  VdbeCoverageIf(v, op==OP_Ne);
108981  }
108982  }
108983  }
108984  }
108985 
108986  /* Generate code that executes if the new index entry is not unique */
108987  assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
108988  || onError==OE_Ignore || onError==OE_Replace );
108989  switch( onError ){
108990  case OE_Rollback:
108991  case OE_Abort:
108992  case OE_Fail: {
108993  sqlite3UniqueConstraint(pParse, onError, pIdx);
108994  break;
108995  }
108996  case OE_Ignore: {
108997  sqlite3VdbeGoto(v, ignoreDest);
108998  break;
108999  }
109000  default: {
109001  Trigger *pTrigger = 0;
109002  assert( onError==OE_Replace );
109003  sqlite3MultiWrite(pParse);
109004  if( db->flags&SQLITE_RecTriggers ){
109005  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
109006  }
109007  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
109008  regR, nPkField, 0, OE_Replace,
109009  (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
109010  seenReplace = 1;
109011  break;
109012  }
109013  }
109014  sqlite3VdbeResolveLabel(v, addrUniqueOk);
109015  sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
109016  if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
109017  }
109018  if( ipkTop ){
109019  sqlite3VdbeGoto(v, ipkTop+1);
109020  sqlite3VdbeJumpHere(v, ipkBottom);
109021  }
109022 
109023  *pbMayReplace = seenReplace;
109024  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
109025 }
109026 
109027 /*
109028 ** This routine generates code to finish the INSERT or UPDATE operation
109029 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
109030 ** A consecutive range of registers starting at regNewData contains the
109031 ** rowid and the content to be inserted.
109032 **
109033 ** The arguments to this routine should be the same as the first six
109034 ** arguments to sqlite3GenerateConstraintChecks.
109035 */
109037  Parse *pParse, /* The parser context */
109038  Table *pTab, /* the table into which we are inserting */
109039  int iDataCur, /* Cursor of the canonical data source */
109040  int iIdxCur, /* First index cursor */
109041  int regNewData, /* Range of content */
109042  int *aRegIdx, /* Register used by each index. 0 for unused indices */
109043  int isUpdate, /* True for UPDATE, False for INSERT */
109044  int appendBias, /* True if this is likely to be an append */
109045  int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
109046 ){
109047  Vdbe *v; /* Prepared statements under construction */
109048  Index *pIdx; /* An index being inserted or updated */
109049  u8 pik_flags; /* flag values passed to the btree insert */
109050  int regData; /* Content registers (after the rowid) */
109051  int regRec; /* Register holding assembled record for the table */
109052  int i; /* Loop counter */
109053  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
109054 
109055  v = sqlite3GetVdbe(pParse);
109056  assert( v!=0 );
109057  assert( pTab->pSelect==0 ); /* This table is not a VIEW */
109058  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
109059  if( aRegIdx[i]==0 ) continue;
109060  bAffinityDone = 1;
109061  if( pIdx->pPartIdxWhere ){
109062  sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
109063  VdbeCoverage(v);
109064  }
109065  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
109066  pik_flags = 0;
109067  if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
109068  if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
109069  assert( pParse->nested==0 );
109070  pik_flags |= OPFLAG_NCHANGE;
109071  }
109072  sqlite3VdbeChangeP5(v, pik_flags);
109073  }
109074  if( !HasRowid(pTab) ) return;
109075  regData = regNewData + 1;
109076  regRec = sqlite3GetTempReg(pParse);
109077  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
109078  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
109079  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
109080  if( pParse->nested ){
109081  pik_flags = 0;
109082  }else{
109083  pik_flags = OPFLAG_NCHANGE;
109084  pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
109085  }
109086  if( appendBias ){
109087  pik_flags |= OPFLAG_APPEND;
109088  }
109089  if( useSeekResult ){
109090  pik_flags |= OPFLAG_USESEEKRESULT;
109091  }
109092  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
109093  if( !pParse->nested ){
109094  sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
109095  }
109096  sqlite3VdbeChangeP5(v, pik_flags);
109097 }
109098 
109099 /*
109100 ** Allocate cursors for the pTab table and all its indices and generate
109101 ** code to open and initialized those cursors.
109102 **
109103 ** The cursor for the object that contains the complete data (normally
109104 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
109105 ** ROWID table) is returned in *piDataCur. The first index cursor is
109106 ** returned in *piIdxCur. The number of indices is returned.
109107 **
109108 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
109109 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
109110 ** If iBase is negative, then allocate the next available cursor.
109111 **
109112 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
109113 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
109114 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
109115 ** pTab->pIndex list.
109116 **
109117 ** If pTab is a virtual table, then this routine is a no-op and the
109118 ** *piDataCur and *piIdxCur values are left uninitialized.
109119 */
109121  Parse *pParse, /* Parsing context */
109122  Table *pTab, /* Table to be opened */
109123  int op, /* OP_OpenRead or OP_OpenWrite */
109124  u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
109125  int iBase, /* Use this for the table cursor, if there is one */
109126  u8 *aToOpen, /* If not NULL: boolean for each table and index */
109127  int *piDataCur, /* Write the database source cursor number here */
109128  int *piIdxCur /* Write the first index cursor number here */
109129 ){
109130  int i;
109131  int iDb;
109132  int iDataCur;
109133  Index *pIdx;
109134  Vdbe *v;
109135 
109136  assert( op==OP_OpenRead || op==OP_OpenWrite );
109137  assert( op==OP_OpenWrite || p5==0 );
109138  if( IsVirtual(pTab) ){
109139  /* This routine is a no-op for virtual tables. Leave the output
109140  ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
109141  ** can detect if they are used by mistake in the caller. */
109142  return 0;
109143  }
109144  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
109145  v = sqlite3GetVdbe(pParse);
109146  assert( v!=0 );
109147  if( iBase<0 ) iBase = pParse->nTab;
109148  iDataCur = iBase++;
109149  if( piDataCur ) *piDataCur = iDataCur;
109150  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
109151  sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
109152  }else{
109153  sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
109154  }
109155  if( piIdxCur ) *piIdxCur = iBase;
109156  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
109157  int iIdxCur = iBase++;
109158  assert( pIdx->pSchema==pTab->pSchema );
109159  if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
109160  if( piDataCur ) *piDataCur = iIdxCur;
109161  p5 = 0;
109162  }
109163  if( aToOpen==0 || aToOpen[i+1] ){
109164  sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
109165  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
109166  sqlite3VdbeChangeP5(v, p5);
109167  VdbeComment((v, "%s", pIdx->zName));
109168  }
109169  }
109170  if( iBase>pParse->nTab ) pParse->nTab = iBase;
109171  return i;
109172 }
109173 
109174 
109175 #ifdef SQLITE_TEST
109176 /*
109177 ** The following global variable is incremented whenever the
109178 ** transfer optimization is used. This is used for testing
109179 ** purposes only - to make sure the transfer optimization really
109180 ** is happening when it is supposed to.
109181 */
109182 SQLITE_API int sqlite3_xferopt_count;
109183 #endif /* SQLITE_TEST */
109184 
109185 
109186 #ifndef SQLITE_OMIT_XFER_OPT
109187 /*
109188 ** Check to see if index pSrc is compatible as a source of data
109189 ** for index pDest in an insert transfer optimization. The rules
109190 ** for a compatible index:
109191 **
109192 ** * The index is over the same set of columns
109193 ** * The same DESC and ASC markings occurs on all columns
109194 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
109195 ** * The same collating sequence on each column
109196 ** * The index has the exact same WHERE clause
109197 */
109198 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
109199  int i;
109200  assert( pDest && pSrc );
109201  assert( pDest->pTable!=pSrc->pTable );
109202  if( pDest->nKeyCol!=pSrc->nKeyCol ){
109203  return 0; /* Different number of columns */
109204  }
109205  if( pDest->onError!=pSrc->onError ){
109206  return 0; /* Different conflict resolution strategies */
109207  }
109208  for(i=0; i<pSrc->nKeyCol; i++){
109209  if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
109210  return 0; /* Different columns indexed */
109211  }
109212  if( pSrc->aiColumn[i]==XN_EXPR ){
109213  assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
109214  if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
109215  pDest->aColExpr->a[i].pExpr, -1)!=0 ){
109216  return 0; /* Different expressions in the index */
109217  }
109218  }
109219  if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
109220  return 0; /* Different sort orders */
109221  }
109222  if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
109223  return 0; /* Different collating sequences */
109224  }
109225  }
109226  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
109227  return 0; /* Different WHERE clauses */
109228  }
109229 
109230  /* If no test above fails then the indices must be compatible */
109231  return 1;
109232 }
109233 
109234 /*
109235 ** Attempt the transfer optimization on INSERTs of the form
109236 **
109237 ** INSERT INTO tab1 SELECT * FROM tab2;
109238 **
109239 ** The xfer optimization transfers raw records from tab2 over to tab1.
109240 ** Columns are not decoded and reassembled, which greatly improves
109241 ** performance. Raw index records are transferred in the same way.
109242 **
109243 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
109244 ** There are lots of rules for determining compatibility - see comments
109245 ** embedded in the code for details.
109246 **
109247 ** This routine returns TRUE if the optimization is guaranteed to be used.
109248 ** Sometimes the xfer optimization will only work if the destination table
109249 ** is empty - a factor that can only be determined at run-time. In that
109250 ** case, this routine generates code for the xfer optimization but also
109251 ** does a test to see if the destination table is empty and jumps over the
109252 ** xfer optimization code if the test fails. In that case, this routine
109253 ** returns FALSE so that the caller will know to go ahead and generate
109254 ** an unoptimized transfer. This routine also returns FALSE if there
109255 ** is no chance that the xfer optimization can be applied.
109256 **
109257 ** This optimization is particularly useful at making VACUUM run faster.
109258 */
109260  Parse *pParse, /* Parser context */
109261  Table *pDest, /* The table we are inserting into */
109262  Select *pSelect, /* A SELECT statement to use as the data source */
109263  int onError, /* How to handle constraint errors */
109264  int iDbDest /* The database of pDest */
109265 ){
109266  sqlite3 *db = pParse->db;
109267  ExprList *pEList; /* The result set of the SELECT */
109268  Table *pSrc; /* The table in the FROM clause of SELECT */
109269  Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
109270  struct SrcList_item *pItem; /* An element of pSelect->pSrc */
109271  int i; /* Loop counter */
109272  int iDbSrc; /* The database of pSrc */
109273  int iSrc, iDest; /* Cursors from source and destination */
109274  int addr1, addr2; /* Loop addresses */
109275  int emptyDestTest = 0; /* Address of test for empty pDest */
109276  int emptySrcTest = 0; /* Address of test for empty pSrc */
109277  Vdbe *v; /* The VDBE we are building */
109278  int regAutoinc; /* Memory register used by AUTOINC */
109279  int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
109280  int regData, regRowid; /* Registers holding data and rowid */
109281 
109282  if( pSelect==0 ){
109283  return 0; /* Must be of the form INSERT INTO ... SELECT ... */
109284  }
109285  if( pParse->pWith || pSelect->pWith ){
109286  /* Do not attempt to process this query if there are an WITH clauses
109287  ** attached to it. Proceeding may generate a false "no such table: xxx"
109288  ** error if pSelect reads from a CTE named "xxx". */
109289  return 0;
109290  }
109291  if( sqlite3TriggerList(pParse, pDest) ){
109292  return 0; /* tab1 must not have triggers */
109293  }
109294 #ifndef SQLITE_OMIT_VIRTUALTABLE
109295  if( pDest->tabFlags & TF_Virtual ){
109296  return 0; /* tab1 must not be a virtual table */
109297  }
109298 #endif
109299  if( onError==OE_Default ){
109300  if( pDest->iPKey>=0 ) onError = pDest->keyConf;
109301  if( onError==OE_Default ) onError = OE_Abort;
109302  }
109303  assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
109304  if( pSelect->pSrc->nSrc!=1 ){
109305  return 0; /* FROM clause must have exactly one term */
109306  }
109307  if( pSelect->pSrc->a[0].pSelect ){
109308  return 0; /* FROM clause cannot contain a subquery */
109309  }
109310  if( pSelect->pWhere ){
109311  return 0; /* SELECT may not have a WHERE clause */
109312  }
109313  if( pSelect->pOrderBy ){
109314  return 0; /* SELECT may not have an ORDER BY clause */
109315  }
109316  /* Do not need to test for a HAVING clause. If HAVING is present but
109317  ** there is no ORDER BY, we will get an error. */
109318  if( pSelect->pGroupBy ){
109319  return 0; /* SELECT may not have a GROUP BY clause */
109320  }
109321  if( pSelect->pLimit ){
109322  return 0; /* SELECT may not have a LIMIT clause */
109323  }
109324  assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
109325  if( pSelect->pPrior ){
109326  return 0; /* SELECT may not be a compound query */
109327  }
109328  if( pSelect->selFlags & SF_Distinct ){
109329  return 0; /* SELECT may not be DISTINCT */
109330  }
109331  pEList = pSelect->pEList;
109332  assert( pEList!=0 );
109333  if( pEList->nExpr!=1 ){
109334  return 0; /* The result set must have exactly one column */
109335  }
109336  assert( pEList->a[0].pExpr );
109337  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
109338  return 0; /* The result set must be the special operator "*" */
109339  }
109340 
109341  /* At this point we have established that the statement is of the
109342  ** correct syntactic form to participate in this optimization. Now
109343  ** we have to check the semantics.
109344  */
109345  pItem = pSelect->pSrc->a;
109346  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
109347  if( pSrc==0 ){
109348  return 0; /* FROM clause does not contain a real table */
109349  }
109350  if( pSrc==pDest ){
109351  return 0; /* tab1 and tab2 may not be the same table */
109352  }
109353  if( HasRowid(pDest)!=HasRowid(pSrc) ){
109354  return 0; /* source and destination must both be WITHOUT ROWID or not */
109355  }
109356 #ifndef SQLITE_OMIT_VIRTUALTABLE
109357  if( pSrc->tabFlags & TF_Virtual ){
109358  return 0; /* tab2 must not be a virtual table */
109359  }
109360 #endif
109361  if( pSrc->pSelect ){
109362  return 0; /* tab2 may not be a view */
109363  }
109364  if( pDest->nCol!=pSrc->nCol ){
109365  return 0; /* Number of columns must be the same in tab1 and tab2 */
109366  }
109367  if( pDest->iPKey!=pSrc->iPKey ){
109368  return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
109369  }
109370  for(i=0; i<pDest->nCol; i++){
109371  Column *pDestCol = &pDest->aCol[i];
109372  Column *pSrcCol = &pSrc->aCol[i];
109373 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
109374  if( (db->flags & SQLITE_Vacuum)==0
109375  && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
109376  ){
109377  return 0; /* Neither table may have __hidden__ columns */
109378  }
109379 #endif
109380  if( pDestCol->affinity!=pSrcCol->affinity ){
109381  return 0; /* Affinity must be the same on all columns */
109382  }
109383  if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
109384  return 0; /* Collating sequence must be the same on all columns */
109385  }
109386  if( pDestCol->notNull && !pSrcCol->notNull ){
109387  return 0; /* tab2 must be NOT NULL if tab1 is */
109388  }
109389  /* Default values for second and subsequent columns need to match. */
109390  if( i>0 ){
109391  assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
109392  assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
109393  if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
109394  || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
109395  pSrcCol->pDflt->u.zToken)!=0)
109396  ){
109397  return 0; /* Default values must be the same for all columns */
109398  }
109399  }
109400  }
109401  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
109402  if( IsUniqueIndex(pDestIdx) ){
109403  destHasUniqueIdx = 1;
109404  }
109405  for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
109406  if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
109407  }
109408  if( pSrcIdx==0 ){
109409  return 0; /* pDestIdx has no corresponding index in pSrc */
109410  }
109411  }
109412 #ifndef SQLITE_OMIT_CHECK
109413  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
109414  return 0; /* Tables have different CHECK constraints. Ticket #2252 */
109415  }
109416 #endif
109417 #ifndef SQLITE_OMIT_FOREIGN_KEY
109418  /* Disallow the transfer optimization if the destination table constains
109419  ** any foreign key constraints. This is more restrictive than necessary.
109420  ** But the main beneficiary of the transfer optimization is the VACUUM
109421  ** command, and the VACUUM command disables foreign key constraints. So
109422  ** the extra complication to make this rule less restrictive is probably
109423  ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
109424  */
109425  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
109426  return 0;
109427  }
109428 #endif
109429  if( (db->flags & SQLITE_CountRows)!=0 ){
109430  return 0; /* xfer opt does not play well with PRAGMA count_changes */
109431  }
109432 
109433  /* If we get this far, it means that the xfer optimization is at
109434  ** least a possibility, though it might only work if the destination
109435  ** table (tab1) is initially empty.
109436  */
109437 #ifdef SQLITE_TEST
109438  sqlite3_xferopt_count++;
109439 #endif
109440  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
109441  v = sqlite3GetVdbe(pParse);
109442  sqlite3CodeVerifySchema(pParse, iDbSrc);
109443  iSrc = pParse->nTab++;
109444  iDest = pParse->nTab++;
109445  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
109446  regData = sqlite3GetTempReg(pParse);
109447  regRowid = sqlite3GetTempReg(pParse);
109448  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
109449  assert( HasRowid(pDest) || destHasUniqueIdx );
109450  if( (db->flags & SQLITE_Vacuum)==0 && (
109451  (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
109452  || destHasUniqueIdx /* (2) */
109453  || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
109454  )){
109455  /* In some circumstances, we are able to run the xfer optimization
109456  ** only if the destination table is initially empty. Unless the
109457  ** SQLITE_Vacuum flag is set, this block generates code to make
109458  ** that determination. If SQLITE_Vacuum is set, then the destination
109459  ** table is always empty.
109460  **
109461  ** Conditions under which the destination must be empty:
109462  **
109463  ** (1) There is no INTEGER PRIMARY KEY but there are indices.
109464  ** (If the destination is not initially empty, the rowid fields
109465  ** of index entries might need to change.)
109466  **
109467  ** (2) The destination has a unique index. (The xfer optimization
109468  ** is unable to test uniqueness.)
109469  **
109470  ** (3) onError is something other than OE_Abort and OE_Rollback.
109471  */
109472  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
109473  emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
109474  sqlite3VdbeJumpHere(v, addr1);
109475  }
109476  if( HasRowid(pSrc) ){
109477  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
109478  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
109479  if( pDest->iPKey>=0 ){
109480  addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
109481  addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
109482  VdbeCoverage(v);
109483  sqlite3RowidConstraint(pParse, onError, pDest);
109484  sqlite3VdbeJumpHere(v, addr2);
109485  autoIncStep(pParse, regAutoinc, regRowid);
109486  }else if( pDest->pIndex==0 ){
109487  addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
109488  }else{
109489  addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
109490  assert( (pDest->tabFlags & TF_Autoincrement)==0 );
109491  }
109492  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
109493  sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
109494  (char*)pDest, P4_TABLE);
109496  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
109497  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
109498  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
109499  }else{
109500  sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
109501  sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
109502  }
109503  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
109504  u8 idxInsFlags = 0;
109505  for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
109506  if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
109507  }
109508  assert( pSrcIdx );
109509  sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
109510  sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
109511  VdbeComment((v, "%s", pSrcIdx->zName));
109512  sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
109513  sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
109515  VdbeComment((v, "%s", pDestIdx->zName));
109516  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
109517  sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
109518  if( db->flags & SQLITE_Vacuum ){
109519  /* This INSERT command is part of a VACUUM operation, which guarantees
109520  ** that the destination table is empty. If all indexed columns use
109521  ** collation sequence BINARY, then it can also be assumed that the
109522  ** index will be populated by inserting keys in strictly sorted
109523  ** order. In this case, instead of seeking within the b-tree as part
109524  ** of every OP_IdxInsert opcode, an OP_Last is added before the
109525  ** OP_IdxInsert to seek to the point within the b-tree where each key
109526  ** should be inserted. This is faster.
109527  **
109528  ** If any of the indexed columns use a collation sequence other than
109529  ** BINARY, this optimization is disabled. This is because the user
109530  ** might change the definition of a collation sequence and then run
109531  ** a VACUUM command. In that case keys may not be written in strictly
109532  ** sorted order. */
109533  for(i=0; i<pSrcIdx->nColumn; i++){
109534  const char *zColl = pSrcIdx->azColl[i];
109535  assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
109536  || sqlite3StrBINARY==zColl );
109537  if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
109538  }
109539  if( i==pSrcIdx->nColumn ){
109540  idxInsFlags = OPFLAG_USESEEKRESULT;
109541  sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
109542  }
109543  }
109544  if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
109545  idxInsFlags |= OPFLAG_NCHANGE;
109546  }
109547  sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
109548  sqlite3VdbeChangeP5(v, idxInsFlags);
109549  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
109550  sqlite3VdbeJumpHere(v, addr1);
109551  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
109552  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
109553  }
109554  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
109555  sqlite3ReleaseTempReg(pParse, regRowid);
109556  sqlite3ReleaseTempReg(pParse, regData);
109557  if( emptyDestTest ){
109558  sqlite3AutoincrementEnd(pParse);
109560  sqlite3VdbeJumpHere(v, emptyDestTest);
109561  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
109562  return 0;
109563  }else{
109564  return 1;
109565  }
109566 }
109567 #endif /* SQLITE_OMIT_XFER_OPT */
109568 
109569 /************** End of insert.c **********************************************/
109570 /************** Begin file legacy.c ******************************************/
109571 /*
109572 ** 2001 September 15
109573 **
109574 ** The author disclaims copyright to this source code. In place of
109575 ** a legal notice, here is a blessing:
109576 **
109577 ** May you do good and not evil.
109578 ** May you find forgiveness for yourself and forgive others.
109579 ** May you share freely, never taking more than you give.
109580 **
109581 *************************************************************************
109582 ** Main file for the SQLite library. The routines in this file
109583 ** implement the programmer interface to the library. Routines in
109584 ** other files are for internal use by SQLite and should not be
109585 ** accessed by users of the library.
109586 */
109587 
109588 /* #include "sqliteInt.h" */
109589 
109590 /*
109591 ** Execute SQL code. Return one of the SQLITE_ success/failure
109592 ** codes. Also write an error message into memory obtained from
109593 ** malloc() and make *pzErrMsg point to that message.
109594 **
109595 ** If the SQL is a query, then for each row in the query result
109596 ** the xCallback() function is called. pArg becomes the first
109597 ** argument to xCallback(). If xCallback=NULL then no callback
109598 ** is invoked, even for queries.
109599 */
109601  sqlite3 *db, /* The database on which the SQL executes */
109602  const char *zSql, /* The SQL to be executed */
109603  sqlite3_callback xCallback, /* Invoke this callback routine */
109604  void *pArg, /* First argument to xCallback() */
109605  char **pzErrMsg /* Write error messages here */
109606 ){
109607  int rc = SQLITE_OK; /* Return code */
109608  const char *zLeftover; /* Tail of unprocessed SQL */
109609  sqlite3_stmt *pStmt = 0; /* The current SQL statement */
109610  char **azCols = 0; /* Names of result columns */
109611  int callbackIsInit; /* True if callback data is initialized */
109612 
109613  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
109614  if( zSql==0 ) zSql = "";
109615 
109616  sqlite3_mutex_enter(db->mutex);
109617  sqlite3Error(db, SQLITE_OK);
109618  while( rc==SQLITE_OK && zSql[0] ){
109619  int nCol;
109620  char **azVals = 0;
109621 
109622  pStmt = 0;
109623  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
109624  assert( rc==SQLITE_OK || pStmt==0 );
109625  if( rc!=SQLITE_OK ){
109626  continue;
109627  }
109628  if( !pStmt ){
109629  /* this happens for a comment or white-space */
109630  zSql = zLeftover;
109631  continue;
109632  }
109633 
109634  callbackIsInit = 0;
109635  nCol = sqlite3_column_count(pStmt);
109636 
109637  while( 1 ){
109638  int i;
109639  rc = sqlite3_step(pStmt);
109640 
109641  /* Invoke the callback function if required */
109642  if( xCallback && (SQLITE_ROW==rc ||
109643  (SQLITE_DONE==rc && !callbackIsInit
109644  && db->flags&SQLITE_NullCallback)) ){
109645  if( !callbackIsInit ){
109646  azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
109647  if( azCols==0 ){
109648  goto exec_out;
109649  }
109650  for(i=0; i<nCol; i++){
109651  azCols[i] = (char *)sqlite3_column_name(pStmt, i);
109652  /* sqlite3VdbeSetColName() installs column names as UTF8
109653  ** strings so there is no way for sqlite3_column_name() to fail. */
109654  assert( azCols[i]!=0 );
109655  }
109656  callbackIsInit = 1;
109657  }
109658  if( rc==SQLITE_ROW ){
109659  azVals = &azCols[nCol];
109660  for(i=0; i<nCol; i++){
109661  azVals[i] = (char *)sqlite3_column_text(pStmt, i);
109662  if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
109663  sqlite3OomFault(db);
109664  goto exec_out;
109665  }
109666  }
109667  }
109668  if( xCallback(pArg, nCol, azVals, azCols) ){
109669  /* EVIDENCE-OF: R-38229-40159 If the callback function to
109670  ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
109671  ** return SQLITE_ABORT. */
109672  rc = SQLITE_ABORT;
109673  sqlite3VdbeFinalize((Vdbe *)pStmt);
109674  pStmt = 0;
109675  sqlite3Error(db, SQLITE_ABORT);
109676  goto exec_out;
109677  }
109678  }
109679 
109680  if( rc!=SQLITE_ROW ){
109681  rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
109682  pStmt = 0;
109683  zSql = zLeftover;
109684  while( sqlite3Isspace(zSql[0]) ) zSql++;
109685  break;
109686  }
109687  }
109688 
109689  sqlite3DbFree(db, azCols);
109690  azCols = 0;
109691  }
109692 
109693 exec_out:
109694  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
109695  sqlite3DbFree(db, azCols);
109696 
109697  rc = sqlite3ApiExit(db, rc);
109698  if( rc!=SQLITE_OK && pzErrMsg ){
109699  int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
109700  *pzErrMsg = sqlite3Malloc(nErrMsg);
109701  if( *pzErrMsg ){
109702  memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
109703  }else{
109704  rc = SQLITE_NOMEM_BKPT;
109705  sqlite3Error(db, SQLITE_NOMEM);
109706  }
109707  }else if( pzErrMsg ){
109708  *pzErrMsg = 0;
109709  }
109710 
109711  assert( (rc&db->errMask)==rc );
109712  sqlite3_mutex_leave(db->mutex);
109713  return rc;
109714 }
109715 
109716 /************** End of legacy.c **********************************************/
109717 /************** Begin file loadext.c *****************************************/
109718 /*
109719 ** 2006 June 7
109720 **
109721 ** The author disclaims copyright to this source code. In place of
109722 ** a legal notice, here is a blessing:
109723 **
109724 ** May you do good and not evil.
109725 ** May you find forgiveness for yourself and forgive others.
109726 ** May you share freely, never taking more than you give.
109727 **
109728 *************************************************************************
109729 ** This file contains code used to dynamically load extensions into
109730 ** the SQLite library.
109731 */
109732 
109733 #ifndef SQLITE_CORE
109734  #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
109735 #endif
109736 /************** Include sqlite3ext.h in the middle of loadext.c **************/
109737 /************** Begin file sqlite3ext.h **************************************/
109738 /*
109739 ** 2006 June 7
109740 **
109741 ** The author disclaims copyright to this source code. In place of
109742 ** a legal notice, here is a blessing:
109743 **
109744 ** May you do good and not evil.
109745 ** May you find forgiveness for yourself and forgive others.
109746 ** May you share freely, never taking more than you give.
109747 **
109748 *************************************************************************
109749 ** This header file defines the SQLite interface for use by
109750 ** shared libraries that want to be imported as extensions into
109751 ** an SQLite instance. Shared libraries that intend to be loaded
109752 ** as extensions by SQLite should #include this file instead of
109753 ** sqlite3.h.
109754 */
109755 #ifndef SQLITE3EXT_H
109756 #define SQLITE3EXT_H
109757 /* #include "sqlite3.h" */
109758 
109759 /*
109760 ** The following structure holds pointers to all of the SQLite API
109761 ** routines.
109762 **
109763 ** WARNING: In order to maintain backwards compatibility, add new
109764 ** interfaces to the end of this structure only. If you insert new
109765 ** interfaces in the middle of this structure, then older different
109766 ** versions of SQLite will not be able to load each other's shared
109767 ** libraries!
109768 */
109770  void * (*aggregate_context)(sqlite3_context*,int nBytes);
109771  int (*aggregate_count)(sqlite3_context*);
109772  int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
109773  int (*bind_double)(sqlite3_stmt*,int,double);
109774  int (*bind_int)(sqlite3_stmt*,int,int);
109775  int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
109776  int (*bind_null)(sqlite3_stmt*,int);
109777  int (*bind_parameter_count)(sqlite3_stmt*);
109778  int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
109779  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
109780  int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
109781  int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
109782  int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
109783  int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
109784  int (*busy_timeout)(sqlite3*,int ms);
109785  int (*changes)(sqlite3*);
109786  int (*close)(sqlite3*);
109787  int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
109788  int eTextRep,const char*));
109789  int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
109790  int eTextRep,const void*));
109791  const void * (*column_blob)(sqlite3_stmt*,int iCol);
109792  int (*column_bytes)(sqlite3_stmt*,int iCol);
109793  int (*column_bytes16)(sqlite3_stmt*,int iCol);
109794  int (*column_count)(sqlite3_stmt*pStmt);
109795  const char * (*column_database_name)(sqlite3_stmt*,int);
109796  const void * (*column_database_name16)(sqlite3_stmt*,int);
109797  const char * (*column_decltype)(sqlite3_stmt*,int i);
109798  const void * (*column_decltype16)(sqlite3_stmt*,int);
109799  double (*column_double)(sqlite3_stmt*,int iCol);
109800  int (*column_int)(sqlite3_stmt*,int iCol);
109801  sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
109802  const char * (*column_name)(sqlite3_stmt*,int);
109803  const void * (*column_name16)(sqlite3_stmt*,int);
109804  const char * (*column_origin_name)(sqlite3_stmt*,int);
109805  const void * (*column_origin_name16)(sqlite3_stmt*,int);
109806  const char * (*column_table_name)(sqlite3_stmt*,int);
109807  const void * (*column_table_name16)(sqlite3_stmt*,int);
109808  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
109809  const void * (*column_text16)(sqlite3_stmt*,int iCol);
109810  int (*column_type)(sqlite3_stmt*,int iCol);
109811  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
109812  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
109813  int (*complete)(const char*sql);
109814  int (*complete16)(const void*sql);
109815  int (*create_collation)(sqlite3*,const char*,int,void*,
109816  int(*)(void*,int,const void*,int,const void*));
109817  int (*create_collation16)(sqlite3*,const void*,int,void*,
109818  int(*)(void*,int,const void*,int,const void*));
109819  int (*create_function)(sqlite3*,const char*,int,int,void*,
109820  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109821  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109822  void (*xFinal)(sqlite3_context*));
109823  int (*create_function16)(sqlite3*,const void*,int,int,void*,
109824  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109825  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109826  void (*xFinal)(sqlite3_context*));
109827  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
109828  int (*data_count)(sqlite3_stmt*pStmt);
109829  sqlite3 * (*db_handle)(sqlite3_stmt*);
109830  int (*declare_vtab)(sqlite3*,const char*);
109831  int (*enable_shared_cache)(int);
109832  int (*errcode)(sqlite3*db);
109833  const char * (*errmsg)(sqlite3*);
109834  const void * (*errmsg16)(sqlite3*);
109835  int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
109836  int (*expired)(sqlite3_stmt*);
109837  int (*finalize)(sqlite3_stmt*pStmt);
109838  void (*free)(void*);
109839  void (*free_table)(char**result);
109840  int (*get_autocommit)(sqlite3*);
109841  void * (*get_auxdata)(sqlite3_context*,int);
109842  int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
109843  int (*global_recover)(void);
109844  void (*interruptx)(sqlite3*);
109846  const char * (*libversion)(void);
109847  int (*libversion_number)(void);
109848  void *(*malloc)(int);
109849  char * (*mprintf)(const char*,...);
109850  int (*open)(const char*,sqlite3**);
109851  int (*open16)(const void*,sqlite3**);
109852  int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
109853  int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
109854  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
109855  void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
109856  void *(*realloc)(void*,int);
109857  int (*reset)(sqlite3_stmt*pStmt);
109858  void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
109859  void (*result_double)(sqlite3_context*,double);
109860  void (*result_error)(sqlite3_context*,const char*,int);
109861  void (*result_error16)(sqlite3_context*,const void*,int);
109862  void (*result_int)(sqlite3_context*,int);
109863  void (*result_int64)(sqlite3_context*,sqlite_int64);
109864  void (*result_null)(sqlite3_context*);
109865  void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
109866  void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
109867  void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
109868  void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
109869  void (*result_value)(sqlite3_context*,sqlite3_value*);
109870  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
109871  int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
109872  const char*,const char*),void*);
109873  void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
109874  char * (*snprintf)(int,char*,const char*,...);
109875  int (*step)(sqlite3_stmt*);
109876  int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
109877  char const**,char const**,int*,int*,int*);
109878  void (*thread_cleanup)(void);
109880  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
109881  int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
109882  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
109883  sqlite_int64),void*);
109884  void * (*user_data)(sqlite3_context*);
109885  const void * (*value_blob)(sqlite3_value*);
109886  int (*value_bytes)(sqlite3_value*);
109887  int (*value_bytes16)(sqlite3_value*);
109888  double (*value_double)(sqlite3_value*);
109889  int (*value_int)(sqlite3_value*);
109890  sqlite_int64 (*value_int64)(sqlite3_value*);
109891  int (*value_numeric_type)(sqlite3_value*);
109892  const unsigned char * (*value_text)(sqlite3_value*);
109893  const void * (*value_text16)(sqlite3_value*);
109894  const void * (*value_text16be)(sqlite3_value*);
109895  const void * (*value_text16le)(sqlite3_value*);
109896  int (*value_type)(sqlite3_value*);
109897  char *(*vmprintf)(const char*,va_list);
109898  /* Added ??? */
109899  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
109900  /* Added by 3.3.13 */
109901  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
109902  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
109903  int (*clear_bindings)(sqlite3_stmt*);
109904  /* Added by 3.4.1 */
109905  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
109906  void (*xDestroy)(void *));
109907  /* Added by 3.5.0 */
109908  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
109909  int (*blob_bytes)(sqlite3_blob*);
109910  int (*blob_close)(sqlite3_blob*);
109911  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
109912  int,sqlite3_blob**);
109913  int (*blob_read)(sqlite3_blob*,void*,int,int);
109914  int (*blob_write)(sqlite3_blob*,const void*,int,int);
109915  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
109916  int(*)(void*,int,const void*,int,const void*),
109917  void(*)(void*));
109918  int (*file_control)(sqlite3*,const char*,int,void*);
109919  sqlite3_int64 (*memory_highwater)(int);
109920  sqlite3_int64 (*memory_used)(void);
109921  sqlite3_mutex *(*mutex_alloc)(int);
109922  void (*mutex_enter)(sqlite3_mutex*);
109923  void (*mutex_free)(sqlite3_mutex*);
109924  void (*mutex_leave)(sqlite3_mutex*);
109925  int (*mutex_try)(sqlite3_mutex*);
109926  int (*open_v2)(const char*,sqlite3**,int,const char*);
109927  int (*release_memory)(int);
109928  void (*result_error_nomem)(sqlite3_context*);
109929  void (*result_error_toobig)(sqlite3_context*);
109930  int (*sleep)(int);
109931  void (*soft_heap_limit)(int);
109932  sqlite3_vfs *(*vfs_find)(const char*);
109933  int (*vfs_register)(sqlite3_vfs*,int);
109934  int (*vfs_unregister)(sqlite3_vfs*);
109935  int (*xthreadsafe)(void);
109936  void (*result_zeroblob)(sqlite3_context*,int);
109937  void (*result_error_code)(sqlite3_context*,int);
109938  int (*test_control)(int, ...);
109939  void (*randomness)(int,void*);
109940  sqlite3 *(*context_db_handle)(sqlite3_context*);
109941  int (*extended_result_codes)(sqlite3*,int);
109942  int (*limit)(sqlite3*,int,int);
109943  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
109944  const char *(*sql)(sqlite3_stmt*);
109945  int (*status)(int,int*,int*,int);
109946  int (*backup_finish)(sqlite3_backup*);
109947  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
109948  int (*backup_pagecount)(sqlite3_backup*);
109949  int (*backup_remaining)(sqlite3_backup*);
109950  int (*backup_step)(sqlite3_backup*,int);
109951  const char *(*compileoption_get)(int);
109952  int (*compileoption_used)(const char*);
109953  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
109954  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109955  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109956  void (*xFinal)(sqlite3_context*),
109957  void(*xDestroy)(void*));
109958  int (*db_config)(sqlite3*,int,...);
109959  sqlite3_mutex *(*db_mutex)(sqlite3*);
109960  int (*db_status)(sqlite3*,int,int*,int*,int);
109961  int (*extended_errcode)(sqlite3*);
109962  void (*log)(int,const char*,...);
109963  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
109964  const char *(*sourceid)(void);
109965  int (*stmt_status)(sqlite3_stmt*,int,int);
109966  int (*strnicmp)(const char*,const char*,int);
109967  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
109968  int (*wal_autocheckpoint)(sqlite3*,int);
109969  int (*wal_checkpoint)(sqlite3*,const char*);
109970  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
109971  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
109972  int (*vtab_config)(sqlite3*,int op,...);
109973  int (*vtab_on_conflict)(sqlite3*);
109974  /* Version 3.7.16 and later */
109975  int (*close_v2)(sqlite3*);
109976  const char *(*db_filename)(sqlite3*,const char*);
109977  int (*db_readonly)(sqlite3*,const char*);
109978  int (*db_release_memory)(sqlite3*);
109979  const char *(*errstr)(int);
109980  int (*stmt_busy)(sqlite3_stmt*);
109981  int (*stmt_readonly)(sqlite3_stmt*);
109982  int (*stricmp)(const char*,const char*);
109983  int (*uri_boolean)(const char*,const char*,int);
109984  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
109985  const char *(*uri_parameter)(const char*,const char*);
109986  char *(*vsnprintf)(int,char*,const char*,va_list);
109987  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
109988  /* Version 3.8.7 and later */
109989  int (*auto_extension)(void(*)(void));
109990  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
109991  void(*)(void*));
109992  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
109993  void(*)(void*),unsigned char);
109994  int (*cancel_auto_extension)(void(*)(void));
109995  int (*load_extension)(sqlite3*,const char*,const char*,char**);
109996  void *(*malloc64)(sqlite3_uint64);
109997  sqlite3_uint64 (*msize)(void*);
109998  void *(*realloc64)(void*,sqlite3_uint64);
109999  void (*reset_auto_extension)(void);
110000  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
110001  void(*)(void*));
110002  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
110003  void(*)(void*), unsigned char);
110004  int (*strglob)(const char*,const char*);
110005  /* Version 3.8.11 and later */
110006  sqlite3_value *(*value_dup)(const sqlite3_value*);
110007  void (*value_free)(sqlite3_value*);
110008  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
110009  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
110010  /* Version 3.9.0 and later */
110011  unsigned int (*value_subtype)(sqlite3_value*);
110012  void (*result_subtype)(sqlite3_context*,unsigned int);
110013  /* Version 3.10.0 and later */
110014  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
110015  int (*strlike)(const char*,const char*,unsigned int);
110016  int (*db_cacheflush)(sqlite3*);
110017  /* Version 3.12.0 and later */
110018  int (*system_errno)(sqlite3*);
110019  /* Version 3.14.0 and later */
110020  int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
110021  char *(*expanded_sql)(sqlite3_stmt*);
110022 };
110023 
110024 /*
110025 ** This is the function signature used for all extension entry points. It
110026 ** is also defined in the file "loadext.c".
110027 */
110028 typedef int (*sqlite3_loadext_entry)(
110029  sqlite3 *db, /* Handle to the database. */
110030  char **pzErrMsg, /* Used to set error string on failure. */
110031  const sqlite3_api_routines *pThunk /* Extension API function pointers. */
110032 );
110033 
110034 /*
110035 ** The following macros redefine the API routines so that they are
110036 ** redirected through the global sqlite3_api structure.
110037 **
110038 ** This header file is also used by the loadext.c source file
110039 ** (part of the main SQLite library - not an extension) so that
110040 ** it can get access to the sqlite3_api_routines structure
110041 ** definition. But the main library does not want to redefine
110042 ** the API. So the redefinition macros are only valid if the
110043 ** SQLITE_CORE macros is undefined.
110044 */
110045 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
110046 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
110047 #ifndef SQLITE_OMIT_DEPRECATED
110048 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
110049 #endif
110050 #define sqlite3_bind_blob sqlite3_api->bind_blob
110051 #define sqlite3_bind_double sqlite3_api->bind_double
110052 #define sqlite3_bind_int sqlite3_api->bind_int
110053 #define sqlite3_bind_int64 sqlite3_api->bind_int64
110054 #define sqlite3_bind_null sqlite3_api->bind_null
110055 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
110056 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
110057 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
110058 #define sqlite3_bind_text sqlite3_api->bind_text
110059 #define sqlite3_bind_text16 sqlite3_api->bind_text16
110060 #define sqlite3_bind_value sqlite3_api->bind_value
110061 #define sqlite3_busy_handler sqlite3_api->busy_handler
110062 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
110063 #define sqlite3_changes sqlite3_api->changes
110064 #define sqlite3_close sqlite3_api->close
110065 #define sqlite3_collation_needed sqlite3_api->collation_needed
110066 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
110067 #define sqlite3_column_blob sqlite3_api->column_blob
110068 #define sqlite3_column_bytes sqlite3_api->column_bytes
110069 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
110070 #define sqlite3_column_count sqlite3_api->column_count
110071 #define sqlite3_column_database_name sqlite3_api->column_database_name
110072 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
110073 #define sqlite3_column_decltype sqlite3_api->column_decltype
110074 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
110075 #define sqlite3_column_double sqlite3_api->column_double
110076 #define sqlite3_column_int sqlite3_api->column_int
110077 #define sqlite3_column_int64 sqlite3_api->column_int64
110078 #define sqlite3_column_name sqlite3_api->column_name
110079 #define sqlite3_column_name16 sqlite3_api->column_name16
110080 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
110081 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
110082 #define sqlite3_column_table_name sqlite3_api->column_table_name
110083 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
110084 #define sqlite3_column_text sqlite3_api->column_text
110085 #define sqlite3_column_text16 sqlite3_api->column_text16
110086 #define sqlite3_column_type sqlite3_api->column_type
110087 #define sqlite3_column_value sqlite3_api->column_value
110088 #define sqlite3_commit_hook sqlite3_api->commit_hook
110089 #define sqlite3_complete sqlite3_api->complete
110090 #define sqlite3_complete16 sqlite3_api->complete16
110091 #define sqlite3_create_collation sqlite3_api->create_collation
110092 #define sqlite3_create_collation16 sqlite3_api->create_collation16
110093 #define sqlite3_create_function sqlite3_api->create_function
110094 #define sqlite3_create_function16 sqlite3_api->create_function16
110095 #define sqlite3_create_module sqlite3_api->create_module
110096 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
110097 #define sqlite3_data_count sqlite3_api->data_count
110098 #define sqlite3_db_handle sqlite3_api->db_handle
110099 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
110100 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
110101 #define sqlite3_errcode sqlite3_api->errcode
110102 #define sqlite3_errmsg sqlite3_api->errmsg
110103 #define sqlite3_errmsg16 sqlite3_api->errmsg16
110104 #define sqlite3_exec sqlite3_api->exec
110105 #ifndef SQLITE_OMIT_DEPRECATED
110106 #define sqlite3_expired sqlite3_api->expired
110107 #endif
110108 #define sqlite3_finalize sqlite3_api->finalize
110109 #define sqlite3_free sqlite3_api->free
110110 #define sqlite3_free_table sqlite3_api->free_table
110111 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
110112 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
110113 #define sqlite3_get_table sqlite3_api->get_table
110114 #ifndef SQLITE_OMIT_DEPRECATED
110115 #define sqlite3_global_recover sqlite3_api->global_recover
110116 #endif
110117 #define sqlite3_interrupt sqlite3_api->interruptx
110118 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
110119 #define sqlite3_libversion sqlite3_api->libversion
110120 #define sqlite3_libversion_number sqlite3_api->libversion_number
110121 #define sqlite3_malloc sqlite3_api->malloc
110122 #define sqlite3_mprintf sqlite3_api->mprintf
110123 #define sqlite3_open sqlite3_api->open
110124 #define sqlite3_open16 sqlite3_api->open16
110125 #define sqlite3_prepare sqlite3_api->prepare
110126 #define sqlite3_prepare16 sqlite3_api->prepare16
110127 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
110128 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
110129 #define sqlite3_profile sqlite3_api->profile
110130 #define sqlite3_progress_handler sqlite3_api->progress_handler
110131 #define sqlite3_realloc sqlite3_api->realloc
110132 #define sqlite3_reset sqlite3_api->reset
110133 #define sqlite3_result_blob sqlite3_api->result_blob
110134 #define sqlite3_result_double sqlite3_api->result_double
110135 #define sqlite3_result_error sqlite3_api->result_error
110136 #define sqlite3_result_error16 sqlite3_api->result_error16
110137 #define sqlite3_result_int sqlite3_api->result_int
110138 #define sqlite3_result_int64 sqlite3_api->result_int64
110139 #define sqlite3_result_null sqlite3_api->result_null
110140 #define sqlite3_result_text sqlite3_api->result_text
110141 #define sqlite3_result_text16 sqlite3_api->result_text16
110142 #define sqlite3_result_text16be sqlite3_api->result_text16be
110143 #define sqlite3_result_text16le sqlite3_api->result_text16le
110144 #define sqlite3_result_value sqlite3_api->result_value
110145 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
110146 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
110147 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
110148 #define sqlite3_snprintf sqlite3_api->snprintf
110149 #define sqlite3_step sqlite3_api->step
110150 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
110151 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
110152 #define sqlite3_total_changes sqlite3_api->total_changes
110153 #define sqlite3_trace sqlite3_api->trace
110154 #ifndef SQLITE_OMIT_DEPRECATED
110155 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
110156 #endif
110157 #define sqlite3_update_hook sqlite3_api->update_hook
110158 #define sqlite3_user_data sqlite3_api->user_data
110159 #define sqlite3_value_blob sqlite3_api->value_blob
110160 #define sqlite3_value_bytes sqlite3_api->value_bytes
110161 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
110162 #define sqlite3_value_double sqlite3_api->value_double
110163 #define sqlite3_value_int sqlite3_api->value_int
110164 #define sqlite3_value_int64 sqlite3_api->value_int64
110165 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
110166 #define sqlite3_value_text sqlite3_api->value_text
110167 #define sqlite3_value_text16 sqlite3_api->value_text16
110168 #define sqlite3_value_text16be sqlite3_api->value_text16be
110169 #define sqlite3_value_text16le sqlite3_api->value_text16le
110170 #define sqlite3_value_type sqlite3_api->value_type
110171 #define sqlite3_vmprintf sqlite3_api->vmprintf
110172 #define sqlite3_vsnprintf sqlite3_api->vsnprintf
110173 #define sqlite3_overload_function sqlite3_api->overload_function
110174 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
110175 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
110176 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
110177 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
110178 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
110179 #define sqlite3_blob_close sqlite3_api->blob_close
110180 #define sqlite3_blob_open sqlite3_api->blob_open
110181 #define sqlite3_blob_read sqlite3_api->blob_read
110182 #define sqlite3_blob_write sqlite3_api->blob_write
110183 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
110184 #define sqlite3_file_control sqlite3_api->file_control
110185 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
110186 #define sqlite3_memory_used sqlite3_api->memory_used
110187 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
110188 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
110189 #define sqlite3_mutex_free sqlite3_api->mutex_free
110190 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
110191 #define sqlite3_mutex_try sqlite3_api->mutex_try
110192 #define sqlite3_open_v2 sqlite3_api->open_v2
110193 #define sqlite3_release_memory sqlite3_api->release_memory
110194 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
110195 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
110196 #define sqlite3_sleep sqlite3_api->sleep
110197 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
110198 #define sqlite3_vfs_find sqlite3_api->vfs_find
110199 #define sqlite3_vfs_register sqlite3_api->vfs_register
110200 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
110201 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
110202 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
110203 #define sqlite3_result_error_code sqlite3_api->result_error_code
110204 #define sqlite3_test_control sqlite3_api->test_control
110205 #define sqlite3_randomness sqlite3_api->randomness
110206 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
110207 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
110208 #define sqlite3_limit sqlite3_api->limit
110209 #define sqlite3_next_stmt sqlite3_api->next_stmt
110210 #define sqlite3_sql sqlite3_api->sql
110211 #define sqlite3_status sqlite3_api->status
110212 #define sqlite3_backup_finish sqlite3_api->backup_finish
110213 #define sqlite3_backup_init sqlite3_api->backup_init
110214 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
110215 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
110216 #define sqlite3_backup_step sqlite3_api->backup_step
110217 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
110218 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
110219 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
110220 #define sqlite3_db_config sqlite3_api->db_config
110221 #define sqlite3_db_mutex sqlite3_api->db_mutex
110222 #define sqlite3_db_status sqlite3_api->db_status
110223 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
110224 #define sqlite3_log sqlite3_api->log
110225 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
110226 #define sqlite3_sourceid sqlite3_api->sourceid
110227 #define sqlite3_stmt_status sqlite3_api->stmt_status
110228 #define sqlite3_strnicmp sqlite3_api->strnicmp
110229 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
110230 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
110231 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
110232 #define sqlite3_wal_hook sqlite3_api->wal_hook
110233 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
110234 #define sqlite3_vtab_config sqlite3_api->vtab_config
110235 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
110236 /* Version 3.7.16 and later */
110237 #define sqlite3_close_v2 sqlite3_api->close_v2
110238 #define sqlite3_db_filename sqlite3_api->db_filename
110239 #define sqlite3_db_readonly sqlite3_api->db_readonly
110240 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
110241 #define sqlite3_errstr sqlite3_api->errstr
110242 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
110243 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
110244 #define sqlite3_stricmp sqlite3_api->stricmp
110245 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
110246 #define sqlite3_uri_int64 sqlite3_api->uri_int64
110247 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
110248 #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
110249 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
110250 /* Version 3.8.7 and later */
110251 #define sqlite3_auto_extension sqlite3_api->auto_extension
110252 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
110253 #define sqlite3_bind_text64 sqlite3_api->bind_text64
110254 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
110255 #define sqlite3_load_extension sqlite3_api->load_extension
110256 #define sqlite3_malloc64 sqlite3_api->malloc64
110257 #define sqlite3_msize sqlite3_api->msize
110258 #define sqlite3_realloc64 sqlite3_api->realloc64
110259 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
110260 #define sqlite3_result_blob64 sqlite3_api->result_blob64
110261 #define sqlite3_result_text64 sqlite3_api->result_text64
110262 #define sqlite3_strglob sqlite3_api->strglob
110263 /* Version 3.8.11 and later */
110264 #define sqlite3_value_dup sqlite3_api->value_dup
110265 #define sqlite3_value_free sqlite3_api->value_free
110266 #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
110267 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
110268 /* Version 3.9.0 and later */
110269 #define sqlite3_value_subtype sqlite3_api->value_subtype
110270 #define sqlite3_result_subtype sqlite3_api->result_subtype
110271 /* Version 3.10.0 and later */
110272 #define sqlite3_status64 sqlite3_api->status64
110273 #define sqlite3_strlike sqlite3_api->strlike
110274 #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
110275 /* Version 3.12.0 and later */
110276 #define sqlite3_system_errno sqlite3_api->system_errno
110277 /* Version 3.14.0 and later */
110278 #define sqlite3_trace_v2 sqlite3_api->trace_v2
110279 #define sqlite3_expanded_sql sqlite3_api->expanded_sql
110280 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
110281 
110282 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
110283  /* This case when the file really is being compiled as a loadable
110284  ** extension */
110285 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
110286 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
110287 # define SQLITE_EXTENSION_INIT3 \
110288  extern const sqlite3_api_routines *sqlite3_api;
110289 #else
110290  /* This case when the file is being statically linked into the
110291  ** application */
110292 # define SQLITE_EXTENSION_INIT1 /*no-op*/
110293 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
110294 # define SQLITE_EXTENSION_INIT3 /*no-op*/
110295 #endif
110296 
110297 #endif /* SQLITE3EXT_H */
110298 
110299 /************** End of sqlite3ext.h ******************************************/
110300 /************** Continuing where we left off in loadext.c ********************/
110301 /* #include "sqliteInt.h" */
110302 /* #include <string.h> */
110303 
110304 #ifndef SQLITE_OMIT_LOAD_EXTENSION
110305 /*
110306 ** Some API routines are omitted when various features are
110307 ** excluded from a build of SQLite. Substitute a NULL pointer
110308 ** for any missing APIs.
110309 */
110310 #ifndef SQLITE_ENABLE_COLUMN_METADATA
110311 # define sqlite3_column_database_name 0
110312 # define sqlite3_column_database_name16 0
110313 # define sqlite3_column_table_name 0
110314 # define sqlite3_column_table_name16 0
110315 # define sqlite3_column_origin_name 0
110316 # define sqlite3_column_origin_name16 0
110317 #endif
110318 
110319 #ifdef SQLITE_OMIT_AUTHORIZATION
110320 # define sqlite3_set_authorizer 0
110321 #endif
110322 
110323 #ifdef SQLITE_OMIT_UTF16
110324 # define sqlite3_bind_text16 0
110325 # define sqlite3_collation_needed16 0
110326 # define sqlite3_column_decltype16 0
110327 # define sqlite3_column_name16 0
110328 # define sqlite3_column_text16 0
110329 # define sqlite3_complete16 0
110330 # define sqlite3_create_collation16 0
110331 # define sqlite3_create_function16 0
110332 # define sqlite3_errmsg16 0
110333 # define sqlite3_open16 0
110334 # define sqlite3_prepare16 0
110335 # define sqlite3_prepare16_v2 0
110336 # define sqlite3_result_error16 0
110337 # define sqlite3_result_text16 0
110338 # define sqlite3_result_text16be 0
110339 # define sqlite3_result_text16le 0
110340 # define sqlite3_value_text16 0
110341 # define sqlite3_value_text16be 0
110342 # define sqlite3_value_text16le 0
110343 # define sqlite3_column_database_name16 0
110344 # define sqlite3_column_table_name16 0
110345 # define sqlite3_column_origin_name16 0
110346 #endif
110347 
110348 #ifdef SQLITE_OMIT_COMPLETE
110349 # define sqlite3_complete 0
110350 # define sqlite3_complete16 0
110351 #endif
110352 
110353 #ifdef SQLITE_OMIT_DECLTYPE
110354 # define sqlite3_column_decltype16 0
110355 # define sqlite3_column_decltype 0
110356 #endif
110357 
110358 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
110359 # define sqlite3_progress_handler 0
110360 #endif
110361 
110362 #ifdef SQLITE_OMIT_VIRTUALTABLE
110363 # define sqlite3_create_module 0
110364 # define sqlite3_create_module_v2 0
110365 # define sqlite3_declare_vtab 0
110366 # define sqlite3_vtab_config 0
110367 # define sqlite3_vtab_on_conflict 0
110368 #endif
110369 
110370 #ifdef SQLITE_OMIT_SHARED_CACHE
110371 # define sqlite3_enable_shared_cache 0
110372 #endif
110373 
110374 #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
110375 # define sqlite3_profile 0
110376 # define sqlite3_trace 0
110377 #endif
110378 
110379 #ifdef SQLITE_OMIT_GET_TABLE
110380 # define sqlite3_free_table 0
110381 # define sqlite3_get_table 0
110382 #endif
110383 
110384 #ifdef SQLITE_OMIT_INCRBLOB
110385 #define sqlite3_bind_zeroblob 0
110386 #define sqlite3_blob_bytes 0
110387 #define sqlite3_blob_close 0
110388 #define sqlite3_blob_open 0
110389 #define sqlite3_blob_read 0
110390 #define sqlite3_blob_write 0
110391 #define sqlite3_blob_reopen 0
110392 #endif
110393 
110394 #if defined(SQLITE_OMIT_TRACE)
110395 # define sqlite3_trace_v2 0
110396 #endif
110397 
110398 /*
110399 ** The following structure contains pointers to all SQLite API routines.
110400 ** A pointer to this structure is passed into extensions when they are
110401 ** loaded so that the extension can make calls back into the SQLite
110402 ** library.
110403 **
110404 ** When adding new APIs, add them to the bottom of this structure
110405 ** in order to preserve backwards compatibility.
110406 **
110407 ** Extensions that use newer APIs should first call the
110408 ** sqlite3_libversion_number() to make sure that the API they
110409 ** intend to use is supported by the library. Extensions should
110410 ** also check to make sure that the pointer to the function is
110411 ** not NULL before calling it.
110412 */
110415 #ifndef SQLITE_OMIT_DEPRECATED
110417 #else
110418  0,
110419 #endif
110433  sqlite3_changes,
110434  sqlite3_close,
110470  sqlite3_errcode,
110471  sqlite3_errmsg,
110473  sqlite3_exec,
110474 #ifndef SQLITE_OMIT_DEPRECATED
110475  sqlite3_expired,
110476 #else
110477  0,
110478 #endif
110480  sqlite3_free,
110485  0, /* Was sqlite3_global_recover(), but that function is deprecated */
110490  sqlite3_malloc,
110491  sqlite3_mprintf,
110492  sqlite3_open,
110493  sqlite3_open16,
110494  sqlite3_prepare,
110496  sqlite3_profile,
110498  sqlite3_realloc,
110499  sqlite3_reset,
110516  sqlite3_step,
110518 #ifndef SQLITE_OMIT_DEPRECATED
110520 #else
110521  0,
110522 #endif
110524  sqlite3_trace,
110525 #ifndef SQLITE_OMIT_DEPRECATED
110527 #else
110528  0,
110529 #endif
110545  /*
110546  ** The original API set ends here. All extensions can call any
110547  ** of the APIs above provided that the pointer is not NULL. But
110548  ** before calling APIs that follow, extension should check the
110549  ** sqlite3_libversion_number() to make sure they are dealing with
110550  ** a library that is new enough to support that API.
110551  *************************************************************************
110552  */
110554 
110555  /*
110556  ** Added after 3.3.13
110557  */
110561 
110562  /*
110563  ** Added for 3.4.1
110564  */
110566 
110567  /*
110568  ** Added for 3.5.0
110569  */
110580 #ifdef SQLITE_MUTEX_OMIT
110581  0,
110582  0,
110583  0,
110584  0,
110585  0,
110586 #else
110592 #endif
110593  sqlite3_open_v2,
110597  sqlite3_sleep,
110602 
110603  /*
110604  ** Added for 3.5.8
110605  */
110612 
110613  /*
110614  ** Added for 3.6.0
110615  */
110617  sqlite3_limit,
110619  sqlite3_sql,
110620  sqlite3_status,
110621 
110622  /*
110623  ** Added for 3.7.4
110624  */
110630 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
110633 #else
110634  0,
110635  0,
110636 #endif
110642  sqlite3_log,
110647 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
110649 #else
110650  0,
110651 #endif
110652 #ifndef SQLITE_OMIT_WAL
110656 #else
110657  0,
110658  0,
110659  0,
110660 #endif
110668  sqlite3_errstr,
110671  sqlite3_stricmp,
110677  /* Version 3.8.7 and later */
110684  sqlite3_msize,
110689  sqlite3_strglob,
110690  /* Version 3.8.11 and later */
110695  /* Version 3.9.0 and later */
110698  /* Version 3.10.0 and later */
110700  sqlite3_strlike,
110702  /* Version 3.12.0 and later */
110704  /* Version 3.14.0 and later */
110707 };
110708 
110709 /*
110710 ** Attempt to load an SQLite extension library contained in the file
110711 ** zFile. The entry point is zProc. zProc may be 0 in which case a
110712 ** default entry point name (sqlite3_extension_init) is used. Use
110713 ** of the default name is recommended.
110714 **
110715 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
110716 **
110717 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
110718 ** error message text. The calling function should free this memory
110719 ** by calling sqlite3DbFree(db, ).
110720 */
110722  sqlite3 *db, /* Load the extension into this database connection */
110723  const char *zFile, /* Name of the shared library containing extension */
110724  const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
110725  char **pzErrMsg /* Put error message here if not 0 */
110726 ){
110727  sqlite3_vfs *pVfs = db->pVfs;
110728  void *handle;
110729  sqlite3_loadext_entry xInit;
110730  char *zErrmsg = 0;
110731  const char *zEntry;
110732  char *zAltEntry = 0;
110733  void **aHandle;
110734  u64 nMsg = 300 + sqlite3Strlen30(zFile);
110735  int ii;
110736  int rc;
110737 
110738  /* Shared library endings to try if zFile cannot be loaded as written */
110739  static const char *azEndings[] = {
110740 #if SQLITE_OS_WIN
110741  "dll"
110742 #elif defined(__APPLE__)
110743  "dylib"
110744 #else
110745  "so"
110746 #endif
110747  };
110748 
110749 
110750  if( pzErrMsg ) *pzErrMsg = 0;
110751 
110752  /* Ticket #1863. To avoid a creating security problems for older
110753  ** applications that relink against newer versions of SQLite, the
110754  ** ability to run load_extension is turned off by default. One
110755  ** must call either sqlite3_enable_load_extension(db) or
110756  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
110757  ** to turn on extension loading.
110758  */
110759  if( (db->flags & SQLITE_LoadExtension)==0 ){
110760  if( pzErrMsg ){
110761  *pzErrMsg = sqlite3_mprintf("not authorized");
110762  }
110763  return SQLITE_ERROR;
110764  }
110765 
110766  zEntry = zProc ? zProc : "sqlite3_extension_init";
110767 
110768  handle = sqlite3OsDlOpen(pVfs, zFile);
110769 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
110770  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
110771  char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
110772  if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
110773  handle = sqlite3OsDlOpen(pVfs, zAltFile);
110774  sqlite3_free(zAltFile);
110775  }
110776 #endif
110777  if( handle==0 ){
110778  if( pzErrMsg ){
110779  *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
110780  if( zErrmsg ){
110781  sqlite3_snprintf(nMsg, zErrmsg,
110782  "unable to open shared library [%s]", zFile);
110783  sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
110784  }
110785  }
110786  return SQLITE_ERROR;
110787  }
110788  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
110789 
110790  /* If no entry point was specified and the default legacy
110791  ** entry point name "sqlite3_extension_init" was not found, then
110792  ** construct an entry point name "sqlite3_X_init" where the X is
110793  ** replaced by the lowercase value of every ASCII alphabetic
110794  ** character in the filename after the last "/" upto the first ".",
110795  ** and eliding the first three characters if they are "lib".
110796  ** Examples:
110797  **
110798  ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
110799  ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
110800  */
110801  if( xInit==0 && zProc==0 ){
110802  int iFile, iEntry, c;
110803  int ncFile = sqlite3Strlen30(zFile);
110804  zAltEntry = sqlite3_malloc64(ncFile+30);
110805  if( zAltEntry==0 ){
110806  sqlite3OsDlClose(pVfs, handle);
110807  return SQLITE_NOMEM_BKPT;
110808  }
110809  memcpy(zAltEntry, "sqlite3_", 8);
110810  for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
110811  iFile++;
110812  if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
110813  for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
110814  if( sqlite3Isalpha(c) ){
110815  zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
110816  }
110817  }
110818  memcpy(zAltEntry+iEntry, "_init", 6);
110819  zEntry = zAltEntry;
110820  xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
110821  }
110822  if( xInit==0 ){
110823  if( pzErrMsg ){
110824  nMsg += sqlite3Strlen30(zEntry);
110825  *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
110826  if( zErrmsg ){
110827  sqlite3_snprintf(nMsg, zErrmsg,
110828  "no entry point [%s] in shared library [%s]", zEntry, zFile);
110829  sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
110830  }
110831  }
110832  sqlite3OsDlClose(pVfs, handle);
110833  sqlite3_free(zAltEntry);
110834  return SQLITE_ERROR;
110835  }
110836  sqlite3_free(zAltEntry);
110837  rc = xInit(db, &zErrmsg, &sqlite3Apis);
110838  if( rc ){
110839  if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
110840  if( pzErrMsg ){
110841  *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
110842  }
110843  sqlite3_free(zErrmsg);
110844  sqlite3OsDlClose(pVfs, handle);
110845  return SQLITE_ERROR;
110846  }
110847 
110848  /* Append the new shared library handle to the db->aExtension array. */
110849  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
110850  if( aHandle==0 ){
110851  return SQLITE_NOMEM_BKPT;
110852  }
110853  if( db->nExtension>0 ){
110854  memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
110855  }
110856  sqlite3DbFree(db, db->aExtension);
110857  db->aExtension = aHandle;
110858 
110859  db->aExtension[db->nExtension++] = handle;
110860  return SQLITE_OK;
110861 }
110863  sqlite3 *db, /* Load the extension into this database connection */
110864  const char *zFile, /* Name of the shared library containing extension */
110865  const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
110866  char **pzErrMsg /* Put error message here if not 0 */
110867 ){
110868  int rc;
110869  sqlite3_mutex_enter(db->mutex);
110870  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
110871  rc = sqlite3ApiExit(db, rc);
110872  sqlite3_mutex_leave(db->mutex);
110873  return rc;
110874 }
110875 
110876 /*
110877 ** Call this routine when the database connection is closing in order
110878 ** to clean up loaded extensions
110879 */
110881  int i;
110882  assert( sqlite3_mutex_held(db->mutex) );
110883  for(i=0; i<db->nExtension; i++){
110884  sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
110885  }
110886  sqlite3DbFree(db, db->aExtension);
110887 }
110888 
110889 /*
110890 ** Enable or disable extension loading. Extension loading is disabled by
110891 ** default so as not to open security holes in older applications.
110892 */
110893 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
110894  sqlite3_mutex_enter(db->mutex);
110895  if( onoff ){
110897  }else{
110899  }
110900  sqlite3_mutex_leave(db->mutex);
110901  return SQLITE_OK;
110902 }
110903 
110904 #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
110905 
110906 /*
110907 ** The following object holds the list of automatically loaded
110908 ** extensions.
110909 **
110910 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
110911 ** mutex must be held while accessing this list.
110912 */
110915  u32 nExt; /* Number of entries in aExt[] */
110916  void (**aExt)(void); /* Pointers to the extension init functions */
110917 } sqlite3Autoext = { 0, 0 };
110918 
110919 /* The "wsdAutoext" macro will resolve to the autoextension
110920 ** state vector. If writable static data is unsupported on the target,
110921 ** we have to locate the state vector at run-time. In the more common
110922 ** case where writable static data is supported, wsdStat can refer directly
110923 ** to the "sqlite3Autoext" state vector declared above.
110924 */
110925 #ifdef SQLITE_OMIT_WSD
110926 # define wsdAutoextInit \
110927  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
110928 # define wsdAutoext x[0]
110929 #else
110930 # define wsdAutoextInit
110931 # define wsdAutoext sqlite3Autoext
110932 #endif
110933 
110934 
110935 /*
110936 ** Register a statically linked extension that is automatically
110937 ** loaded by every new database connection.
110938 */
110940  void (*xInit)(void)
110941 ){
110942  int rc = SQLITE_OK;
110943 #ifndef SQLITE_OMIT_AUTOINIT
110944  rc = sqlite3_initialize();
110945  if( rc ){
110946  return rc;
110947  }else
110948 #endif
110949  {
110950  u32 i;
110951 #if SQLITE_THREADSAFE
110953 #endif
110954  wsdAutoextInit;
110955  sqlite3_mutex_enter(mutex);
110956  for(i=0; i<wsdAutoext.nExt; i++){
110957  if( wsdAutoext.aExt[i]==xInit ) break;
110958  }
110959  if( i==wsdAutoext.nExt ){
110960  u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
110961  void (**aNew)(void);
110962  aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
110963  if( aNew==0 ){
110964  rc = SQLITE_NOMEM_BKPT;
110965  }else{
110966  wsdAutoext.aExt = aNew;
110967  wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
110968  wsdAutoext.nExt++;
110969  }
110970  }
110971  sqlite3_mutex_leave(mutex);
110972  assert( (rc&0xff)==rc );
110973  return rc;
110974  }
110975 }
110976 
110977 /*
110978 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
110979 ** set of routines that is invoked for each new database connection, if it
110980 ** is currently on the list. If xInit is not on the list, then this
110981 ** routine is a no-op.
110982 **
110983 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
110984 ** was not on the list.
110985 */
110987  void (*xInit)(void)
110988 ){
110989 #if SQLITE_THREADSAFE
110991 #endif
110992  int i;
110993  int n = 0;
110994  wsdAutoextInit;
110995  sqlite3_mutex_enter(mutex);
110996  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
110997  if( wsdAutoext.aExt[i]==xInit ){
110998  wsdAutoext.nExt--;
110999  wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
111000  n++;
111001  break;
111002  }
111003  }
111004  sqlite3_mutex_leave(mutex);
111005  return n;
111006 }
111007 
111008 /*
111009 ** Reset the automatic extension loading mechanism.
111010 */
111012 #ifndef SQLITE_OMIT_AUTOINIT
111013  if( sqlite3_initialize()==SQLITE_OK )
111014 #endif
111015  {
111016 #if SQLITE_THREADSAFE
111018 #endif
111019  wsdAutoextInit;
111020  sqlite3_mutex_enter(mutex);
111021  sqlite3_free(wsdAutoext.aExt);
111022  wsdAutoext.aExt = 0;
111023  wsdAutoext.nExt = 0;
111024  sqlite3_mutex_leave(mutex);
111025  }
111026 }
111027 
111028 /*
111029 ** Load all automatic extensions.
111030 **
111031 ** If anything goes wrong, set an error in the database connection.
111032 */
111034  u32 i;
111035  int go = 1;
111036  int rc;
111037  sqlite3_loadext_entry xInit;
111038 
111039  wsdAutoextInit;
111040  if( wsdAutoext.nExt==0 ){
111041  /* Common case: early out without every having to acquire a mutex */
111042  return;
111043  }
111044  for(i=0; go; i++){
111045  char *zErrmsg;
111046 #if SQLITE_THREADSAFE
111048 #endif
111049 #ifdef SQLITE_OMIT_LOAD_EXTENSION
111050  const sqlite3_api_routines *pThunk = 0;
111051 #else
111052  const sqlite3_api_routines *pThunk = &sqlite3Apis;
111053 #endif
111054  sqlite3_mutex_enter(mutex);
111055  if( i>=wsdAutoext.nExt ){
111056  xInit = 0;
111057  go = 0;
111058  }else{
111059  xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
111060  }
111061  sqlite3_mutex_leave(mutex);
111062  zErrmsg = 0;
111063  if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
111064  sqlite3ErrorWithMsg(db, rc,
111065  "automatic extension loading failed: %s", zErrmsg);
111066  go = 0;
111067  }
111068  sqlite3_free(zErrmsg);
111069  }
111070 }
111071 
111072 /************** End of loadext.c *********************************************/
111073 /************** Begin file pragma.c ******************************************/
111074 /*
111075 ** 2003 April 6
111076 **
111077 ** The author disclaims copyright to this source code. In place of
111078 ** a legal notice, here is a blessing:
111079 **
111080 ** May you do good and not evil.
111081 ** May you find forgiveness for yourself and forgive others.
111082 ** May you share freely, never taking more than you give.
111083 **
111084 *************************************************************************
111085 ** This file contains code used to implement the PRAGMA command.
111086 */
111087 /* #include "sqliteInt.h" */
111088 
111089 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
111090 # if defined(__APPLE__)
111091 # define SQLITE_ENABLE_LOCKING_STYLE 1
111092 # else
111093 # define SQLITE_ENABLE_LOCKING_STYLE 0
111094 # endif
111095 #endif
111096 
111097 /***************************************************************************
111098 ** The "pragma.h" include file is an automatically generated file that
111099 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
111100 ** object. This ensures that the aPragmaName[] table is arranged in
111101 ** lexicographical order to facility a binary search of the pragma name.
111102 ** Do not edit pragma.h directly. Edit and rerun the script in at
111103 ** ../tool/mkpragmatab.tcl. */
111104 /************** Include pragma.h in the middle of pragma.c *******************/
111105 /************** Begin file pragma.h ******************************************/
111106 /* DO NOT EDIT!
111107 ** This file is automatically generated by the script at
111108 ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
111109 ** that script and rerun it.
111110 */
111111 #define PragTyp_HEADER_VALUE 0
111112 #define PragTyp_AUTO_VACUUM 1
111113 #define PragTyp_FLAG 2
111114 #define PragTyp_BUSY_TIMEOUT 3
111115 #define PragTyp_CACHE_SIZE 4
111116 #define PragTyp_CACHE_SPILL 5
111117 #define PragTyp_CASE_SENSITIVE_LIKE 6
111118 #define PragTyp_COLLATION_LIST 7
111119 #define PragTyp_COMPILE_OPTIONS 8
111120 #define PragTyp_DATA_STORE_DIRECTORY 9
111121 #define PragTyp_DATABASE_LIST 10
111122 #define PragTyp_DEFAULT_CACHE_SIZE 11
111123 #define PragTyp_ENCODING 12
111124 #define PragTyp_FOREIGN_KEY_CHECK 13
111125 #define PragTyp_FOREIGN_KEY_LIST 14
111126 #define PragTyp_INCREMENTAL_VACUUM 15
111127 #define PragTyp_INDEX_INFO 16
111128 #define PragTyp_INDEX_LIST 17
111129 #define PragTyp_INTEGRITY_CHECK 18
111130 #define PragTyp_JOURNAL_MODE 19
111131 #define PragTyp_JOURNAL_SIZE_LIMIT 20
111132 #define PragTyp_LOCK_PROXY_FILE 21
111133 #define PragTyp_LOCKING_MODE 22
111134 #define PragTyp_PAGE_COUNT 23
111135 #define PragTyp_MMAP_SIZE 24
111136 #define PragTyp_PAGE_SIZE 25
111137 #define PragTyp_SECURE_DELETE 26
111138 #define PragTyp_SHRINK_MEMORY 27
111139 #define PragTyp_SOFT_HEAP_LIMIT 28
111140 #define PragTyp_STATS 29
111141 #define PragTyp_SYNCHRONOUS 30
111142 #define PragTyp_TABLE_INFO 31
111143 #define PragTyp_TEMP_STORE 32
111144 #define PragTyp_TEMP_STORE_DIRECTORY 33
111145 #define PragTyp_THREADS 34
111146 #define PragTyp_WAL_AUTOCHECKPOINT 35
111147 #define PragTyp_WAL_CHECKPOINT 36
111148 #define PragTyp_ACTIVATE_EXTENSIONS 37
111149 #define PragTyp_HEXKEY 38
111150 #define PragTyp_KEY 39
111151 #define PragTyp_REKEY 40
111152 #define PragTyp_LOCK_STATUS 41
111153 #define PragTyp_PARSER_TRACE 42
111154 #define PragFlag_NeedSchema 0x01
111155 #define PragFlag_ReadOnly 0x02
111156 static const struct sPragmaNames {
111157  const char *const zName; /* Name of pragma */
111158  u8 ePragTyp; /* PragTyp_XXX value */
111159  u8 mPragFlag; /* Zero or more PragFlag_XXX values */
111160  u32 iArg; /* Extra argument */
111161 } aPragmaNames[] = {
111162 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
111163  { /* zName: */ "activate_extensions",
111164  /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
111165  /* ePragFlag: */ 0,
111166  /* iArg: */ 0 },
111167 #endif
111168 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111169  { /* zName: */ "application_id",
111170  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111171  /* ePragFlag: */ 0,
111172  /* iArg: */ BTREE_APPLICATION_ID },
111173 #endif
111174 #if !defined(SQLITE_OMIT_AUTOVACUUM)
111175  { /* zName: */ "auto_vacuum",
111176  /* ePragTyp: */ PragTyp_AUTO_VACUUM,
111177  /* ePragFlag: */ PragFlag_NeedSchema,
111178  /* iArg: */ 0 },
111179 #endif
111180 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111181 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
111182  { /* zName: */ "automatic_index",
111183  /* ePragTyp: */ PragTyp_FLAG,
111184  /* ePragFlag: */ 0,
111185  /* iArg: */ SQLITE_AutoIndex },
111186 #endif
111187 #endif
111188  { /* zName: */ "busy_timeout",
111189  /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
111190  /* ePragFlag: */ 0,
111191  /* iArg: */ 0 },
111192 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111193  { /* zName: */ "cache_size",
111194  /* ePragTyp: */ PragTyp_CACHE_SIZE,
111195  /* ePragFlag: */ PragFlag_NeedSchema,
111196  /* iArg: */ 0 },
111197 #endif
111198 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111199  { /* zName: */ "cache_spill",
111200  /* ePragTyp: */ PragTyp_CACHE_SPILL,
111201  /* ePragFlag: */ 0,
111202  /* iArg: */ 0 },
111203 #endif
111204  { /* zName: */ "case_sensitive_like",
111205  /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
111206  /* ePragFlag: */ 0,
111207  /* iArg: */ 0 },
111208  { /* zName: */ "cell_size_check",
111209  /* ePragTyp: */ PragTyp_FLAG,
111210  /* ePragFlag: */ 0,
111211  /* iArg: */ SQLITE_CellSizeCk },
111212 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111213  { /* zName: */ "checkpoint_fullfsync",
111214  /* ePragTyp: */ PragTyp_FLAG,
111215  /* ePragFlag: */ 0,
111216  /* iArg: */ SQLITE_CkptFullFSync },
111217 #endif
111218 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111219  { /* zName: */ "collation_list",
111220  /* ePragTyp: */ PragTyp_COLLATION_LIST,
111221  /* ePragFlag: */ 0,
111222  /* iArg: */ 0 },
111223 #endif
111224 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
111225  { /* zName: */ "compile_options",
111226  /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
111227  /* ePragFlag: */ 0,
111228  /* iArg: */ 0 },
111229 #endif
111230 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111231  { /* zName: */ "count_changes",
111232  /* ePragTyp: */ PragTyp_FLAG,
111233  /* ePragFlag: */ 0,
111234  /* iArg: */ SQLITE_CountRows },
111235 #endif
111236 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
111237  { /* zName: */ "data_store_directory",
111238  /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
111239  /* ePragFlag: */ 0,
111240  /* iArg: */ 0 },
111241 #endif
111242 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111243  { /* zName: */ "data_version",
111244  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111245  /* ePragFlag: */ PragFlag_ReadOnly,
111246  /* iArg: */ BTREE_DATA_VERSION },
111247 #endif
111248 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111249  { /* zName: */ "database_list",
111250  /* ePragTyp: */ PragTyp_DATABASE_LIST,
111251  /* ePragFlag: */ PragFlag_NeedSchema,
111252  /* iArg: */ 0 },
111253 #endif
111254 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
111255  { /* zName: */ "default_cache_size",
111256  /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
111257  /* ePragFlag: */ PragFlag_NeedSchema,
111258  /* iArg: */ 0 },
111259 #endif
111260 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111261 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
111262  { /* zName: */ "defer_foreign_keys",
111263  /* ePragTyp: */ PragTyp_FLAG,
111264  /* ePragFlag: */ 0,
111265  /* iArg: */ SQLITE_DeferFKs },
111266 #endif
111267 #endif
111268 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111269  { /* zName: */ "empty_result_callbacks",
111270  /* ePragTyp: */ PragTyp_FLAG,
111271  /* ePragFlag: */ 0,
111272  /* iArg: */ SQLITE_NullCallback },
111273 #endif
111274 #if !defined(SQLITE_OMIT_UTF16)
111275  { /* zName: */ "encoding",
111276  /* ePragTyp: */ PragTyp_ENCODING,
111277  /* ePragFlag: */ 0,
111278  /* iArg: */ 0 },
111279 #endif
111280 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
111281  { /* zName: */ "foreign_key_check",
111282  /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
111283  /* ePragFlag: */ PragFlag_NeedSchema,
111284  /* iArg: */ 0 },
111285 #endif
111286 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
111287  { /* zName: */ "foreign_key_list",
111288  /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
111289  /* ePragFlag: */ PragFlag_NeedSchema,
111290  /* iArg: */ 0 },
111291 #endif
111292 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111293 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
111294  { /* zName: */ "foreign_keys",
111295  /* ePragTyp: */ PragTyp_FLAG,
111296  /* ePragFlag: */ 0,
111297  /* iArg: */ SQLITE_ForeignKeys },
111298 #endif
111299 #endif
111300 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111301  { /* zName: */ "freelist_count",
111302  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111303  /* ePragFlag: */ PragFlag_ReadOnly,
111304  /* iArg: */ BTREE_FREE_PAGE_COUNT },
111305 #endif
111306 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111307  { /* zName: */ "full_column_names",
111308  /* ePragTyp: */ PragTyp_FLAG,
111309  /* ePragFlag: */ 0,
111310  /* iArg: */ SQLITE_FullColNames },
111311  { /* zName: */ "fullfsync",
111312  /* ePragTyp: */ PragTyp_FLAG,
111313  /* ePragFlag: */ 0,
111314  /* iArg: */ SQLITE_FullFSync },
111315 #endif
111316 #if defined(SQLITE_HAS_CODEC)
111317  { /* zName: */ "hexkey",
111318  /* ePragTyp: */ PragTyp_HEXKEY,
111319  /* ePragFlag: */ 0,
111320  /* iArg: */ 0 },
111321  { /* zName: */ "hexrekey",
111322  /* ePragTyp: */ PragTyp_HEXKEY,
111323  /* ePragFlag: */ 0,
111324  /* iArg: */ 0 },
111325 #endif
111326 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111327 #if !defined(SQLITE_OMIT_CHECK)
111328  { /* zName: */ "ignore_check_constraints",
111329  /* ePragTyp: */ PragTyp_FLAG,
111330  /* ePragFlag: */ 0,
111331  /* iArg: */ SQLITE_IgnoreChecks },
111332 #endif
111333 #endif
111334 #if !defined(SQLITE_OMIT_AUTOVACUUM)
111335  { /* zName: */ "incremental_vacuum",
111336  /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
111337  /* ePragFlag: */ PragFlag_NeedSchema,
111338  /* iArg: */ 0 },
111339 #endif
111340 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111341  { /* zName: */ "index_info",
111342  /* ePragTyp: */ PragTyp_INDEX_INFO,
111343  /* ePragFlag: */ PragFlag_NeedSchema,
111344  /* iArg: */ 0 },
111345  { /* zName: */ "index_list",
111346  /* ePragTyp: */ PragTyp_INDEX_LIST,
111347  /* ePragFlag: */ PragFlag_NeedSchema,
111348  /* iArg: */ 0 },
111349  { /* zName: */ "index_xinfo",
111350  /* ePragTyp: */ PragTyp_INDEX_INFO,
111351  /* ePragFlag: */ PragFlag_NeedSchema,
111352  /* iArg: */ 1 },
111353 #endif
111354 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
111355  { /* zName: */ "integrity_check",
111356  /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
111357  /* ePragFlag: */ PragFlag_NeedSchema,
111358  /* iArg: */ 0 },
111359 #endif
111360 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111361  { /* zName: */ "journal_mode",
111362  /* ePragTyp: */ PragTyp_JOURNAL_MODE,
111363  /* ePragFlag: */ PragFlag_NeedSchema,
111364  /* iArg: */ 0 },
111365  { /* zName: */ "journal_size_limit",
111366  /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
111367  /* ePragFlag: */ 0,
111368  /* iArg: */ 0 },
111369 #endif
111370 #if defined(SQLITE_HAS_CODEC)
111371  { /* zName: */ "key",
111372  /* ePragTyp: */ PragTyp_KEY,
111373  /* ePragFlag: */ 0,
111374  /* iArg: */ 0 },
111375 #endif
111376 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111377  { /* zName: */ "legacy_file_format",
111378  /* ePragTyp: */ PragTyp_FLAG,
111379  /* ePragFlag: */ 0,
111380  /* iArg: */ SQLITE_LegacyFileFmt },
111381 #endif
111382 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
111383  { /* zName: */ "lock_proxy_file",
111384  /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
111385  /* ePragFlag: */ 0,
111386  /* iArg: */ 0 },
111387 #endif
111388 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
111389  { /* zName: */ "lock_status",
111390  /* ePragTyp: */ PragTyp_LOCK_STATUS,
111391  /* ePragFlag: */ 0,
111392  /* iArg: */ 0 },
111393 #endif
111394 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111395  { /* zName: */ "locking_mode",
111396  /* ePragTyp: */ PragTyp_LOCKING_MODE,
111397  /* ePragFlag: */ 0,
111398  /* iArg: */ 0 },
111399  { /* zName: */ "max_page_count",
111400  /* ePragTyp: */ PragTyp_PAGE_COUNT,
111401  /* ePragFlag: */ PragFlag_NeedSchema,
111402  /* iArg: */ 0 },
111403  { /* zName: */ "mmap_size",
111404  /* ePragTyp: */ PragTyp_MMAP_SIZE,
111405  /* ePragFlag: */ 0,
111406  /* iArg: */ 0 },
111407  { /* zName: */ "page_count",
111408  /* ePragTyp: */ PragTyp_PAGE_COUNT,
111409  /* ePragFlag: */ PragFlag_NeedSchema,
111410  /* iArg: */ 0 },
111411  { /* zName: */ "page_size",
111412  /* ePragTyp: */ PragTyp_PAGE_SIZE,
111413  /* ePragFlag: */ 0,
111414  /* iArg: */ 0 },
111415 #endif
111416 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
111417  { /* zName: */ "parser_trace",
111418  /* ePragTyp: */ PragTyp_PARSER_TRACE,
111419  /* ePragFlag: */ 0,
111420  /* iArg: */ 0 },
111421 #endif
111422 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111423  { /* zName: */ "query_only",
111424  /* ePragTyp: */ PragTyp_FLAG,
111425  /* ePragFlag: */ 0,
111426  /* iArg: */ SQLITE_QueryOnly },
111427 #endif
111428 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
111429  { /* zName: */ "quick_check",
111430  /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
111431  /* ePragFlag: */ PragFlag_NeedSchema,
111432  /* iArg: */ 0 },
111433 #endif
111434 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111435  { /* zName: */ "read_uncommitted",
111436  /* ePragTyp: */ PragTyp_FLAG,
111437  /* ePragFlag: */ 0,
111438  /* iArg: */ SQLITE_ReadUncommitted },
111439  { /* zName: */ "recursive_triggers",
111440  /* ePragTyp: */ PragTyp_FLAG,
111441  /* ePragFlag: */ 0,
111442  /* iArg: */ SQLITE_RecTriggers },
111443 #endif
111444 #if defined(SQLITE_HAS_CODEC)
111445  { /* zName: */ "rekey",
111446  /* ePragTyp: */ PragTyp_REKEY,
111447  /* ePragFlag: */ 0,
111448  /* iArg: */ 0 },
111449 #endif
111450 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111451  { /* zName: */ "reverse_unordered_selects",
111452  /* ePragTyp: */ PragTyp_FLAG,
111453  /* ePragFlag: */ 0,
111454  /* iArg: */ SQLITE_ReverseOrder },
111455 #endif
111456 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111457  { /* zName: */ "schema_version",
111458  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111459  /* ePragFlag: */ 0,
111460  /* iArg: */ BTREE_SCHEMA_VERSION },
111461 #endif
111462 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111463  { /* zName: */ "secure_delete",
111464  /* ePragTyp: */ PragTyp_SECURE_DELETE,
111465  /* ePragFlag: */ 0,
111466  /* iArg: */ 0 },
111467 #endif
111468 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111469  { /* zName: */ "short_column_names",
111470  /* ePragTyp: */ PragTyp_FLAG,
111471  /* ePragFlag: */ 0,
111472  /* iArg: */ SQLITE_ShortColNames },
111473 #endif
111474  { /* zName: */ "shrink_memory",
111475  /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
111476  /* ePragFlag: */ 0,
111477  /* iArg: */ 0 },
111478  { /* zName: */ "soft_heap_limit",
111479  /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
111480  /* ePragFlag: */ 0,
111481  /* iArg: */ 0 },
111482 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111483 #if defined(SQLITE_DEBUG)
111484  { /* zName: */ "sql_trace",
111485  /* ePragTyp: */ PragTyp_FLAG,
111486  /* ePragFlag: */ 0,
111487  /* iArg: */ SQLITE_SqlTrace },
111488 #endif
111489 #endif
111490 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111491  { /* zName: */ "stats",
111492  /* ePragTyp: */ PragTyp_STATS,
111493  /* ePragFlag: */ PragFlag_NeedSchema,
111494  /* iArg: */ 0 },
111495 #endif
111496 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111497  { /* zName: */ "synchronous",
111498  /* ePragTyp: */ PragTyp_SYNCHRONOUS,
111499  /* ePragFlag: */ PragFlag_NeedSchema,
111500  /* iArg: */ 0 },
111501 #endif
111502 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
111503  { /* zName: */ "table_info",
111504  /* ePragTyp: */ PragTyp_TABLE_INFO,
111505  /* ePragFlag: */ PragFlag_NeedSchema,
111506  /* iArg: */ 0 },
111507 #endif
111508 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111509  { /* zName: */ "temp_store",
111510  /* ePragTyp: */ PragTyp_TEMP_STORE,
111511  /* ePragFlag: */ 0,
111512  /* iArg: */ 0 },
111513  { /* zName: */ "temp_store_directory",
111514  /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
111515  /* ePragFlag: */ 0,
111516  /* iArg: */ 0 },
111517 #endif
111518  { /* zName: */ "threads",
111519  /* ePragTyp: */ PragTyp_THREADS,
111520  /* ePragFlag: */ 0,
111521  /* iArg: */ 0 },
111522 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
111523  { /* zName: */ "user_version",
111524  /* ePragTyp: */ PragTyp_HEADER_VALUE,
111525  /* ePragFlag: */ 0,
111526  /* iArg: */ BTREE_USER_VERSION },
111527 #endif
111528 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111529 #if defined(SQLITE_DEBUG)
111530  { /* zName: */ "vdbe_addoptrace",
111531  /* ePragTyp: */ PragTyp_FLAG,
111532  /* ePragFlag: */ 0,
111533  /* iArg: */ SQLITE_VdbeAddopTrace },
111534  { /* zName: */ "vdbe_debug",
111535  /* ePragTyp: */ PragTyp_FLAG,
111536  /* ePragFlag: */ 0,
111537  /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
111538  { /* zName: */ "vdbe_eqp",
111539  /* ePragTyp: */ PragTyp_FLAG,
111540  /* ePragFlag: */ 0,
111541  /* iArg: */ SQLITE_VdbeEQP },
111542  { /* zName: */ "vdbe_listing",
111543  /* ePragTyp: */ PragTyp_FLAG,
111544  /* ePragFlag: */ 0,
111545  /* iArg: */ SQLITE_VdbeListing },
111546  { /* zName: */ "vdbe_trace",
111547  /* ePragTyp: */ PragTyp_FLAG,
111548  /* ePragFlag: */ 0,
111549  /* iArg: */ SQLITE_VdbeTrace },
111550 #endif
111551 #endif
111552 #if !defined(SQLITE_OMIT_WAL)
111553  { /* zName: */ "wal_autocheckpoint",
111554  /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
111555  /* ePragFlag: */ 0,
111556  /* iArg: */ 0 },
111557  { /* zName: */ "wal_checkpoint",
111558  /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
111559  /* ePragFlag: */ PragFlag_NeedSchema,
111560  /* iArg: */ 0 },
111561 #endif
111562 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
111563  { /* zName: */ "writable_schema",
111564  /* ePragTyp: */ PragTyp_FLAG,
111565  /* ePragFlag: */ 0,
111566  /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
111567 #endif
111568 };
111569 /* Number of pragmas: 60 on by default, 73 total. */
111570 
111571 /************** End of pragma.h **********************************************/
111572 /************** Continuing where we left off in pragma.c *********************/
111573 
111574 /*
111575 ** Interpret the given string as a safety level. Return 0 for OFF,
111576 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
111577 ** unrecognized string argument. The FULL and EXTRA option is disallowed
111578 ** if the omitFull parameter it 1.
111579 **
111580 ** Note that the values returned are one less that the values that
111581 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
111582 ** to support legacy SQL code. The safety level used to be boolean
111583 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
111584 */
111585 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
111586  /* 123456789 123456789 123 */
111587  static const char zText[] = "onoffalseyestruextrafull";
111588  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
111589  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
111590  static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
111591  /* on no off false yes true extra full */
111592  int i, n;
111593  if( sqlite3Isdigit(*z) ){
111594  return (u8)sqlite3Atoi(z);
111595  }
111596  n = sqlite3Strlen30(z);
111597  for(i=0; i<ArraySize(iLength); i++){
111598  if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
111599  && (!omitFull || iValue[i]<=1)
111600  ){
111601  return iValue[i];
111602  }
111603  }
111604  return dflt;
111605 }
111606 
111607 /*
111608 ** Interpret the given string as a boolean value.
111609 */
111610 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
111611  return getSafetyLevel(z,1,dflt)!=0;
111612 }
111613 
111614 /* The sqlite3GetBoolean() function is used by other modules but the
111615 ** remainder of this file is specific to PRAGMA processing. So omit
111616 ** the rest of the file if PRAGMAs are omitted from the build.
111617 */
111618 #if !defined(SQLITE_OMIT_PRAGMA)
111619 
111620 /*
111621 ** Interpret the given string as a locking mode value.
111622 */
111623 static int getLockingMode(const char *z){
111624  if( z ){
111625  if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
111626  if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
111627  }
111628  return PAGER_LOCKINGMODE_QUERY;
111629 }
111630 
111631 #ifndef SQLITE_OMIT_AUTOVACUUM
111632 /*
111633 ** Interpret the given string as an auto-vacuum mode value.
111634 **
111635 ** The following strings, "none", "full" and "incremental" are
111636 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
111637 */
111638 static int getAutoVacuum(const char *z){
111639  int i;
111640  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
111641  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
111642  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
111643  i = sqlite3Atoi(z);
111644  return (u8)((i>=0&&i<=2)?i:0);
111645 }
111646 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
111647 
111648 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111649 /*
111650 ** Interpret the given string as a temp db location. Return 1 for file
111651 ** backed temporary databases, 2 for the Red-Black tree in memory database
111652 ** and 0 to use the compile-time default.
111653 */
111654 static int getTempStore(const char *z){
111655  if( z[0]>='0' && z[0]<='2' ){
111656  return z[0] - '0';
111657  }else if( sqlite3StrICmp(z, "file")==0 ){
111658  return 1;
111659  }else if( sqlite3StrICmp(z, "memory")==0 ){
111660  return 2;
111661  }else{
111662  return 0;
111663  }
111664 }
111665 #endif /* SQLITE_PAGER_PRAGMAS */
111666 
111667 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111668 /*
111669 ** Invalidate temp storage, either when the temp storage is changed
111670 ** from default, or when 'file' and the temp_store_directory has changed
111671 */
111672 static int invalidateTempStorage(Parse *pParse){
111673  sqlite3 *db = pParse->db;
111674  if( db->aDb[1].pBt!=0 ){
111675  if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
111676  sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
111677  "from within a transaction");
111678  return SQLITE_ERROR;
111679  }
111680  sqlite3BtreeClose(db->aDb[1].pBt);
111681  db->aDb[1].pBt = 0;
111683  }
111684  return SQLITE_OK;
111685 }
111686 #endif /* SQLITE_PAGER_PRAGMAS */
111687 
111688 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111689 /*
111690 ** If the TEMP database is open, close it and mark the database schema
111691 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
111692 ** or DEFAULT_TEMP_STORE pragmas.
111693 */
111694 static int changeTempStorage(Parse *pParse, const char *zStorageType){
111695  int ts = getTempStore(zStorageType);
111696  sqlite3 *db = pParse->db;
111697  if( db->temp_store==ts ) return SQLITE_OK;
111698  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
111699  return SQLITE_ERROR;
111700  }
111701  db->temp_store = (u8)ts;
111702  return SQLITE_OK;
111703 }
111704 #endif /* SQLITE_PAGER_PRAGMAS */
111705 
111706 /*
111707 ** Set the names of the first N columns to the values in azCol[]
111708 */
111710  Vdbe *v, /* The query under construction */
111711  int N, /* Number of columns */
111712  const char **azCol /* Names of columns */
111713 ){
111714  int i;
111715  sqlite3VdbeSetNumCols(v, N);
111716  for(i=0; i<N; i++){
111718  }
111719 }
111720 static void setOneColumnName(Vdbe *v, const char *z){
111721  setAllColumnNames(v, 1, &z);
111722 }
111723 
111724 /*
111725 ** Generate code to return a single integer value.
111726 */
111727 static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
111728  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
111729  setOneColumnName(v, zLabel);
111730  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111731 }
111732 
111733 /*
111734 ** Generate code to return a single text value.
111735 */
111736 static void returnSingleText(
111737  Vdbe *v, /* Prepared statement under construction */
111738  const char *zLabel, /* Name of the result column */
111739  const char *zValue /* Value to be returned */
111740 ){
111741  if( zValue ){
111742  sqlite3VdbeLoadString(v, 1, (const char*)zValue);
111743  setOneColumnName(v, zLabel);
111744  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111745  }
111746 }
111747 
111748 
111749 /*
111750 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
111751 ** set these values for all pagers.
111752 */
111753 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111754 static void setAllPagerFlags(sqlite3 *db){
111755  if( db->autoCommit ){
111756  Db *pDb = db->aDb;
111757  int n = db->nDb;
111758  assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
111760  assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
111762  == PAGER_FLAGS_MASK );
111763  assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
111764  while( (n--) > 0 ){
111765  if( pDb->pBt ){
111767  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
111768  }
111769  pDb++;
111770  }
111771  }
111772 }
111773 #else
111774 # define setAllPagerFlags(X) /* no-op */
111775 #endif
111776 
111777 
111778 /*
111779 ** Return a human-readable name for a constraint resolution action.
111780 */
111781 #ifndef SQLITE_OMIT_FOREIGN_KEY
111782 static const char *actionName(u8 action){
111783  const char *zName;
111784  switch( action ){
111785  case OE_SetNull: zName = "SET NULL"; break;
111786  case OE_SetDflt: zName = "SET DEFAULT"; break;
111787  case OE_Cascade: zName = "CASCADE"; break;
111788  case OE_Restrict: zName = "RESTRICT"; break;
111789  default: zName = "NO ACTION";
111790  assert( action==OE_None ); break;
111791  }
111792  return zName;
111793 }
111794 #endif
111795 
111796 
111797 /*
111798 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
111799 ** defined in pager.h. This function returns the associated lowercase
111800 ** journal-mode name.
111801 */
111803  static char * const azModeName[] = {
111804  "delete", "persist", "off", "truncate", "memory"
111805 #ifndef SQLITE_OMIT_WAL
111806  , "wal"
111807 #endif
111808  };
111809  assert( PAGER_JOURNALMODE_DELETE==0 );
111810  assert( PAGER_JOURNALMODE_PERSIST==1 );
111811  assert( PAGER_JOURNALMODE_OFF==2 );
111812  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
111813  assert( PAGER_JOURNALMODE_MEMORY==4 );
111814  assert( PAGER_JOURNALMODE_WAL==5 );
111815  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
111816 
111817  if( eMode==ArraySize(azModeName) ) return 0;
111818  return azModeName[eMode];
111819 }
111820 
111821 /*
111822 ** Process a pragma statement.
111823 **
111824 ** Pragmas are of this form:
111825 **
111826 ** PRAGMA [schema.]id [= value]
111827 **
111828 ** The identifier might also be a string. The value is a string, and
111829 ** identifier, or a number. If minusFlag is true, then the value is
111830 ** a number that was preceded by a minus sign.
111831 **
111832 ** If the left side is "database.id" then pId1 is the database name
111833 ** and pId2 is the id. If the left side is just "id" then pId1 is the
111834 ** id and pId2 is any empty string.
111835 */
111837  Parse *pParse,
111838  Token *pId1, /* First part of [schema.]id field */
111839  Token *pId2, /* Second part of [schema.]id field, or NULL */
111840  Token *pValue, /* Token for <value>, or NULL */
111841  int minusFlag /* True if a '-' sign preceded <value> */
111842 ){
111843  char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
111844  char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
111845  const char *zDb = 0; /* The database name */
111846  Token *pId; /* Pointer to <id> token */
111847  char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
111848  int iDb; /* Database index for <database> */
111849  int lwr, upr, mid = 0; /* Binary search bounds */
111850  int rc; /* return value form SQLITE_FCNTL_PRAGMA */
111851  sqlite3 *db = pParse->db; /* The database connection */
111852  Db *pDb; /* The specific database being pragmaed */
111853  Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
111854  const struct sPragmaNames *pPragma;
111855 
111856  if( v==0 ) return;
111858  pParse->nMem = 2;
111859 
111860  /* Interpret the [schema.] part of the pragma statement. iDb is the
111861  ** index of the database this pragma is being applied to in db.aDb[]. */
111862  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
111863  if( iDb<0 ) return;
111864  pDb = &db->aDb[iDb];
111865 
111866  /* If the temp database has been explicitly named as part of the
111867  ** pragma, make sure it is open.
111868  */
111869  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
111870  return;
111871  }
111872 
111873  zLeft = sqlite3NameFromToken(db, pId);
111874  if( !zLeft ) return;
111875  if( minusFlag ){
111876  zRight = sqlite3MPrintf(db, "-%T", pValue);
111877  }else{
111878  zRight = sqlite3NameFromToken(db, pValue);
111879  }
111880 
111881  assert( pId2 );
111882  zDb = pId2->n>0 ? pDb->zDbSName : 0;
111883  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
111884  goto pragma_out;
111885  }
111886 
111887  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
111888  ** connection. If it returns SQLITE_OK, then assume that the VFS
111889  ** handled the pragma and generate a no-op prepared statement.
111890  **
111891  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
111892  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
111893  ** object corresponding to the database file to which the pragma
111894  ** statement refers.
111895  **
111896  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
111897  ** file control is an array of pointers to strings (char**) in which the
111898  ** second element of the array is the name of the pragma and the third
111899  ** element is the argument to the pragma or NULL if the pragma has no
111900  ** argument.
111901  */
111902  aFcntl[0] = 0;
111903  aFcntl[1] = zLeft;
111904  aFcntl[2] = zRight;
111905  aFcntl[3] = 0;
111906  db->busyHandler.nBusy = 0;
111907  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
111908  if( rc==SQLITE_OK ){
111909  returnSingleText(v, "result", aFcntl[0]);
111910  sqlite3_free(aFcntl[0]);
111911  goto pragma_out;
111912  }
111913  if( rc!=SQLITE_NOTFOUND ){
111914  if( aFcntl[0] ){
111915  sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
111916  sqlite3_free(aFcntl[0]);
111917  }
111918  pParse->nErr++;
111919  pParse->rc = rc;
111920  goto pragma_out;
111921  }
111922 
111923  /* Locate the pragma in the lookup table */
111924  lwr = 0;
111925  upr = ArraySize(aPragmaNames)-1;
111926  while( lwr<=upr ){
111927  mid = (lwr+upr)/2;
111928  rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
111929  if( rc==0 ) break;
111930  if( rc<0 ){
111931  upr = mid - 1;
111932  }else{
111933  lwr = mid + 1;
111934  }
111935  }
111936  if( lwr>upr ) goto pragma_out;
111937  pPragma = &aPragmaNames[mid];
111938 
111939  /* Make sure the database schema is loaded if the pragma requires that */
111940  if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
111941  if( sqlite3ReadSchema(pParse) ) goto pragma_out;
111942  }
111943 
111944  /* Jump to the appropriate pragma handler */
111945  switch( pPragma->ePragTyp ){
111946 
111947 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
111948  /*
111949  ** PRAGMA [schema.]default_cache_size
111950  ** PRAGMA [schema.]default_cache_size=N
111951  **
111952  ** The first form reports the current persistent setting for the
111953  ** page cache size. The value returned is the maximum number of
111954  ** pages in the page cache. The second form sets both the current
111955  ** page cache size value and the persistent page cache size value
111956  ** stored in the database file.
111957  **
111958  ** Older versions of SQLite would set the default cache size to a
111959  ** negative number to indicate synchronous=OFF. These days, synchronous
111960  ** is always on by default regardless of the sign of the default cache
111961  ** size. But continue to take the absolute value of the default cache
111962  ** size of historical compatibility.
111963  */
111965  static const int iLn = VDBE_OFFSET_LINENO(2);
111966  static const VdbeOpList getCacheSize[] = {
111967  { OP_Transaction, 0, 0, 0}, /* 0 */
111968  { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
111969  { OP_IfPos, 1, 8, 0},
111970  { OP_Integer, 0, 2, 0},
111971  { OP_Subtract, 1, 2, 1},
111972  { OP_IfPos, 1, 8, 0},
111973  { OP_Integer, 0, 1, 0}, /* 6 */
111974  { OP_Noop, 0, 0, 0},
111975  { OP_ResultRow, 1, 1, 0},
111976  };
111977  VdbeOp *aOp;
111978  sqlite3VdbeUsesBtree(v, iDb);
111979  if( !zRight ){
111980  setOneColumnName(v, "cache_size");
111981  pParse->nMem += 2;
111982  sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
111983  aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
111984  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111985  aOp[0].p1 = iDb;
111986  aOp[1].p1 = iDb;
111987  aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
111988  }else{
111989  int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
111990  sqlite3BeginWriteOperation(pParse, 0, iDb);
111992  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111993  pDb->pSchema->cache_size = size;
111995  }
111996  break;
111997  }
111998 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
111999 
112000 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
112001  /*
112002  ** PRAGMA [schema.]page_size
112003  ** PRAGMA [schema.]page_size=N
112004  **
112005  ** The first form reports the current setting for the
112006  ** database page size in bytes. The second form sets the
112007  ** database page size value. The value can only be set if
112008  ** the database has not yet been created.
112009  */
112010  case PragTyp_PAGE_SIZE: {
112011  Btree *pBt = pDb->pBt;
112012  assert( pBt!=0 );
112013  if( !zRight ){
112014  int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
112015  returnSingleInt(v, "page_size", size);
112016  }else{
112017  /* Malloc may fail when setting the page-size, as there is an internal
112018  ** buffer that the pager module resizes using sqlite3_realloc().
112019  */
112020  db->nextPagesize = sqlite3Atoi(zRight);
112021  if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
112022  sqlite3OomFault(db);
112023  }
112024  }
112025  break;
112026  }
112027 
112028  /*
112029  ** PRAGMA [schema.]secure_delete
112030  ** PRAGMA [schema.]secure_delete=ON/OFF
112031  **
112032  ** The first form reports the current setting for the
112033  ** secure_delete flag. The second form changes the secure_delete
112034  ** flag setting and reports thenew value.
112035  */
112036  case PragTyp_SECURE_DELETE: {
112037  Btree *pBt = pDb->pBt;
112038  int b = -1;
112039  assert( pBt!=0 );
112040  if( zRight ){
112041  b = sqlite3GetBoolean(zRight, 0);
112042  }
112043  if( pId2->n==0 && b>=0 ){
112044  int ii;
112045  for(ii=0; ii<db->nDb; ii++){
112046  sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
112047  }
112048  }
112049  b = sqlite3BtreeSecureDelete(pBt, b);
112050  returnSingleInt(v, "secure_delete", b);
112051  break;
112052  }
112053 
112054  /*
112055  ** PRAGMA [schema.]max_page_count
112056  ** PRAGMA [schema.]max_page_count=N
112057  **
112058  ** The first form reports the current setting for the
112059  ** maximum number of pages in the database file. The
112060  ** second form attempts to change this setting. Both
112061  ** forms return the current setting.
112062  **
112063  ** The absolute value of N is used. This is undocumented and might
112064  ** change. The only purpose is to provide an easy way to test
112065  ** the sqlite3AbsInt32() function.
112066  **
112067  ** PRAGMA [schema.]page_count
112068  **
112069  ** Return the number of pages in the specified database.
112070  */
112071  case PragTyp_PAGE_COUNT: {
112072  int iReg;
112073  sqlite3CodeVerifySchema(pParse, iDb);
112074  iReg = ++pParse->nMem;
112075  if( sqlite3Tolower(zLeft[0])=='p' ){
112076  sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
112077  }else{
112078  sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
112079  sqlite3AbsInt32(sqlite3Atoi(zRight)));
112080  }
112081  sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
112082  sqlite3VdbeSetNumCols(v, 1);
112084  break;
112085  }
112086 
112087  /*
112088  ** PRAGMA [schema.]locking_mode
112089  ** PRAGMA [schema.]locking_mode = (normal|exclusive)
112090  */
112091  case PragTyp_LOCKING_MODE: {
112092  const char *zRet = "normal";
112093  int eMode = getLockingMode(zRight);
112094 
112095  if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
112096  /* Simple "PRAGMA locking_mode;" statement. This is a query for
112097  ** the current default locking mode (which may be different to
112098  ** the locking-mode of the main database).
112099  */
112100  eMode = db->dfltLockMode;
112101  }else{
112102  Pager *pPager;
112103  if( pId2->n==0 ){
112104  /* This indicates that no database name was specified as part
112105  ** of the PRAGMA command. In this case the locking-mode must be
112106  ** set on all attached databases, as well as the main db file.
112107  **
112108  ** Also, the sqlite3.dfltLockMode variable is set so that
112109  ** any subsequently attached databases also use the specified
112110  ** locking mode.
112111  */
112112  int ii;
112113  assert(pDb==&db->aDb[0]);
112114  for(ii=2; ii<db->nDb; ii++){
112115  pPager = sqlite3BtreePager(db->aDb[ii].pBt);
112116  sqlite3PagerLockingMode(pPager, eMode);
112117  }
112118  db->dfltLockMode = (u8)eMode;
112119  }
112120  pPager = sqlite3BtreePager(pDb->pBt);
112121  eMode = sqlite3PagerLockingMode(pPager, eMode);
112122  }
112123 
112124  assert( eMode==PAGER_LOCKINGMODE_NORMAL
112125  || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
112126  if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
112127  zRet = "exclusive";
112128  }
112129  returnSingleText(v, "locking_mode", zRet);
112130  break;
112131  }
112132 
112133  /*
112134  ** PRAGMA [schema.]journal_mode
112135  ** PRAGMA [schema.]journal_mode =
112136  ** (delete|persist|off|truncate|memory|wal|off)
112137  */
112138  case PragTyp_JOURNAL_MODE: {
112139  int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
112140  int ii; /* Loop counter */
112141 
112142  setOneColumnName(v, "journal_mode");
112143  if( zRight==0 ){
112144  /* If there is no "=MODE" part of the pragma, do a query for the
112145  ** current mode */
112146  eMode = PAGER_JOURNALMODE_QUERY;
112147  }else{
112148  const char *zMode;
112149  int n = sqlite3Strlen30(zRight);
112150  for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
112151  if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
112152  }
112153  if( !zMode ){
112154  /* If the "=MODE" part does not match any known journal mode,
112155  ** then do a query */
112156  eMode = PAGER_JOURNALMODE_QUERY;
112157  }
112158  }
112159  if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
112160  /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
112161  iDb = 0;
112162  pId2->n = 1;
112163  }
112164  for(ii=db->nDb-1; ii>=0; ii--){
112165  if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
112166  sqlite3VdbeUsesBtree(v, ii);
112167  sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
112168  }
112169  }
112170  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
112171  break;
112172  }
112173 
112174  /*
112175  ** PRAGMA [schema.]journal_size_limit
112176  ** PRAGMA [schema.]journal_size_limit=N
112177  **
112178  ** Get or set the size limit on rollback journal files.
112179  */
112181  Pager *pPager = sqlite3BtreePager(pDb->pBt);
112182  i64 iLimit = -2;
112183  if( zRight ){
112184  sqlite3DecOrHexToI64(zRight, &iLimit);
112185  if( iLimit<-1 ) iLimit = -1;
112186  }
112187  iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
112188  returnSingleInt(v, "journal_size_limit", iLimit);
112189  break;
112190  }
112191 
112192 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
112193 
112194  /*
112195  ** PRAGMA [schema.]auto_vacuum
112196  ** PRAGMA [schema.]auto_vacuum=N
112197  **
112198  ** Get or set the value of the database 'auto-vacuum' parameter.
112199  ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
112200  */
112201 #ifndef SQLITE_OMIT_AUTOVACUUM
112202  case PragTyp_AUTO_VACUUM: {
112203  Btree *pBt = pDb->pBt;
112204  assert( pBt!=0 );
112205  if( !zRight ){
112206  returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
112207  }else{
112208  int eAuto = getAutoVacuum(zRight);
112209  assert( eAuto>=0 && eAuto<=2 );
112210  db->nextAutovac = (u8)eAuto;
112211  /* Call SetAutoVacuum() to set initialize the internal auto and
112212  ** incr-vacuum flags. This is required in case this connection
112213  ** creates the database file. It is important that it is created
112214  ** as an auto-vacuum capable db.
112215  */
112216  rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
112217  if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
112218  /* When setting the auto_vacuum mode to either "full" or
112219  ** "incremental", write the value of meta[6] in the database
112220  ** file. Before writing to meta[6], check that meta[3] indicates
112221  ** that this really is an auto-vacuum capable database.
112222  */
112223  static const int iLn = VDBE_OFFSET_LINENO(2);
112224  static const VdbeOpList setMeta6[] = {
112225  { OP_Transaction, 0, 1, 0}, /* 0 */
112227  { OP_If, 1, 0, 0}, /* 2 */
112228  { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
112229  { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
112230  };
112231  VdbeOp *aOp;
112232  int iAddr = sqlite3VdbeCurrentAddr(v);
112234  aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
112235  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112236  aOp[0].p1 = iDb;
112237  aOp[1].p1 = iDb;
112238  aOp[2].p2 = iAddr+4;
112239  aOp[4].p1 = iDb;
112240  aOp[4].p3 = eAuto - 1;
112241  sqlite3VdbeUsesBtree(v, iDb);
112242  }
112243  }
112244  break;
112245  }
112246 #endif
112247 
112248  /*
112249  ** PRAGMA [schema.]incremental_vacuum(N)
112250  **
112251  ** Do N steps of incremental vacuuming on a database.
112252  */
112253 #ifndef SQLITE_OMIT_AUTOVACUUM
112255  int iLimit, addr;
112256  if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
112257  iLimit = 0x7fffffff;
112258  }
112259  sqlite3BeginWriteOperation(pParse, 0, iDb);
112260  sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
112261  addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
112263  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
112264  sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
112265  sqlite3VdbeJumpHere(v, addr);
112266  break;
112267  }
112268 #endif
112269 
112270 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
112271  /*
112272  ** PRAGMA [schema.]cache_size
112273  ** PRAGMA [schema.]cache_size=N
112274  **
112275  ** The first form reports the current local setting for the
112276  ** page cache size. The second form sets the local
112277  ** page cache size value. If N is positive then that is the
112278  ** number of pages in the cache. If N is negative, then the
112279  ** number of pages is adjusted so that the cache uses -N kibibytes
112280  ** of memory.
112281  */
112282  case PragTyp_CACHE_SIZE: {
112283  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112284  if( !zRight ){
112285  returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
112286  }else{
112287  int size = sqlite3Atoi(zRight);
112288  pDb->pSchema->cache_size = size;
112290  }
112291  break;
112292  }
112293 
112294  /*
112295  ** PRAGMA [schema.]cache_spill
112296  ** PRAGMA cache_spill=BOOLEAN
112297  ** PRAGMA [schema.]cache_spill=N
112298  **
112299  ** The first form reports the current local setting for the
112300  ** page cache spill size. The second form turns cache spill on
112301  ** or off. When turnning cache spill on, the size is set to the
112302  ** current cache_size. The third form sets a spill size that
112303  ** may be different form the cache size.
112304  ** If N is positive then that is the
112305  ** number of pages in the cache. If N is negative, then the
112306  ** number of pages is adjusted so that the cache uses -N kibibytes
112307  ** of memory.
112308  **
112309  ** If the number of cache_spill pages is less then the number of
112310  ** cache_size pages, no spilling occurs until the page count exceeds
112311  ** the number of cache_size pages.
112312  **
112313  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
112314  ** not just the schema specified.
112315  */
112316  case PragTyp_CACHE_SPILL: {
112317  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112318  if( !zRight ){
112319  returnSingleInt(v, "cache_spill",
112320  (db->flags & SQLITE_CacheSpill)==0 ? 0 :
112321  sqlite3BtreeSetSpillSize(pDb->pBt,0));
112322  }else{
112323  int size = 1;
112324  if( sqlite3GetInt32(zRight, &size) ){
112325  sqlite3BtreeSetSpillSize(pDb->pBt, size);
112326  }
112327  if( sqlite3GetBoolean(zRight, size!=0) ){
112328  db->flags |= SQLITE_CacheSpill;
112329  }else{
112330  db->flags &= ~SQLITE_CacheSpill;
112331  }
112332  setAllPagerFlags(db);
112333  }
112334  break;
112335  }
112336 
112337  /*
112338  ** PRAGMA [schema.]mmap_size(N)
112339  **
112340  ** Used to set mapping size limit. The mapping size limit is
112341  ** used to limit the aggregate size of all memory mapped regions of the
112342  ** database file. If this parameter is set to zero, then memory mapping
112343  ** is not used at all. If N is negative, then the default memory map
112344  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
112345  ** The parameter N is measured in bytes.
112346  **
112347  ** This value is advisory. The underlying VFS is free to memory map
112348  ** as little or as much as it wants. Except, if N is set to 0 then the
112349  ** upper layers will never invoke the xFetch interfaces to the VFS.
112350  */
112351  case PragTyp_MMAP_SIZE: {
112352  sqlite3_int64 sz;
112353 #if SQLITE_MAX_MMAP_SIZE>0
112354  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112355  if( zRight ){
112356  int ii;
112357  sqlite3DecOrHexToI64(zRight, &sz);
112358  if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
112359  if( pId2->n==0 ) db->szMmap = sz;
112360  for(ii=db->nDb-1; ii>=0; ii--){
112361  if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
112362  sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
112363  }
112364  }
112365  }
112366  sz = -1;
112367  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
112368 #else
112369  sz = 0;
112370  rc = SQLITE_OK;
112371 #endif
112372  if( rc==SQLITE_OK ){
112373  returnSingleInt(v, "mmap_size", sz);
112374  }else if( rc!=SQLITE_NOTFOUND ){
112375  pParse->nErr++;
112376  pParse->rc = rc;
112377  }
112378  break;
112379  }
112380 
112381  /*
112382  ** PRAGMA temp_store
112383  ** PRAGMA temp_store = "default"|"memory"|"file"
112384  **
112385  ** Return or set the local value of the temp_store flag. Changing
112386  ** the local value does not make changes to the disk file and the default
112387  ** value will be restored the next time the database is opened.
112388  **
112389  ** Note that it is possible for the library compile-time options to
112390  ** override this setting
112391  */
112392  case PragTyp_TEMP_STORE: {
112393  if( !zRight ){
112394  returnSingleInt(v, "temp_store", db->temp_store);
112395  }else{
112396  changeTempStorage(pParse, zRight);
112397  }
112398  break;
112399  }
112400 
112401  /*
112402  ** PRAGMA temp_store_directory
112403  ** PRAGMA temp_store_directory = ""|"directory_name"
112404  **
112405  ** Return or set the local value of the temp_store_directory flag. Changing
112406  ** the value sets a specific directory to be used for temporary files.
112407  ** Setting to a null string reverts to the default temporary directory search.
112408  ** If temporary directory is changed, then invalidateTempStorage.
112409  **
112410  */
112412  if( !zRight ){
112413  returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
112414  }else{
112415 #ifndef SQLITE_OMIT_WSD
112416  if( zRight[0] ){
112417  int res;
112418  rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
112419  if( rc!=SQLITE_OK || res==0 ){
112420  sqlite3ErrorMsg(pParse, "not a writable directory");
112421  goto pragma_out;
112422  }
112423  }
112424  if( SQLITE_TEMP_STORE==0
112425  || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
112426  || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
112427  ){
112428  invalidateTempStorage(pParse);
112429  }
112430  sqlite3_free(sqlite3_temp_directory);
112431  if( zRight[0] ){
112432  sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
112433  }else{
112434  sqlite3_temp_directory = 0;
112435  }
112436 #endif /* SQLITE_OMIT_WSD */
112437  }
112438  break;
112439  }
112440 
112441 #if SQLITE_OS_WIN
112442  /*
112443  ** PRAGMA data_store_directory
112444  ** PRAGMA data_store_directory = ""|"directory_name"
112445  **
112446  ** Return or set the local value of the data_store_directory flag. Changing
112447  ** the value sets a specific directory to be used for database files that
112448  ** were specified with a relative pathname. Setting to a null string reverts
112449  ** to the default database directory, which for database files specified with
112450  ** a relative path will probably be based on the current directory for the
112451  ** process. Database file specified with an absolute path are not impacted
112452  ** by this setting, regardless of its value.
112453  **
112454  */
112456  if( !zRight ){
112457  returnSingleText(v, "data_store_directory", sqlite3_data_directory);
112458  }else{
112459 #ifndef SQLITE_OMIT_WSD
112460  if( zRight[0] ){
112461  int res;
112462  rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
112463  if( rc!=SQLITE_OK || res==0 ){
112464  sqlite3ErrorMsg(pParse, "not a writable directory");
112465  goto pragma_out;
112466  }
112467  }
112468  sqlite3_free(sqlite3_data_directory);
112469  if( zRight[0] ){
112470  sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
112471  }else{
112472  sqlite3_data_directory = 0;
112473  }
112474 #endif /* SQLITE_OMIT_WSD */
112475  }
112476  break;
112477  }
112478 #endif
112479 
112480 #if SQLITE_ENABLE_LOCKING_STYLE
112481  /*
112482  ** PRAGMA [schema.]lock_proxy_file
112483  ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
112484  **
112485  ** Return or set the value of the lock_proxy_file flag. Changing
112486  ** the value sets a specific file to be used for database access locks.
112487  **
112488  */
112489  case PragTyp_LOCK_PROXY_FILE: {
112490  if( !zRight ){
112491  Pager *pPager = sqlite3BtreePager(pDb->pBt);
112492  char *proxy_file_path = NULL;
112493  sqlite3_file *pFile = sqlite3PagerFile(pPager);
112495  &proxy_file_path);
112496  returnSingleText(v, "lock_proxy_file", proxy_file_path);
112497  }else{
112498  Pager *pPager = sqlite3BtreePager(pDb->pBt);
112499  sqlite3_file *pFile = sqlite3PagerFile(pPager);
112500  int res;
112501  if( zRight[0] ){
112503  zRight);
112504  } else {
112506  NULL);
112507  }
112508  if( res!=SQLITE_OK ){
112509  sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
112510  goto pragma_out;
112511  }
112512  }
112513  break;
112514  }
112515 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
112516 
112517  /*
112518  ** PRAGMA [schema.]synchronous
112519  ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
112520  **
112521  ** Return or set the local value of the synchronous flag. Changing
112522  ** the local value does not make changes to the disk file and the
112523  ** default value will be restored the next time the database is
112524  ** opened.
112525  */
112526  case PragTyp_SYNCHRONOUS: {
112527  if( !zRight ){
112528  returnSingleInt(v, "synchronous", pDb->safety_level-1);
112529  }else{
112530  if( !db->autoCommit ){
112531  sqlite3ErrorMsg(pParse,
112532  "Safety level may not be changed inside a transaction");
112533  }else{
112534  int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
112535  if( iLevel==0 ) iLevel = 1;
112536  pDb->safety_level = iLevel;
112537  pDb->bSyncSet = 1;
112538  setAllPagerFlags(db);
112539  }
112540  }
112541  break;
112542  }
112543 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
112544 
112545 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
112546  case PragTyp_FLAG: {
112547  if( zRight==0 ){
112548  returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
112549  }else{
112550  int mask = pPragma->iArg; /* Mask of bits to set or clear. */
112551  if( db->autoCommit==0 ){
112552  /* Foreign key support may not be enabled or disabled while not
112553  ** in auto-commit mode. */
112554  mask &= ~(SQLITE_ForeignKeys);
112555  }
112556 #if SQLITE_USER_AUTHENTICATION
112557  if( db->auth.authLevel==UAUTH_User ){
112558  /* Do not allow non-admin users to modify the schema arbitrarily */
112559  mask &= ~(SQLITE_WriteSchema);
112560  }
112561 #endif
112562 
112563  if( sqlite3GetBoolean(zRight, 0) ){
112564  db->flags |= mask;
112565  }else{
112566  db->flags &= ~mask;
112567  if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
112568  }
112569 
112570  /* Many of the flag-pragmas modify the code generated by the SQL
112571  ** compiler (eg. count_changes). So add an opcode to expire all
112572  ** compiled SQL statements after modifying a pragma value.
112573  */
112575  setAllPagerFlags(db);
112576  }
112577  break;
112578  }
112579 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
112580 
112581 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
112582  /*
112583  ** PRAGMA table_info(<table>)
112584  **
112585  ** Return a single row for each column of the named table. The columns of
112586  ** the returned data set are:
112587  **
112588  ** cid: Column id (numbered from left to right, starting at 0)
112589  ** name: Column name
112590  ** type: Column declaration type.
112591  ** notnull: True if 'NOT NULL' is part of column declaration
112592  ** dflt_value: The default value for the column, if any.
112593  */
112594  case PragTyp_TABLE_INFO: if( zRight ){
112595  Table *pTab;
112596  pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
112597  if( pTab ){
112598  static const char *azCol[] = {
112599  "cid", "name", "type", "notnull", "dflt_value", "pk"
112600  };
112601  int i, k;
112602  int nHidden = 0;
112603  Column *pCol;
112604  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
112605  pParse->nMem = 6;
112606  sqlite3CodeVerifySchema(pParse, iDb);
112607  setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
112608  sqlite3ViewGetColumnNames(pParse, pTab);
112609  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
112610  if( IsHiddenColumn(pCol) ){
112611  nHidden++;
112612  continue;
112613  }
112614  if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
112615  k = 0;
112616  }else if( pPk==0 ){
112617  k = 1;
112618  }else{
112619  for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
112620  }
112621  assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
112622  sqlite3VdbeMultiLoad(v, 1, "issisi",
112623  i-nHidden,
112624  pCol->zName,
112625  sqlite3ColumnType(pCol,""),
112626  pCol->notNull ? 1 : 0,
112627  pCol->pDflt ? pCol->pDflt->u.zToken : 0,
112628  k);
112629  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
112630  }
112631  }
112632  }
112633  break;
112634 
112635  case PragTyp_STATS: {
112636  static const char *azCol[] = { "table", "index", "width", "height" };
112637  Index *pIdx;
112638  HashElem *i;
112639  v = sqlite3GetVdbe(pParse);
112640  pParse->nMem = 4;
112641  sqlite3CodeVerifySchema(pParse, iDb);
112642  setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
112643  for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
112644  Table *pTab = sqliteHashData(i);
112645  sqlite3VdbeMultiLoad(v, 1, "ssii",
112646  pTab->zName,
112647  0,
112648  pTab->szTabRow,
112649  pTab->nRowLogEst);
112650  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
112651  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
112652  sqlite3VdbeMultiLoad(v, 2, "sii",
112653  pIdx->zName,
112654  pIdx->szIdxRow,
112655  pIdx->aiRowLogEst[0]);
112656  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
112657  }
112658  }
112659  }
112660  break;
112661 
112662  case PragTyp_INDEX_INFO: if( zRight ){
112663  Index *pIdx;
112664  Table *pTab;
112665  pIdx = sqlite3FindIndex(db, zRight, zDb);
112666  if( pIdx ){
112667  static const char *azCol[] = {
112668  "seqno", "cid", "name", "desc", "coll", "key"
112669  };
112670  int i;
112671  int mx;
112672  if( pPragma->iArg ){
112673  /* PRAGMA index_xinfo (newer version with more rows and columns) */
112674  mx = pIdx->nColumn;
112675  pParse->nMem = 6;
112676  }else{
112677  /* PRAGMA index_info (legacy version) */
112678  mx = pIdx->nKeyCol;
112679  pParse->nMem = 3;
112680  }
112681  pTab = pIdx->pTable;
112682  sqlite3CodeVerifySchema(pParse, iDb);
112683  assert( pParse->nMem<=ArraySize(azCol) );
112684  setAllColumnNames(v, pParse->nMem, azCol);
112685  for(i=0; i<mx; i++){
112686  i16 cnum = pIdx->aiColumn[i];
112687  sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
112688  cnum<0 ? 0 : pTab->aCol[cnum].zName);
112689  if( pPragma->iArg ){
112690  sqlite3VdbeMultiLoad(v, 4, "isi",
112691  pIdx->aSortOrder[i],
112692  pIdx->azColl[i],
112693  i<pIdx->nKeyCol);
112694  }
112695  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
112696  }
112697  }
112698  }
112699  break;
112700 
112701  case PragTyp_INDEX_LIST: if( zRight ){
112702  Index *pIdx;
112703  Table *pTab;
112704  int i;
112705  pTab = sqlite3FindTable(db, zRight, zDb);
112706  if( pTab ){
112707  static const char *azCol[] = {
112708  "seq", "name", "unique", "origin", "partial"
112709  };
112710  v = sqlite3GetVdbe(pParse);
112711  pParse->nMem = 5;
112712  sqlite3CodeVerifySchema(pParse, iDb);
112713  setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) );
112714  for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
112715  const char *azOrigin[] = { "c", "u", "pk" };
112716  sqlite3VdbeMultiLoad(v, 1, "isisi",
112717  i,
112718  pIdx->zName,
112719  IsUniqueIndex(pIdx),
112720  azOrigin[pIdx->idxType],
112721  pIdx->pPartIdxWhere!=0);
112722  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
112723  }
112724  }
112725  }
112726  break;
112727 
112728  case PragTyp_DATABASE_LIST: {
112729  static const char *azCol[] = { "seq", "name", "file" };
112730  int i;
112731  pParse->nMem = 3;
112732  setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
112733  for(i=0; i<db->nDb; i++){
112734  if( db->aDb[i].pBt==0 ) continue;
112735  assert( db->aDb[i].zDbSName!=0 );
112736  sqlite3VdbeMultiLoad(v, 1, "iss",
112737  i,
112738  db->aDb[i].zDbSName,
112739  sqlite3BtreeGetFilename(db->aDb[i].pBt));
112740  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
112741  }
112742  }
112743  break;
112744 
112745  case PragTyp_COLLATION_LIST: {
112746  static const char *azCol[] = { "seq", "name" };
112747  int i = 0;
112748  HashElem *p;
112749  pParse->nMem = 2;
112750  setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
112751  for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
112752  CollSeq *pColl = (CollSeq *)sqliteHashData(p);
112753  sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
112754  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
112755  }
112756  }
112757  break;
112758 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
112759 
112760 #ifndef SQLITE_OMIT_FOREIGN_KEY
112761  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
112762  FKey *pFK;
112763  Table *pTab;
112764  pTab = sqlite3FindTable(db, zRight, zDb);
112765  if( pTab ){
112766  v = sqlite3GetVdbe(pParse);
112767  pFK = pTab->pFKey;
112768  if( pFK ){
112769  static const char *azCol[] = {
112770  "id", "seq", "table", "from", "to", "on_update", "on_delete",
112771  "match"
112772  };
112773  int i = 0;
112774  pParse->nMem = 8;
112775  sqlite3CodeVerifySchema(pParse, iDb);
112776  setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
112777  while(pFK){
112778  int j;
112779  for(j=0; j<pFK->nCol; j++){
112780  sqlite3VdbeMultiLoad(v, 1, "iissssss",
112781  i,
112782  j,
112783  pFK->zTo,
112784  pTab->aCol[pFK->aCol[j].iFrom].zName,
112785  pFK->aCol[j].zCol,
112786  actionName(pFK->aAction[1]), /* ON UPDATE */
112787  actionName(pFK->aAction[0]), /* ON DELETE */
112788  "NONE");
112789  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
112790  }
112791  ++i;
112792  pFK = pFK->pNextFrom;
112793  }
112794  }
112795  }
112796  }
112797  break;
112798 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
112799 
112800 #ifndef SQLITE_OMIT_FOREIGN_KEY
112801 #ifndef SQLITE_OMIT_TRIGGER
112802  case PragTyp_FOREIGN_KEY_CHECK: {
112803  FKey *pFK; /* A foreign key constraint */
112804  Table *pTab; /* Child table contain "REFERENCES" keyword */
112805  Table *pParent; /* Parent table that child points to */
112806  Index *pIdx; /* Index in the parent table */
112807  int i; /* Loop counter: Foreign key number for pTab */
112808  int j; /* Loop counter: Field of the foreign key */
112809  HashElem *k; /* Loop counter: Next table in schema */
112810  int x; /* result variable */
112811  int regResult; /* 3 registers to hold a result row */
112812  int regKey; /* Register to hold key for checking the FK */
112813  int regRow; /* Registers to hold a row from pTab */
112814  int addrTop; /* Top of a loop checking foreign keys */
112815  int addrOk; /* Jump here if the key is OK */
112816  int *aiCols; /* child to parent column mapping */
112817  static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
112818 
112819  regResult = pParse->nMem+1;
112820  pParse->nMem += 4;
112821  regKey = ++pParse->nMem;
112822  regRow = ++pParse->nMem;
112823  v = sqlite3GetVdbe(pParse);
112824  setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
112825  sqlite3CodeVerifySchema(pParse, iDb);
112826  k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
112827  while( k ){
112828  if( zRight ){
112829  pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
112830  k = 0;
112831  }else{
112832  pTab = (Table*)sqliteHashData(k);
112833  k = sqliteHashNext(k);
112834  }
112835  if( pTab==0 || pTab->pFKey==0 ) continue;
112836  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
112837  if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
112838  sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
112839  sqlite3VdbeLoadString(v, regResult, pTab->zName);
112840  for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
112841  pParent = sqlite3FindTable(db, pFK->zTo, zDb);
112842  if( pParent==0 ) continue;
112843  pIdx = 0;
112844  sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
112845  x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
112846  if( x==0 ){
112847  if( pIdx==0 ){
112848  sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
112849  }else{
112850  sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
112851  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
112852  }
112853  }else{
112854  k = 0;
112855  break;
112856  }
112857  }
112858  assert( pParse->nErr>0 || pFK==0 );
112859  if( pFK ) break;
112860  if( pParse->nTab<i ) pParse->nTab = i;
112861  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
112862  for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
112863  pParent = sqlite3FindTable(db, pFK->zTo, zDb);
112864  pIdx = 0;
112865  aiCols = 0;
112866  if( pParent ){
112867  x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
112868  assert( x==0 );
112869  }
112870  addrOk = sqlite3VdbeMakeLabel(v);
112871  if( pParent && pIdx==0 ){
112872  int iKey = pFK->aCol[0].iFrom;
112873  assert( iKey>=0 && iKey<pTab->nCol );
112874  if( iKey!=pTab->iPKey ){
112875  sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
112876  sqlite3ColumnDefault(v, pTab, iKey, regRow);
112877  sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
112878  }else{
112879  sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
112880  }
112881  sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
112882  sqlite3VdbeGoto(v, addrOk);
112884  }else{
112885  for(j=0; j<pFK->nCol; j++){
112886  sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
112887  aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
112888  sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
112889  }
112890  if( pParent ){
112891  sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
112892  sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
112893  sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
112894  VdbeCoverage(v);
112895  }
112896  }
112897  sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
112898  sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
112899  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
112900  sqlite3VdbeResolveLabel(v, addrOk);
112901  sqlite3DbFree(db, aiCols);
112902  }
112903  sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
112904  sqlite3VdbeJumpHere(v, addrTop);
112905  }
112906  }
112907  break;
112908 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
112909 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
112910 
112911 #ifndef NDEBUG
112912  case PragTyp_PARSER_TRACE: {
112913  if( zRight ){
112914  if( sqlite3GetBoolean(zRight, 0) ){
112915  sqlite3ParserTrace(stdout, "parser: ");
112916  }else{
112917  sqlite3ParserTrace(0, 0);
112918  }
112919  }
112920  }
112921  break;
112922 #endif
112923 
112924  /* Reinstall the LIKE and GLOB functions. The variant of LIKE
112925  ** used will be case sensitive or not depending on the RHS.
112926  */
112928  if( zRight ){
112930  }
112931  }
112932  break;
112933 
112934 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
112935 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
112936 #endif
112937 
112938 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
112939  /* Pragma "quick_check" is reduced version of
112940  ** integrity_check designed to detect most database corruption
112941  ** without most of the overhead of a full integrity-check.
112942  */
112943  case PragTyp_INTEGRITY_CHECK: {
112944  int i, j, addr, mxErr;
112945 
112946  int isQuick = (sqlite3Tolower(zLeft[0])=='q');
112947 
112948  /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
112949  ** then iDb is set to the index of the database identified by <db>.
112950  ** In this case, the integrity of database iDb only is verified by
112951  ** the VDBE created below.
112952  **
112953  ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
112954  ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
112955  ** to -1 here, to indicate that the VDBE should verify the integrity
112956  ** of all attached databases. */
112957  assert( iDb>=0 );
112958  assert( iDb==0 || pId2->z );
112959  if( pId2->z==0 ) iDb = -1;
112960 
112961  /* Initialize the VDBE program */
112962  pParse->nMem = 6;
112963  setOneColumnName(v, "integrity_check");
112964 
112965  /* Set the maximum error count */
112967  if( zRight ){
112968  sqlite3GetInt32(zRight, &mxErr);
112969  if( mxErr<=0 ){
112971  }
112972  }
112973  sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
112974 
112975  /* Do an integrity check on each database file */
112976  for(i=0; i<db->nDb; i++){
112977  HashElem *x;
112978  Hash *pTbls;
112979  int *aRoot;
112980  int cnt = 0;
112981  int mxIdx = 0;
112982  int nIdx;
112983 
112984  if( OMIT_TEMPDB && i==1 ) continue;
112985  if( iDb>=0 && i!=iDb ) continue;
112986 
112987  sqlite3CodeVerifySchema(pParse, i);
112988  addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
112989  VdbeCoverage(v);
112990  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112991  sqlite3VdbeJumpHere(v, addr);
112992 
112993  /* Do an integrity check of the B-Tree
112994  **
112995  ** Begin by finding the root pages numbers
112996  ** for all tables and indices in the database.
112997  */
112998  assert( sqlite3SchemaMutexHeld(db, i, 0) );
112999  pTbls = &db->aDb[i].pSchema->tblHash;
113000  for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
113001  Table *pTab = sqliteHashData(x);
113002  Index *pIdx;
113003  if( HasRowid(pTab) ) cnt++;
113004  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
113005  if( nIdx>mxIdx ) mxIdx = nIdx;
113006  }
113007  aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
113008  if( aRoot==0 ) break;
113009  for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
113010  Table *pTab = sqliteHashData(x);
113011  Index *pIdx;
113012  if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
113013  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
113014  aRoot[cnt++] = pIdx->tnum;
113015  }
113016  }
113017  aRoot[cnt] = 0;
113018 
113019  /* Make sure sufficient number of registers have been allocated */
113020  pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
113021 
113022  /* Do the b-tree integrity checks */
113023  sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
113024  sqlite3VdbeChangeP5(v, (u8)i);
113025  addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
113026  sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
113027  sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
113028  P4_DYNAMIC);
113029  sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
113030  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
113031  sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
113032  sqlite3VdbeJumpHere(v, addr);
113033 
113034  /* Make sure all the indices are constructed correctly.
113035  */
113036  for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
113037  Table *pTab = sqliteHashData(x);
113038  Index *pIdx, *pPk;
113039  Index *pPrior = 0;
113040  int loopTop;
113041  int iDataCur, iIdxCur;
113042  int r1 = -1;
113043 
113044  if( pTab->pIndex==0 ) continue;
113045  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
113046  addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
113047  VdbeCoverage(v);
113048  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
113049  sqlite3VdbeJumpHere(v, addr);
113050  sqlite3ExprCacheClear(pParse);
113051  sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
113052  1, 0, &iDataCur, &iIdxCur);
113053  sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
113054  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113055  sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
113056  }
113057  assert( pParse->nMem>=8+j );
113058  assert( sqlite3NoTempsInRange(pParse,1,7+j) );
113059  sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
113060  loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
113061  /* Verify that all NOT NULL columns really are NOT NULL */
113062  for(j=0; j<pTab->nCol; j++){
113063  char *zErr;
113064  int jmp2, jmp3;
113065  if( j==pTab->iPKey ) continue;
113066  if( pTab->aCol[j].notNull==0 ) continue;
113067  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
113069  jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
113070  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
113071  zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
113072  pTab->aCol[j].zName);
113073  sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
113074  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
113075  jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
113077  sqlite3VdbeJumpHere(v, jmp2);
113078  sqlite3VdbeJumpHere(v, jmp3);
113079  }
113080  /* Validate index entries for the current row */
113081  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113082  int jmp2, jmp3, jmp4, jmp5;
113083  int ckUniq = sqlite3VdbeMakeLabel(v);
113084  if( pPk==pIdx ) continue;
113085  r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
113086  pPrior, r1);
113087  pPrior = pIdx;
113088  sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
113089  /* Verify that an index entry exists for the current table row */
113090  jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
113091  pIdx->nColumn); VdbeCoverage(v);
113092  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
113093  sqlite3VdbeLoadString(v, 3, "row ");
113094  sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
113095  sqlite3VdbeLoadString(v, 4, " missing from index ");
113096  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
113097  jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
113098  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
113099  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
113100  jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
113102  sqlite3VdbeJumpHere(v, jmp2);
113103  /* For UNIQUE indexes, verify that only one entry exists with the
113104  ** current key. The entry is unique if (1) any column is NULL
113105  ** or (2) the next entry has a different key */
113106  if( IsUniqueIndex(pIdx) ){
113107  int uniqOk = sqlite3VdbeMakeLabel(v);
113108  int jmp6;
113109  int kk;
113110  for(kk=0; kk<pIdx->nKeyCol; kk++){
113111  int iCol = pIdx->aiColumn[kk];
113112  assert( iCol!=XN_ROWID && iCol<pTab->nCol );
113113  if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
113114  sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
113115  VdbeCoverage(v);
113116  }
113117  jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
113118  sqlite3VdbeGoto(v, uniqOk);
113119  sqlite3VdbeJumpHere(v, jmp6);
113120  sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
113121  pIdx->nKeyCol); VdbeCoverage(v);
113122  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
113123  sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
113124  sqlite3VdbeGoto(v, jmp5);
113125  sqlite3VdbeResolveLabel(v, uniqOk);
113126  }
113127  sqlite3VdbeJumpHere(v, jmp4);
113128  sqlite3ResolvePartIdxLabel(pParse, jmp3);
113129  }
113130  sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
113131  sqlite3VdbeJumpHere(v, loopTop-1);
113132 #ifndef SQLITE_OMIT_BTREECOUNT
113133  sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
113134  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113135  if( pPk==pIdx ) continue;
113136  addr = sqlite3VdbeCurrentAddr(v);
113137  sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
113138  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
113139  sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
113140  sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
113142  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
113143  sqlite3VdbeLoadString(v, 3, pIdx->zName);
113144  sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
113145  sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
113146  }
113147 #endif /* SQLITE_OMIT_BTREECOUNT */
113148  }
113149  }
113150  {
113151  static const int iLn = VDBE_OFFSET_LINENO(2);
113152  static const VdbeOpList endCode[] = {
113153  { OP_AddImm, 1, 0, 0}, /* 0 */
113154  { OP_If, 1, 4, 0}, /* 1 */
113155  { OP_String8, 0, 3, 0}, /* 2 */
113156  { OP_ResultRow, 3, 1, 0}, /* 3 */
113157  };
113158  VdbeOp *aOp;
113159 
113160  aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
113161  if( aOp ){
113162  aOp[0].p2 = -mxErr;
113163  aOp[2].p4type = P4_STATIC;
113164  aOp[2].p4.z = "ok";
113165  }
113166  }
113167  }
113168  break;
113169 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
113170 
113171 #ifndef SQLITE_OMIT_UTF16
113172  /*
113173  ** PRAGMA encoding
113174  ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
113175  **
113176  ** In its first form, this pragma returns the encoding of the main
113177  ** database. If the database is not initialized, it is initialized now.
113178  **
113179  ** The second form of this pragma is a no-op if the main database file
113180  ** has not already been initialized. In this case it sets the default
113181  ** encoding that will be used for the main database file if a new file
113182  ** is created. If an existing main database file is opened, then the
113183  ** default text encoding for the existing database is used.
113184  **
113185  ** In all cases new databases created using the ATTACH command are
113186  ** created to use the same default text encoding as the main database. If
113187  ** the main database has not been initialized and/or created when ATTACH
113188  ** is executed, this is done before the ATTACH operation.
113189  **
113190  ** In the second form this pragma sets the text encoding to be used in
113191  ** new database files created using this database handle. It is only
113192  ** useful if invoked immediately after the main database i
113193  */
113194  case PragTyp_ENCODING: {
113195  static const struct EncName {
113196  char *zName;
113197  u8 enc;
113198  } encnames[] = {
113199  { "UTF8", SQLITE_UTF8 },
113200  { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
113201  { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
113202  { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
113203  { "UTF16le", SQLITE_UTF16LE },
113204  { "UTF16be", SQLITE_UTF16BE },
113205  { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
113206  { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
113207  { 0, 0 }
113208  };
113209  const struct EncName *pEnc;
113210  if( !zRight ){ /* "PRAGMA encoding" */
113211  if( sqlite3ReadSchema(pParse) ) goto pragma_out;
113212  assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
113213  assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
113214  assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
113215  returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
113216  }else{ /* "PRAGMA encoding = XXX" */
113217  /* Only change the value of sqlite.enc if the database handle is not
113218  ** initialized. If the main database exists, the new sqlite.enc value
113219  ** will be overwritten when the schema is next loaded. If it does not
113220  ** already exists, it will be created to use the new encoding value.
113221  */
113222  if(
113223  !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
113224  DbHasProperty(db, 0, DB_Empty)
113225  ){
113226  for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
113227  if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
113228  SCHEMA_ENC(db) = ENC(db) =
113229  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
113230  break;
113231  }
113232  }
113233  if( !pEnc->zName ){
113234  sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
113235  }
113236  }
113237  }
113238  }
113239  break;
113240 #endif /* SQLITE_OMIT_UTF16 */
113241 
113242 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
113243  /*
113244  ** PRAGMA [schema.]schema_version
113245  ** PRAGMA [schema.]schema_version = <integer>
113246  **
113247  ** PRAGMA [schema.]user_version
113248  ** PRAGMA [schema.]user_version = <integer>
113249  **
113250  ** PRAGMA [schema.]freelist_count
113251  **
113252  ** PRAGMA [schema.]data_version
113253  **
113254  ** PRAGMA [schema.]application_id
113255  ** PRAGMA [schema.]application_id = <integer>
113256  **
113257  ** The pragma's schema_version and user_version are used to set or get
113258  ** the value of the schema-version and user-version, respectively. Both
113259  ** the schema-version and the user-version are 32-bit signed integers
113260  ** stored in the database header.
113261  **
113262  ** The schema-cookie is usually only manipulated internally by SQLite. It
113263  ** is incremented by SQLite whenever the database schema is modified (by
113264  ** creating or dropping a table or index). The schema version is used by
113265  ** SQLite each time a query is executed to ensure that the internal cache
113266  ** of the schema used when compiling the SQL query matches the schema of
113267  ** the database against which the compiled query is actually executed.
113268  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
113269  ** the schema-version is potentially dangerous and may lead to program
113270  ** crashes or database corruption. Use with caution!
113271  **
113272  ** The user-version is not used internally by SQLite. It may be used by
113273  ** applications for any purpose.
113274  */
113275  case PragTyp_HEADER_VALUE: {
113276  int iCookie = pPragma->iArg; /* Which cookie to read or write */
113277  sqlite3VdbeUsesBtree(v, iDb);
113278  if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
113279  /* Write the specified cookie value */
113280  static const VdbeOpList setCookie[] = {
113281  { OP_Transaction, 0, 1, 0}, /* 0 */
113282  { OP_SetCookie, 0, 0, 0}, /* 1 */
113283  };
113284  VdbeOp *aOp;
113286  aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
113287  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
113288  aOp[0].p1 = iDb;
113289  aOp[1].p1 = iDb;
113290  aOp[1].p2 = iCookie;
113291  aOp[1].p3 = sqlite3Atoi(zRight);
113292  }else{
113293  /* Read the specified cookie value */
113294  static const VdbeOpList readCookie[] = {
113295  { OP_Transaction, 0, 0, 0}, /* 0 */
113296  { OP_ReadCookie, 0, 1, 0}, /* 1 */
113297  { OP_ResultRow, 1, 1, 0}
113298  };
113299  VdbeOp *aOp;
113301  aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
113302  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
113303  aOp[0].p1 = iDb;
113304  aOp[1].p1 = iDb;
113305  aOp[1].p3 = iCookie;
113306  sqlite3VdbeSetNumCols(v, 1);
113308  sqlite3VdbeReusable(v);
113309  }
113310  }
113311  break;
113312 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
113313 
113314 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
113315  /*
113316  ** PRAGMA compile_options
113317  **
113318  ** Return the names of all compile-time options used in this build,
113319  ** one option per row.
113320  */
113321  case PragTyp_COMPILE_OPTIONS: {
113322  int i = 0;
113323  const char *zOpt;
113324  pParse->nMem = 1;
113325  setOneColumnName(v, "compile_option");
113326  while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
113327  sqlite3VdbeLoadString(v, 1, zOpt);
113328  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
113329  }
113330  sqlite3VdbeReusable(v);
113331  }
113332  break;
113333 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
113334 
113335 #ifndef SQLITE_OMIT_WAL
113336  /*
113337  ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
113338  **
113339  ** Checkpoint the database.
113340  */
113341  case PragTyp_WAL_CHECKPOINT: {
113342  static const char *azCol[] = { "busy", "log", "checkpointed" };
113343  int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
113344  int eMode = SQLITE_CHECKPOINT_PASSIVE;
113345  if( zRight ){
113346  if( sqlite3StrICmp(zRight, "full")==0 ){
113347  eMode = SQLITE_CHECKPOINT_FULL;
113348  }else if( sqlite3StrICmp(zRight, "restart")==0 ){
113349  eMode = SQLITE_CHECKPOINT_RESTART;
113350  }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
113351  eMode = SQLITE_CHECKPOINT_TRUNCATE;
113352  }
113353  }
113354  setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
113355  pParse->nMem = 3;
113356  sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
113357  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
113358  }
113359  break;
113360 
113361  /*
113362  ** PRAGMA wal_autocheckpoint
113363  ** PRAGMA wal_autocheckpoint = N
113364  **
113365  ** Configure a database connection to automatically checkpoint a database
113366  ** after accumulating N frames in the log. Or query for the current value
113367  ** of N.
113368  */
113370  if( zRight ){
113372  }
113373  returnSingleInt(v, "wal_autocheckpoint",
113375  SQLITE_PTR_TO_INT(db->pWalArg) : 0);
113376  }
113377  break;
113378 #endif
113379 
113380  /*
113381  ** PRAGMA shrink_memory
113382  **
113383  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
113384  ** connection on which it is invoked to free up as much memory as it
113385  ** can, by calling sqlite3_db_release_memory().
113386  */
113387  case PragTyp_SHRINK_MEMORY: {
113389  break;
113390  }
113391 
113392  /*
113393  ** PRAGMA busy_timeout
113394  ** PRAGMA busy_timeout = N
113395  **
113396  ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
113397  ** if one is set. If no busy handler or a different busy handler is set
113398  ** then 0 is returned. Setting the busy_timeout to 0 or negative
113399  ** disables the timeout.
113400  */
113401  /*case PragTyp_BUSY_TIMEOUT*/ default: {
113402  assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
113403  if( zRight ){
113404  sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
113405  }
113406  returnSingleInt(v, "timeout", db->busyTimeout);
113407  break;
113408  }
113409 
113410  /*
113411  ** PRAGMA soft_heap_limit
113412  ** PRAGMA soft_heap_limit = N
113413  **
113414  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
113415  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
113416  ** specified and is a non-negative integer.
113417  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
113418  ** returns the same integer that would be returned by the
113419  ** sqlite3_soft_heap_limit64(-1) C-language function.
113420  */
113421  case PragTyp_SOFT_HEAP_LIMIT: {
113422  sqlite3_int64 N;
113423  if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
113425  }
113426  returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
113427  break;
113428  }
113429 
113430  /*
113431  ** PRAGMA threads
113432  ** PRAGMA threads = N
113433  **
113434  ** Configure the maximum number of worker threads. Return the new
113435  ** maximum, which might be less than requested.
113436  */
113437  case PragTyp_THREADS: {
113438  sqlite3_int64 N;
113439  if( zRight
113440  && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
113441  && N>=0
113442  ){
113443  sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
113444  }
113445  returnSingleInt(v, "threads",
113447  break;
113448  }
113449 
113450 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
113451  /*
113452  ** Report the current state of file logs for all databases
113453  */
113454  case PragTyp_LOCK_STATUS: {
113455  static const char *const azLockName[] = {
113456  "unlocked", "shared", "reserved", "pending", "exclusive"
113457  };
113458  static const char *azCol[] = { "database", "status" };
113459  int i;
113460  setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
113461  pParse->nMem = 2;
113462  for(i=0; i<db->nDb; i++){
113463  Btree *pBt;
113464  const char *zState = "unknown";
113465  int j;
113466  if( db->aDb[i].zDbSName==0 ) continue;
113467  pBt = db->aDb[i].pBt;
113468  if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
113469  zState = "closed";
113470  }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
113472  zState = azLockName[j];
113473  }
113474  sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
113475  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
113476  }
113477  break;
113478  }
113479 #endif
113480 
113481 #ifdef SQLITE_HAS_CODEC
113482  case PragTyp_KEY: {
113483  if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
113484  break;
113485  }
113486  case PragTyp_REKEY: {
113487  if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
113488  break;
113489  }
113490  case PragTyp_HEXKEY: {
113491  if( zRight ){
113492  u8 iByte;
113493  int i;
113494  char zKey[40];
113495  for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
113496  iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
113497  if( (i&1)!=0 ) zKey[i/2] = iByte;
113498  }
113499  if( (zLeft[3] & 0xf)==0xb ){
113500  sqlite3_key_v2(db, zDb, zKey, i/2);
113501  }else{
113502  sqlite3_rekey_v2(db, zDb, zKey, i/2);
113503  }
113504  }
113505  break;
113506  }
113507 #endif
113508 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
113509  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
113510 #ifdef SQLITE_HAS_CODEC
113511  if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
113512  sqlite3_activate_see(&zRight[4]);
113513  }
113514 #endif
113515 #ifdef SQLITE_ENABLE_CEROD
113516  if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
113517  sqlite3_activate_cerod(&zRight[6]);
113518  }
113519 #endif
113520  }
113521  break;
113522 #endif
113523 
113524  } /* End of the PRAGMA switch */
113525 
113526 pragma_out:
113527  sqlite3DbFree(db, zLeft);
113528  sqlite3DbFree(db, zRight);
113529 }
113530 
113531 #endif /* SQLITE_OMIT_PRAGMA */
113532 
113533 /************** End of pragma.c **********************************************/
113534 /************** Begin file prepare.c *****************************************/
113535 /*
113536 ** 2005 May 25
113537 **
113538 ** The author disclaims copyright to this source code. In place of
113539 ** a legal notice, here is a blessing:
113540 **
113541 ** May you do good and not evil.
113542 ** May you find forgiveness for yourself and forgive others.
113543 ** May you share freely, never taking more than you give.
113544 **
113545 *************************************************************************
113546 ** This file contains the implementation of the sqlite3_prepare()
113547 ** interface, and routines that contribute to loading the database schema
113548 ** from disk.
113549 */
113550 /* #include "sqliteInt.h" */
113551 
113552 /*
113553 ** Fill the InitData structure with an error message that indicates
113554 ** that the database is corrupt.
113555 */
113556 static void corruptSchema(
113557  InitData *pData, /* Initialization context */
113558  const char *zObj, /* Object being parsed at the point of error */
113559  const char *zExtra /* Error information */
113560 ){
113561  sqlite3 *db = pData->db;
113562  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
113563  char *z;
113564  if( zObj==0 ) zObj = "?";
113565  z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
113566  if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
113567  sqlite3DbFree(db, *pData->pzErrMsg);
113568  *pData->pzErrMsg = z;
113569  }
113571 }
113572 
113573 /*
113574 ** This is the callback routine for the code that initializes the
113575 ** database. See sqlite3Init() below for additional information.
113576 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
113577 **
113578 ** Each callback contains the following information:
113579 **
113580 ** argv[0] = name of thing being created
113581 ** argv[1] = root page number for table or index. 0 for trigger or view.
113582 ** argv[2] = SQL text for the CREATE statement.
113583 **
113584 */
113585 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
113586  InitData *pData = (InitData*)pInit;
113587  sqlite3 *db = pData->db;
113588  int iDb = pData->iDb;
113589 
113590  assert( argc==3 );
113591  UNUSED_PARAMETER2(NotUsed, argc);
113592  assert( sqlite3_mutex_held(db->mutex) );
113593  DbClearProperty(db, iDb, DB_Empty);
113594  if( db->mallocFailed ){
113595  corruptSchema(pData, argv[0], 0);
113596  return 1;
113597  }
113598 
113599  assert( iDb>=0 && iDb<db->nDb );
113600  if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
113601  if( argv[1]==0 ){
113602  corruptSchema(pData, argv[0], 0);
113603  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
113604  /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
113605  ** But because db->init.busy is set to 1, no VDBE code is generated
113606  ** or executed. All the parser does is build the internal data
113607  ** structures that describe the table, index, or view.
113608  */
113609  int rc;
113610  u8 saved_iDb = db->init.iDb;
113611  sqlite3_stmt *pStmt;
113612  TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
113613 
113614  assert( db->init.busy );
113615  db->init.iDb = iDb;
113616  db->init.newTnum = sqlite3Atoi(argv[1]);
113617  db->init.orphanTrigger = 0;
113618  TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
113619  rc = db->errCode;
113620  assert( (rc&0xFF)==(rcp&0xFF) );
113621  db->init.iDb = saved_iDb;
113622  assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 );
113623  if( SQLITE_OK!=rc ){
113624  if( db->init.orphanTrigger ){
113625  assert( iDb==1 );
113626  }else{
113627  pData->rc = rc;
113628  if( rc==SQLITE_NOMEM ){
113629  sqlite3OomFault(db);
113630  }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
113631  corruptSchema(pData, argv[0], sqlite3_errmsg(db));
113632  }
113633  }
113634  }
113635  sqlite3_finalize(pStmt);
113636  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
113637  corruptSchema(pData, argv[0], 0);
113638  }else{
113639  /* If the SQL column is blank it means this is an index that
113640  ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
113641  ** constraint for a CREATE TABLE. The index should have already
113642  ** been created when we processed the CREATE TABLE. All we have
113643  ** to do here is record the root page number for that index.
113644  */
113645  Index *pIndex;
113646  pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
113647  if( pIndex==0 ){
113648  /* This can occur if there exists an index on a TEMP table which
113649  ** has the same name as another index on a permanent index. Since
113650  ** the permanent table is hidden by the TEMP table, we can also
113651  ** safely ignore the index on the permanent table.
113652  */
113653  /* Do Nothing */;
113654  }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
113655  corruptSchema(pData, argv[0], "invalid rootpage");
113656  }
113657  }
113658  return 0;
113659 }
113660 
113661 /*
113662 ** Attempt to read the database schema and initialize internal
113663 ** data structures for a single database file. The index of the
113664 ** database file is given by iDb. iDb==0 is used for the main
113665 ** database. iDb==1 should never be used. iDb>=2 is used for
113666 ** auxiliary databases. Return one of the SQLITE_ error codes to
113667 ** indicate success or failure.
113668 */
113669 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
113670  int rc;
113671  int i;
113672 #ifndef SQLITE_OMIT_DEPRECATED
113673  int size;
113674 #endif
113675  Db *pDb;
113676  char const *azArg[4];
113677  int meta[5];
113678  InitData initData;
113679  const char *zMasterName;
113680  int openedTransaction = 0;
113681 
113682  assert( iDb>=0 && iDb<db->nDb );
113683  assert( db->aDb[iDb].pSchema );
113684  assert( sqlite3_mutex_held(db->mutex) );
113685  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
113686 
113687  /* Construct the in-memory representation schema tables (sqlite_master or
113688  ** sqlite_temp_master) by invoking the parser directly. The appropriate
113689  ** table name will be inserted automatically by the parser so we can just
113690  ** use the abbreviation "x" here. The parser will also automatically tag
113691  ** the schema table as read-only. */
113692  azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
113693  azArg[1] = "1";
113694  azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
113695  "rootpage integer,sql text)";
113696  azArg[3] = 0;
113697  initData.db = db;
113698  initData.iDb = iDb;
113699  initData.rc = SQLITE_OK;
113700  initData.pzErrMsg = pzErrMsg;
113701  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
113702  if( initData.rc ){
113703  rc = initData.rc;
113704  goto error_out;
113705  }
113706 
113707  /* Create a cursor to hold the database open
113708  */
113709  pDb = &db->aDb[iDb];
113710  if( pDb->pBt==0 ){
113711  if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
113712  DbSetProperty(db, 1, DB_SchemaLoaded);
113713  }
113714  return SQLITE_OK;
113715  }
113716 
113717  /* If there is not already a read-only (or read-write) transaction opened
113718  ** on the b-tree database, open one now. If a transaction is opened, it
113719  ** will be closed before this function returns. */
113720  sqlite3BtreeEnter(pDb->pBt);
113721  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
113722  rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
113723  if( rc!=SQLITE_OK ){
113724  sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
113725  goto initone_error_out;
113726  }
113727  openedTransaction = 1;
113728  }
113729 
113730  /* Get the database meta information.
113731  **
113732  ** Meta values are as follows:
113733  ** meta[0] Schema cookie. Changes with each schema change.
113734  ** meta[1] File format of schema layer.
113735  ** meta[2] Size of the page cache.
113736  ** meta[3] Largest rootpage (auto/incr_vacuum mode)
113737  ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
113738  ** meta[5] User version
113739  ** meta[6] Incremental vacuum mode
113740  ** meta[7] unused
113741  ** meta[8] unused
113742  ** meta[9] unused
113743  **
113744  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
113745  ** the possible values of meta[4].
113746  */
113747  for(i=0; i<ArraySize(meta); i++){
113748  sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
113749  }
113750  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
113751 
113752  /* If opening a non-empty database, check the text encoding. For the
113753  ** main database, set sqlite3.enc to the encoding of the main database.
113754  ** For an attached db, it is an error if the encoding is not the same
113755  ** as sqlite3.enc.
113756  */
113757  if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
113758  if( iDb==0 ){
113759 #ifndef SQLITE_OMIT_UTF16
113760  u8 encoding;
113761  /* If opening the main database, set ENC(db). */
113762  encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
113763  if( encoding==0 ) encoding = SQLITE_UTF8;
113764  ENC(db) = encoding;
113765 #else
113766  ENC(db) = SQLITE_UTF8;
113767 #endif
113768  }else{
113769  /* If opening an attached database, the encoding much match ENC(db) */
113770  if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
113771  sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
113772  " text encoding as main database");
113773  rc = SQLITE_ERROR;
113774  goto initone_error_out;
113775  }
113776  }
113777  }else{
113778  DbSetProperty(db, iDb, DB_Empty);
113779  }
113780  pDb->pSchema->enc = ENC(db);
113781 
113782  if( pDb->pSchema->cache_size==0 ){
113783 #ifndef SQLITE_OMIT_DEPRECATED
113784  size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
113785  if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
113786  pDb->pSchema->cache_size = size;
113787 #else
113789 #endif
113791  }
113792 
113793  /*
113794  ** file_format==1 Version 3.0.0.
113795  ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
113796  ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
113797  ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
113798  */
113799  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
113800  if( pDb->pSchema->file_format==0 ){
113801  pDb->pSchema->file_format = 1;
113802  }
113804  sqlite3SetString(pzErrMsg, db, "unsupported file format");
113805  rc = SQLITE_ERROR;
113806  goto initone_error_out;
113807  }
113808 
113809  /* Ticket #2804: When we open a database in the newer file format,
113810  ** clear the legacy_file_format pragma flag so that a VACUUM will
113811  ** not downgrade the database and thus invalidate any descending
113812  ** indices that the user might have created.
113813  */
113814  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
113815  db->flags &= ~SQLITE_LegacyFileFmt;
113816  }
113817 
113818  /* Read the schema information out of the schema tables
113819  */
113820  assert( db->init.busy );
113821  {
113822  char *zSql;
113823  zSql = sqlite3MPrintf(db,
113824  "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
113825  db->aDb[iDb].zDbSName, zMasterName);
113826 #ifndef SQLITE_OMIT_AUTHORIZATION
113827  {
113828  sqlite3_xauth xAuth;
113829  xAuth = db->xAuth;
113830  db->xAuth = 0;
113831 #endif
113832  rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
113833 #ifndef SQLITE_OMIT_AUTHORIZATION
113834  db->xAuth = xAuth;
113835  }
113836 #endif
113837  if( rc==SQLITE_OK ) rc = initData.rc;
113838  sqlite3DbFree(db, zSql);
113839 #ifndef SQLITE_OMIT_ANALYZE
113840  if( rc==SQLITE_OK ){
113841  sqlite3AnalysisLoad(db, iDb);
113842  }
113843 #endif
113844  }
113845  if( db->mallocFailed ){
113846  rc = SQLITE_NOMEM_BKPT;
113848  }
113849  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
113850  /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
113851  ** the schema loaded, even if errors occurred. In this situation the
113852  ** current sqlite3_prepare() operation will fail, but the following one
113853  ** will attempt to compile the supplied statement against whatever subset
113854  ** of the schema was loaded before the error occurred. The primary
113855  ** purpose of this is to allow access to the sqlite_master table
113856  ** even when its contents have been corrupted.
113857  */
113858  DbSetProperty(db, iDb, DB_SchemaLoaded);
113859  rc = SQLITE_OK;
113860  }
113861 
113862  /* Jump here for an error that occurs after successfully allocating
113863  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
113864  ** before that point, jump to error_out.
113865  */
113866 initone_error_out:
113867  if( openedTransaction ){
113868  sqlite3BtreeCommit(pDb->pBt);
113869  }
113870  sqlite3BtreeLeave(pDb->pBt);
113871 
113872 error_out:
113873  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
113874  sqlite3OomFault(db);
113875  }
113876  return rc;
113877 }
113878 
113879 /*
113880 ** Initialize all database files - the main database file, the file
113881 ** used to store temporary tables, and any additional database files
113882 ** created using ATTACH statements. Return a success code. If an
113883 ** error occurs, write an error message into *pzErrMsg.
113884 **
113885 ** After a database is initialized, the DB_SchemaLoaded bit is set
113886 ** bit is set in the flags field of the Db structure. If the database
113887 ** file was of zero-length, then the DB_Empty flag is also set.
113888 */
113889 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
113890  int i, rc;
113891  int commit_internal = !(db->flags&SQLITE_InternChanges);
113892 
113893  assert( sqlite3_mutex_held(db->mutex) );
113894  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
113895  assert( db->init.busy==0 );
113896  rc = SQLITE_OK;
113897  db->init.busy = 1;
113898  ENC(db) = SCHEMA_ENC(db);
113899  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
113900  if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
113901  rc = sqlite3InitOne(db, i, pzErrMsg);
113902  if( rc ){
113903  sqlite3ResetOneSchema(db, i);
113904  }
113905  }
113906 
113907  /* Once all the other databases have been initialized, load the schema
113908  ** for the TEMP database. This is loaded last, as the TEMP database
113909  ** schema may contain references to objects in other databases.
113910  */
113911 #ifndef SQLITE_OMIT_TEMPDB
113912  assert( db->nDb>1 );
113913  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
113914  rc = sqlite3InitOne(db, 1, pzErrMsg);
113915  if( rc ){
113916  sqlite3ResetOneSchema(db, 1);
113917  }
113918  }
113919 #endif
113920 
113921  db->init.busy = 0;
113922  if( rc==SQLITE_OK && commit_internal ){
113924  }
113925 
113926  return rc;
113927 }
113928 
113929 /*
113930 ** This routine is a no-op if the database schema is already initialized.
113931 ** Otherwise, the schema is loaded. An error code is returned.
113932 */
113934  int rc = SQLITE_OK;
113935  sqlite3 *db = pParse->db;
113936  assert( sqlite3_mutex_held(db->mutex) );
113937  if( !db->init.busy ){
113938  rc = sqlite3Init(db, &pParse->zErrMsg);
113939  }
113940  if( rc!=SQLITE_OK ){
113941  pParse->rc = rc;
113942  pParse->nErr++;
113943  }
113944  return rc;
113945 }
113946 
113947 
113948 /*
113949 ** Check schema cookies in all databases. If any cookie is out
113950 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
113951 ** make no changes to pParse->rc.
113952 */
113953 static void schemaIsValid(Parse *pParse){
113954  sqlite3 *db = pParse->db;
113955  int iDb;
113956  int rc;
113957  int cookie;
113958 
113959  assert( pParse->checkSchema );
113960  assert( sqlite3_mutex_held(db->mutex) );
113961  for(iDb=0; iDb<db->nDb; iDb++){
113962  int openedTransaction = 0; /* True if a transaction is opened */
113963  Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
113964  if( pBt==0 ) continue;
113965 
113966  /* If there is not already a read-only (or read-write) transaction opened
113967  ** on the b-tree database, open one now. If a transaction is opened, it
113968  ** will be closed immediately after reading the meta-value. */
113969  if( !sqlite3BtreeIsInReadTrans(pBt) ){
113970  rc = sqlite3BtreeBeginTrans(pBt, 0);
113971  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
113972  sqlite3OomFault(db);
113973  }
113974  if( rc!=SQLITE_OK ) return;
113975  openedTransaction = 1;
113976  }
113977 
113978  /* Read the schema cookie from the database. If it does not match the
113979  ** value stored as part of the in-memory schema representation,
113980  ** set Parse.rc to SQLITE_SCHEMA. */
113981  sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
113982  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113983  if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
113984  sqlite3ResetOneSchema(db, iDb);
113985  pParse->rc = SQLITE_SCHEMA;
113986  }
113987 
113988  /* Close the transaction, if one was opened. */
113989  if( openedTransaction ){
113990  sqlite3BtreeCommit(pBt);
113991  }
113992  }
113993 }
113994 
113995 /*
113996 ** Convert a schema pointer into the iDb index that indicates
113997 ** which database file in db->aDb[] the schema refers to.
113998 **
113999 ** If the same database is attached more than once, the first
114000 ** attached database is returned.
114001 */
114002 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
114003  int i = -1000000;
114004 
114005  /* If pSchema is NULL, then return -1000000. This happens when code in
114006  ** expr.c is trying to resolve a reference to a transient table (i.e. one
114007  ** created by a sub-select). In this case the return value of this
114008  ** function should never be used.
114009  **
114010  ** We return -1000000 instead of the more usual -1 simply because using
114011  ** -1000000 as the incorrect index into db->aDb[] is much
114012  ** more likely to cause a segfault than -1 (of course there are assert()
114013  ** statements too, but it never hurts to play the odds).
114014  */
114015  assert( sqlite3_mutex_held(db->mutex) );
114016  if( pSchema ){
114017  for(i=0; ALWAYS(i<db->nDb); i++){
114018  if( db->aDb[i].pSchema==pSchema ){
114019  break;
114020  }
114021  }
114022  assert( i>=0 && i<db->nDb );
114023  }
114024  return i;
114025 }
114026 
114027 /*
114028 ** Free all memory allocations in the pParse object
114029 */
114031  if( pParse ){
114032  sqlite3 *db = pParse->db;
114033  sqlite3DbFree(db, pParse->aLabel);
114034  sqlite3ExprListDelete(db, pParse->pConstExpr);
114035  if( db ){
114036  assert( db->lookaside.bDisable >= pParse->disableLookaside );
114037  db->lookaside.bDisable -= pParse->disableLookaside;
114038  }
114039  pParse->disableLookaside = 0;
114040  }
114041 }
114042 
114043 /*
114044 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
114045 */
114046 static int sqlite3Prepare(
114047  sqlite3 *db, /* Database handle. */
114048  const char *zSql, /* UTF-8 encoded SQL statement. */
114049  int nBytes, /* Length of zSql in bytes. */
114050  int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
114051  Vdbe *pReprepare, /* VM being reprepared */
114052  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114053  const char **pzTail /* OUT: End of parsed string */
114054 ){
114055  char *zErrMsg = 0; /* Error message */
114056  int rc = SQLITE_OK; /* Result code */
114057  int i; /* Loop counter */
114058  Parse sParse; /* Parsing context */
114059 
114060  memset(&sParse, 0, PARSE_HDR_SZ);
114061  memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
114062  sParse.pReprepare = pReprepare;
114063  assert( ppStmt && *ppStmt==0 );
114064  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
114065  assert( sqlite3_mutex_held(db->mutex) );
114066 
114067  /* Check to verify that it is possible to get a read lock on all
114068  ** database schemas. The inability to get a read lock indicates that
114069  ** some other database connection is holding a write-lock, which in
114070  ** turn means that the other connection has made uncommitted changes
114071  ** to the schema.
114072  **
114073  ** Were we to proceed and prepare the statement against the uncommitted
114074  ** schema changes and if those schema changes are subsequently rolled
114075  ** back and different changes are made in their place, then when this
114076  ** prepared statement goes to run the schema cookie would fail to detect
114077  ** the schema change. Disaster would follow.
114078  **
114079  ** This thread is currently holding mutexes on all Btrees (because
114080  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
114081  ** is not possible for another thread to start a new schema change
114082  ** while this routine is running. Hence, we do not need to hold
114083  ** locks on the schema, we just need to make sure nobody else is
114084  ** holding them.
114085  **
114086  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
114087  ** but it does *not* override schema lock detection, so this all still
114088  ** works even if READ_UNCOMMITTED is set.
114089  */
114090  for(i=0; i<db->nDb; i++) {
114091  Btree *pBt = db->aDb[i].pBt;
114092  if( pBt ){
114093  assert( sqlite3BtreeHoldsMutex(pBt) );
114094  rc = sqlite3BtreeSchemaLocked(pBt);
114095  if( rc ){
114096  const char *zDb = db->aDb[i].zDbSName;
114097  sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
114099  goto end_prepare;
114100  }
114101  }
114102  }
114103 
114104  sqlite3VtabUnlockList(db);
114105 
114106  sParse.db = db;
114107  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
114108  char *zSqlCopy;
114109  int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
114110  testcase( nBytes==mxLen );
114111  testcase( nBytes==mxLen+1 );
114112  if( nBytes>mxLen ){
114113  sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
114114  rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
114115  goto end_prepare;
114116  }
114117  zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
114118  if( zSqlCopy ){
114119  sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
114120  sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
114121  sqlite3DbFree(db, zSqlCopy);
114122  }else{
114123  sParse.zTail = &zSql[nBytes];
114124  }
114125  }else{
114126  sqlite3RunParser(&sParse, zSql, &zErrMsg);
114127  }
114128  assert( 0==sParse.nQueryLoop );
114129 
114130  if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
114131  if( sParse.checkSchema ){
114132  schemaIsValid(&sParse);
114133  }
114134  if( db->mallocFailed ){
114135  sParse.rc = SQLITE_NOMEM_BKPT;
114136  }
114137  if( pzTail ){
114138  *pzTail = sParse.zTail;
114139  }
114140  rc = sParse.rc;
114141 
114142 #ifndef SQLITE_OMIT_EXPLAIN
114143  if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
114144  static const char * const azColName[] = {
114145  "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
114146  "selectid", "order", "from", "detail"
114147  };
114148  int iFirst, mx;
114149  if( sParse.explain==2 ){
114150  sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
114151  iFirst = 8;
114152  mx = 12;
114153  }else{
114154  sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
114155  iFirst = 0;
114156  mx = 8;
114157  }
114158  for(i=iFirst; i<mx; i++){
114159  sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
114160  azColName[i], SQLITE_STATIC);
114161  }
114162  }
114163 #endif
114164 
114165  if( db->init.busy==0 ){
114166  Vdbe *pVdbe = sParse.pVdbe;
114167  sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag);
114168  }
114169  if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
114170  sqlite3VdbeFinalize(sParse.pVdbe);
114171  assert(!(*ppStmt));
114172  }else{
114173  *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
114174  }
114175 
114176  if( zErrMsg ){
114177  sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
114178  sqlite3DbFree(db, zErrMsg);
114179  }else{
114180  sqlite3Error(db, rc);
114181  }
114182 
114183  /* Delete any TriggerPrg structures allocated while parsing this statement. */
114184  while( sParse.pTriggerPrg ){
114185  TriggerPrg *pT = sParse.pTriggerPrg;
114186  sParse.pTriggerPrg = pT->pNext;
114187  sqlite3DbFree(db, pT);
114188  }
114189 
114190 end_prepare:
114191 
114192  sqlite3ParserReset(&sParse);
114193  rc = sqlite3ApiExit(db, rc);
114194  assert( (rc&db->errMask)==rc );
114195  return rc;
114196 }
114198  sqlite3 *db, /* Database handle. */
114199  const char *zSql, /* UTF-8 encoded SQL statement. */
114200  int nBytes, /* Length of zSql in bytes. */
114201  int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
114202  Vdbe *pOld, /* VM being reprepared */
114203  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114204  const char **pzTail /* OUT: End of parsed string */
114205 ){
114206  int rc;
114207 
114208 #ifdef SQLITE_ENABLE_API_ARMOR
114209  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
114210 #endif
114211  *ppStmt = 0;
114212  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
114213  return SQLITE_MISUSE_BKPT;
114214  }
114215  sqlite3_mutex_enter(db->mutex);
114216  sqlite3BtreeEnterAll(db);
114217  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
114218  if( rc==SQLITE_SCHEMA ){
114219  sqlite3_finalize(*ppStmt);
114220  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
114221  }
114222  sqlite3BtreeLeaveAll(db);
114223  sqlite3_mutex_leave(db->mutex);
114224  assert( rc==SQLITE_OK || *ppStmt==0 );
114225  return rc;
114226 }
114227 
114228 /*
114229 ** Rerun the compilation of a statement after a schema change.
114230 **
114231 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
114232 ** if the statement cannot be recompiled because another connection has
114233 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
114234 ** occurs, return SQLITE_SCHEMA.
114235 */
114237  int rc;
114238  sqlite3_stmt *pNew;
114239  const char *zSql;
114240  sqlite3 *db;
114241 
114242  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
114243  zSql = sqlite3_sql((sqlite3_stmt *)p);
114244  assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
114245  db = sqlite3VdbeDb(p);
114246  assert( sqlite3_mutex_held(db->mutex) );
114247  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
114248  if( rc ){
114249  if( rc==SQLITE_NOMEM ){
114250  sqlite3OomFault(db);
114251  }
114252  assert( pNew==0 );
114253  return rc;
114254  }else{
114255  assert( pNew!=0 );
114256  }
114257  sqlite3VdbeSwap((Vdbe*)pNew, p);
114258  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
114260  sqlite3VdbeFinalize((Vdbe*)pNew);
114261  return SQLITE_OK;
114262 }
114263 
114264 
114265 /*
114266 ** Two versions of the official API. Legacy and new use. In the legacy
114267 ** version, the original SQL text is not saved in the prepared statement
114268 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
114269 ** sqlite3_step(). In the new version, the original SQL text is retained
114270 ** and the statement is automatically recompiled if an schema change
114271 ** occurs.
114272 */
114274  sqlite3 *db, /* Database handle. */
114275  const char *zSql, /* UTF-8 encoded SQL statement. */
114276  int nBytes, /* Length of zSql in bytes. */
114277  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114278  const char **pzTail /* OUT: End of parsed string */
114279 ){
114280  int rc;
114281  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
114282  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114283  return rc;
114284 }
114286  sqlite3 *db, /* Database handle. */
114287  const char *zSql, /* UTF-8 encoded SQL statement. */
114288  int nBytes, /* Length of zSql in bytes. */
114289  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114290  const char **pzTail /* OUT: End of parsed string */
114291 ){
114292  int rc;
114293  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
114294  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114295  return rc;
114296 }
114297 
114298 
114299 #ifndef SQLITE_OMIT_UTF16
114300 /*
114301 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
114302 */
114304  sqlite3 *db, /* Database handle. */
114305  const void *zSql, /* UTF-16 encoded SQL statement. */
114306  int nBytes, /* Length of zSql in bytes. */
114307  int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
114308  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114309  const void **pzTail /* OUT: End of parsed string */
114310 ){
114311  /* This function currently works by first transforming the UTF-16
114312  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
114313  ** tricky bit is figuring out the pointer to return in *pzTail.
114314  */
114315  char *zSql8;
114316  const char *zTail8 = 0;
114317  int rc = SQLITE_OK;
114318 
114319 #ifdef SQLITE_ENABLE_API_ARMOR
114320  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
114321 #endif
114322  *ppStmt = 0;
114323  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
114324  return SQLITE_MISUSE_BKPT;
114325  }
114326  if( nBytes>=0 ){
114327  int sz;
114328  const char *z = (const char*)zSql;
114329  for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
114330  nBytes = sz;
114331  }
114332  sqlite3_mutex_enter(db->mutex);
114333  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
114334  if( zSql8 ){
114335  rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
114336  }
114337 
114338  if( zTail8 && pzTail ){
114339  /* If sqlite3_prepare returns a tail pointer, we calculate the
114340  ** equivalent pointer into the UTF-16 string by counting the unicode
114341  ** characters between zSql8 and zTail8, and then returning a pointer
114342  ** the same number of characters into the UTF-16 string.
114343  */
114344  int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
114345  *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
114346  }
114347  sqlite3DbFree(db, zSql8);
114348  rc = sqlite3ApiExit(db, rc);
114349  sqlite3_mutex_leave(db->mutex);
114350  return rc;
114351 }
114352 
114353 /*
114354 ** Two versions of the official API. Legacy and new use. In the legacy
114355 ** version, the original SQL text is not saved in the prepared statement
114356 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
114357 ** sqlite3_step(). In the new version, the original SQL text is retained
114358 ** and the statement is automatically recompiled if an schema change
114359 ** occurs.
114360 */
114362  sqlite3 *db, /* Database handle. */
114363  const void *zSql, /* UTF-16 encoded SQL statement. */
114364  int nBytes, /* Length of zSql in bytes. */
114365  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114366  const void **pzTail /* OUT: End of parsed string */
114367 ){
114368  int rc;
114369  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
114370  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114371  return rc;
114372 }
114374  sqlite3 *db, /* Database handle. */
114375  const void *zSql, /* UTF-16 encoded SQL statement. */
114376  int nBytes, /* Length of zSql in bytes. */
114377  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
114378  const void **pzTail /* OUT: End of parsed string */
114379 ){
114380  int rc;
114381  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
114382  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
114383  return rc;
114384 }
114385 
114386 #endif /* SQLITE_OMIT_UTF16 */
114387 
114388 /************** End of prepare.c *********************************************/
114389 /************** Begin file select.c ******************************************/
114390 /*
114391 ** 2001 September 15
114392 **
114393 ** The author disclaims copyright to this source code. In place of
114394 ** a legal notice, here is a blessing:
114395 **
114396 ** May you do good and not evil.
114397 ** May you find forgiveness for yourself and forgive others.
114398 ** May you share freely, never taking more than you give.
114399 **
114400 *************************************************************************
114401 ** This file contains C code routines that are called by the parser
114402 ** to handle SELECT statements in SQLite.
114403 */
114404 /* #include "sqliteInt.h" */
114405 
114406 /*
114407 ** Trace output macros
114408 */
114409 #if SELECTTRACE_ENABLED
114410 /***/ int sqlite3SelectTrace = 0;
114411 # define SELECTTRACE(K,P,S,X) \
114412  if(sqlite3SelectTrace&(K)) \
114413  sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
114414  (S)->zSelName,(S)),\
114415  sqlite3DebugPrintf X
114416 #else
114417 # define SELECTTRACE(K,P,S,X)
114418 #endif
114419 
114420 
114421 /*
114422 ** An instance of the following object is used to record information about
114423 ** how to process the DISTINCT keyword, to simplify passing that information
114424 ** into the selectInnerLoop() routine.
114425 */
114426 typedef struct DistinctCtx DistinctCtx;
114428  u8 isTnct; /* True if the DISTINCT keyword is present */
114429  u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
114430  int tabTnct; /* Ephemeral table used for DISTINCT processing */
114431  int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
114432 };
114433 
114434 /*
114435 ** An instance of the following object is used to record information about
114436 ** the ORDER BY (or GROUP BY) clause of query is being coded.
114437 */
114438 typedef struct SortCtx SortCtx;
114439 struct SortCtx {
114440  ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
114441  int nOBSat; /* Number of ORDER BY terms satisfied by indices */
114442  int iECursor; /* Cursor number for the sorter */
114443  int regReturn; /* Register holding block-output return address */
114444  int labelBkOut; /* Start label for the block-output subroutine */
114445  int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
114446  int labelDone; /* Jump here when done, ex: LIMIT reached */
114447  u8 sortFlags; /* Zero or more SORTFLAG_* bits */
114448  u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
114449 };
114450 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
114451 
114452 /*
114453 ** Delete all the content of a Select structure. Deallocate the structure
114454 ** itself only if bFree is true.
114455 */
114456 static void clearSelect(sqlite3 *db, Select *p, int bFree){
114457  while( p ){
114458  Select *pPrior = p->pPrior;
114459  sqlite3ExprListDelete(db, p->pEList);
114460  sqlite3SrcListDelete(db, p->pSrc);
114461  sqlite3ExprDelete(db, p->pWhere);
114463  sqlite3ExprDelete(db, p->pHaving);
114465  sqlite3ExprDelete(db, p->pLimit);
114466  sqlite3ExprDelete(db, p->pOffset);
114467  if( p->pWith ) sqlite3WithDelete(db, p->pWith);
114468  if( bFree ) sqlite3DbFree(db, p);
114469  p = pPrior;
114470  bFree = 1;
114471  }
114472 }
114473 
114474 /*
114475 ** Initialize a SelectDest structure.
114476 */
114477 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
114478  pDest->eDest = (u8)eDest;
114479  pDest->iSDParm = iParm;
114480  pDest->zAffSdst = 0;
114481  pDest->iSdst = 0;
114482  pDest->nSdst = 0;
114483 }
114484 
114485 
114486 /*
114487 ** Allocate a new Select structure and return a pointer to that
114488 ** structure.
114489 */
114491  Parse *pParse, /* Parsing context */
114492  ExprList *pEList, /* which columns to include in the result */
114493  SrcList *pSrc, /* the FROM clause -- which tables to scan */
114494  Expr *pWhere, /* the WHERE clause */
114495  ExprList *pGroupBy, /* the GROUP BY clause */
114496  Expr *pHaving, /* the HAVING clause */
114497  ExprList *pOrderBy, /* the ORDER BY clause */
114498  u32 selFlags, /* Flag parameters, such as SF_Distinct */
114499  Expr *pLimit, /* LIMIT value. NULL means not used */
114500  Expr *pOffset /* OFFSET value. NULL means no offset */
114501 ){
114502  Select *pNew;
114503  Select standin;
114504  sqlite3 *db = pParse->db;
114505  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
114506  if( pNew==0 ){
114507  assert( db->mallocFailed );
114508  pNew = &standin;
114509  }
114510  if( pEList==0 ){
114511  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
114512  }
114513  pNew->pEList = pEList;
114514  pNew->op = TK_SELECT;
114515  pNew->selFlags = selFlags;
114516  pNew->iLimit = 0;
114517  pNew->iOffset = 0;
114518 #if SELECTTRACE_ENABLED
114519  pNew->zSelName[0] = 0;
114520 #endif
114521  pNew->addrOpenEphm[0] = -1;
114522  pNew->addrOpenEphm[1] = -1;
114523  pNew->nSelectRow = 0;
114524  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
114525  pNew->pSrc = pSrc;
114526  pNew->pWhere = pWhere;
114527  pNew->pGroupBy = pGroupBy;
114528  pNew->pHaving = pHaving;
114529  pNew->pOrderBy = pOrderBy;
114530  pNew->pPrior = 0;
114531  pNew->pNext = 0;
114532  pNew->pLimit = pLimit;
114533  pNew->pOffset = pOffset;
114534  pNew->pWith = 0;
114535  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
114536  if( db->mallocFailed ) {
114537  clearSelect(db, pNew, pNew!=&standin);
114538  pNew = 0;
114539  }else{
114540  assert( pNew->pSrc!=0 || pParse->nErr>0 );
114541  }
114542  assert( pNew!=&standin );
114543  return pNew;
114544 }
114545 
114546 #if SELECTTRACE_ENABLED
114547 /*
114548 ** Set the name of a Select object
114549 */
114550 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
114551  if( p && zName ){
114552  sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
114553  }
114554 }
114555 #endif
114556 
114557 
114558 /*
114559 ** Delete the given Select structure and all of its substructures.
114560 */
114562  if( p ) clearSelect(db, p, 1);
114563 }
114564 
114565 /*
114566 ** Return a pointer to the right-most SELECT statement in a compound.
114567 */
114569  while( p->pNext ) p = p->pNext;
114570  return p;
114571 }
114572 
114573 /*
114574 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
114575 ** type of join. Return an integer constant that expresses that type
114576 ** in terms of the following bit values:
114577 **
114578 ** JT_INNER
114579 ** JT_CROSS
114580 ** JT_OUTER
114581 ** JT_NATURAL
114582 ** JT_LEFT
114583 ** JT_RIGHT
114584 **
114585 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
114586 **
114587 ** If an illegal or unsupported join type is seen, then still return
114588 ** a join type, but put an error in the pParse structure.
114589 */
114591  int jointype = 0;
114592  Token *apAll[3];
114593  Token *p;
114594  /* 0123456789 123456789 123456789 123 */
114595  static const char zKeyText[] = "naturaleftouterightfullinnercross";
114596  static const struct {
114597  u8 i; /* Beginning of keyword text in zKeyText[] */
114598  u8 nChar; /* Length of the keyword in characters */
114599  u8 code; /* Join type mask */
114600  } aKeyword[] = {
114601  /* natural */ { 0, 7, JT_NATURAL },
114602  /* left */ { 6, 4, JT_LEFT|JT_OUTER },
114603  /* outer */ { 10, 5, JT_OUTER },
114604  /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
114605  /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
114606  /* inner */ { 23, 5, JT_INNER },
114607  /* cross */ { 28, 5, JT_INNER|JT_CROSS },
114608  };
114609  int i, j;
114610  apAll[0] = pA;
114611  apAll[1] = pB;
114612  apAll[2] = pC;
114613  for(i=0; i<3 && apAll[i]; i++){
114614  p = apAll[i];
114615  for(j=0; j<ArraySize(aKeyword); j++){
114616  if( p->n==aKeyword[j].nChar
114617  && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
114618  jointype |= aKeyword[j].code;
114619  break;
114620  }
114621  }
114622  testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
114623  if( j>=ArraySize(aKeyword) ){
114624  jointype |= JT_ERROR;
114625  break;
114626  }
114627  }
114628  if(
114629  (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
114630  (jointype & JT_ERROR)!=0
114631  ){
114632  const char *zSp = " ";
114633  assert( pB!=0 );
114634  if( pC==0 ){ zSp++; }
114635  sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
114636  "%T %T%s%T", pA, pB, zSp, pC);
114637  jointype = JT_INNER;
114638  }else if( (jointype & JT_OUTER)!=0
114639  && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
114640  sqlite3ErrorMsg(pParse,
114641  "RIGHT and FULL OUTER JOINs are not currently supported");
114642  jointype = JT_INNER;
114643  }
114644  return jointype;
114645 }
114646 
114647 /*
114648 ** Return the index of a column in a table. Return -1 if the column
114649 ** is not contained in the table.
114650 */
114651 static int columnIndex(Table *pTab, const char *zCol){
114652  int i;
114653  for(i=0; i<pTab->nCol; i++){
114654  if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
114655  }
114656  return -1;
114657 }
114658 
114659 /*
114660 ** Search the first N tables in pSrc, from left to right, looking for a
114661 ** table that has a column named zCol.
114662 **
114663 ** When found, set *piTab and *piCol to the table index and column index
114664 ** of the matching column and return TRUE.
114665 **
114666 ** If not found, return FALSE.
114667 */
114669  SrcList *pSrc, /* Array of tables to search */
114670  int N, /* Number of tables in pSrc->a[] to search */
114671  const char *zCol, /* Name of the column we are looking for */
114672  int *piTab, /* Write index of pSrc->a[] here */
114673  int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
114674 ){
114675  int i; /* For looping over tables in pSrc */
114676  int iCol; /* Index of column matching zCol */
114677 
114678  assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
114679  for(i=0; i<N; i++){
114680  iCol = columnIndex(pSrc->a[i].pTab, zCol);
114681  if( iCol>=0 ){
114682  if( piTab ){
114683  *piTab = i;
114684  *piCol = iCol;
114685  }
114686  return 1;
114687  }
114688  }
114689  return 0;
114690 }
114691 
114692 /*
114693 ** This function is used to add terms implied by JOIN syntax to the
114694 ** WHERE clause expression of a SELECT statement. The new term, which
114695 ** is ANDed with the existing WHERE clause, is of the form:
114696 **
114697 ** (tab1.col1 = tab2.col2)
114698 **
114699 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
114700 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
114701 ** column iColRight of tab2.
114702 */
114703 static void addWhereTerm(
114704  Parse *pParse, /* Parsing context */
114705  SrcList *pSrc, /* List of tables in FROM clause */
114706  int iLeft, /* Index of first table to join in pSrc */
114707  int iColLeft, /* Index of column in first table */
114708  int iRight, /* Index of second table in pSrc */
114709  int iColRight, /* Index of column in second table */
114710  int isOuterJoin, /* True if this is an OUTER join */
114711  Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
114712 ){
114713  sqlite3 *db = pParse->db;
114714  Expr *pE1;
114715  Expr *pE2;
114716  Expr *pEq;
114717 
114718  assert( iLeft<iRight );
114719  assert( pSrc->nSrc>iRight );
114720  assert( pSrc->a[iLeft].pTab );
114721  assert( pSrc->a[iRight].pTab );
114722 
114723  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
114724  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
114725 
114726  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
114727  if( pEq && isOuterJoin ){
114729  assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
114731  pEq->iRightJoinTable = (i16)pE2->iTable;
114732  }
114733  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
114734 }
114735 
114736 /*
114737 ** Set the EP_FromJoin property on all terms of the given expression.
114738 ** And set the Expr.iRightJoinTable to iTable for every term in the
114739 ** expression.
114740 **
114741 ** The EP_FromJoin property is used on terms of an expression to tell
114742 ** the LEFT OUTER JOIN processing logic that this term is part of the
114743 ** join restriction specified in the ON or USING clause and not a part
114744 ** of the more general WHERE clause. These terms are moved over to the
114745 ** WHERE clause during join processing but we need to remember that they
114746 ** originated in the ON or USING clause.
114747 **
114748 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
114749 ** expression depends on table iRightJoinTable even if that table is not
114750 ** explicitly mentioned in the expression. That information is needed
114751 ** for cases like this:
114752 **
114753 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
114754 **
114755 ** The where clause needs to defer the handling of the t1.x=5
114756 ** term until after the t2 loop of the join. In that way, a
114757 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
114758 ** defer the handling of t1.x=5, it will be processed immediately
114759 ** after the t1 loop and rows with t1.x!=5 will never appear in
114760 ** the output, which is incorrect.
114761 */
114762 static void setJoinExpr(Expr *p, int iTable){
114763  while( p ){
114765  assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
114767  p->iRightJoinTable = (i16)iTable;
114768  if( p->op==TK_FUNCTION && p->x.pList ){
114769  int i;
114770  for(i=0; i<p->x.pList->nExpr; i++){
114771  setJoinExpr(p->x.pList->a[i].pExpr, iTable);
114772  }
114773  }
114774  setJoinExpr(p->pLeft, iTable);
114775  p = p->pRight;
114776  }
114777 }
114778 
114779 /*
114780 ** This routine processes the join information for a SELECT statement.
114781 ** ON and USING clauses are converted into extra terms of the WHERE clause.
114782 ** NATURAL joins also create extra WHERE clause terms.
114783 **
114784 ** The terms of a FROM clause are contained in the Select.pSrc structure.
114785 ** The left most table is the first entry in Select.pSrc. The right-most
114786 ** table is the last entry. The join operator is held in the entry to
114787 ** the left. Thus entry 0 contains the join operator for the join between
114788 ** entries 0 and 1. Any ON or USING clauses associated with the join are
114789 ** also attached to the left entry.
114790 **
114791 ** This routine returns the number of errors encountered.
114792 */
114793 static int sqliteProcessJoin(Parse *pParse, Select *p){
114794  SrcList *pSrc; /* All tables in the FROM clause */
114795  int i, j; /* Loop counters */
114796  struct SrcList_item *pLeft; /* Left table being joined */
114797  struct SrcList_item *pRight; /* Right table being joined */
114798 
114799  pSrc = p->pSrc;
114800  pLeft = &pSrc->a[0];
114801  pRight = &pLeft[1];
114802  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
114803  Table *pLeftTab = pLeft->pTab;
114804  Table *pRightTab = pRight->pTab;
114805  int isOuter;
114806 
114807  if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
114808  isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
114809 
114810  /* When the NATURAL keyword is present, add WHERE clause terms for
114811  ** every column that the two tables have in common.
114812  */
114813  if( pRight->fg.jointype & JT_NATURAL ){
114814  if( pRight->pOn || pRight->pUsing ){
114815  sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
114816  "an ON or USING clause", 0);
114817  return 1;
114818  }
114819  for(j=0; j<pRightTab->nCol; j++){
114820  char *zName; /* Name of column in the right table */
114821  int iLeft; /* Matching left table */
114822  int iLeftCol; /* Matching column in the left table */
114823 
114824  zName = pRightTab->aCol[j].zName;
114825  if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
114826  addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
114827  isOuter, &p->pWhere);
114828  }
114829  }
114830  }
114831 
114832  /* Disallow both ON and USING clauses in the same join
114833  */
114834  if( pRight->pOn && pRight->pUsing ){
114835  sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
114836  "clauses in the same join");
114837  return 1;
114838  }
114839 
114840  /* Add the ON clause to the end of the WHERE clause, connected by
114841  ** an AND operator.
114842  */
114843  if( pRight->pOn ){
114844  if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
114845  p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
114846  pRight->pOn = 0;
114847  }
114848 
114849  /* Create extra terms on the WHERE clause for each column named
114850  ** in the USING clause. Example: If the two tables to be joined are
114851  ** A and B and the USING clause names X, Y, and Z, then add this
114852  ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
114853  ** Report an error if any column mentioned in the USING clause is
114854  ** not contained in both tables to be joined.
114855  */
114856  if( pRight->pUsing ){
114857  IdList *pList = pRight->pUsing;
114858  for(j=0; j<pList->nId; j++){
114859  char *zName; /* Name of the term in the USING clause */
114860  int iLeft; /* Table on the left with matching column name */
114861  int iLeftCol; /* Column number of matching column on the left */
114862  int iRightCol; /* Column number of matching column on the right */
114863 
114864  zName = pList->a[j].zName;
114865  iRightCol = columnIndex(pRightTab, zName);
114866  if( iRightCol<0
114867  || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
114868  ){
114869  sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
114870  "not present in both tables", zName);
114871  return 1;
114872  }
114873  addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
114874  isOuter, &p->pWhere);
114875  }
114876  }
114877  }
114878  return 0;
114879 }
114880 
114881 /* Forward reference */
114882 static KeyInfo *keyInfoFromExprList(
114883  Parse *pParse, /* Parsing context */
114884  ExprList *pList, /* Form the KeyInfo object from this ExprList */
114885  int iStart, /* Begin with this column of pList */
114886  int nExtra /* Add this many extra columns to the end */
114887 );
114888 
114889 /*
114890 ** Generate code that will push the record in registers regData
114891 ** through regData+nData-1 onto the sorter.
114892 */
114893 static void pushOntoSorter(
114894  Parse *pParse, /* Parser context */
114895  SortCtx *pSort, /* Information about the ORDER BY clause */
114896  Select *pSelect, /* The whole SELECT statement */
114897  int regData, /* First register holding data to be sorted */
114898  int regOrigData, /* First register holding data before packing */
114899  int nData, /* Number of elements in the data array */
114900  int nPrefixReg /* No. of reg prior to regData available for use */
114901 ){
114902  Vdbe *v = pParse->pVdbe; /* Stmt under construction */
114903  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
114904  int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
114905  int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
114906  int regBase; /* Regs for sorter record */
114907  int regRecord = ++pParse->nMem; /* Assembled sorter record */
114908  int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
114909  int op; /* Opcode to add sorter record to sorter */
114910  int iLimit; /* LIMIT counter */
114911 
114912  assert( bSeq==0 || bSeq==1 );
114913  assert( nData==1 || regData==regOrigData );
114914  if( nPrefixReg ){
114915  assert( nPrefixReg==nExpr+bSeq );
114916  regBase = regData - nExpr - bSeq;
114917  }else{
114918  regBase = pParse->nMem + 1;
114919  pParse->nMem += nBase;
114920  }
114921  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
114922  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
114923  pSort->labelDone = sqlite3VdbeMakeLabel(v);
114924  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
114926  if( bSeq ){
114927  sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
114928  }
114929  if( nPrefixReg==0 ){
114930  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
114931  }
114932  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
114933  if( nOBSat>0 ){
114934  int regPrevKey; /* The first nOBSat columns of the previous row */
114935  int addrFirst; /* Address of the OP_IfNot opcode */
114936  int addrJmp; /* Address of the OP_Jump opcode */
114937  VdbeOp *pOp; /* Opcode that opens the sorter */
114938  int nKey; /* Number of sorting key columns, including OP_Sequence */
114939  KeyInfo *pKI; /* Original KeyInfo on the sorter table */
114940 
114941  regPrevKey = pParse->nMem+1;
114942  pParse->nMem += pSort->nOBSat;
114943  nKey = nExpr - pSort->nOBSat + bSeq;
114944  if( bSeq ){
114945  addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
114946  }else{
114947  addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
114948  }
114949  VdbeCoverage(v);
114950  sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
114951  pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
114952  if( pParse->db->mallocFailed ) return;
114953  pOp->p2 = nKey + nData;
114954  pKI = pOp->p4.pKeyInfo;
114955  memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
114956  sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
114957  testcase( pKI->nXField>2 );
114958  pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
114959  pKI->nXField-1);
114960  addrJmp = sqlite3VdbeCurrentAddr(v);
114961  sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
114962  pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
114963  pSort->regReturn = ++pParse->nMem;
114964  sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114966  if( iLimit ){
114967  sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
114968  VdbeCoverage(v);
114969  }
114970  sqlite3VdbeJumpHere(v, addrFirst);
114971  sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
114972  sqlite3VdbeJumpHere(v, addrJmp);
114973  }
114974  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114975  op = OP_SorterInsert;
114976  }else{
114977  op = OP_IdxInsert;
114978  }
114979  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
114980  if( iLimit ){
114981  int addr;
114982  int r1 = 0;
114983  /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit
114984  ** register is initialized with value of LIMIT+OFFSET.) After the sorter
114985  ** fills up, delete the least entry in the sorter after each insert.
114986  ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
114987  addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
114988  sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
114989  if( pSort->bOrderedInnerLoop ){
114990  r1 = ++pParse->nMem;
114991  sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
114992  VdbeComment((v, "seq"));
114993  }
114994  sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
114995  if( pSort->bOrderedInnerLoop ){
114996  /* If the inner loop is driven by an index such that values from
114997  ** the same iteration of the inner loop are in sorted order, then
114998  ** immediately jump to the next iteration of an inner loop if the
114999  ** entry from the current iteration does not fit into the top
115000  ** LIMIT+OFFSET entries of the sorter. */
115001  int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
115002  sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
115004  VdbeCoverage(v);
115005  }
115006  sqlite3VdbeJumpHere(v, addr);
115007  }
115008 }
115009 
115010 /*
115011 ** Add code to implement the OFFSET
115012 */
115013 static void codeOffset(
115014  Vdbe *v, /* Generate code into this VM */
115015  int iOffset, /* Register holding the offset counter */
115016  int iContinue /* Jump here to skip the current record */
115017 ){
115018  if( iOffset>0 ){
115019  sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
115020  VdbeComment((v, "OFFSET"));
115021  }
115022 }
115023 
115024 /*
115025 ** Add code that will check to make sure the N registers starting at iMem
115026 ** form a distinct entry. iTab is a sorting index that holds previously
115027 ** seen combinations of the N values. A new entry is made in iTab
115028 ** if the current N values are new.
115029 **
115030 ** A jump to addrRepeat is made and the N+1 values are popped from the
115031 ** stack if the top N elements are not distinct.
115032 */
115033 static void codeDistinct(
115034  Parse *pParse, /* Parsing and code generating context */
115035  int iTab, /* A sorting index used to test for distinctness */
115036  int addrRepeat, /* Jump to here if not distinct */
115037  int N, /* Number of elements */
115038  int iMem /* First element */
115039 ){
115040  Vdbe *v;
115041  int r1;
115042 
115043  v = pParse->pVdbe;
115044  r1 = sqlite3GetTempReg(pParse);
115045  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
115046  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
115047  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
115048  sqlite3ReleaseTempReg(pParse, r1);
115049 }
115050 
115051 /*
115052 ** This routine generates the code for the inside of the inner loop
115053 ** of a SELECT.
115054 **
115055 ** If srcTab is negative, then the pEList expressions
115056 ** are evaluated in order to get the data for this row. If srcTab is
115057 ** zero or more, then data is pulled from srcTab and pEList is used only
115058 ** to get number columns and the datatype for each column.
115059 */
115060 static void selectInnerLoop(
115061  Parse *pParse, /* The parser context */
115062  Select *p, /* The complete select statement being coded */
115063  ExprList *pEList, /* List of values being extracted */
115064  int srcTab, /* Pull data from this table */
115065  SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
115066  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
115067  SelectDest *pDest, /* How to dispose of the results */
115068  int iContinue, /* Jump here to continue with next row */
115069  int iBreak /* Jump here to break out of the inner loop */
115070 ){
115071  Vdbe *v = pParse->pVdbe;
115072  int i;
115073  int hasDistinct; /* True if the DISTINCT keyword is present */
115074  int regResult; /* Start of memory holding result set */
115075  int eDest = pDest->eDest; /* How to dispose of results */
115076  int iParm = pDest->iSDParm; /* First argument to disposal method */
115077  int nResultCol; /* Number of result columns */
115078  int nPrefixReg = 0; /* Number of extra registers before regResult */
115079 
115080  assert( v );
115081  assert( pEList!=0 );
115082  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
115083  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
115084  if( pSort==0 && !hasDistinct ){
115085  assert( iContinue!=0 );
115086  codeOffset(v, p->iOffset, iContinue);
115087  }
115088 
115089  /* Pull the requested columns.
115090  */
115091  nResultCol = pEList->nExpr;
115092 
115093  if( pDest->iSdst==0 ){
115094  if( pSort ){
115095  nPrefixReg = pSort->pOrderBy->nExpr;
115096  if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
115097  pParse->nMem += nPrefixReg;
115098  }
115099  pDest->iSdst = pParse->nMem+1;
115100  pParse->nMem += nResultCol;
115101  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
115102  /* This is an error condition that can result, for example, when a SELECT
115103  ** on the right-hand side of an INSERT contains more result columns than
115104  ** there are columns in the table on the left. The error will be caught
115105  ** and reported later. But we need to make sure enough memory is allocated
115106  ** to avoid other spurious errors in the meantime. */
115107  pParse->nMem += nResultCol;
115108  }
115109  pDest->nSdst = nResultCol;
115110  regResult = pDest->iSdst;
115111  if( srcTab>=0 ){
115112  for(i=0; i<nResultCol; i++){
115113  sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
115114  VdbeComment((v, "%s", pEList->a[i].zName));
115115  }
115116  }else if( eDest!=SRT_Exists ){
115117  /* If the destination is an EXISTS(...) expression, the actual
115118  ** values returned by the SELECT are not required.
115119  */
115120  u8 ecelFlags;
115121  if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
115122  ecelFlags = SQLITE_ECEL_DUP;
115123  }else{
115124  ecelFlags = 0;
115125  }
115126  sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
115127  }
115128 
115129  /* If the DISTINCT keyword was present on the SELECT statement
115130  ** and this row has been seen before, then do not make this row
115131  ** part of the result.
115132  */
115133  if( hasDistinct ){
115134  switch( pDistinct->eTnctType ){
115135  case WHERE_DISTINCT_ORDERED: {
115136  VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
115137  int iJump; /* Jump destination */
115138  int regPrev; /* Previous row content */
115139 
115140  /* Allocate space for the previous row */
115141  regPrev = pParse->nMem+1;
115142  pParse->nMem += nResultCol;
115143 
115144  /* Change the OP_OpenEphemeral coded earlier to an OP_Null
115145  ** sets the MEM_Cleared bit on the first register of the
115146  ** previous value. This will cause the OP_Ne below to always
115147  ** fail on the first iteration of the loop even if the first
115148  ** row is all NULLs.
115149  */
115150  sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
115151  pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
115152  pOp->opcode = OP_Null;
115153  pOp->p1 = 1;
115154  pOp->p2 = regPrev;
115155 
115156  iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
115157  for(i=0; i<nResultCol; i++){
115158  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
115159  if( i<nResultCol-1 ){
115160  sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
115161  VdbeCoverage(v);
115162  }else{
115163  sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
115164  VdbeCoverage(v);
115165  }
115166  sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
115168  }
115169  assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
115170  sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
115171  break;
115172  }
115173 
115174  case WHERE_DISTINCT_UNIQUE: {
115175  sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
115176  break;
115177  }
115178 
115179  default: {
115180  assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
115181  codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
115182  regResult);
115183  break;
115184  }
115185  }
115186  if( pSort==0 ){
115187  codeOffset(v, p->iOffset, iContinue);
115188  }
115189  }
115190 
115191  switch( eDest ){
115192  /* In this mode, write each query result to the key of the temporary
115193  ** table iParm.
115194  */
115195 #ifndef SQLITE_OMIT_COMPOUND_SELECT
115196  case SRT_Union: {
115197  int r1;
115198  r1 = sqlite3GetTempReg(pParse);
115199  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
115200  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
115201  sqlite3ReleaseTempReg(pParse, r1);
115202  break;
115203  }
115204 
115205  /* Construct a record from the query result, but instead of
115206  ** saving that record, use it as a key to delete elements from
115207  ** the temporary table iParm.
115208  */
115209  case SRT_Except: {
115210  sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
115211  break;
115212  }
115213 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
115214 
115215  /* Store the result as data using a unique key.
115216  */
115217  case SRT_Fifo:
115218  case SRT_DistFifo:
115219  case SRT_Table:
115220  case SRT_EphemTab: {
115221  int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
115222  testcase( eDest==SRT_Table );
115223  testcase( eDest==SRT_EphemTab );
115224  testcase( eDest==SRT_Fifo );
115225  testcase( eDest==SRT_DistFifo );
115226  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
115227 #ifndef SQLITE_OMIT_CTE
115228  if( eDest==SRT_DistFifo ){
115229  /* If the destination is DistFifo, then cursor (iParm+1) is open
115230  ** on an ephemeral index. If the current row is already present
115231  ** in the index, do not write it to the output. If not, add the
115232  ** current row to the index and proceed with writing it to the
115233  ** output table as well. */
115234  int addr = sqlite3VdbeCurrentAddr(v) + 4;
115235  sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
115236  VdbeCoverage(v);
115237  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
115238  assert( pSort==0 );
115239  }
115240 #endif
115241  if( pSort ){
115242  pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
115243  }else{
115244  int r2 = sqlite3GetTempReg(pParse);
115245  sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
115246  sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
115248  sqlite3ReleaseTempReg(pParse, r2);
115249  }
115250  sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
115251  break;
115252  }
115253 
115254 #ifndef SQLITE_OMIT_SUBQUERY
115255  /* If we are creating a set for an "expr IN (SELECT ...)" construct,
115256  ** then there should be a single item on the stack. Write this
115257  ** item into the set table with bogus data.
115258  */
115259  case SRT_Set: {
115260  if( pSort ){
115261  /* At first glance you would think we could optimize out the
115262  ** ORDER BY in this case since the order of entries in the set
115263  ** does not matter. But there might be a LIMIT clause, in which
115264  ** case the order does matter */
115265  pushOntoSorter(
115266  pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg);
115267  }else{
115268  int r1 = sqlite3GetTempReg(pParse);
115269  assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
115270  sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
115271  r1, pDest->zAffSdst, nResultCol);
115272  sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
115273  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
115274  sqlite3ReleaseTempReg(pParse, r1);
115275  }
115276  break;
115277  }
115278 
115279  /* If any row exist in the result set, record that fact and abort.
115280  */
115281  case SRT_Exists: {
115282  sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
115283  /* The LIMIT clause will terminate the loop for us */
115284  break;
115285  }
115286 
115287  /* If this is a scalar select that is part of an expression, then
115288  ** store the results in the appropriate memory cell or array of
115289  ** memory cells and break out of the scan loop.
115290  */
115291  case SRT_Mem: {
115292  assert( nResultCol==pDest->nSdst );
115293  if( pSort ){
115294  pushOntoSorter(
115295  pParse, pSort, p, regResult, regResult, nResultCol, nPrefixReg);
115296  }else{
115297  assert( regResult==iParm );
115298  /* The LIMIT clause will jump out of the loop for us */
115299  }
115300  break;
115301  }
115302 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
115303 
115304  case SRT_Coroutine: /* Send data to a co-routine */
115305  case SRT_Output: { /* Return the results */
115306  testcase( eDest==SRT_Coroutine );
115307  testcase( eDest==SRT_Output );
115308  if( pSort ){
115309  pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
115310  nPrefixReg);
115311  }else if( eDest==SRT_Coroutine ){
115312  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
115313  }else{
115314  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
115315  sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
115316  }
115317  break;
115318  }
115319 
115320 #ifndef SQLITE_OMIT_CTE
115321  /* Write the results into a priority queue that is order according to
115322  ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
115323  ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
115324  ** pSO->nExpr columns, then make sure all keys are unique by adding a
115325  ** final OP_Sequence column. The last column is the record as a blob.
115326  */
115327  case SRT_DistQueue:
115328  case SRT_Queue: {
115329  int nKey;
115330  int r1, r2, r3;
115331  int addrTest = 0;
115332  ExprList *pSO;
115333  pSO = pDest->pOrderBy;
115334  assert( pSO );
115335  nKey = pSO->nExpr;
115336  r1 = sqlite3GetTempReg(pParse);
115337  r2 = sqlite3GetTempRange(pParse, nKey+2);
115338  r3 = r2+nKey+1;
115339  if( eDest==SRT_DistQueue ){
115340  /* If the destination is DistQueue, then cursor (iParm+1) is open
115341  ** on a second ephemeral index that holds all values every previously
115342  ** added to the queue. */
115343  addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
115344  regResult, nResultCol);
115345  VdbeCoverage(v);
115346  }
115347  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
115348  if( eDest==SRT_DistQueue ){
115349  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
115351  }
115352  for(i=0; i<nKey; i++){
115354  regResult + pSO->a[i].u.x.iOrderByCol - 1,
115355  r2+i);
115356  }
115357  sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
115358  sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
115359  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
115360  if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
115361  sqlite3ReleaseTempReg(pParse, r1);
115362  sqlite3ReleaseTempRange(pParse, r2, nKey+2);
115363  break;
115364  }
115365 #endif /* SQLITE_OMIT_CTE */
115366 
115367 
115368 
115369 #if !defined(SQLITE_OMIT_TRIGGER)
115370  /* Discard the results. This is used for SELECT statements inside
115371  ** the body of a TRIGGER. The purpose of such selects is to call
115372  ** user-defined functions that have side effects. We do not care
115373  ** about the actual results of the select.
115374  */
115375  default: {
115376  assert( eDest==SRT_Discard );
115377  break;
115378  }
115379 #endif
115380  }
115381 
115382  /* Jump to the end of the loop if the LIMIT is reached. Except, if
115383  ** there is a sorter, in which case the sorter has already limited
115384  ** the output for us.
115385  */
115386  if( pSort==0 && p->iLimit ){
115388  }
115389 }
115390 
115391 /*
115392 ** Allocate a KeyInfo object sufficient for an index of N key columns and
115393 ** X extra columns.
115394 */
115395 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
115396  int nExtra = (N+X)*(sizeof(CollSeq*)+1);
115397  KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
115398  if( p ){
115399  p->aSortOrder = (u8*)&p->aColl[N+X];
115400  p->nField = (u16)N;
115401  p->nXField = (u16)X;
115402  p->enc = ENC(db);
115403  p->db = db;
115404  p->nRef = 1;
115405  memset(&p[1], 0, nExtra);
115406  }else{
115407  sqlite3OomFault(db);
115408  }
115409  return p;
115410 }
115411 
115412 /*
115413 ** Deallocate a KeyInfo object
115414 */
115416  if( p ){
115417  assert( p->nRef>0 );
115418  p->nRef--;
115419  if( p->nRef==0 ) sqlite3DbFree(p->db, p);
115420  }
115421 }
115422 
115423 /*
115424 ** Make a new pointer to a KeyInfo object
115425 */
115427  if( p ){
115428  assert( p->nRef>0 );
115429  p->nRef++;
115430  }
115431  return p;
115432 }
115433 
115434 #ifdef SQLITE_DEBUG
115435 /*
115436 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
115437 ** can only be changed if this is just a single reference to the object.
115438 **
115439 ** This routine is used only inside of assert() statements.
115440 */
115441 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
115442 #endif /* SQLITE_DEBUG */
115443 
115444 /*
115445 ** Given an expression list, generate a KeyInfo structure that records
115446 ** the collating sequence for each expression in that expression list.
115447 **
115448 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
115449 ** KeyInfo structure is appropriate for initializing a virtual index to
115450 ** implement that clause. If the ExprList is the result set of a SELECT
115451 ** then the KeyInfo structure is appropriate for initializing a virtual
115452 ** index to implement a DISTINCT test.
115453 **
115454 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
115455 ** function is responsible for seeing that this structure is eventually
115456 ** freed.
115457 */
115459  Parse *pParse, /* Parsing context */
115460  ExprList *pList, /* Form the KeyInfo object from this ExprList */
115461  int iStart, /* Begin with this column of pList */
115462  int nExtra /* Add this many extra columns to the end */
115463 ){
115464  int nExpr;
115465  KeyInfo *pInfo;
115466  struct ExprList_item *pItem;
115467  sqlite3 *db = pParse->db;
115468  int i;
115469 
115470  nExpr = pList->nExpr;
115471  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
115472  if( pInfo ){
115473  assert( sqlite3KeyInfoIsWriteable(pInfo) );
115474  for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
115475  CollSeq *pColl;
115476  pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
115477  if( !pColl ) pColl = db->pDfltColl;
115478  pInfo->aColl[i-iStart] = pColl;
115479  pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
115480  }
115481  }
115482  return pInfo;
115483 }
115484 
115485 /*
115486 ** Name of the connection operator, used for error messages.
115487 */
115488 static const char *selectOpName(int id){
115489  char *z;
115490  switch( id ){
115491  case TK_ALL: z = "UNION ALL"; break;
115492  case TK_INTERSECT: z = "INTERSECT"; break;
115493  case TK_EXCEPT: z = "EXCEPT"; break;
115494  default: z = "UNION"; break;
115495  }
115496  return z;
115497 }
115498 
115499 #ifndef SQLITE_OMIT_EXPLAIN
115500 /*
115501 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
115502 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
115503 ** where the caption is of the form:
115504 **
115505 ** "USE TEMP B-TREE FOR xxx"
115506 **
115507 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
115508 ** is determined by the zUsage argument.
115509 */
115510 static void explainTempTable(Parse *pParse, const char *zUsage){
115511  if( pParse->explain==2 ){
115512  Vdbe *v = pParse->pVdbe;
115513  char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
115514  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
115515  }
115516 }
115517 
115518 /*
115519 ** Assign expression b to lvalue a. A second, no-op, version of this macro
115520 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
115521 ** in sqlite3Select() to assign values to structure member variables that
115522 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
115523 ** code with #ifndef directives.
115524 */
115525 # define explainSetInteger(a, b) a = b
115526 
115527 #else
115528 /* No-op versions of the explainXXX() functions and macros. */
115529 # define explainTempTable(y,z)
115530 # define explainSetInteger(y,z)
115531 #endif
115532 
115533 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
115534 /*
115535 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
115536 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
115537 ** where the caption is of one of the two forms:
115538 **
115539 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
115540 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
115541 **
115542 ** where iSub1 and iSub2 are the integers passed as the corresponding
115543 ** function parameters, and op is the text representation of the parameter
115544 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
115545 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
115546 ** false, or the second form if it is true.
115547 */
115548 static void explainComposite(
115549  Parse *pParse, /* Parse context */
115550  int op, /* One of TK_UNION, TK_EXCEPT etc. */
115551  int iSub1, /* Subquery id 1 */
115552  int iSub2, /* Subquery id 2 */
115553  int bUseTmp /* True if a temp table was used */
115554 ){
115555  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
115556  if( pParse->explain==2 ){
115557  Vdbe *v = pParse->pVdbe;
115558  char *zMsg = sqlite3MPrintf(
115559  pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
115560  bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
115561  );
115562  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
115563  }
115564 }
115565 #else
115566 /* No-op versions of the explainXXX() functions and macros. */
115567 # define explainComposite(v,w,x,y,z)
115568 #endif
115569 
115570 /*
115571 ** If the inner loop was generated using a non-null pOrderBy argument,
115572 ** then the results were placed in a sorter. After the loop is terminated
115573 ** we need to run the sorter and output the results. The following
115574 ** routine generates the code needed to do that.
115575 */
115576 static void generateSortTail(
115577  Parse *pParse, /* Parsing context */
115578  Select *p, /* The SELECT statement */
115579  SortCtx *pSort, /* Information on the ORDER BY clause */
115580  int nColumn, /* Number of columns of data */
115581  SelectDest *pDest /* Write the sorted results here */
115582 ){
115583  Vdbe *v = pParse->pVdbe; /* The prepared statement */
115584  int addrBreak = pSort->labelDone; /* Jump here to exit loop */
115585  int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
115586  int addr;
115587  int addrOnce = 0;
115588  int iTab;
115589  ExprList *pOrderBy = pSort->pOrderBy;
115590  int eDest = pDest->eDest;
115591  int iParm = pDest->iSDParm;
115592  int regRow;
115593  int regRowid;
115594  int nKey;
115595  int iSortTab; /* Sorter cursor to read from */
115596  int nSortData; /* Trailing values to read from sorter */
115597  int i;
115598  int bSeq; /* True if sorter record includes seq. no. */
115599 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
115600  struct ExprList_item *aOutEx = p->pEList->a;
115601 #endif
115602 
115603  assert( addrBreak<0 );
115604  if( pSort->labelBkOut ){
115605  sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
115606  sqlite3VdbeGoto(v, addrBreak);
115607  sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
115608  }
115609  iTab = pSort->iECursor;
115610  if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
115611  regRowid = 0;
115612  regRow = pDest->iSdst;
115613  nSortData = nColumn;
115614  }else{
115615  regRowid = sqlite3GetTempReg(pParse);
115616  regRow = sqlite3GetTempRange(pParse, nColumn);
115617  nSortData = nColumn;
115618  }
115619  nKey = pOrderBy->nExpr - pSort->nOBSat;
115620  if( pSort->sortFlags & SORTFLAG_UseSorter ){
115621  int regSortOut = ++pParse->nMem;
115622  iSortTab = pParse->nTab++;
115623  if( pSort->labelBkOut ){
115624  addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
115625  }
115626  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
115627  if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
115628  addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
115629  VdbeCoverage(v);
115630  codeOffset(v, p->iOffset, addrContinue);
115631  sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
115632  bSeq = 0;
115633  }else{
115634  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
115635  codeOffset(v, p->iOffset, addrContinue);
115636  iSortTab = iTab;
115637  bSeq = 1;
115638  }
115639  for(i=0; i<nSortData; i++){
115640  sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
115641  VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
115642  }
115643  switch( eDest ){
115644  case SRT_EphemTab: {
115645  sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
115646  sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
115648  break;
115649  }
115650 #ifndef SQLITE_OMIT_SUBQUERY
115651  case SRT_Set: {
115652  assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
115653  sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
115654  pDest->zAffSdst, nColumn);
115655  sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
115656  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
115657  break;
115658  }
115659  case SRT_Mem: {
115660  /* The LIMIT clause will terminate the loop for us */
115661  break;
115662  }
115663 #endif
115664  default: {
115665  assert( eDest==SRT_Output || eDest==SRT_Coroutine );
115666  testcase( eDest==SRT_Output );
115667  testcase( eDest==SRT_Coroutine );
115668  if( eDest==SRT_Output ){
115669  sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
115670  sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
115671  }else{
115672  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
115673  }
115674  break;
115675  }
115676  }
115677  if( regRowid ){
115678  if( eDest==SRT_Set ){
115679  sqlite3ReleaseTempRange(pParse, regRow, nColumn);
115680  }else{
115681  sqlite3ReleaseTempReg(pParse, regRow);
115682  }
115683  sqlite3ReleaseTempReg(pParse, regRowid);
115684  }
115685  /* The bottom of the loop
115686  */
115687  sqlite3VdbeResolveLabel(v, addrContinue);
115688  if( pSort->sortFlags & SORTFLAG_UseSorter ){
115689  sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
115690  }else{
115691  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
115692  }
115693  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
115694  sqlite3VdbeResolveLabel(v, addrBreak);
115695 }
115696 
115697 /*
115698 ** Return a pointer to a string containing the 'declaration type' of the
115699 ** expression pExpr. The string may be treated as static by the caller.
115700 **
115701 ** Also try to estimate the size of the returned value and return that
115702 ** result in *pEstWidth.
115703 **
115704 ** The declaration type is the exact datatype definition extracted from the
115705 ** original CREATE TABLE statement if the expression is a column. The
115706 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
115707 ** is considered a column can be complex in the presence of subqueries. The
115708 ** result-set expression in all of the following SELECT statements is
115709 ** considered a column by this function.
115710 **
115711 ** SELECT col FROM tbl;
115712 ** SELECT (SELECT col FROM tbl;
115713 ** SELECT (SELECT col FROM tbl);
115714 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
115715 **
115716 ** The declaration type for any expression other than a column is NULL.
115717 **
115718 ** This routine has either 3 or 6 parameters depending on whether or not
115719 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
115720 */
115721 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115722 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
115723 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
115724 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
115725 #endif
115726 static const char *columnTypeImpl(
115727  NameContext *pNC,
115728  Expr *pExpr,
115729 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115730  const char **pzOrigDb,
115731  const char **pzOrigTab,
115732  const char **pzOrigCol,
115733 #endif
115734  u8 *pEstWidth
115735 ){
115736  char const *zType = 0;
115737  int j;
115738  u8 estWidth = 1;
115739 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115740  char const *zOrigDb = 0;
115741  char const *zOrigTab = 0;
115742  char const *zOrigCol = 0;
115743 #endif
115744 
115745  assert( pExpr!=0 );
115746  assert( pNC->pSrcList!=0 );
115747  switch( pExpr->op ){
115748  case TK_AGG_COLUMN:
115749  case TK_COLUMN: {
115750  /* The expression is a column. Locate the table the column is being
115751  ** extracted from in NameContext.pSrcList. This table may be real
115752  ** database table or a subquery.
115753  */
115754  Table *pTab = 0; /* Table structure column is extracted from */
115755  Select *pS = 0; /* Select the column is extracted from */
115756  int iCol = pExpr->iColumn; /* Index of column in pTab */
115757  testcase( pExpr->op==TK_AGG_COLUMN );
115758  testcase( pExpr->op==TK_COLUMN );
115759  while( pNC && !pTab ){
115760  SrcList *pTabList = pNC->pSrcList;
115761  for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
115762  if( j<pTabList->nSrc ){
115763  pTab = pTabList->a[j].pTab;
115764  pS = pTabList->a[j].pSelect;
115765  }else{
115766  pNC = pNC->pNext;
115767  }
115768  }
115769 
115770  if( pTab==0 ){
115771  /* At one time, code such as "SELECT new.x" within a trigger would
115772  ** cause this condition to run. Since then, we have restructured how
115773  ** trigger code is generated and so this condition is no longer
115774  ** possible. However, it can still be true for statements like
115775  ** the following:
115776  **
115777  ** CREATE TABLE t1(col INTEGER);
115778  ** SELECT (SELECT t1.col) FROM FROM t1;
115779  **
115780  ** when columnType() is called on the expression "t1.col" in the
115781  ** sub-select. In this case, set the column type to NULL, even
115782  ** though it should really be "INTEGER".
115783  **
115784  ** This is not a problem, as the column type of "t1.col" is never
115785  ** used. When columnType() is called on the expression
115786  ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
115787  ** branch below. */
115788  break;
115789  }
115790 
115791  assert( pTab && pExpr->pTab==pTab );
115792  if( pS ){
115793  /* The "table" is actually a sub-select or a view in the FROM clause
115794  ** of the SELECT statement. Return the declaration type and origin
115795  ** data for the result-set column of the sub-select.
115796  */
115797  if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
115798  /* If iCol is less than zero, then the expression requests the
115799  ** rowid of the sub-select or view. This expression is legal (see
115800  ** test case misc2.2.2) - it always evaluates to NULL.
115801  **
115802  ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
115803  ** caught already by name resolution.
115804  */
115805  NameContext sNC;
115806  Expr *p = pS->pEList->a[iCol].pExpr;
115807  sNC.pSrcList = pS->pSrc;
115808  sNC.pNext = pNC;
115809  sNC.pParse = pNC->pParse;
115810  zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
115811  }
115812  }else if( pTab->pSchema ){
115813  /* A real table */
115814  assert( !pS );
115815  if( iCol<0 ) iCol = pTab->iPKey;
115816  assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
115817 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115818  if( iCol<0 ){
115819  zType = "INTEGER";
115820  zOrigCol = "rowid";
115821  }else{
115822  zOrigCol = pTab->aCol[iCol].zName;
115823  zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
115824  estWidth = pTab->aCol[iCol].szEst;
115825  }
115826  zOrigTab = pTab->zName;
115827  if( pNC->pParse ){
115828  int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
115829  zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
115830  }
115831 #else
115832  if( iCol<0 ){
115833  zType = "INTEGER";
115834  }else{
115835  zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
115836  estWidth = pTab->aCol[iCol].szEst;
115837  }
115838 #endif
115839  }
115840  break;
115841  }
115842 #ifndef SQLITE_OMIT_SUBQUERY
115843  case TK_SELECT: {
115844  /* The expression is a sub-select. Return the declaration type and
115845  ** origin info for the single column in the result set of the SELECT
115846  ** statement.
115847  */
115848  NameContext sNC;
115849  Select *pS = pExpr->x.pSelect;
115850  Expr *p = pS->pEList->a[0].pExpr;
115851  assert( ExprHasProperty(pExpr, EP_xIsSelect) );
115852  sNC.pSrcList = pS->pSrc;
115853  sNC.pNext = pNC;
115854  sNC.pParse = pNC->pParse;
115855  zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
115856  break;
115857  }
115858 #endif
115859  }
115860 
115861 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115862  if( pzOrigDb ){
115863  assert( pzOrigTab && pzOrigCol );
115864  *pzOrigDb = zOrigDb;
115865  *pzOrigTab = zOrigTab;
115866  *pzOrigCol = zOrigCol;
115867  }
115868 #endif
115869  if( pEstWidth ) *pEstWidth = estWidth;
115870  return zType;
115871 }
115872 
115873 /*
115874 ** Generate code that will tell the VDBE the declaration types of columns
115875 ** in the result set.
115876 */
115878  Parse *pParse, /* Parser context */
115879  SrcList *pTabList, /* List of tables */
115880  ExprList *pEList /* Expressions defining the result set */
115881 ){
115882 #ifndef SQLITE_OMIT_DECLTYPE
115883  Vdbe *v = pParse->pVdbe;
115884  int i;
115885  NameContext sNC;
115886  sNC.pSrcList = pTabList;
115887  sNC.pParse = pParse;
115888  for(i=0; i<pEList->nExpr; i++){
115889  Expr *p = pEList->a[i].pExpr;
115890  const char *zType;
115891 #ifdef SQLITE_ENABLE_COLUMN_METADATA
115892  const char *zOrigDb = 0;
115893  const char *zOrigTab = 0;
115894  const char *zOrigCol = 0;
115895  zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
115896 
115897  /* The vdbe must make its own copy of the column-type and other
115898  ** column specific strings, in case the schema is reset before this
115899  ** virtual machine is deleted.
115900  */
115904 #else
115905  zType = columnType(&sNC, p, 0, 0, 0, 0);
115906 #endif
115908  }
115909 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
115910 }
115911 
115912 /*
115913 ** Generate code that will tell the VDBE the names of columns
115914 ** in the result set. This information is used to provide the
115915 ** azCol[] values in the callback.
115916 */
115918  Parse *pParse, /* Parser context */
115919  SrcList *pTabList, /* List of tables */
115920  ExprList *pEList /* Expressions defining the result set */
115921 ){
115922  Vdbe *v = pParse->pVdbe;
115923  int i, j;
115924  sqlite3 *db = pParse->db;
115925  int fullNames, shortNames;
115926 
115927 #ifndef SQLITE_OMIT_EXPLAIN
115928  /* If this is an EXPLAIN, skip this step */
115929  if( pParse->explain ){
115930  return;
115931  }
115932 #endif
115933 
115934  if( pParse->colNamesSet || db->mallocFailed ) return;
115935  assert( v!=0 );
115936  assert( pTabList!=0 );
115937  pParse->colNamesSet = 1;
115938  fullNames = (db->flags & SQLITE_FullColNames)!=0;
115939  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
115940  sqlite3VdbeSetNumCols(v, pEList->nExpr);
115941  for(i=0; i<pEList->nExpr; i++){
115942  Expr *p;
115943  p = pEList->a[i].pExpr;
115944  if( NEVER(p==0) ) continue;
115945  if( pEList->a[i].zName ){
115946  char *zName = pEList->a[i].zName;
115948  }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
115949  Table *pTab;
115950  char *zCol;
115951  int iCol = p->iColumn;
115952  for(j=0; ALWAYS(j<pTabList->nSrc); j++){
115953  if( pTabList->a[j].iCursor==p->iTable ) break;
115954  }
115955  assert( j<pTabList->nSrc );
115956  pTab = pTabList->a[j].pTab;
115957  if( iCol<0 ) iCol = pTab->iPKey;
115958  assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
115959  if( iCol<0 ){
115960  zCol = "rowid";
115961  }else{
115962  zCol = pTab->aCol[iCol].zName;
115963  }
115964  if( !shortNames && !fullNames ){
115966  sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
115967  }else if( fullNames ){
115968  char *zName = 0;
115969  zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
115971  }else{
115973  }
115974  }else{
115975  const char *z = pEList->a[i].zSpan;
115976  z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
115978  }
115979  }
115980  generateColumnTypes(pParse, pTabList, pEList);
115981 }
115982 
115983 /*
115984 ** Given an expression list (which is really the list of expressions
115985 ** that form the result set of a SELECT statement) compute appropriate
115986 ** column names for a table that would hold the expression list.
115987 **
115988 ** All column names will be unique.
115989 **
115990 ** Only the column names are computed. Column.zType, Column.zColl,
115991 ** and other fields of Column are zeroed.
115992 **
115993 ** Return SQLITE_OK on success. If a memory allocation error occurs,
115994 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
115995 */
115997  Parse *pParse, /* Parsing context */
115998  ExprList *pEList, /* Expr list from which to derive column names */
115999  i16 *pnCol, /* Write the number of columns here */
116000  Column **paCol /* Write the new column list here */
116001 ){
116002  sqlite3 *db = pParse->db; /* Database connection */
116003  int i, j; /* Loop counters */
116004  u32 cnt; /* Index added to make the name unique */
116005  Column *aCol, *pCol; /* For looping over result columns */
116006  int nCol; /* Number of columns in the result set */
116007  Expr *p; /* Expression for a single result column */
116008  char *zName; /* Column name */
116009  int nName; /* Size of name in zName[] */
116010  Hash ht; /* Hash table of column names */
116011 
116012  sqlite3HashInit(&ht);
116013  if( pEList ){
116014  nCol = pEList->nExpr;
116015  aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
116016  testcase( aCol==0 );
116017  }else{
116018  nCol = 0;
116019  aCol = 0;
116020  }
116021  assert( nCol==(i16)nCol );
116022  *pnCol = nCol;
116023  *paCol = aCol;
116024 
116025  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
116026  /* Get an appropriate name for the column
116027  */
116028  p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
116029  if( (zName = pEList->a[i].zName)!=0 ){
116030  /* If the column contains an "AS <name>" phrase, use <name> as the name */
116031  }else{
116032  Expr *pColExpr = p; /* The expression that is the result column name */
116033  Table *pTab; /* Table associated with this expression */
116034  while( pColExpr->op==TK_DOT ){
116035  pColExpr = pColExpr->pRight;
116036  assert( pColExpr!=0 );
116037  }
116038  if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
116039  /* For columns use the column name name */
116040  int iCol = pColExpr->iColumn;
116041  pTab = pColExpr->pTab;
116042  if( iCol<0 ) iCol = pTab->iPKey;
116043  zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
116044  }else if( pColExpr->op==TK_ID ){
116045  assert( !ExprHasProperty(pColExpr, EP_IntValue) );
116046  zName = pColExpr->u.zToken;
116047  }else{
116048  /* Use the original text of the column expression as its name */
116049  zName = pEList->a[i].zSpan;
116050  }
116051  }
116052  zName = sqlite3MPrintf(db, "%s", zName);
116053 
116054  /* Make sure the column name is unique. If the name is not unique,
116055  ** append an integer to the name so that it becomes unique.
116056  */
116057  cnt = 0;
116058  while( zName && sqlite3HashFind(&ht, zName)!=0 ){
116059  nName = sqlite3Strlen30(zName);
116060  if( nName>0 ){
116061  for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
116062  if( zName[j]==':' ) nName = j;
116063  }
116064  zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
116065  if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
116066  }
116067  pCol->zName = zName;
116069  if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
116070  sqlite3OomFault(db);
116071  }
116072  }
116073  sqlite3HashClear(&ht);
116074  if( db->mallocFailed ){
116075  for(j=0; j<i; j++){
116076  sqlite3DbFree(db, aCol[j].zName);
116077  }
116078  sqlite3DbFree(db, aCol);
116079  *paCol = 0;
116080  *pnCol = 0;
116081  return SQLITE_NOMEM_BKPT;
116082  }
116083  return SQLITE_OK;
116084 }
116085 
116086 /*
116087 ** Add type and collation information to a column list based on
116088 ** a SELECT statement.
116089 **
116090 ** The column list presumably came from selectColumnNamesFromExprList().
116091 ** The column list has only names, not types or collations. This
116092 ** routine goes through and adds the types and collations.
116093 **
116094 ** This routine requires that all identifiers in the SELECT
116095 ** statement be resolved.
116096 */
116098  Parse *pParse, /* Parsing contexts */
116099  Table *pTab, /* Add column type information to this table */
116100  Select *pSelect /* SELECT used to determine types and collations */
116101 ){
116102  sqlite3 *db = pParse->db;
116103  NameContext sNC;
116104  Column *pCol;
116105  CollSeq *pColl;
116106  int i;
116107  Expr *p;
116108  struct ExprList_item *a;
116109  u64 szAll = 0;
116110 
116111  assert( pSelect!=0 );
116112  assert( (pSelect->selFlags & SF_Resolved)!=0 );
116113  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
116114  if( db->mallocFailed ) return;
116115  memset(&sNC, 0, sizeof(sNC));
116116  sNC.pSrcList = pSelect->pSrc;
116117  a = pSelect->pEList->a;
116118  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
116119  const char *zType;
116120  int n, m;
116121  p = a[i].pExpr;
116122  zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
116123  szAll += pCol->szEst;
116124  pCol->affinity = sqlite3ExprAffinity(p);
116125  if( zType && (m = sqlite3Strlen30(zType))>0 ){
116126  n = sqlite3Strlen30(pCol->zName);
116127  pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
116128  if( pCol->zName ){
116129  memcpy(&pCol->zName[n+1], zType, m+1);
116130  pCol->colFlags |= COLFLAG_HASTYPE;
116131  }
116132  }
116133  if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
116134  pColl = sqlite3ExprCollSeq(pParse, p);
116135  if( pColl && pCol->zColl==0 ){
116136  pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
116137  }
116138  }
116139  pTab->szTabRow = sqlite3LogEst(szAll*4);
116140 }
116141 
116142 /*
116143 ** Given a SELECT statement, generate a Table structure that describes
116144 ** the result set of that SELECT.
116145 */
116147  Table *pTab;
116148  sqlite3 *db = pParse->db;
116149  int savedFlags;
116150 
116151  savedFlags = db->flags;
116152  db->flags &= ~SQLITE_FullColNames;
116153  db->flags |= SQLITE_ShortColNames;
116154  sqlite3SelectPrep(pParse, pSelect, 0);
116155  if( pParse->nErr ) return 0;
116156  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
116157  db->flags = savedFlags;
116158  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
116159  if( pTab==0 ){
116160  return 0;
116161  }
116162  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
116163  ** is disabled */
116164  assert( db->lookaside.bDisable );
116165  pTab->nRef = 1;
116166  pTab->zName = 0;
116167  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
116168  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
116169  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
116170  pTab->iPKey = -1;
116171  if( db->mallocFailed ){
116172  sqlite3DeleteTable(db, pTab);
116173  return 0;
116174  }
116175  return pTab;
116176 }
116177 
116178 /*
116179 ** Get a VDBE for the given parser context. Create a new one if necessary.
116180 ** If an error occurs, return NULL and leave a message in pParse.
116181 */
116183  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
116184  if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1);
116185  if( pParse->pToplevel==0
116187  ){
116188  pParse->okConstFactor = 1;
116189  }
116190  return v;
116191 }
116193  Vdbe *v = pParse->pVdbe;
116194  return v ? v : allocVdbe(pParse);
116195 }
116196 
116197 
116198 /*
116199 ** Compute the iLimit and iOffset fields of the SELECT based on the
116200 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
116201 ** that appear in the original SQL statement after the LIMIT and OFFSET
116202 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
116203 ** are the integer memory register numbers for counters used to compute
116204 ** the limit and offset. If there is no limit and/or offset, then
116205 ** iLimit and iOffset are negative.
116206 **
116207 ** This routine changes the values of iLimit and iOffset only if
116208 ** a limit or offset is defined by pLimit and pOffset. iLimit and
116209 ** iOffset should have been preset to appropriate default values (zero)
116210 ** prior to calling this routine.
116211 **
116212 ** The iOffset register (if it exists) is initialized to the value
116213 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
116214 ** iOffset+1 is initialized to LIMIT+OFFSET.
116215 **
116216 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
116217 ** redefined. The UNION ALL operator uses this property to force
116218 ** the reuse of the same limit and offset registers across multiple
116219 ** SELECT statements.
116220 */
116221 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
116222  Vdbe *v = 0;
116223  int iLimit = 0;
116224  int iOffset;
116225  int n;
116226  if( p->iLimit ) return;
116227 
116228  /*
116229  ** "LIMIT -1" always shows all rows. There is some
116230  ** controversy about what the correct behavior should be.
116231  ** The current implementation interprets "LIMIT 0" to mean
116232  ** no rows.
116233  */
116234  sqlite3ExprCacheClear(pParse);
116235  assert( p->pOffset==0 || p->pLimit!=0 );
116236  if( p->pLimit ){
116237  p->iLimit = iLimit = ++pParse->nMem;
116238  v = sqlite3GetVdbe(pParse);
116239  assert( v!=0 );
116240  if( sqlite3ExprIsInteger(p->pLimit, &n) ){
116241  sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
116242  VdbeComment((v, "LIMIT counter"));
116243  if( n==0 ){
116244  sqlite3VdbeGoto(v, iBreak);
116245  }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
116246  p->nSelectRow = sqlite3LogEst((u64)n);
116247  p->selFlags |= SF_FixedLimit;
116248  }
116249  }else{
116250  sqlite3ExprCode(pParse, p->pLimit, iLimit);
116251  sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
116252  VdbeComment((v, "LIMIT counter"));
116253  sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
116254  }
116255  if( p->pOffset ){
116256  p->iOffset = iOffset = ++pParse->nMem;
116257  pParse->nMem++; /* Allocate an extra register for limit+offset */
116258  sqlite3ExprCode(pParse, p->pOffset, iOffset);
116259  sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
116260  VdbeComment((v, "OFFSET counter"));
116261  sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
116262  VdbeComment((v, "LIMIT+OFFSET"));
116263  }
116264  }
116265 }
116266 
116267 #ifndef SQLITE_OMIT_COMPOUND_SELECT
116268 /*
116269 ** Return the appropriate collating sequence for the iCol-th column of
116270 ** the result set for the compound-select statement "p". Return NULL if
116271 ** the column has no default collating sequence.
116272 **
116273 ** The collating sequence for the compound select is taken from the
116274 ** left-most term of the select that has a collating sequence.
116275 */
116276 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
116277  CollSeq *pRet;
116278  if( p->pPrior ){
116279  pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
116280  }else{
116281  pRet = 0;
116282  }
116283  assert( iCol>=0 );
116284  /* iCol must be less than p->pEList->nExpr. Otherwise an error would
116285  ** have been thrown during name resolution and we would not have gotten
116286  ** this far */
116287  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
116288  pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
116289  }
116290  return pRet;
116291 }
116292 
116293 /*
116294 ** The select statement passed as the second parameter is a compound SELECT
116295 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
116296 ** structure suitable for implementing the ORDER BY.
116297 **
116298 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
116299 ** function is responsible for ensuring that this structure is eventually
116300 ** freed.
116301 */
116302 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
116303  ExprList *pOrderBy = p->pOrderBy;
116304  int nOrderBy = p->pOrderBy->nExpr;
116305  sqlite3 *db = pParse->db;
116306  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
116307  if( pRet ){
116308  int i;
116309  for(i=0; i<nOrderBy; i++){
116310  struct ExprList_item *pItem = &pOrderBy->a[i];
116311  Expr *pTerm = pItem->pExpr;
116312  CollSeq *pColl;
116313 
116314  if( pTerm->flags & EP_Collate ){
116315  pColl = sqlite3ExprCollSeq(pParse, pTerm);
116316  }else{
116317  pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
116318  if( pColl==0 ) pColl = db->pDfltColl;
116319  pOrderBy->a[i].pExpr =
116320  sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
116321  }
116322  assert( sqlite3KeyInfoIsWriteable(pRet) );
116323  pRet->aColl[i] = pColl;
116324  pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
116325  }
116326  }
116327 
116328  return pRet;
116329 }
116330 
116331 #ifndef SQLITE_OMIT_CTE
116332 /*
116333 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
116334 ** query of the form:
116335 **
116336 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
116337 ** \___________/ \_______________/
116338 ** p->pPrior p
116339 **
116340 **
116341 ** There is exactly one reference to the recursive-table in the FROM clause
116342 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
116343 **
116344 ** The setup-query runs once to generate an initial set of rows that go
116345 ** into a Queue table. Rows are extracted from the Queue table one by
116346 ** one. Each row extracted from Queue is output to pDest. Then the single
116347 ** extracted row (now in the iCurrent table) becomes the content of the
116348 ** recursive-table for a recursive-query run. The output of the recursive-query
116349 ** is added back into the Queue table. Then another row is extracted from Queue
116350 ** and the iteration continues until the Queue table is empty.
116351 **
116352 ** If the compound query operator is UNION then no duplicate rows are ever
116353 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
116354 ** that have ever been inserted into Queue and causes duplicates to be
116355 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
116356 **
116357 ** If the query has an ORDER BY, then entries in the Queue table are kept in
116358 ** ORDER BY order and the first entry is extracted for each cycle. Without
116359 ** an ORDER BY, the Queue table is just a FIFO.
116360 **
116361 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
116362 ** have been output to pDest. A LIMIT of zero means to output no rows and a
116363 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
116364 ** with a positive value, then the first OFFSET outputs are discarded rather
116365 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
116366 ** rows have been skipped.
116367 */
116369  Parse *pParse, /* Parsing context */
116370  Select *p, /* The recursive SELECT to be coded */
116371  SelectDest *pDest /* What to do with query results */
116372 ){
116373  SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
116374  int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
116375  Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
116376  Select *pSetup = p->pPrior; /* The setup query */
116377  int addrTop; /* Top of the loop */
116378  int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
116379  int iCurrent = 0; /* The Current table */
116380  int regCurrent; /* Register holding Current table */
116381  int iQueue; /* The Queue table */
116382  int iDistinct = 0; /* To ensure unique results if UNION */
116383  int eDest = SRT_Fifo; /* How to write to Queue */
116384  SelectDest destQueue; /* SelectDest targetting the Queue table */
116385  int i; /* Loop counter */
116386  int rc; /* Result code */
116387  ExprList *pOrderBy; /* The ORDER BY clause */
116388  Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
116389  int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
116390 
116391  /* Obtain authorization to do a recursive query */
116392  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
116393 
116394  /* Process the LIMIT and OFFSET clauses, if they exist */
116395  addrBreak = sqlite3VdbeMakeLabel(v);
116396  computeLimitRegisters(pParse, p, addrBreak);
116397  pLimit = p->pLimit;
116398  pOffset = p->pOffset;
116399  regLimit = p->iLimit;
116400  regOffset = p->iOffset;
116401  p->pLimit = p->pOffset = 0;
116402  p->iLimit = p->iOffset = 0;
116403  pOrderBy = p->pOrderBy;
116404 
116405  /* Locate the cursor number of the Current table */
116406  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
116407  if( pSrc->a[i].fg.isRecursive ){
116408  iCurrent = pSrc->a[i].iCursor;
116409  break;
116410  }
116411  }
116412 
116413  /* Allocate cursors numbers for Queue and Distinct. The cursor number for
116414  ** the Distinct table must be exactly one greater than Queue in order
116415  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
116416  iQueue = pParse->nTab++;
116417  if( p->op==TK_UNION ){
116418  eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
116419  iDistinct = pParse->nTab++;
116420  }else{
116421  eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
116422  }
116423  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
116424 
116425  /* Allocate cursors for Current, Queue, and Distinct. */
116426  regCurrent = ++pParse->nMem;
116427  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
116428  if( pOrderBy ){
116429  KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
116430  sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
116431  (char*)pKeyInfo, P4_KEYINFO);
116432  destQueue.pOrderBy = pOrderBy;
116433  }else{
116434  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
116435  }
116436  VdbeComment((v, "Queue table"));
116437  if( iDistinct ){
116438  p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
116439  p->selFlags |= SF_UsesEphemeral;
116440  }
116441 
116442  /* Detach the ORDER BY clause from the compound SELECT */
116443  p->pOrderBy = 0;
116444 
116445  /* Store the results of the setup-query in Queue. */
116446  pSetup->pNext = 0;
116447  rc = sqlite3Select(pParse, pSetup, &destQueue);
116448  pSetup->pNext = p;
116449  if( rc ) goto end_of_recursive_query;
116450 
116451  /* Find the next row in the Queue and output that row */
116452  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
116453 
116454  /* Transfer the next row in Queue over to Current */
116455  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
116456  if( pOrderBy ){
116457  sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
116458  }else{
116459  sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
116460  }
116461  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
116462 
116463  /* Output the single row in Current */
116464  addrCont = sqlite3VdbeMakeLabel(v);
116465  codeOffset(v, regOffset, addrCont);
116466  selectInnerLoop(pParse, p, p->pEList, iCurrent,
116467  0, 0, pDest, addrCont, addrBreak);
116468  if( regLimit ){
116469  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
116470  VdbeCoverage(v);
116471  }
116472  sqlite3VdbeResolveLabel(v, addrCont);
116473 
116474  /* Execute the recursive SELECT taking the single row in Current as
116475  ** the value for the recursive-table. Store the results in the Queue.
116476  */
116477  if( p->selFlags & SF_Aggregate ){
116478  sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
116479  }else{
116480  p->pPrior = 0;
116481  sqlite3Select(pParse, p, &destQueue);
116482  assert( p->pPrior==0 );
116483  p->pPrior = pSetup;
116484  }
116485 
116486  /* Keep running the loop until the Queue is empty */
116487  sqlite3VdbeGoto(v, addrTop);
116488  sqlite3VdbeResolveLabel(v, addrBreak);
116489 
116490 end_of_recursive_query:
116491  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
116492  p->pOrderBy = pOrderBy;
116493  p->pLimit = pLimit;
116494  p->pOffset = pOffset;
116495  return;
116496 }
116497 #endif /* SQLITE_OMIT_CTE */
116498 
116499 /* Forward references */
116500 static int multiSelectOrderBy(
116501  Parse *pParse, /* Parsing context */
116502  Select *p, /* The right-most of SELECTs to be coded */
116503  SelectDest *pDest /* What to do with query results */
116504 );
116505 
116506 /*
116507 ** Handle the special case of a compound-select that originates from a
116508 ** VALUES clause. By handling this as a special case, we avoid deep
116509 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
116510 ** on a VALUES clause.
116511 **
116512 ** Because the Select object originates from a VALUES clause:
116513 ** (1) It has no LIMIT or OFFSET
116514 ** (2) All terms are UNION ALL
116515 ** (3) There is no ORDER BY clause
116516 */
116518  Parse *pParse, /* Parsing context */
116519  Select *p, /* The right-most of SELECTs to be coded */
116520  SelectDest *pDest /* What to do with query results */
116521 ){
116522  Select *pPrior;
116523  int nRow = 1;
116524  int rc = 0;
116525  assert( p->selFlags & SF_MultiValue );
116526  do{
116527  assert( p->selFlags & SF_Values );
116528  assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
116529  assert( p->pLimit==0 );
116530  assert( p->pOffset==0 );
116531  assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
116532  if( p->pPrior==0 ) break;
116533  assert( p->pPrior->pNext==p );
116534  p = p->pPrior;
116535  nRow++;
116536  }while(1);
116537  while( p ){
116538  pPrior = p->pPrior;
116539  p->pPrior = 0;
116540  rc = sqlite3Select(pParse, p, pDest);
116541  p->pPrior = pPrior;
116542  if( rc ) break;
116543  p->nSelectRow = nRow;
116544  p = p->pNext;
116545  }
116546  return rc;
116547 }
116548 
116549 /*
116550 ** This routine is called to process a compound query form from
116551 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
116552 ** INTERSECT
116553 **
116554 ** "p" points to the right-most of the two queries. the query on the
116555 ** left is p->pPrior. The left query could also be a compound query
116556 ** in which case this routine will be called recursively.
116557 **
116558 ** The results of the total query are to be written into a destination
116559 ** of type eDest with parameter iParm.
116560 **
116561 ** Example 1: Consider a three-way compound SQL statement.
116562 **
116563 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
116564 **
116565 ** This statement is parsed up as follows:
116566 **
116567 ** SELECT c FROM t3
116568 ** |
116569 ** `-----> SELECT b FROM t2
116570 ** |
116571 ** `------> SELECT a FROM t1
116572 **
116573 ** The arrows in the diagram above represent the Select.pPrior pointer.
116574 ** So if this routine is called with p equal to the t3 query, then
116575 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
116576 **
116577 ** Notice that because of the way SQLite parses compound SELECTs, the
116578 ** individual selects always group from left to right.
116579 */
116580 static int multiSelect(
116581  Parse *pParse, /* Parsing context */
116582  Select *p, /* The right-most of SELECTs to be coded */
116583  SelectDest *pDest /* What to do with query results */
116584 ){
116585  int rc = SQLITE_OK; /* Success code from a subroutine */
116586  Select *pPrior; /* Another SELECT immediately to our left */
116587  Vdbe *v; /* Generate code to this VDBE */
116588  SelectDest dest; /* Alternative data destination */
116589  Select *pDelete = 0; /* Chain of simple selects to delete */
116590  sqlite3 *db; /* Database connection */
116591 #ifndef SQLITE_OMIT_EXPLAIN
116592  int iSub1 = 0; /* EQP id of left-hand query */
116593  int iSub2 = 0; /* EQP id of right-hand query */
116594 #endif
116595 
116596  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
116597  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
116598  */
116599  assert( p && p->pPrior ); /* Calling function guarantees this much */
116600  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
116601  db = pParse->db;
116602  pPrior = p->pPrior;
116603  dest = *pDest;
116604  if( pPrior->pOrderBy ){
116605  sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
116606  selectOpName(p->op));
116607  rc = 1;
116608  goto multi_select_end;
116609  }
116610  if( pPrior->pLimit ){
116611  sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
116612  selectOpName(p->op));
116613  rc = 1;
116614  goto multi_select_end;
116615  }
116616 
116617  v = sqlite3GetVdbe(pParse);
116618  assert( v!=0 ); /* The VDBE already created by calling function */
116619 
116620  /* Create the destination temporary table if necessary
116621  */
116622  if( dest.eDest==SRT_EphemTab ){
116623  assert( p->pEList );
116625  dest.eDest = SRT_Table;
116626  }
116627 
116628  /* Special handling for a compound-select that originates as a VALUES clause.
116629  */
116630  if( p->selFlags & SF_MultiValue ){
116631  rc = multiSelectValues(pParse, p, &dest);
116632  goto multi_select_end;
116633  }
116634 
116635  /* Make sure all SELECTs in the statement have the same number of elements
116636  ** in their result sets.
116637  */
116638  assert( p->pEList && pPrior->pEList );
116639  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
116640 
116641 #ifndef SQLITE_OMIT_CTE
116642  if( p->selFlags & SF_Recursive ){
116643  generateWithRecursiveQuery(pParse, p, &dest);
116644  }else
116645 #endif
116646 
116647  /* Compound SELECTs that have an ORDER BY clause are handled separately.
116648  */
116649  if( p->pOrderBy ){
116650  return multiSelectOrderBy(pParse, p, pDest);
116651  }else
116652 
116653  /* Generate code for the left and right SELECT statements.
116654  */
116655  switch( p->op ){
116656  case TK_ALL: {
116657  int addr = 0;
116658  int nLimit;
116659  assert( !pPrior->pLimit );
116660  pPrior->iLimit = p->iLimit;
116661  pPrior->iOffset = p->iOffset;
116662  pPrior->pLimit = p->pLimit;
116663  pPrior->pOffset = p->pOffset;
116664  explainSetInteger(iSub1, pParse->iNextSelectId);
116665  rc = sqlite3Select(pParse, pPrior, &dest);
116666  p->pLimit = 0;
116667  p->pOffset = 0;
116668  if( rc ){
116669  goto multi_select_end;
116670  }
116671  p->pPrior = 0;
116672  p->iLimit = pPrior->iLimit;
116673  p->iOffset = pPrior->iOffset;
116674  if( p->iLimit ){
116675  addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
116676  VdbeComment((v, "Jump ahead if LIMIT reached"));
116677  if( p->iOffset ){
116679  p->iLimit, p->iOffset+1, p->iOffset);
116680  }
116681  }
116682  explainSetInteger(iSub2, pParse->iNextSelectId);
116683  rc = sqlite3Select(pParse, p, &dest);
116684  testcase( rc!=SQLITE_OK );
116685  pDelete = p->pPrior;
116686  p->pPrior = pPrior;
116687  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
116688  if( pPrior->pLimit
116689  && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
116690  && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
116691  ){
116692  p->nSelectRow = sqlite3LogEst((u64)nLimit);
116693  }
116694  if( addr ){
116695  sqlite3VdbeJumpHere(v, addr);
116696  }
116697  break;
116698  }
116699  case TK_EXCEPT:
116700  case TK_UNION: {
116701  int unionTab; /* Cursor number of the temporary table holding result */
116702  u8 op = 0; /* One of the SRT_ operations to apply to self */
116703  int priorOp; /* The SRT_ operation to apply to prior selects */
116704  Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
116705  int addr;
116706  SelectDest uniondest;
116707 
116708  testcase( p->op==TK_EXCEPT );
116709  testcase( p->op==TK_UNION );
116710  priorOp = SRT_Union;
116711  if( dest.eDest==priorOp ){
116712  /* We can reuse a temporary table generated by a SELECT to our
116713  ** right.
116714  */
116715  assert( p->pLimit==0 ); /* Not allowed on leftward elements */
116716  assert( p->pOffset==0 ); /* Not allowed on leftward elements */
116717  unionTab = dest.iSDParm;
116718  }else{
116719  /* We will need to create our own temporary table to hold the
116720  ** intermediate results.
116721  */
116722  unionTab = pParse->nTab++;
116723  assert( p->pOrderBy==0 );
116724  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
116725  assert( p->addrOpenEphm[0] == -1 );
116726  p->addrOpenEphm[0] = addr;
116728  assert( p->pEList );
116729  }
116730 
116731  /* Code the SELECT statements to our left
116732  */
116733  assert( !pPrior->pOrderBy );
116734  sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
116735  explainSetInteger(iSub1, pParse->iNextSelectId);
116736  rc = sqlite3Select(pParse, pPrior, &uniondest);
116737  if( rc ){
116738  goto multi_select_end;
116739  }
116740 
116741  /* Code the current SELECT statement
116742  */
116743  if( p->op==TK_EXCEPT ){
116744  op = SRT_Except;
116745  }else{
116746  assert( p->op==TK_UNION );
116747  op = SRT_Union;
116748  }
116749  p->pPrior = 0;
116750  pLimit = p->pLimit;
116751  p->pLimit = 0;
116752  pOffset = p->pOffset;
116753  p->pOffset = 0;
116754  uniondest.eDest = op;
116755  explainSetInteger(iSub2, pParse->iNextSelectId);
116756  rc = sqlite3Select(pParse, p, &uniondest);
116757  testcase( rc!=SQLITE_OK );
116758  /* Query flattening in sqlite3Select() might refill p->pOrderBy.
116759  ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
116761  pDelete = p->pPrior;
116762  p->pPrior = pPrior;
116763  p->pOrderBy = 0;
116764  if( p->op==TK_UNION ){
116765  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
116766  }
116767  sqlite3ExprDelete(db, p->pLimit);
116768  p->pLimit = pLimit;
116769  p->pOffset = pOffset;
116770  p->iLimit = 0;
116771  p->iOffset = 0;
116772 
116773  /* Convert the data in the temporary table into whatever form
116774  ** it is that we currently need.
116775  */
116776  assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
116777  if( dest.eDest!=priorOp ){
116778  int iCont, iBreak, iStart;
116779  assert( p->pEList );
116780  if( dest.eDest==SRT_Output ){
116781  Select *pFirst = p;
116782  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
116783  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
116784  }
116785  iBreak = sqlite3VdbeMakeLabel(v);
116786  iCont = sqlite3VdbeMakeLabel(v);
116787  computeLimitRegisters(pParse, p, iBreak);
116788  sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
116789  iStart = sqlite3VdbeCurrentAddr(v);
116790  selectInnerLoop(pParse, p, p->pEList, unionTab,
116791  0, 0, &dest, iCont, iBreak);
116792  sqlite3VdbeResolveLabel(v, iCont);
116793  sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
116794  sqlite3VdbeResolveLabel(v, iBreak);
116795  sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
116796  }
116797  break;
116798  }
116799  default: assert( p->op==TK_INTERSECT ); {
116800  int tab1, tab2;
116801  int iCont, iBreak, iStart;
116802  Expr *pLimit, *pOffset;
116803  int addr;
116804  SelectDest intersectdest;
116805  int r1;
116806 
116807  /* INTERSECT is different from the others since it requires
116808  ** two temporary tables. Hence it has its own case. Begin
116809  ** by allocating the tables we will need.
116810  */
116811  tab1 = pParse->nTab++;
116812  tab2 = pParse->nTab++;
116813  assert( p->pOrderBy==0 );
116814 
116815  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
116816  assert( p->addrOpenEphm[0] == -1 );
116817  p->addrOpenEphm[0] = addr;
116819  assert( p->pEList );
116820 
116821  /* Code the SELECTs to our left into temporary table "tab1".
116822  */
116823  sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
116824  explainSetInteger(iSub1, pParse->iNextSelectId);
116825  rc = sqlite3Select(pParse, pPrior, &intersectdest);
116826  if( rc ){
116827  goto multi_select_end;
116828  }
116829 
116830  /* Code the current SELECT into temporary table "tab2"
116831  */
116832  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
116833  assert( p->addrOpenEphm[1] == -1 );
116834  p->addrOpenEphm[1] = addr;
116835  p->pPrior = 0;
116836  pLimit = p->pLimit;
116837  p->pLimit = 0;
116838  pOffset = p->pOffset;
116839  p->pOffset = 0;
116840  intersectdest.iSDParm = tab2;
116841  explainSetInteger(iSub2, pParse->iNextSelectId);
116842  rc = sqlite3Select(pParse, p, &intersectdest);
116843  testcase( rc!=SQLITE_OK );
116844  pDelete = p->pPrior;
116845  p->pPrior = pPrior;
116846  if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
116847  sqlite3ExprDelete(db, p->pLimit);
116848  p->pLimit = pLimit;
116849  p->pOffset = pOffset;
116850 
116851  /* Generate code to take the intersection of the two temporary
116852  ** tables.
116853  */
116854  assert( p->pEList );
116855  if( dest.eDest==SRT_Output ){
116856  Select *pFirst = p;
116857  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
116858  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
116859  }
116860  iBreak = sqlite3VdbeMakeLabel(v);
116861  iCont = sqlite3VdbeMakeLabel(v);
116862  computeLimitRegisters(pParse, p, iBreak);
116863  sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
116864  r1 = sqlite3GetTempReg(pParse);
116865  iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
116866  sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
116867  sqlite3ReleaseTempReg(pParse, r1);
116868  selectInnerLoop(pParse, p, p->pEList, tab1,
116869  0, 0, &dest, iCont, iBreak);
116870  sqlite3VdbeResolveLabel(v, iCont);
116871  sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
116872  sqlite3VdbeResolveLabel(v, iBreak);
116873  sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
116874  sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
116875  break;
116876  }
116877  }
116878 
116879  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
116880 
116881  /* Compute collating sequences used by
116882  ** temporary tables needed to implement the compound select.
116883  ** Attach the KeyInfo structure to all temporary tables.
116884  **
116885  ** This section is run by the right-most SELECT statement only.
116886  ** SELECT statements to the left always skip this part. The right-most
116887  ** SELECT might also skip this part if it has no ORDER BY clause and
116888  ** no temp tables are required.
116889  */
116890  if( p->selFlags & SF_UsesEphemeral ){
116891  int i; /* Loop counter */
116892  KeyInfo *pKeyInfo; /* Collating sequence for the result set */
116893  Select *pLoop; /* For looping through SELECT statements */
116894  CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
116895  int nCol; /* Number of columns in result set */
116896 
116897  assert( p->pNext==0 );
116898  nCol = p->pEList->nExpr;
116899  pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
116900  if( !pKeyInfo ){
116901  rc = SQLITE_NOMEM_BKPT;
116902  goto multi_select_end;
116903  }
116904  for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
116905  *apColl = multiSelectCollSeq(pParse, p, i);
116906  if( 0==*apColl ){
116907  *apColl = db->pDfltColl;
116908  }
116909  }
116910 
116911  for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
116912  for(i=0; i<2; i++){
116913  int addr = pLoop->addrOpenEphm[i];
116914  if( addr<0 ){
116915  /* If [0] is unused then [1] is also unused. So we can
116916  ** always safely abort as soon as the first unused slot is found */
116917  assert( pLoop->addrOpenEphm[1]<0 );
116918  break;
116919  }
116920  sqlite3VdbeChangeP2(v, addr, nCol);
116921  sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
116922  P4_KEYINFO);
116923  pLoop->addrOpenEphm[i] = -1;
116924  }
116925  }
116926  sqlite3KeyInfoUnref(pKeyInfo);
116927  }
116928 
116929 multi_select_end:
116930  pDest->iSdst = dest.iSdst;
116931  pDest->nSdst = dest.nSdst;
116932  sqlite3SelectDelete(db, pDelete);
116933  return rc;
116934 }
116935 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
116936 
116937 /*
116938 ** Error message for when two or more terms of a compound select have different
116939 ** size result sets.
116940 */
116942  if( p->selFlags & SF_Values ){
116943  sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
116944  }else{
116945  sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
116946  " do not have the same number of result columns", selectOpName(p->op));
116947  }
116948 }
116949 
116950 /*
116951 ** Code an output subroutine for a coroutine implementation of a
116952 ** SELECT statment.
116953 **
116954 ** The data to be output is contained in pIn->iSdst. There are
116955 ** pIn->nSdst columns to be output. pDest is where the output should
116956 ** be sent.
116957 **
116958 ** regReturn is the number of the register holding the subroutine
116959 ** return address.
116960 **
116961 ** If regPrev>0 then it is the first register in a vector that
116962 ** records the previous output. mem[regPrev] is a flag that is false
116963 ** if there has been no previous output. If regPrev>0 then code is
116964 ** generated to suppress duplicates. pKeyInfo is used for comparing
116965 ** keys.
116966 **
116967 ** If the LIMIT found in p->iLimit is reached, jump immediately to
116968 ** iBreak.
116969 */
116971  Parse *pParse, /* Parsing context */
116972  Select *p, /* The SELECT statement */
116973  SelectDest *pIn, /* Coroutine supplying data */
116974  SelectDest *pDest, /* Where to send the data */
116975  int regReturn, /* The return address register */
116976  int regPrev, /* Previous result register. No uniqueness if 0 */
116977  KeyInfo *pKeyInfo, /* For comparing with previous entry */
116978  int iBreak /* Jump here if we hit the LIMIT */
116979 ){
116980  Vdbe *v = pParse->pVdbe;
116981  int iContinue;
116982  int addr;
116983 
116984  addr = sqlite3VdbeCurrentAddr(v);
116985  iContinue = sqlite3VdbeMakeLabel(v);
116986 
116987  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
116988  */
116989  if( regPrev ){
116990  int addr1, addr2;
116991  addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
116992  addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
116993  (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
116994  sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
116995  sqlite3VdbeJumpHere(v, addr1);
116996  sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
116997  sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
116998  }
116999  if( pParse->db->mallocFailed ) return 0;
117000 
117001  /* Suppress the first OFFSET entries if there is an OFFSET clause
117002  */
117003  codeOffset(v, p->iOffset, iContinue);
117004 
117005  assert( pDest->eDest!=SRT_Exists );
117006  assert( pDest->eDest!=SRT_Table );
117007  switch( pDest->eDest ){
117008  /* Store the result as data using a unique key.
117009  */
117010  case SRT_EphemTab: {
117011  int r1 = sqlite3GetTempReg(pParse);
117012  int r2 = sqlite3GetTempReg(pParse);
117013  sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
117014  sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
117015  sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
117017  sqlite3ReleaseTempReg(pParse, r2);
117018  sqlite3ReleaseTempReg(pParse, r1);
117019  break;
117020  }
117021 
117022 #ifndef SQLITE_OMIT_SUBQUERY
117023  /* If we are creating a set for an "expr IN (SELECT ...)".
117024  */
117025  case SRT_Set: {
117026  int r1;
117027  testcase( pIn->nSdst>1 );
117028  r1 = sqlite3GetTempReg(pParse);
117029  sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
117030  r1, pDest->zAffSdst, pIn->nSdst);
117031  sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
117032  sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
117033  sqlite3ReleaseTempReg(pParse, r1);
117034  break;
117035  }
117036 
117037  /* If this is a scalar select that is part of an expression, then
117038  ** store the results in the appropriate memory cell and break out
117039  ** of the scan loop.
117040  */
117041  case SRT_Mem: {
117042  assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
117043  sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
117044  /* The LIMIT clause will jump out of the loop for us */
117045  break;
117046  }
117047 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
117048 
117049  /* The results are stored in a sequence of registers
117050  ** starting at pDest->iSdst. Then the co-routine yields.
117051  */
117052  case SRT_Coroutine: {
117053  if( pDest->iSdst==0 ){
117054  pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
117055  pDest->nSdst = pIn->nSdst;
117056  }
117057  sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
117058  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
117059  break;
117060  }
117061 
117062  /* If none of the above, then the result destination must be
117063  ** SRT_Output. This routine is never called with any other
117064  ** destination other than the ones handled above or SRT_Output.
117065  **
117066  ** For SRT_Output, results are stored in a sequence of registers.
117067  ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
117068  ** return the next row of result.
117069  */
117070  default: {
117071  assert( pDest->eDest==SRT_Output );
117072  sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
117073  sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
117074  break;
117075  }
117076  }
117077 
117078  /* Jump to the end of the loop if the LIMIT is reached.
117079  */
117080  if( p->iLimit ){
117082  }
117083 
117084  /* Generate the subroutine return
117085  */
117086  sqlite3VdbeResolveLabel(v, iContinue);
117087  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
117088 
117089  return addr;
117090 }
117091 
117092 /*
117093 ** Alternative compound select code generator for cases when there
117094 ** is an ORDER BY clause.
117095 **
117096 ** We assume a query of the following form:
117097 **
117098 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
117099 **
117100 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
117101 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
117102 ** co-routines. Then run the co-routines in parallel and merge the results
117103 ** into the output. In addition to the two coroutines (called selectA and
117104 ** selectB) there are 7 subroutines:
117105 **
117106 ** outA: Move the output of the selectA coroutine into the output
117107 ** of the compound query.
117108 **
117109 ** outB: Move the output of the selectB coroutine into the output
117110 ** of the compound query. (Only generated for UNION and
117111 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
117112 ** appears only in B.)
117113 **
117114 ** AltB: Called when there is data from both coroutines and A<B.
117115 **
117116 ** AeqB: Called when there is data from both coroutines and A==B.
117117 **
117118 ** AgtB: Called when there is data from both coroutines and A>B.
117119 **
117120 ** EofA: Called when data is exhausted from selectA.
117121 **
117122 ** EofB: Called when data is exhausted from selectB.
117123 **
117124 ** The implementation of the latter five subroutines depend on which
117125 ** <operator> is used:
117126 **
117127 **
117128 ** UNION ALL UNION EXCEPT INTERSECT
117129 ** ------------- ----------------- -------------- -----------------
117130 ** AltB: outA, nextA outA, nextA outA, nextA nextA
117131 **
117132 ** AeqB: outA, nextA nextA nextA outA, nextA
117133 **
117134 ** AgtB: outB, nextB outB, nextB nextB nextB
117135 **
117136 ** EofA: outB, nextB outB, nextB halt halt
117137 **
117138 ** EofB: outA, nextA outA, nextA outA, nextA halt
117139 **
117140 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
117141 ** causes an immediate jump to EofA and an EOF on B following nextB causes
117142 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
117143 ** following nextX causes a jump to the end of the select processing.
117144 **
117145 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
117146 ** within the output subroutine. The regPrev register set holds the previously
117147 ** output value. A comparison is made against this value and the output
117148 ** is skipped if the next results would be the same as the previous.
117149 **
117150 ** The implementation plan is to implement the two coroutines and seven
117151 ** subroutines first, then put the control logic at the bottom. Like this:
117152 **
117153 ** goto Init
117154 ** coA: coroutine for left query (A)
117155 ** coB: coroutine for right query (B)
117156 ** outA: output one row of A
117157 ** outB: output one row of B (UNION and UNION ALL only)
117158 ** EofA: ...
117159 ** EofB: ...
117160 ** AltB: ...
117161 ** AeqB: ...
117162 ** AgtB: ...
117163 ** Init: initialize coroutine registers
117164 ** yield coA
117165 ** if eof(A) goto EofA
117166 ** yield coB
117167 ** if eof(B) goto EofB
117168 ** Cmpr: Compare A, B
117169 ** Jump AltB, AeqB, AgtB
117170 ** End: ...
117171 **
117172 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
117173 ** actually called using Gosub and they do not Return. EofA and EofB loop
117174 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
117175 ** and AgtB jump to either L2 or to one of EofA or EofB.
117176 */
117177 #ifndef SQLITE_OMIT_COMPOUND_SELECT
117179  Parse *pParse, /* Parsing context */
117180  Select *p, /* The right-most of SELECTs to be coded */
117181  SelectDest *pDest /* What to do with query results */
117182 ){
117183  int i, j; /* Loop counters */
117184  Select *pPrior; /* Another SELECT immediately to our left */
117185  Vdbe *v; /* Generate code to this VDBE */
117186  SelectDest destA; /* Destination for coroutine A */
117187  SelectDest destB; /* Destination for coroutine B */
117188  int regAddrA; /* Address register for select-A coroutine */
117189  int regAddrB; /* Address register for select-B coroutine */
117190  int addrSelectA; /* Address of the select-A coroutine */
117191  int addrSelectB; /* Address of the select-B coroutine */
117192  int regOutA; /* Address register for the output-A subroutine */
117193  int regOutB; /* Address register for the output-B subroutine */
117194  int addrOutA; /* Address of the output-A subroutine */
117195  int addrOutB = 0; /* Address of the output-B subroutine */
117196  int addrEofA; /* Address of the select-A-exhausted subroutine */
117197  int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
117198  int addrEofB; /* Address of the select-B-exhausted subroutine */
117199  int addrAltB; /* Address of the A<B subroutine */
117200  int addrAeqB; /* Address of the A==B subroutine */
117201  int addrAgtB; /* Address of the A>B subroutine */
117202  int regLimitA; /* Limit register for select-A */
117203  int regLimitB; /* Limit register for select-A */
117204  int regPrev; /* A range of registers to hold previous output */
117205  int savedLimit; /* Saved value of p->iLimit */
117206  int savedOffset; /* Saved value of p->iOffset */
117207  int labelCmpr; /* Label for the start of the merge algorithm */
117208  int labelEnd; /* Label for the end of the overall SELECT stmt */
117209  int addr1; /* Jump instructions that get retargetted */
117210  int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
117211  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
117212  KeyInfo *pKeyMerge; /* Comparison information for merging rows */
117213  sqlite3 *db; /* Database connection */
117214  ExprList *pOrderBy; /* The ORDER BY clause */
117215  int nOrderBy; /* Number of terms in the ORDER BY clause */
117216  int *aPermute; /* Mapping from ORDER BY terms to result set columns */
117217 #ifndef SQLITE_OMIT_EXPLAIN
117218  int iSub1; /* EQP id of left-hand query */
117219  int iSub2; /* EQP id of right-hand query */
117220 #endif
117221 
117222  assert( p->pOrderBy!=0 );
117223  assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
117224  db = pParse->db;
117225  v = pParse->pVdbe;
117226  assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
117227  labelEnd = sqlite3VdbeMakeLabel(v);
117228  labelCmpr = sqlite3VdbeMakeLabel(v);
117229 
117230 
117231  /* Patch up the ORDER BY clause
117232  */
117233  op = p->op;
117234  pPrior = p->pPrior;
117235  assert( pPrior->pOrderBy==0 );
117236  pOrderBy = p->pOrderBy;
117237  assert( pOrderBy );
117238  nOrderBy = pOrderBy->nExpr;
117239 
117240  /* For operators other than UNION ALL we have to make sure that
117241  ** the ORDER BY clause covers every term of the result set. Add
117242  ** terms to the ORDER BY clause as necessary.
117243  */
117244  if( op!=TK_ALL ){
117245  for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
117246  struct ExprList_item *pItem;
117247  for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
117248  assert( pItem->u.x.iOrderByCol>0 );
117249  if( pItem->u.x.iOrderByCol==i ) break;
117250  }
117251  if( j==nOrderBy ){
117252  Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
117253  if( pNew==0 ) return SQLITE_NOMEM_BKPT;
117254  pNew->flags |= EP_IntValue;
117255  pNew->u.iValue = i;
117256  pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
117257  if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
117258  }
117259  }
117260  }
117261 
117262  /* Compute the comparison permutation and keyinfo that is used with
117263  ** the permutation used to determine if the next
117264  ** row of results comes from selectA or selectB. Also add explicit
117265  ** collations to the ORDER BY clause terms so that when the subqueries
117266  ** to the right and the left are evaluated, they use the correct
117267  ** collation.
117268  */
117269  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
117270  if( aPermute ){
117271  struct ExprList_item *pItem;
117272  aPermute[0] = nOrderBy;
117273  for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
117274  assert( pItem->u.x.iOrderByCol>0 );
117275  assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
117276  aPermute[i] = pItem->u.x.iOrderByCol - 1;
117277  }
117278  pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
117279  }else{
117280  pKeyMerge = 0;
117281  }
117282 
117283  /* Reattach the ORDER BY clause to the query.
117284  */
117285  p->pOrderBy = pOrderBy;
117286  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
117287 
117288  /* Allocate a range of temporary registers and the KeyInfo needed
117289  ** for the logic that removes duplicate result rows when the
117290  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
117291  */
117292  if( op==TK_ALL ){
117293  regPrev = 0;
117294  }else{
117295  int nExpr = p->pEList->nExpr;
117296  assert( nOrderBy>=nExpr || db->mallocFailed );
117297  regPrev = pParse->nMem+1;
117298  pParse->nMem += nExpr+1;
117299  sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
117300  pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
117301  if( pKeyDup ){
117302  assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
117303  for(i=0; i<nExpr; i++){
117304  pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
117305  pKeyDup->aSortOrder[i] = 0;
117306  }
117307  }
117308  }
117309 
117310  /* Separate the left and the right query from one another
117311  */
117312  p->pPrior = 0;
117313  pPrior->pNext = 0;
117314  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
117315  if( pPrior->pPrior==0 ){
117316  sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
117317  }
117318 
117319  /* Compute the limit registers */
117320  computeLimitRegisters(pParse, p, labelEnd);
117321  if( p->iLimit && op==TK_ALL ){
117322  regLimitA = ++pParse->nMem;
117323  regLimitB = ++pParse->nMem;
117324  sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
117325  regLimitA);
117326  sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
117327  }else{
117328  regLimitA = regLimitB = 0;
117329  }
117330  sqlite3ExprDelete(db, p->pLimit);
117331  p->pLimit = 0;
117332  sqlite3ExprDelete(db, p->pOffset);
117333  p->pOffset = 0;
117334 
117335  regAddrA = ++pParse->nMem;
117336  regAddrB = ++pParse->nMem;
117337  regOutA = ++pParse->nMem;
117338  regOutB = ++pParse->nMem;
117339  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
117340  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
117341 
117342  /* Generate a coroutine to evaluate the SELECT statement to the
117343  ** left of the compound operator - the "A" select.
117344  */
117345  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
117346  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
117347  VdbeComment((v, "left SELECT"));
117348  pPrior->iLimit = regLimitA;
117349  explainSetInteger(iSub1, pParse->iNextSelectId);
117350  sqlite3Select(pParse, pPrior, &destA);
117351  sqlite3VdbeEndCoroutine(v, regAddrA);
117352  sqlite3VdbeJumpHere(v, addr1);
117353 
117354  /* Generate a coroutine to evaluate the SELECT statement on
117355  ** the right - the "B" select
117356  */
117357  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
117358  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
117359  VdbeComment((v, "right SELECT"));
117360  savedLimit = p->iLimit;
117361  savedOffset = p->iOffset;
117362  p->iLimit = regLimitB;
117363  p->iOffset = 0;
117364  explainSetInteger(iSub2, pParse->iNextSelectId);
117365  sqlite3Select(pParse, p, &destB);
117366  p->iLimit = savedLimit;
117367  p->iOffset = savedOffset;
117368  sqlite3VdbeEndCoroutine(v, regAddrB);
117369 
117370  /* Generate a subroutine that outputs the current row of the A
117371  ** select as the next output row of the compound select.
117372  */
117373  VdbeNoopComment((v, "Output routine for A"));
117374  addrOutA = generateOutputSubroutine(pParse,
117375  p, &destA, pDest, regOutA,
117376  regPrev, pKeyDup, labelEnd);
117377 
117378  /* Generate a subroutine that outputs the current row of the B
117379  ** select as the next output row of the compound select.
117380  */
117381  if( op==TK_ALL || op==TK_UNION ){
117382  VdbeNoopComment((v, "Output routine for B"));
117383  addrOutB = generateOutputSubroutine(pParse,
117384  p, &destB, pDest, regOutB,
117385  regPrev, pKeyDup, labelEnd);
117386  }
117387  sqlite3KeyInfoUnref(pKeyDup);
117388 
117389  /* Generate a subroutine to run when the results from select A
117390  ** are exhausted and only data in select B remains.
117391  */
117392  if( op==TK_EXCEPT || op==TK_INTERSECT ){
117393  addrEofA_noB = addrEofA = labelEnd;
117394  }else{
117395  VdbeNoopComment((v, "eof-A subroutine"));
117396  addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
117397  addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
117398  VdbeCoverage(v);
117399  sqlite3VdbeGoto(v, addrEofA);
117400  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
117401  }
117402 
117403  /* Generate a subroutine to run when the results from select B
117404  ** are exhausted and only data in select A remains.
117405  */
117406  if( op==TK_INTERSECT ){
117407  addrEofB = addrEofA;
117408  if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
117409  }else{
117410  VdbeNoopComment((v, "eof-B subroutine"));
117411  addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
117412  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
117413  sqlite3VdbeGoto(v, addrEofB);
117414  }
117415 
117416  /* Generate code to handle the case of A<B
117417  */
117418  VdbeNoopComment((v, "A-lt-B subroutine"));
117419  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
117420  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
117421  sqlite3VdbeGoto(v, labelCmpr);
117422 
117423  /* Generate code to handle the case of A==B
117424  */
117425  if( op==TK_ALL ){
117426  addrAeqB = addrAltB;
117427  }else if( op==TK_INTERSECT ){
117428  addrAeqB = addrAltB;
117429  addrAltB++;
117430  }else{
117431  VdbeNoopComment((v, "A-eq-B subroutine"));
117432  addrAeqB =
117433  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
117434  sqlite3VdbeGoto(v, labelCmpr);
117435  }
117436 
117437  /* Generate code to handle the case of A>B
117438  */
117439  VdbeNoopComment((v, "A-gt-B subroutine"));
117440  addrAgtB = sqlite3VdbeCurrentAddr(v);
117441  if( op==TK_ALL || op==TK_UNION ){
117442  sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
117443  }
117444  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
117445  sqlite3VdbeGoto(v, labelCmpr);
117446 
117447  /* This code runs once to initialize everything.
117448  */
117449  sqlite3VdbeJumpHere(v, addr1);
117450  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
117451  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
117452 
117453  /* Implement the main merge loop
117454  */
117455  sqlite3VdbeResolveLabel(v, labelCmpr);
117456  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
117457  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
117458  (char*)pKeyMerge, P4_KEYINFO);
117460  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
117461 
117462  /* Jump to the this point in order to terminate the query.
117463  */
117464  sqlite3VdbeResolveLabel(v, labelEnd);
117465 
117466  /* Set the number of output columns
117467  */
117468  if( pDest->eDest==SRT_Output ){
117469  Select *pFirst = pPrior;
117470  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
117471  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
117472  }
117473 
117474  /* Reassembly the compound query so that it will be freed correctly
117475  ** by the calling function */
117476  if( p->pPrior ){
117477  sqlite3SelectDelete(db, p->pPrior);
117478  }
117479  p->pPrior = pPrior;
117480  pPrior->pNext = p;
117481 
117482  /*** TBD: Insert subroutine calls to close cursors on incomplete
117483  **** subqueries ****/
117484  explainComposite(pParse, p->op, iSub1, iSub2, 0);
117485  return pParse->nErr!=0;
117486 }
117487 #endif
117488 
117489 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117490 /* Forward Declarations */
117491 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
117492 static void substSelect(sqlite3*, Select *, int, ExprList*, int);
117493 
117494 /*
117495 ** Scan through the expression pExpr. Replace every reference to
117496 ** a column in table number iTable with a copy of the iColumn-th
117497 ** entry in pEList. (But leave references to the ROWID column
117498 ** unchanged.)
117499 **
117500 ** This routine is part of the flattening procedure. A subquery
117501 ** whose result set is defined by pEList appears as entry in the
117502 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
117503 ** FORM clause entry is iTable. This routine make the necessary
117504 ** changes to pExpr so that it refers directly to the source table
117505 ** of the subquery rather the result set of the subquery.
117506 */
117508  sqlite3 *db, /* Report malloc errors to this connection */
117509  Expr *pExpr, /* Expr in which substitution occurs */
117510  int iTable, /* Table to be substituted */
117511  ExprList *pEList /* Substitute expressions */
117512 ){
117513  if( pExpr==0 ) return 0;
117514  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
117515  if( pExpr->iColumn<0 ){
117516  pExpr->op = TK_NULL;
117517  }else{
117518  Expr *pNew;
117519  assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
117520  assert( pExpr->pLeft==0 && pExpr->pRight==0 );
117521  pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
117522  sqlite3ExprDelete(db, pExpr);
117523  pExpr = pNew;
117524  }
117525  }else{
117526  pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
117527  pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
117528  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
117529  substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
117530  }else{
117531  substExprList(db, pExpr->x.pList, iTable, pEList);
117532  }
117533  }
117534  return pExpr;
117535 }
117536 static void substExprList(
117537  sqlite3 *db, /* Report malloc errors here */
117538  ExprList *pList, /* List to scan and in which to make substitutes */
117539  int iTable, /* Table to be substituted */
117540  ExprList *pEList /* Substitute values */
117541 ){
117542  int i;
117543  if( pList==0 ) return;
117544  for(i=0; i<pList->nExpr; i++){
117545  pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
117546  }
117547 }
117548 static void substSelect(
117549  sqlite3 *db, /* Report malloc errors here */
117550  Select *p, /* SELECT statement in which to make substitutions */
117551  int iTable, /* Table to be replaced */
117552  ExprList *pEList, /* Substitute values */
117553  int doPrior /* Do substitutes on p->pPrior too */
117554 ){
117555  SrcList *pSrc;
117556  struct SrcList_item *pItem;
117557  int i;
117558  if( !p ) return;
117559  do{
117560  substExprList(db, p->pEList, iTable, pEList);
117561  substExprList(db, p->pGroupBy, iTable, pEList);
117562  substExprList(db, p->pOrderBy, iTable, pEList);
117563  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
117564  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
117565  pSrc = p->pSrc;
117566  assert( pSrc!=0 );
117567  for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
117568  substSelect(db, pItem->pSelect, iTable, pEList, 1);
117569  if( pItem->fg.isTabFunc ){
117570  substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
117571  }
117572  }
117573  }while( doPrior && (p = p->pPrior)!=0 );
117574 }
117575 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117576 
117577 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117578 /*
117579 ** This routine attempts to flatten subqueries as a performance optimization.
117580 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
117581 **
117582 ** To understand the concept of flattening, consider the following
117583 ** query:
117584 **
117585 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
117586 **
117587 ** The default way of implementing this query is to execute the
117588 ** subquery first and store the results in a temporary table, then
117589 ** run the outer query on that temporary table. This requires two
117590 ** passes over the data. Furthermore, because the temporary table
117591 ** has no indices, the WHERE clause on the outer query cannot be
117592 ** optimized.
117593 **
117594 ** This routine attempts to rewrite queries such as the above into
117595 ** a single flat select, like this:
117596 **
117597 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
117598 **
117599 ** The code generated for this simplification gives the same result
117600 ** but only has to scan the data once. And because indices might
117601 ** exist on the table t1, a complete scan of the data might be
117602 ** avoided.
117603 **
117604 ** Flattening is only attempted if all of the following are true:
117605 **
117606 ** (1) The subquery and the outer query do not both use aggregates.
117607 **
117608 ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
117609 ** and (2b) the outer query does not use subqueries other than the one
117610 ** FROM-clause subquery that is a candidate for flattening. (2b is
117611 ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
117612 **
117613 ** (3) The subquery is not the right operand of a left outer join
117614 ** (Originally ticket #306. Strengthened by ticket #3300)
117615 **
117616 ** (4) The subquery is not DISTINCT.
117617 **
117618 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
117619 ** sub-queries that were excluded from this optimization. Restriction
117620 ** (4) has since been expanded to exclude all DISTINCT subqueries.
117621 **
117622 ** (6) The subquery does not use aggregates or the outer query is not
117623 ** DISTINCT.
117624 **
117625 ** (7) The subquery has a FROM clause. TODO: For subqueries without
117626 ** A FROM clause, consider adding a FROM close with the special
117627 ** table sqlite_once that consists of a single row containing a
117628 ** single NULL.
117629 **
117630 ** (8) The subquery does not use LIMIT or the outer query is not a join.
117631 **
117632 ** (9) The subquery does not use LIMIT or the outer query does not use
117633 ** aggregates.
117634 **
117635 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
117636 ** accidently carried the comment forward until 2014-09-15. Original
117637 ** text: "The subquery does not use aggregates or the outer query
117638 ** does not use LIMIT."
117639 **
117640 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
117641 **
117642 ** (**) Not implemented. Subsumed into restriction (3). Was previously
117643 ** a separate restriction deriving from ticket #350.
117644 **
117645 ** (13) The subquery and outer query do not both use LIMIT.
117646 **
117647 ** (14) The subquery does not use OFFSET.
117648 **
117649 ** (15) The outer query is not part of a compound select or the
117650 ** subquery does not have a LIMIT clause.
117651 ** (See ticket #2339 and ticket [02a8e81d44]).
117652 **
117653 ** (16) The outer query is not an aggregate or the subquery does
117654 ** not contain ORDER BY. (Ticket #2942) This used to not matter
117655 ** until we introduced the group_concat() function.
117656 **
117657 ** (17) The sub-query is not a compound select, or it is a UNION ALL
117658 ** compound clause made up entirely of non-aggregate queries, and
117659 ** the parent query:
117660 **
117661 ** * is not itself part of a compound select,
117662 ** * is not an aggregate or DISTINCT query, and
117663 ** * is not a join
117664 **
117665 ** The parent and sub-query may contain WHERE clauses. Subject to
117666 ** rules (11), (13) and (14), they may also contain ORDER BY,
117667 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
117668 ** operator other than UNION ALL because all the other compound
117669 ** operators have an implied DISTINCT which is disallowed by
117670 ** restriction (4).
117671 **
117672 ** Also, each component of the sub-query must return the same number
117673 ** of result columns. This is actually a requirement for any compound
117674 ** SELECT statement, but all the code here does is make sure that no
117675 ** such (illegal) sub-query is flattened. The caller will detect the
117676 ** syntax error and return a detailed message.
117677 **
117678 ** (18) If the sub-query is a compound select, then all terms of the
117679 ** ORDER by clause of the parent must be simple references to
117680 ** columns of the sub-query.
117681 **
117682 ** (19) The subquery does not use LIMIT or the outer query does not
117683 ** have a WHERE clause.
117684 **
117685 ** (20) If the sub-query is a compound select, then it must not use
117686 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
117687 ** somewhat by saying that the terms of the ORDER BY clause must
117688 ** appear as unmodified result columns in the outer query. But we
117689 ** have other optimizations in mind to deal with that case.
117690 **
117691 ** (21) The subquery does not use LIMIT or the outer query is not
117692 ** DISTINCT. (See ticket [752e1646fc]).
117693 **
117694 ** (22) The subquery is not a recursive CTE.
117695 **
117696 ** (23) The parent is not a recursive CTE, or the sub-query is not a
117697 ** compound query. This restriction is because transforming the
117698 ** parent to a compound query confuses the code that handles
117699 ** recursive queries in multiSelect().
117700 **
117701 ** (24) The subquery is not an aggregate that uses the built-in min() or
117702 ** or max() functions. (Without this restriction, a query like:
117703 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
117704 ** return the value X for which Y was maximal.)
117705 **
117706 **
117707 ** In this routine, the "p" parameter is a pointer to the outer query.
117708 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
117709 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
117710 **
117711 ** If flattening is not attempted, this routine is a no-op and returns 0.
117712 ** If flattening is attempted this routine returns 1.
117713 **
117714 ** All of the expression analysis must occur on both the outer query and
117715 ** the subquery before this routine runs.
117716 */
117717 static int flattenSubquery(
117718  Parse *pParse, /* Parsing context */
117719  Select *p, /* The parent or outer SELECT statement */
117720  int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
117721  int isAgg, /* True if outer SELECT uses aggregate functions */
117722  int subqueryIsAgg /* True if the subquery uses aggregate functions */
117723 ){
117724  const char *zSavedAuthContext = pParse->zAuthContext;
117725  Select *pParent; /* Current UNION ALL term of the other query */
117726  Select *pSub; /* The inner query or "subquery" */
117727  Select *pSub1; /* Pointer to the rightmost select in sub-query */
117728  SrcList *pSrc; /* The FROM clause of the outer query */
117729  SrcList *pSubSrc; /* The FROM clause of the subquery */
117730  ExprList *pList; /* The result set of the outer query */
117731  int iParent; /* VDBE cursor number of the pSub result set temp table */
117732  int i; /* Loop counter */
117733  Expr *pWhere; /* The WHERE clause */
117734  struct SrcList_item *pSubitem; /* The subquery */
117735  sqlite3 *db = pParse->db;
117736 
117737  /* Check to see if flattening is permitted. Return 0 if not.
117738  */
117739  assert( p!=0 );
117740  assert( p->pPrior==0 ); /* Unable to flatten compound queries */
117741  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
117742  pSrc = p->pSrc;
117743  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
117744  pSubitem = &pSrc->a[iFrom];
117745  iParent = pSubitem->iCursor;
117746  pSub = pSubitem->pSelect;
117747  assert( pSub!=0 );
117748  if( subqueryIsAgg ){
117749  if( isAgg ) return 0; /* Restriction (1) */
117750  if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
117751  if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
117752  || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
117754  ){
117755  return 0; /* Restriction (2b) */
117756  }
117757  }
117758 
117759  pSubSrc = pSub->pSrc;
117760  assert( pSubSrc );
117761  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
117762  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
117763  ** because they could be computed at compile-time. But when LIMIT and OFFSET
117764  ** became arbitrary expressions, we were forced to add restrictions (13)
117765  ** and (14). */
117766  if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
117767  if( pSub->pOffset ) return 0; /* Restriction (14) */
117768  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
117769  return 0; /* Restriction (15) */
117770  }
117771  if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
117772  if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
117773  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
117774  return 0; /* Restrictions (8)(9) */
117775  }
117776  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
117777  return 0; /* Restriction (6) */
117778  }
117779  if( p->pOrderBy && pSub->pOrderBy ){
117780  return 0; /* Restriction (11) */
117781  }
117782  if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
117783  if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
117784  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
117785  return 0; /* Restriction (21) */
117786  }
117787  testcase( pSub->selFlags & SF_Recursive );
117788  testcase( pSub->selFlags & SF_MinMaxAgg );
117789  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
117790  return 0; /* Restrictions (22) and (24) */
117791  }
117792  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
117793  return 0; /* Restriction (23) */
117794  }
117795 
117796  /* OBSOLETE COMMENT 1:
117797  ** Restriction 3: If the subquery is a join, make sure the subquery is
117798  ** not used as the right operand of an outer join. Examples of why this
117799  ** is not allowed:
117800  **
117801  ** t1 LEFT OUTER JOIN (t2 JOIN t3)
117802  **
117803  ** If we flatten the above, we would get
117804  **
117805  ** (t1 LEFT OUTER JOIN t2) JOIN t3
117806  **
117807  ** which is not at all the same thing.
117808  **
117809  ** OBSOLETE COMMENT 2:
117810  ** Restriction 12: If the subquery is the right operand of a left outer
117811  ** join, make sure the subquery has no WHERE clause.
117812  ** An examples of why this is not allowed:
117813  **
117814  ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
117815  **
117816  ** If we flatten the above, we would get
117817  **
117818  ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
117819  **
117820  ** But the t2.x>0 test will always fail on a NULL row of t2, which
117821  ** effectively converts the OUTER JOIN into an INNER JOIN.
117822  **
117823  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
117824  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
117825  ** is fraught with danger. Best to avoid the whole thing. If the
117826  ** subquery is the right term of a LEFT JOIN, then do not flatten.
117827  */
117828  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
117829  return 0;
117830  }
117831 
117832  /* Restriction 17: If the sub-query is a compound SELECT, then it must
117833  ** use only the UNION ALL operator. And none of the simple select queries
117834  ** that make up the compound SELECT are allowed to be aggregate or distinct
117835  ** queries.
117836  */
117837  if( pSub->pPrior ){
117838  if( pSub->pOrderBy ){
117839  return 0; /* Restriction 20 */
117840  }
117841  if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
117842  return 0;
117843  }
117844  for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
117847  assert( pSub->pSrc!=0 );
117848  assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
117849  if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
117850  || (pSub1->pPrior && pSub1->op!=TK_ALL)
117851  || pSub1->pSrc->nSrc<1
117852  ){
117853  return 0;
117854  }
117855  testcase( pSub1->pSrc->nSrc>1 );
117856  }
117857 
117858  /* Restriction 18. */
117859  if( p->pOrderBy ){
117860  int ii;
117861  for(ii=0; ii<p->pOrderBy->nExpr; ii++){
117862  if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
117863  }
117864  }
117865  }
117866 
117867  /***** If we reach this point, flattening is permitted. *****/
117868  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
117869  pSub->zSelName, pSub, iFrom));
117870 
117871  /* Authorize the subquery */
117872  pParse->zAuthContext = pSubitem->zName;
117873  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
117874  testcase( i==SQLITE_DENY );
117875  pParse->zAuthContext = zSavedAuthContext;
117876 
117877  /* If the sub-query is a compound SELECT statement, then (by restrictions
117878  ** 17 and 18 above) it must be a UNION ALL and the parent query must
117879  ** be of the form:
117880  **
117881  ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
117882  **
117883  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
117884  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
117885  ** OFFSET clauses and joins them to the left-hand-side of the original
117886  ** using UNION ALL operators. In this case N is the number of simple
117887  ** select statements in the compound sub-query.
117888  **
117889  ** Example:
117890  **
117891  ** SELECT a+1 FROM (
117892  ** SELECT x FROM tab
117893  ** UNION ALL
117894  ** SELECT y FROM tab
117895  ** UNION ALL
117896  ** SELECT abs(z*2) FROM tab2
117897  ** ) WHERE a!=5 ORDER BY 1
117898  **
117899  ** Transformed into:
117900  **
117901  ** SELECT x+1 FROM tab WHERE x+1!=5
117902  ** UNION ALL
117903  ** SELECT y+1 FROM tab WHERE y+1!=5
117904  ** UNION ALL
117905  ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
117906  ** ORDER BY 1
117907  **
117908  ** We call this the "compound-subquery flattening".
117909  */
117910  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
117911  Select *pNew;
117912  ExprList *pOrderBy = p->pOrderBy;
117913  Expr *pLimit = p->pLimit;
117914  Expr *pOffset = p->pOffset;
117915  Select *pPrior = p->pPrior;
117916  p->pOrderBy = 0;
117917  p->pSrc = 0;
117918  p->pPrior = 0;
117919  p->pLimit = 0;
117920  p->pOffset = 0;
117921  pNew = sqlite3SelectDup(db, p, 0);
117922  sqlite3SelectSetName(pNew, pSub->zSelName);
117923  p->pOffset = pOffset;
117924  p->pLimit = pLimit;
117925  p->pOrderBy = pOrderBy;
117926  p->pSrc = pSrc;
117927  p->op = TK_ALL;
117928  if( pNew==0 ){
117929  p->pPrior = pPrior;
117930  }else{
117931  pNew->pPrior = pPrior;
117932  if( pPrior ) pPrior->pNext = pNew;
117933  pNew->pNext = p;
117934  p->pPrior = pNew;
117935  SELECTTRACE(2,pParse,p,
117936  ("compound-subquery flattener creates %s.%p as peer\n",
117937  pNew->zSelName, pNew));
117938  }
117939  if( db->mallocFailed ) return 1;
117940  }
117941 
117942  /* Begin flattening the iFrom-th entry of the FROM clause
117943  ** in the outer query.
117944  */
117945  pSub = pSub1 = pSubitem->pSelect;
117946 
117947  /* Delete the transient table structure associated with the
117948  ** subquery
117949  */
117950  sqlite3DbFree(db, pSubitem->zDatabase);
117951  sqlite3DbFree(db, pSubitem->zName);
117952  sqlite3DbFree(db, pSubitem->zAlias);
117953  pSubitem->zDatabase = 0;
117954  pSubitem->zName = 0;
117955  pSubitem->zAlias = 0;
117956  pSubitem->pSelect = 0;
117957 
117958  /* Defer deleting the Table object associated with the
117959  ** subquery until code generation is
117960  ** complete, since there may still exist Expr.pTab entries that
117961  ** refer to the subquery even after flattening. Ticket #3346.
117962  **
117963  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
117964  */
117965  if( ALWAYS(pSubitem->pTab!=0) ){
117966  Table *pTabToDel = pSubitem->pTab;
117967  if( pTabToDel->nRef==1 ){
117968  Parse *pToplevel = sqlite3ParseToplevel(pParse);
117969  pTabToDel->pNextZombie = pToplevel->pZombieTab;
117970  pToplevel->pZombieTab = pTabToDel;
117971  }else{
117972  pTabToDel->nRef--;
117973  }
117974  pSubitem->pTab = 0;
117975  }
117976 
117977  /* The following loop runs once for each term in a compound-subquery
117978  ** flattening (as described above). If we are doing a different kind
117979  ** of flattening - a flattening other than a compound-subquery flattening -
117980  ** then this loop only runs once.
117981  **
117982  ** This loop moves all of the FROM elements of the subquery into the
117983  ** the FROM clause of the outer query. Before doing this, remember
117984  ** the cursor number for the original outer query FROM element in
117985  ** iParent. The iParent cursor will never be used. Subsequent code
117986  ** will scan expressions looking for iParent references and replace
117987  ** those references with expressions that resolve to the subquery FROM
117988  ** elements we are now copying in.
117989  */
117990  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
117991  int nSubSrc;
117992  u8 jointype = 0;
117993  pSubSrc = pSub->pSrc; /* FROM clause of subquery */
117994  nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
117995  pSrc = pParent->pSrc; /* FROM clause of the outer query */
117996 
117997  if( pSrc ){
117998  assert( pParent==p ); /* First time through the loop */
117999  jointype = pSubitem->fg.jointype;
118000  }else{
118001  assert( pParent!=p ); /* 2nd and subsequent times through the loop */
118002  pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
118003  if( pSrc==0 ){
118004  assert( db->mallocFailed );
118005  break;
118006  }
118007  }
118008 
118009  /* The subquery uses a single slot of the FROM clause of the outer
118010  ** query. If the subquery has more than one element in its FROM clause,
118011  ** then expand the outer query to make space for it to hold all elements
118012  ** of the subquery.
118013  **
118014  ** Example:
118015  **
118016  ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
118017  **
118018  ** The outer query has 3 slots in its FROM clause. One slot of the
118019  ** outer query (the middle slot) is used by the subquery. The next
118020  ** block of code will expand the outer query FROM clause to 4 slots.
118021  ** The middle slot is expanded to two slots in order to make space
118022  ** for the two elements in the FROM clause of the subquery.
118023  */
118024  if( nSubSrc>1 ){
118025  pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
118026  if( db->mallocFailed ){
118027  break;
118028  }
118029  }
118030 
118031  /* Transfer the FROM clause terms from the subquery into the
118032  ** outer query.
118033  */
118034  for(i=0; i<nSubSrc; i++){
118035  sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
118036  assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
118037  pSrc->a[i+iFrom] = pSubSrc->a[i];
118038  memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
118039  }
118040  pSrc->a[iFrom].fg.jointype = jointype;
118041 
118042  /* Now begin substituting subquery result set expressions for
118043  ** references to the iParent in the outer query.
118044  **
118045  ** Example:
118046  **
118047  ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
118048  ** \ \_____________ subquery __________/ /
118049  ** \_____________________ outer query ______________________________/
118050  **
118051  ** We look at every expression in the outer query and every place we see
118052  ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
118053  */
118054  pList = pParent->pEList;
118055  for(i=0; i<pList->nExpr; i++){
118056  if( pList->a[i].zName==0 ){
118057  char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
118058  sqlite3Dequote(zName);
118059  pList->a[i].zName = zName;
118060  }
118061  }
118062  if( pSub->pOrderBy ){
118063  /* At this point, any non-zero iOrderByCol values indicate that the
118064  ** ORDER BY column expression is identical to the iOrderByCol'th
118065  ** expression returned by SELECT statement pSub. Since these values
118066  ** do not necessarily correspond to columns in SELECT statement pParent,
118067  ** zero them before transfering the ORDER BY clause.
118068  **
118069  ** Not doing this may cause an error if a subsequent call to this
118070  ** function attempts to flatten a compound sub-query into pParent
118071  ** (the only way this can happen is if the compound sub-query is
118072  ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
118073  ExprList *pOrderBy = pSub->pOrderBy;
118074  for(i=0; i<pOrderBy->nExpr; i++){
118075  pOrderBy->a[i].u.x.iOrderByCol = 0;
118076  }
118077  assert( pParent->pOrderBy==0 );
118078  assert( pSub->pPrior==0 );
118079  pParent->pOrderBy = pOrderBy;
118080  pSub->pOrderBy = 0;
118081  }
118082  pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
118083  if( subqueryIsAgg ){
118084  assert( pParent->pHaving==0 );
118085  pParent->pHaving = pParent->pWhere;
118086  pParent->pWhere = pWhere;
118087  pParent->pHaving = sqlite3ExprAnd(db,
118088  sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving
118089  );
118090  assert( pParent->pGroupBy==0 );
118091  pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
118092  }else{
118093  pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
118094  }
118095  substSelect(db, pParent, iParent, pSub->pEList, 0);
118096 
118097  /* The flattened query is distinct if either the inner or the
118098  ** outer query is distinct.
118099  */
118100  pParent->selFlags |= pSub->selFlags & SF_Distinct;
118101 
118102  /*
118103  ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
118104  **
118105  ** One is tempted to try to add a and b to combine the limits. But this
118106  ** does not work if either limit is negative.
118107  */
118108  if( pSub->pLimit ){
118109  pParent->pLimit = pSub->pLimit;
118110  pSub->pLimit = 0;
118111  }
118112  }
118113 
118114  /* Finially, delete what is left of the subquery and return
118115  ** success.
118116  */
118117  sqlite3SelectDelete(db, pSub1);
118118 
118119 #if SELECTTRACE_ENABLED
118120  if( sqlite3SelectTrace & 0x100 ){
118121  SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
118122  sqlite3TreeViewSelect(0, p, 0);
118123  }
118124 #endif
118125 
118126  return 1;
118127 }
118128 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
118129 
118130 
118131 
118132 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118133 /*
118134 ** Make copies of relevant WHERE clause terms of the outer query into
118135 ** the WHERE clause of subquery. Example:
118136 **
118137 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
118138 **
118139 ** Transformed into:
118140 **
118141 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
118142 ** WHERE x=5 AND y=10;
118143 **
118144 ** The hope is that the terms added to the inner query will make it more
118145 ** efficient.
118146 **
118147 ** Do not attempt this optimization if:
118148 **
118149 ** (1) The inner query is an aggregate. (In that case, we'd really want
118150 ** to copy the outer WHERE-clause terms onto the HAVING clause of the
118151 ** inner query. But they probably won't help there so do not bother.)
118152 **
118153 ** (2) The inner query is the recursive part of a common table expression.
118154 **
118155 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
118156 ** close would change the meaning of the LIMIT).
118157 **
118158 ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
118159 ** enforces this restriction since this routine does not have enough
118160 ** information to know.)
118161 **
118162 ** (5) The WHERE clause expression originates in the ON or USING clause
118163 ** of a LEFT JOIN.
118164 **
118165 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
118166 ** terms are duplicated into the subquery.
118167 */
118169  sqlite3 *db, /* The database connection (for malloc()) */
118170  Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
118171  Expr *pWhere, /* The WHERE clause of the outer query */
118172  int iCursor /* Cursor number of the subquery */
118173 ){
118174  Expr *pNew;
118175  int nChng = 0;
118176  Select *pX; /* For looping over compound SELECTs in pSubq */
118177  if( pWhere==0 ) return 0;
118178  for(pX=pSubq; pX; pX=pX->pPrior){
118179  if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
118180  testcase( pX->selFlags & SF_Aggregate );
118181  testcase( pX->selFlags & SF_Recursive );
118182  testcase( pX!=pSubq );
118183  return 0; /* restrictions (1) and (2) */
118184  }
118185  }
118186  if( pSubq->pLimit!=0 ){
118187  return 0; /* restriction (3) */
118188  }
118189  while( pWhere->op==TK_AND ){
118190  nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
118191  pWhere = pWhere->pLeft;
118192  }
118193  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
118194  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
118195  nChng++;
118196  while( pSubq ){
118197  pNew = sqlite3ExprDup(db, pWhere, 0);
118198  pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
118199  pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
118200  pSubq = pSubq->pPrior;
118201  }
118202  }
118203  return nChng;
118204 }
118205 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
118206 
118207 /*
118208 ** Based on the contents of the AggInfo structure indicated by the first
118209 ** argument, this function checks if the following are true:
118210 **
118211 ** * the query contains just a single aggregate function,
118212 ** * the aggregate function is either min() or max(), and
118213 ** * the argument to the aggregate function is a column value.
118214 **
118215 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
118216 ** is returned as appropriate. Also, *ppMinMax is set to point to the
118217 ** list of arguments passed to the aggregate before returning.
118218 **
118219 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
118220 ** WHERE_ORDERBY_NORMAL is returned.
118221 */
118222 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
118223  int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
118224 
118225  *ppMinMax = 0;
118226  if( pAggInfo->nFunc==1 ){
118227  Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
118228  ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
118229 
118230  assert( pExpr->op==TK_AGG_FUNCTION );
118231  if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
118232  const char *zFunc = pExpr->u.zToken;
118233  if( sqlite3StrICmp(zFunc, "min")==0 ){
118234  eRet = WHERE_ORDERBY_MIN;
118235  *ppMinMax = pEList;
118236  }else if( sqlite3StrICmp(zFunc, "max")==0 ){
118237  eRet = WHERE_ORDERBY_MAX;
118238  *ppMinMax = pEList;
118239  }
118240  }
118241  }
118242 
118243  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
118244  return eRet;
118245 }
118246 
118247 /*
118248 ** The select statement passed as the first argument is an aggregate query.
118249 ** The second argument is the associated aggregate-info object. This
118250 ** function tests if the SELECT is of the form:
118251 **
118252 ** SELECT count(*) FROM <tbl>
118253 **
118254 ** where table is a database table, not a sub-select or view. If the query
118255 ** does match this pattern, then a pointer to the Table object representing
118256 ** <tbl> is returned. Otherwise, 0 is returned.
118257 */
118258 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
118259  Table *pTab;
118260  Expr *pExpr;
118261 
118262  assert( !p->pGroupBy );
118263 
118264  if( p->pWhere || p->pEList->nExpr!=1
118265  || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
118266  ){
118267  return 0;
118268  }
118269  pTab = p->pSrc->a[0].pTab;
118270  pExpr = p->pEList->a[0].pExpr;
118271  assert( pTab && !pTab->pSelect && pExpr );
118272 
118273  if( IsVirtual(pTab) ) return 0;
118274  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
118275  if( NEVER(pAggInfo->nFunc==0) ) return 0;
118276  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
118277  if( pExpr->flags&EP_Distinct ) return 0;
118278 
118279  return pTab;
118280 }
118281 
118282 /*
118283 ** If the source-list item passed as an argument was augmented with an
118284 ** INDEXED BY clause, then try to locate the specified index. If there
118285 ** was such a clause and the named index cannot be found, return
118286 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
118287 ** pFrom->pIndex and return SQLITE_OK.
118288 */
118289 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
118290  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
118291  Table *pTab = pFrom->pTab;
118292  char *zIndexedBy = pFrom->u1.zIndexedBy;
118293  Index *pIdx;
118294  for(pIdx=pTab->pIndex;
118295  pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
118296  pIdx=pIdx->pNext
118297  );
118298  if( !pIdx ){
118299  sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
118300  pParse->checkSchema = 1;
118301  return SQLITE_ERROR;
118302  }
118303  pFrom->pIBIndex = pIdx;
118304  }
118305  return SQLITE_OK;
118306 }
118307 /*
118308 ** Detect compound SELECT statements that use an ORDER BY clause with
118309 ** an alternative collating sequence.
118310 **
118311 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
118312 **
118313 ** These are rewritten as a subquery:
118314 **
118315 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
118316 ** ORDER BY ... COLLATE ...
118317 **
118318 ** This transformation is necessary because the multiSelectOrderBy() routine
118319 ** above that generates the code for a compound SELECT with an ORDER BY clause
118320 ** uses a merge algorithm that requires the same collating sequence on the
118321 ** result columns as on the ORDER BY clause. See ticket
118322 ** http://www.sqlite.org/src/info/6709574d2a
118323 **
118324 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
118325 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
118326 ** there are COLLATE terms in the ORDER BY.
118327 */
118329  int i;
118330  Select *pNew;
118331  Select *pX;
118332  sqlite3 *db;
118333  struct ExprList_item *a;
118334  SrcList *pNewSrc;
118335  Parse *pParse;
118336  Token dummy;
118337 
118338  if( p->pPrior==0 ) return WRC_Continue;
118339  if( p->pOrderBy==0 ) return WRC_Continue;
118340  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
118341  if( pX==0 ) return WRC_Continue;
118342  a = p->pOrderBy->a;
118343  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
118344  if( a[i].pExpr->flags & EP_Collate ) break;
118345  }
118346  if( i<0 ) return WRC_Continue;
118347 
118348  /* If we reach this point, that means the transformation is required. */
118349 
118350  pParse = pWalker->pParse;
118351  db = pParse->db;
118352  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
118353  if( pNew==0 ) return WRC_Abort;
118354  memset(&dummy, 0, sizeof(dummy));
118355  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
118356  if( pNewSrc==0 ) return WRC_Abort;
118357  *pNew = *p;
118358  p->pSrc = pNewSrc;
118359  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
118360  p->op = TK_SELECT;
118361  p->pWhere = 0;
118362  pNew->pGroupBy = 0;
118363  pNew->pHaving = 0;
118364  pNew->pOrderBy = 0;
118365  p->pPrior = 0;
118366  p->pNext = 0;
118367  p->pWith = 0;
118368  p->selFlags &= ~SF_Compound;
118369  assert( (p->selFlags & SF_Converted)==0 );
118370  p->selFlags |= SF_Converted;
118371  assert( pNew->pPrior!=0 );
118372  pNew->pPrior->pNext = pNew;
118373  pNew->pLimit = 0;
118374  pNew->pOffset = 0;
118375  return WRC_Continue;
118376 }
118377 
118378 /*
118379 ** Check to see if the FROM clause term pFrom has table-valued function
118380 ** arguments. If it does, leave an error message in pParse and return
118381 ** non-zero, since pFrom is not allowed to be a table-valued function.
118382 */
118383 static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
118384  if( pFrom->fg.isTabFunc ){
118385  sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
118386  return 1;
118387  }
118388  return 0;
118389 }
118390 
118391 #ifndef SQLITE_OMIT_CTE
118392 /*
118393 ** Argument pWith (which may be NULL) points to a linked list of nested
118394 ** WITH contexts, from inner to outermost. If the table identified by
118395 ** FROM clause element pItem is really a common-table-expression (CTE)
118396 ** then return a pointer to the CTE definition for that table. Otherwise
118397 ** return NULL.
118398 **
118399 ** If a non-NULL value is returned, set *ppContext to point to the With
118400 ** object that the returned CTE belongs to.
118401 */
118402 static struct Cte *searchWith(
118403  With *pWith, /* Current innermost WITH clause */
118404  struct SrcList_item *pItem, /* FROM clause element to resolve */
118405  With **ppContext /* OUT: WITH clause return value belongs to */
118406 ){
118407  const char *zName;
118408  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
118409  With *p;
118410  for(p=pWith; p; p=p->pOuter){
118411  int i;
118412  for(i=0; i<p->nCte; i++){
118413  if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
118414  *ppContext = p;
118415  return &p->a[i];
118416  }
118417  }
118418  }
118419  }
118420  return 0;
118421 }
118422 
118423 /* The code generator maintains a stack of active WITH clauses
118424 ** with the inner-most WITH clause being at the top of the stack.
118425 **
118426 ** This routine pushes the WITH clause passed as the second argument
118427 ** onto the top of the stack. If argument bFree is true, then this
118428 ** WITH clause will never be popped from the stack. In this case it
118429 ** should be freed along with the Parse object. In other cases, when
118430 ** bFree==0, the With object will be freed along with the SELECT
118431 ** statement with which it is associated.
118432 */
118433 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
118434  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
118435  if( pWith ){
118436  assert( pParse->pWith!=pWith );
118437  pWith->pOuter = pParse->pWith;
118438  pParse->pWith = pWith;
118439  if( bFree ) pParse->pWithToFree = pWith;
118440  }
118441 }
118442 
118443 /*
118444 ** This function checks if argument pFrom refers to a CTE declared by
118445 ** a WITH clause on the stack currently maintained by the parser. And,
118446 ** if currently processing a CTE expression, if it is a recursive
118447 ** reference to the current CTE.
118448 **
118449 ** If pFrom falls into either of the two categories above, pFrom->pTab
118450 ** and other fields are populated accordingly. The caller should check
118451 ** (pFrom->pTab!=0) to determine whether or not a successful match
118452 ** was found.
118453 **
118454 ** Whether or not a match is found, SQLITE_OK is returned if no error
118455 ** occurs. If an error does occur, an error message is stored in the
118456 ** parser and some error code other than SQLITE_OK returned.
118457 */
118458 static int withExpand(
118459  Walker *pWalker,
118460  struct SrcList_item *pFrom
118461 ){
118462  Parse *pParse = pWalker->pParse;
118463  sqlite3 *db = pParse->db;
118464  struct Cte *pCte; /* Matched CTE (or NULL if no match) */
118465  With *pWith; /* WITH clause that pCte belongs to */
118466 
118467  assert( pFrom->pTab==0 );
118468 
118469  pCte = searchWith(pParse->pWith, pFrom, &pWith);
118470  if( pCte ){
118471  Table *pTab;
118472  ExprList *pEList;
118473  Select *pSel;
118474  Select *pLeft; /* Left-most SELECT statement */
118475  int bMayRecursive; /* True if compound joined by UNION [ALL] */
118476  With *pSavedWith; /* Initial value of pParse->pWith */
118477 
118478  /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
118479  ** recursive reference to CTE pCte. Leave an error in pParse and return
118480  ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
118481  ** In this case, proceed. */
118482  if( pCte->zCteErr ){
118483  sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
118484  return SQLITE_ERROR;
118485  }
118486  if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
118487 
118488  assert( pFrom->pTab==0 );
118489  pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
118490  if( pTab==0 ) return WRC_Abort;
118491  pTab->nRef = 1;
118492  pTab->zName = sqlite3DbStrDup(db, pCte->zName);
118493  pTab->iPKey = -1;
118494  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
118496  pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
118497  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
118498  assert( pFrom->pSelect );
118499 
118500  /* Check if this is a recursive CTE. */
118501  pSel = pFrom->pSelect;
118502  bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
118503  if( bMayRecursive ){
118504  int i;
118505  SrcList *pSrc = pFrom->pSelect->pSrc;
118506  for(i=0; i<pSrc->nSrc; i++){
118507  struct SrcList_item *pItem = &pSrc->a[i];
118508  if( pItem->zDatabase==0
118509  && pItem->zName!=0
118510  && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
118511  ){
118512  pItem->pTab = pTab;
118513  pItem->fg.isRecursive = 1;
118514  pTab->nRef++;
118515  pSel->selFlags |= SF_Recursive;
118516  }
118517  }
118518  }
118519 
118520  /* Only one recursive reference is permitted. */
118521  if( pTab->nRef>2 ){
118522  sqlite3ErrorMsg(
118523  pParse, "multiple references to recursive table: %s", pCte->zName
118524  );
118525  return SQLITE_ERROR;
118526  }
118527  assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
118528 
118529  pCte->zCteErr = "circular reference: %s";
118530  pSavedWith = pParse->pWith;
118531  pParse->pWith = pWith;
118532  sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
118533  pParse->pWith = pWith;
118534 
118535  for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
118536  pEList = pLeft->pEList;
118537  if( pCte->pCols ){
118538  if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
118539  sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
118540  pCte->zName, pEList->nExpr, pCte->pCols->nExpr
118541  );
118542  pParse->pWith = pSavedWith;
118543  return SQLITE_ERROR;
118544  }
118545  pEList = pCte->pCols;
118546  }
118547 
118548  sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
118549  if( bMayRecursive ){
118550  if( pSel->selFlags & SF_Recursive ){
118551  pCte->zCteErr = "multiple recursive references: %s";
118552  }else{
118553  pCte->zCteErr = "recursive reference in a subquery: %s";
118554  }
118555  sqlite3WalkSelect(pWalker, pSel);
118556  }
118557  pCte->zCteErr = 0;
118558  pParse->pWith = pSavedWith;
118559  }
118560 
118561  return SQLITE_OK;
118562 }
118563 #endif
118564 
118565 #ifndef SQLITE_OMIT_CTE
118566 /*
118567 ** If the SELECT passed as the second argument has an associated WITH
118568 ** clause, pop it from the stack stored as part of the Parse object.
118569 **
118570 ** This function is used as the xSelectCallback2() callback by
118571 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
118572 ** names and other FROM clause elements.
118573 */
118574 static void selectPopWith(Walker *pWalker, Select *p){
118575  Parse *pParse = pWalker->pParse;
118576  With *pWith = findRightmost(p)->pWith;
118577  if( pWith!=0 ){
118578  assert( pParse->pWith==pWith );
118579  pParse->pWith = pWith->pOuter;
118580  }
118581 }
118582 #else
118583 #define selectPopWith 0
118584 #endif
118585 
118586 /*
118587 ** This routine is a Walker callback for "expanding" a SELECT statement.
118588 ** "Expanding" means to do the following:
118589 **
118590 ** (1) Make sure VDBE cursor numbers have been assigned to every
118591 ** element of the FROM clause.
118592 **
118593 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
118594 ** defines FROM clause. When views appear in the FROM clause,
118595 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
118596 ** that implements the view. A copy is made of the view's SELECT
118597 ** statement so that we can freely modify or delete that statement
118598 ** without worrying about messing up the persistent representation
118599 ** of the view.
118600 **
118601 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
118602 ** on joins and the ON and USING clause of joins.
118603 **
118604 ** (4) Scan the list of columns in the result set (pEList) looking
118605 ** for instances of the "*" operator or the TABLE.* operator.
118606 ** If found, expand each "*" to be every column in every table
118607 ** and TABLE.* to be every column in TABLE.
118608 **
118609 */
118610 static int selectExpander(Walker *pWalker, Select *p){
118611  Parse *pParse = pWalker->pParse;
118612  int i, j, k;
118613  SrcList *pTabList;
118614  ExprList *pEList;
118615  struct SrcList_item *pFrom;
118616  sqlite3 *db = pParse->db;
118617  Expr *pE, *pRight, *pExpr;
118618  u16 selFlags = p->selFlags;
118619 
118620  p->selFlags |= SF_Expanded;
118621  if( db->mallocFailed ){
118622  return WRC_Abort;
118623  }
118624  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
118625  return WRC_Prune;
118626  }
118627  pTabList = p->pSrc;
118628  pEList = p->pEList;
118629  if( pWalker->xSelectCallback2==selectPopWith ){
118630  sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
118631  }
118632 
118633  /* Make sure cursor numbers have been assigned to all entries in
118634  ** the FROM clause of the SELECT statement.
118635  */
118636  sqlite3SrcListAssignCursors(pParse, pTabList);
118637 
118638  /* Look up every table named in the FROM clause of the select. If
118639  ** an entry of the FROM clause is a subquery instead of a table or view,
118640  ** then create a transient table structure to describe the subquery.
118641  */
118642  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118643  Table *pTab;
118644  assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
118645  if( pFrom->fg.isRecursive ) continue;
118646  assert( pFrom->pTab==0 );
118647 #ifndef SQLITE_OMIT_CTE
118648  if( withExpand(pWalker, pFrom) ) return WRC_Abort;
118649  if( pFrom->pTab ) {} else
118650 #endif
118651  if( pFrom->zName==0 ){
118652 #ifndef SQLITE_OMIT_SUBQUERY
118653  Select *pSel = pFrom->pSelect;
118654  /* A sub-query in the FROM clause of a SELECT */
118655  assert( pSel!=0 );
118656  assert( pFrom->pTab==0 );
118657  if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
118658  pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
118659  if( pTab==0 ) return WRC_Abort;
118660  pTab->nRef = 1;
118661  pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
118662  while( pSel->pPrior ){ pSel = pSel->pPrior; }
118663  sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
118664  pTab->iPKey = -1;
118665  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
118666  pTab->tabFlags |= TF_Ephemeral;
118667 #endif
118668  }else{
118669  /* An ordinary table or view name in the FROM clause */
118670  assert( pFrom->pTab==0 );
118671  pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
118672  if( pTab==0 ) return WRC_Abort;
118673  if( pTab->nRef==0xffff ){
118674  sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
118675  pTab->zName);
118676  pFrom->pTab = 0;
118677  return WRC_Abort;
118678  }
118679  pTab->nRef++;
118680  if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
118681  return WRC_Abort;
118682  }
118683 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
118684  if( IsVirtual(pTab) || pTab->pSelect ){
118685  i16 nCol;
118686  if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
118687  assert( pFrom->pSelect==0 );
118688  pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
118689  sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
118690  nCol = pTab->nCol;
118691  pTab->nCol = -1;
118692  sqlite3WalkSelect(pWalker, pFrom->pSelect);
118693  pTab->nCol = nCol;
118694  }
118695 #endif
118696  }
118697 
118698  /* Locate the index named by the INDEXED BY clause, if any. */
118699  if( sqlite3IndexedByLookup(pParse, pFrom) ){
118700  return WRC_Abort;
118701  }
118702  }
118703 
118704  /* Process NATURAL keywords, and ON and USING clauses of joins.
118705  */
118706  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
118707  return WRC_Abort;
118708  }
118709 
118710  /* For every "*" that occurs in the column list, insert the names of
118711  ** all columns in all tables. And for every TABLE.* insert the names
118712  ** of all columns in TABLE. The parser inserted a special expression
118713  ** with the TK_ASTERISK operator for each "*" that it found in the column
118714  ** list. The following code just has to locate the TK_ASTERISK
118715  ** expressions and expand each one to the list of all columns in
118716  ** all tables.
118717  **
118718  ** The first loop just checks to see if there are any "*" operators
118719  ** that need expanding.
118720  */
118721  for(k=0; k<pEList->nExpr; k++){
118722  pE = pEList->a[k].pExpr;
118723  if( pE->op==TK_ASTERISK ) break;
118724  assert( pE->op!=TK_DOT || pE->pRight!=0 );
118725  assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
118726  if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
118727  }
118728  if( k<pEList->nExpr ){
118729  /*
118730  ** If we get here it means the result set contains one or more "*"
118731  ** operators that need to be expanded. Loop through each expression
118732  ** in the result set and expand them one by one.
118733  */
118734  struct ExprList_item *a = pEList->a;
118735  ExprList *pNew = 0;
118736  int flags = pParse->db->flags;
118737  int longNames = (flags & SQLITE_FullColNames)!=0
118738  && (flags & SQLITE_ShortColNames)==0;
118739 
118740  for(k=0; k<pEList->nExpr; k++){
118741  pE = a[k].pExpr;
118742  pRight = pE->pRight;
118743  assert( pE->op!=TK_DOT || pRight!=0 );
118744  if( pE->op!=TK_ASTERISK
118745  && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
118746  ){
118747  /* This particular expression does not need to be expanded.
118748  */
118749  pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
118750  if( pNew ){
118751  pNew->a[pNew->nExpr-1].zName = a[k].zName;
118752  pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
118753  a[k].zName = 0;
118754  a[k].zSpan = 0;
118755  }
118756  a[k].pExpr = 0;
118757  }else{
118758  /* This expression is a "*" or a "TABLE.*" and needs to be
118759  ** expanded. */
118760  int tableSeen = 0; /* Set to 1 when TABLE matches */
118761  char *zTName = 0; /* text of name of TABLE */
118762  if( pE->op==TK_DOT ){
118763  assert( pE->pLeft!=0 );
118764  assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
118765  zTName = pE->pLeft->u.zToken;
118766  }
118767  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118768  Table *pTab = pFrom->pTab;
118769  Select *pSub = pFrom->pSelect;
118770  char *zTabName = pFrom->zAlias;
118771  const char *zSchemaName = 0;
118772  int iDb;
118773  if( zTabName==0 ){
118774  zTabName = pTab->zName;
118775  }
118776  if( db->mallocFailed ) break;
118777  if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
118778  pSub = 0;
118779  if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
118780  continue;
118781  }
118782  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
118783  zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
118784  }
118785  for(j=0; j<pTab->nCol; j++){
118786  char *zName = pTab->aCol[j].zName;
118787  char *zColname; /* The computed column name */
118788  char *zToFree; /* Malloced string that needs to be freed */
118789  Token sColname; /* Computed column name as a token */
118790 
118791  assert( zName );
118792  if( zTName && pSub
118793  && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
118794  ){
118795  continue;
118796  }
118797 
118798  /* If a column is marked as 'hidden', omit it from the expanded
118799  ** result-set list unless the SELECT has the SF_IncludeHidden
118800  ** bit set.
118801  */
118802  if( (p->selFlags & SF_IncludeHidden)==0
118803  && IsHiddenColumn(&pTab->aCol[j])
118804  ){
118805  continue;
118806  }
118807  tableSeen = 1;
118808 
118809  if( i>0 && zTName==0 ){
118810  if( (pFrom->fg.jointype & JT_NATURAL)!=0
118811  && tableAndColumnIndex(pTabList, i, zName, 0, 0)
118812  ){
118813  /* In a NATURAL join, omit the join columns from the
118814  ** table to the right of the join */
118815  continue;
118816  }
118817  if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
118818  /* In a join with a USING clause, omit columns in the
118819  ** using clause from the table on the right. */
118820  continue;
118821  }
118822  }
118823  pRight = sqlite3Expr(db, TK_ID, zName);
118824  zColname = zName;
118825  zToFree = 0;
118826  if( longNames || pTabList->nSrc>1 ){
118827  Expr *pLeft;
118828  pLeft = sqlite3Expr(db, TK_ID, zTabName);
118829  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
118830  if( zSchemaName ){
118831  pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
118832  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
118833  }
118834  if( longNames ){
118835  zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
118836  zToFree = zColname;
118837  }
118838  }else{
118839  pExpr = pRight;
118840  }
118841  pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
118842  sqlite3TokenInit(&sColname, zColname);
118843  sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
118844  if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
118845  struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
118846  if( pSub ){
118847  pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
118848  testcase( pX->zSpan==0 );
118849  }else{
118850  pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
118851  zSchemaName, zTabName, zColname);
118852  testcase( pX->zSpan==0 );
118853  }
118854  pX->bSpanIsTab = 1;
118855  }
118856  sqlite3DbFree(db, zToFree);
118857  }
118858  }
118859  if( !tableSeen ){
118860  if( zTName ){
118861  sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
118862  }else{
118863  sqlite3ErrorMsg(pParse, "no tables specified");
118864  }
118865  }
118866  }
118867  }
118868  sqlite3ExprListDelete(db, pEList);
118869  p->pEList = pNew;
118870  }
118871 #if SQLITE_MAX_COLUMN
118872  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
118873  sqlite3ErrorMsg(pParse, "too many columns in result set");
118874  return WRC_Abort;
118875  }
118876 #endif
118877  return WRC_Continue;
118878 }
118879 
118880 /*
118881 ** No-op routine for the parse-tree walker.
118882 **
118883 ** When this routine is the Walker.xExprCallback then expression trees
118884 ** are walked without any actions being taken at each node. Presumably,
118885 ** when this routine is used for Walker.xExprCallback then
118886 ** Walker.xSelectCallback is set to do something useful for every
118887 ** subquery in the parser tree.
118888 */
118890  UNUSED_PARAMETER2(NotUsed, NotUsed2);
118891  return WRC_Continue;
118892 }
118893 
118894 /*
118895 ** This routine "expands" a SELECT statement and all of its subqueries.
118896 ** For additional information on what it means to "expand" a SELECT
118897 ** statement, see the comment on the selectExpand worker callback above.
118898 **
118899 ** Expanding a SELECT statement is the first step in processing a
118900 ** SELECT statement. The SELECT statement must be expanded before
118901 ** name resolution is performed.
118902 **
118903 ** If anything goes wrong, an error message is written into pParse.
118904 ** The calling function can detect the problem by looking at pParse->nErr
118905 ** and/or pParse->db->mallocFailed.
118906 */
118907 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
118908  Walker w;
118909  memset(&w, 0, sizeof(w));
118911  w.pParse = pParse;
118912  if( pParse->hasCompound ){
118914  sqlite3WalkSelect(&w, pSelect);
118915  }
118917  if( (pSelect->selFlags & SF_MultiValue)==0 ){
118919  }
118920  sqlite3WalkSelect(&w, pSelect);
118921 }
118922 
118923 
118924 #ifndef SQLITE_OMIT_SUBQUERY
118925 /*
118926 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
118927 ** interface.
118928 **
118929 ** For each FROM-clause subquery, add Column.zType and Column.zColl
118930 ** information to the Table structure that represents the result set
118931 ** of that subquery.
118932 **
118933 ** The Table structure that represents the result set was constructed
118934 ** by selectExpander() but the type and collation information was omitted
118935 ** at that point because identifiers had not yet been resolved. This
118936 ** routine is called after identifier resolution.
118937 */
118938 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
118939  Parse *pParse;
118940  int i;
118941  SrcList *pTabList;
118942  struct SrcList_item *pFrom;
118943 
118944  assert( p->selFlags & SF_Resolved );
118945  assert( (p->selFlags & SF_HasTypeInfo)==0 );
118946  p->selFlags |= SF_HasTypeInfo;
118947  pParse = pWalker->pParse;
118948  pTabList = p->pSrc;
118949  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118950  Table *pTab = pFrom->pTab;
118951  assert( pTab!=0 );
118952  if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
118953  /* A sub-query in the FROM clause of a SELECT */
118954  Select *pSel = pFrom->pSelect;
118955  if( pSel ){
118956  while( pSel->pPrior ) pSel = pSel->pPrior;
118957  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
118958  }
118959  }
118960  }
118961 }
118962 #endif
118963 
118964 
118965 /*
118966 ** This routine adds datatype and collating sequence information to
118967 ** the Table structures of all FROM-clause subqueries in a
118968 ** SELECT statement.
118969 **
118970 ** Use this routine after name resolution.
118971 */
118972 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
118973 #ifndef SQLITE_OMIT_SUBQUERY
118974  Walker w;
118975  memset(&w, 0, sizeof(w));
118978  w.pParse = pParse;
118979  sqlite3WalkSelect(&w, pSelect);
118980 #endif
118981 }
118982 
118983 
118984 /*
118985 ** This routine sets up a SELECT statement for processing. The
118986 ** following is accomplished:
118987 **
118988 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
118989 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
118990 ** * ON and USING clauses are shifted into WHERE statements
118991 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
118992 ** * Identifiers in expression are matched to tables.
118993 **
118994 ** This routine acts recursively on all subqueries within the SELECT.
118995 */
118997  Parse *pParse, /* The parser context */
118998  Select *p, /* The SELECT statement being coded. */
118999  NameContext *pOuterNC /* Name context for container */
119000 ){
119001  sqlite3 *db;
119002  if( NEVER(p==0) ) return;
119003  db = pParse->db;
119004  if( db->mallocFailed ) return;
119005  if( p->selFlags & SF_HasTypeInfo ) return;
119006  sqlite3SelectExpand(pParse, p);
119007  if( pParse->nErr || db->mallocFailed ) return;
119008  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
119009  if( pParse->nErr || db->mallocFailed ) return;
119010  sqlite3SelectAddTypeInfo(pParse, p);
119011 }
119012 
119013 /*
119014 ** Reset the aggregate accumulator.
119015 **
119016 ** The aggregate accumulator is a set of memory cells that hold
119017 ** intermediate results while calculating an aggregate. This
119018 ** routine generates code that stores NULLs in all of those memory
119019 ** cells.
119020 */
119021 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
119022  Vdbe *v = pParse->pVdbe;
119023  int i;
119024  struct AggInfo_func *pFunc;
119025  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
119026  if( nReg==0 ) return;
119027 #ifdef SQLITE_DEBUG
119028  /* Verify that all AggInfo registers are within the range specified by
119029  ** AggInfo.mnReg..AggInfo.mxReg */
119030  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
119031  for(i=0; i<pAggInfo->nColumn; i++){
119032  assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
119033  && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
119034  }
119035  for(i=0; i<pAggInfo->nFunc; i++){
119036  assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
119037  && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
119038  }
119039 #endif
119040  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
119041  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
119042  if( pFunc->iDistinct>=0 ){
119043  Expr *pE = pFunc->pExpr;
119044  assert( !ExprHasProperty(pE, EP_xIsSelect) );
119045  if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
119046  sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
119047  "argument");
119048  pFunc->iDistinct = -1;
119049  }else{
119050  KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
119051  sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
119052  (char*)pKeyInfo, P4_KEYINFO);
119053  }
119054  }
119055  }
119056 }
119057 
119058 /*
119059 ** Invoke the OP_AggFinalize opcode for every aggregate function
119060 ** in the AggInfo structure.
119061 */
119062 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
119063  Vdbe *v = pParse->pVdbe;
119064  int i;
119065  struct AggInfo_func *pF;
119066  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
119067  ExprList *pList = pF->pExpr->x.pList;
119068  assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
119069  sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
119070  (void*)pF->pFunc, P4_FUNCDEF);
119071  }
119072 }
119073 
119074 /*
119075 ** Update the accumulator memory cells for an aggregate based on
119076 ** the current cursor position.
119077 */
119078 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
119079  Vdbe *v = pParse->pVdbe;
119080  int i;
119081  int regHit = 0;
119082  int addrHitTest = 0;
119083  struct AggInfo_func *pF;
119084  struct AggInfo_col *pC;
119085 
119086  pAggInfo->directMode = 1;
119087  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
119088  int nArg;
119089  int addrNext = 0;
119090  int regAgg;
119091  ExprList *pList = pF->pExpr->x.pList;
119092  assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
119093  if( pList ){
119094  nArg = pList->nExpr;
119095  regAgg = sqlite3GetTempRange(pParse, nArg);
119096  sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
119097  }else{
119098  nArg = 0;
119099  regAgg = 0;
119100  }
119101  if( pF->iDistinct>=0 ){
119102  addrNext = sqlite3VdbeMakeLabel(v);
119103  testcase( nArg==0 ); /* Error condition */
119104  testcase( nArg>1 ); /* Also an error */
119105  codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
119106  }
119107  if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
119108  CollSeq *pColl = 0;
119109  struct ExprList_item *pItem;
119110  int j;
119111  assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
119112  for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
119113  pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
119114  }
119115  if( !pColl ){
119116  pColl = pParse->db->pDfltColl;
119117  }
119118  if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
119119  sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
119120  }
119121  sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
119122  (void*)pF->pFunc, P4_FUNCDEF);
119123  sqlite3VdbeChangeP5(v, (u8)nArg);
119124  sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
119125  sqlite3ReleaseTempRange(pParse, regAgg, nArg);
119126  if( addrNext ){
119127  sqlite3VdbeResolveLabel(v, addrNext);
119128  sqlite3ExprCacheClear(pParse);
119129  }
119130  }
119131 
119132  /* Before populating the accumulator registers, clear the column cache.
119133  ** Otherwise, if any of the required column values are already present
119134  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
119135  ** to pC->iMem. But by the time the value is used, the original register
119136  ** may have been used, invalidating the underlying buffer holding the
119137  ** text or blob value. See ticket [883034dcb5].
119138  **
119139  ** Another solution would be to change the OP_SCopy used to copy cached
119140  ** values to an OP_Copy.
119141  */
119142  if( regHit ){
119143  addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
119144  }
119145  sqlite3ExprCacheClear(pParse);
119146  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
119147  sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
119148  }
119149  pAggInfo->directMode = 0;
119150  sqlite3ExprCacheClear(pParse);
119151  if( addrHitTest ){
119152  sqlite3VdbeJumpHere(v, addrHitTest);
119153  }
119154 }
119155 
119156 /*
119157 ** Add a single OP_Explain instruction to the VDBE to explain a simple
119158 ** count(*) query ("SELECT count(*) FROM pTab").
119159 */
119160 #ifndef SQLITE_OMIT_EXPLAIN
119162  Parse *pParse, /* Parse context */
119163  Table *pTab, /* Table being queried */
119164  Index *pIdx /* Index used to optimize scan, or NULL */
119165 ){
119166  if( pParse->explain==2 ){
119167  int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
119168  char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
119169  pTab->zName,
119170  bCover ? " USING COVERING INDEX " : "",
119171  bCover ? pIdx->zName : ""
119172  );
119174  pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
119175  );
119176  }
119177 }
119178 #else
119179 # define explainSimpleCount(a,b,c)
119180 #endif
119181 
119182 /*
119183 ** Generate code for the SELECT statement given in the p argument.
119184 **
119185 ** The results are returned according to the SelectDest structure.
119186 ** See comments in sqliteInt.h for further information.
119187 **
119188 ** This routine returns the number of errors. If any errors are
119189 ** encountered, then an appropriate error message is left in
119190 ** pParse->zErrMsg.
119191 **
119192 ** This routine does NOT free the Select structure passed in. The
119193 ** calling function needs to do that.
119194 */
119196  Parse *pParse, /* The parser context */
119197  Select *p, /* The SELECT statement being coded. */
119198  SelectDest *pDest /* What to do with the query results */
119199 ){
119200  int i, j; /* Loop counters */
119201  WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
119202  Vdbe *v; /* The virtual machine under construction */
119203  int isAgg; /* True for select lists like "count(*)" */
119204  ExprList *pEList = 0; /* List of columns to extract. */
119205  SrcList *pTabList; /* List of tables to select from */
119206  Expr *pWhere; /* The WHERE clause. May be NULL */
119207  ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
119208  Expr *pHaving; /* The HAVING clause. May be NULL */
119209  int rc = 1; /* Value to return from this function */
119210  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
119211  SortCtx sSort; /* Info on how to code the ORDER BY clause */
119212  AggInfo sAggInfo; /* Information used by aggregate queries */
119213  int iEnd; /* Address of the end of the query */
119214  sqlite3 *db; /* The database connection */
119215 
119216 #ifndef SQLITE_OMIT_EXPLAIN
119217  int iRestoreSelectId = pParse->iSelectId;
119218  pParse->iSelectId = pParse->iNextSelectId++;
119219 #endif
119220 
119221  db = pParse->db;
119222  if( p==0 || db->mallocFailed || pParse->nErr ){
119223  return 1;
119224  }
119225  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
119226  memset(&sAggInfo, 0, sizeof(sAggInfo));
119227 #if SELECTTRACE_ENABLED
119228  pParse->nSelectIndent++;
119229  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
119230  if( sqlite3SelectTrace & 0x100 ){
119231  sqlite3TreeViewSelect(0, p, 0);
119232  }
119233 #endif
119234 
119235  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
119236  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
119237  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
119238  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
119239  if( IgnorableOrderby(pDest) ){
119240  assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
119241  pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
119242  pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
119243  pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
119244  /* If ORDER BY makes no difference in the output then neither does
119245  ** DISTINCT so it can be removed too. */
119247  p->pOrderBy = 0;
119248  p->selFlags &= ~SF_Distinct;
119249  }
119250  sqlite3SelectPrep(pParse, p, 0);
119251  memset(&sSort, 0, sizeof(sSort));
119252  sSort.pOrderBy = p->pOrderBy;
119253  pTabList = p->pSrc;
119254  if( pParse->nErr || db->mallocFailed ){
119255  goto select_end;
119256  }
119257  assert( p->pEList!=0 );
119258  isAgg = (p->selFlags & SF_Aggregate)!=0;
119259 #if SELECTTRACE_ENABLED
119260  if( sqlite3SelectTrace & 0x100 ){
119261  SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
119262  sqlite3TreeViewSelect(0, p, 0);
119263  }
119264 #endif
119265 
119266  /* Try to flatten subqueries in the FROM clause up into the main query
119267  */
119268 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
119269  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
119270  struct SrcList_item *pItem = &pTabList->a[i];
119271  Select *pSub = pItem->pSelect;
119272  int isAggSub;
119273  Table *pTab = pItem->pTab;
119274  if( pSub==0 ) continue;
119275 
119276  /* Catch mismatch in the declared columns of a view and the number of
119277  ** columns in the SELECT on the RHS */
119278  if( pTab->nCol!=pSub->pEList->nExpr ){
119279  sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
119280  pTab->nCol, pTab->zName, pSub->pEList->nExpr);
119281  goto select_end;
119282  }
119283 
119284  isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
119285  if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
119286  /* This subquery can be absorbed into its parent. */
119287  if( isAggSub ){
119288  isAgg = 1;
119289  p->selFlags |= SF_Aggregate;
119290  }
119291  i = -1;
119292  }
119293  pTabList = p->pSrc;
119294  if( db->mallocFailed ) goto select_end;
119295  if( !IgnorableOrderby(pDest) ){
119296  sSort.pOrderBy = p->pOrderBy;
119297  }
119298  }
119299 #endif
119300 
119301  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
119302  ** does not already exist */
119303  v = sqlite3GetVdbe(pParse);
119304  if( v==0 ) goto select_end;
119305 
119306 #ifndef SQLITE_OMIT_COMPOUND_SELECT
119307  /* Handle compound SELECT statements using the separate multiSelect()
119308  ** procedure.
119309  */
119310  if( p->pPrior ){
119311  rc = multiSelect(pParse, p, pDest);
119312  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
119313 #if SELECTTRACE_ENABLED
119314  SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
119315  pParse->nSelectIndent--;
119316 #endif
119317  return rc;
119318  }
119319 #endif
119320 
119321  /* Generate code for all sub-queries in the FROM clause
119322  */
119323 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
119324  for(i=0; i<pTabList->nSrc; i++){
119325  struct SrcList_item *pItem = &pTabList->a[i];
119326  SelectDest dest;
119327  Select *pSub = pItem->pSelect;
119328  if( pSub==0 ) continue;
119329 
119330  /* Sometimes the code for a subquery will be generated more than
119331  ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
119332  ** for example. In that case, do not regenerate the code to manifest
119333  ** a view or the co-routine to implement a view. The first instance
119334  ** is sufficient, though the subroutine to manifest the view does need
119335  ** to be invoked again. */
119336  if( pItem->addrFillSub ){
119337  if( pItem->fg.viaCoroutine==0 ){
119338  sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
119339  }
119340  continue;
119341  }
119342 
119343  /* Increment Parse.nHeight by the height of the largest expression
119344  ** tree referred to by this, the parent select. The child select
119345  ** may contain expression trees of at most
119346  ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
119347  ** more conservative than necessary, but much easier than enforcing
119348  ** an exact limit.
119349  */
119350  pParse->nHeight += sqlite3SelectExprHeight(p);
119351 
119352  /* Make copies of constant WHERE-clause terms in the outer query down
119353  ** inside the subquery. This can help the subquery to run more efficiently.
119354  */
119355  if( (pItem->fg.jointype & JT_OUTER)==0
119356  && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
119357  ){
119358 #if SELECTTRACE_ENABLED
119359  if( sqlite3SelectTrace & 0x100 ){
119360  SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
119361  sqlite3TreeViewSelect(0, p, 0);
119362  }
119363 #endif
119364  }
119365 
119366  /* Generate code to implement the subquery
119367  **
119368  ** The subquery is implemented as a co-routine if all of these are true:
119369  ** (1) The subquery is guaranteed to be the outer loop (so that it
119370  ** does not need to be computed more than once)
119371  ** (2) The ALL keyword after SELECT is omitted. (Applications are
119372  ** allowed to say "SELECT ALL" instead of just "SELECT" to disable
119373  ** the use of co-routines.)
119374  ** (3) Co-routines are not disabled using sqlite3_test_control()
119375  ** with SQLITE_TESTCTRL_OPTIMIZATIONS.
119376  **
119377  ** TODO: Are there other reasons beside (1) to use a co-routine
119378  ** implementation?
119379  */
119380  if( i==0
119381  && (pTabList->nSrc==1
119382  || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
119383  && (p->selFlags & SF_All)==0 /* (2) */
119384  && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */
119385  ){
119386  /* Implement a co-routine that will return a single row of the result
119387  ** set on each invocation.
119388  */
119389  int addrTop = sqlite3VdbeCurrentAddr(v)+1;
119390  pItem->regReturn = ++pParse->nMem;
119391  sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
119392  VdbeComment((v, "%s", pItem->pTab->zName));
119393  pItem->addrFillSub = addrTop;
119394  sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
119395  explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
119396  sqlite3Select(pParse, pSub, &dest);
119397  pItem->pTab->nRowLogEst = pSub->nSelectRow;
119398  pItem->fg.viaCoroutine = 1;
119399  pItem->regResult = dest.iSdst;
119400  sqlite3VdbeEndCoroutine(v, pItem->regReturn);
119401  sqlite3VdbeJumpHere(v, addrTop-1);
119402  sqlite3ClearTempRegCache(pParse);
119403  }else{
119404  /* Generate a subroutine that will fill an ephemeral table with
119405  ** the content of this subquery. pItem->addrFillSub will point
119406  ** to the address of the generated subroutine. pItem->regReturn
119407  ** is a register allocated to hold the subroutine return address
119408  */
119409  int topAddr;
119410  int onceAddr = 0;
119411  int retAddr;
119412  assert( pItem->addrFillSub==0 );
119413  pItem->regReturn = ++pParse->nMem;
119414  topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
119415  pItem->addrFillSub = topAddr+1;
119416  if( pItem->fg.isCorrelated==0 ){
119417  /* If the subquery is not correlated and if we are not inside of
119418  ** a trigger, then we only need to compute the value of the subquery
119419  ** once. */
119420  onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
119421  VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
119422  }else{
119423  VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
119424  }
119425  sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
119426  explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
119427  sqlite3Select(pParse, pSub, &dest);
119428  pItem->pTab->nRowLogEst = pSub->nSelectRow;
119429  if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
119430  retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
119431  VdbeComment((v, "end %s", pItem->pTab->zName));
119432  sqlite3VdbeChangeP1(v, topAddr, retAddr);
119433  sqlite3ClearTempRegCache(pParse);
119434  }
119435  if( db->mallocFailed ) goto select_end;
119436  pParse->nHeight -= sqlite3SelectExprHeight(p);
119437  }
119438 #endif
119439 
119440  /* Various elements of the SELECT copied into local variables for
119441  ** convenience */
119442  pEList = p->pEList;
119443  pWhere = p->pWhere;
119444  pGroupBy = p->pGroupBy;
119445  pHaving = p->pHaving;
119446  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
119447 
119448 #if SELECTTRACE_ENABLED
119449  if( sqlite3SelectTrace & 0x400 ){
119450  SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
119451  sqlite3TreeViewSelect(0, p, 0);
119452  }
119453 #endif
119454 
119455  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
119456  ** if the select-list is the same as the ORDER BY list, then this query
119457  ** can be rewritten as a GROUP BY. In other words, this:
119458  **
119459  ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
119460  **
119461  ** is transformed to:
119462  **
119463  ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
119464  **
119465  ** The second form is preferred as a single index (or temp-table) may be
119466  ** used for both the ORDER BY and DISTINCT processing. As originally
119467  ** written the query must use a temp-table for at least one of the ORDER
119468  ** BY and DISTINCT, and an index or separate temp-table for the other.
119469  */
119471  && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
119472  ){
119473  p->selFlags &= ~SF_Distinct;
119474  pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
119475  /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
119476  ** the sDistinct.isTnct is still set. Hence, isTnct represents the
119477  ** original setting of the SF_Distinct flag, not the current setting */
119478  assert( sDistinct.isTnct );
119479 
119480 #if SELECTTRACE_ENABLED
119481  if( sqlite3SelectTrace & 0x400 ){
119482  SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
119483  sqlite3TreeViewSelect(0, p, 0);
119484  }
119485 #endif
119486  }
119487 
119488  /* If there is an ORDER BY clause, then create an ephemeral index to
119489  ** do the sorting. But this sorting ephemeral index might end up
119490  ** being unused if the data can be extracted in pre-sorted order.
119491  ** If that is the case, then the OP_OpenEphemeral instruction will be
119492  ** changed to an OP_Noop once we figure out that the sorting index is
119493  ** not needed. The sSort.addrSortIndex variable is used to facilitate
119494  ** that change.
119495  */
119496  if( sSort.pOrderBy ){
119497  KeyInfo *pKeyInfo;
119498  pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
119499  sSort.iECursor = pParse->nTab++;
119500  sSort.addrSortIndex =
119502  sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
119503  (char*)pKeyInfo, P4_KEYINFO
119504  );
119505  }else{
119506  sSort.addrSortIndex = -1;
119507  }
119508 
119509  /* If the output is destined for a temporary table, open that table.
119510  */
119511  if( pDest->eDest==SRT_EphemTab ){
119512  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
119513  }
119514 
119515  /* Set the limiter.
119516  */
119517  iEnd = sqlite3VdbeMakeLabel(v);
119518  p->nSelectRow = 320; /* 4 billion rows */
119519  computeLimitRegisters(pParse, p, iEnd);
119520  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
119522  sSort.sortFlags |= SORTFLAG_UseSorter;
119523  }
119524 
119525  /* Open an ephemeral index to use for the distinct set.
119526  */
119527  if( p->selFlags & SF_Distinct ){
119528  sDistinct.tabTnct = pParse->nTab++;
119530  sDistinct.tabTnct, 0, 0,
119531  (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
119532  P4_KEYINFO);
119534  sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
119535  }else{
119536  sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
119537  }
119538 
119539  if( !isAgg && pGroupBy==0 ){
119540  /* No aggregate functions and no GROUP BY clause */
119541  u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
119542  assert( WHERE_USE_LIMIT==SF_FixedLimit );
119543  wctrlFlags |= p->selFlags & SF_FixedLimit;
119544 
119545  /* Begin the database scan. */
119546  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
119547  p->pEList, wctrlFlags, p->nSelectRow);
119548  if( pWInfo==0 ) goto select_end;
119549  if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
119550  p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
119551  }
119552  if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
119553  sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
119554  }
119555  if( sSort.pOrderBy ){
119556  sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
119558  if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
119559  sSort.pOrderBy = 0;
119560  }
119561  }
119562 
119563  /* If sorting index that was created by a prior OP_OpenEphemeral
119564  ** instruction ended up not being needed, then change the OP_OpenEphemeral
119565  ** into an OP_Noop.
119566  */
119567  if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
119569  }
119570 
119571  /* Use the standard inner loop. */
119572  selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
119573  sqlite3WhereContinueLabel(pWInfo),
119574  sqlite3WhereBreakLabel(pWInfo));
119575 
119576  /* End the database scan loop.
119577  */
119578  sqlite3WhereEnd(pWInfo);
119579  }else{
119580  /* This case when there exist aggregate functions or a GROUP BY clause
119581  ** or both */
119582  NameContext sNC; /* Name context for processing aggregate information */
119583  int iAMem; /* First Mem address for storing current GROUP BY */
119584  int iBMem; /* First Mem address for previous GROUP BY */
119585  int iUseFlag; /* Mem address holding flag indicating that at least
119586  ** one row of the input to the aggregator has been
119587  ** processed */
119588  int iAbortFlag; /* Mem address which causes query abort if positive */
119589  int groupBySort; /* Rows come from source in GROUP BY order */
119590  int addrEnd; /* End of processing for this SELECT */
119591  int sortPTab = 0; /* Pseudotable used to decode sorting results */
119592  int sortOut = 0; /* Output register from the sorter */
119593  int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
119594 
119595  /* Remove any and all aliases between the result set and the
119596  ** GROUP BY clause.
119597  */
119598  if( pGroupBy ){
119599  int k; /* Loop counter */
119600  struct ExprList_item *pItem; /* For looping over expression in a list */
119601 
119602  for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
119603  pItem->u.x.iAlias = 0;
119604  }
119605  for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
119606  pItem->u.x.iAlias = 0;
119607  }
119608  assert( 66==sqlite3LogEst(100) );
119609  if( p->nSelectRow>66 ) p->nSelectRow = 66;
119610  }else{
119611  assert( 0==sqlite3LogEst(1) );
119612  p->nSelectRow = 0;
119613  }
119614 
119615  /* If there is both a GROUP BY and an ORDER BY clause and they are
119616  ** identical, then it may be possible to disable the ORDER BY clause
119617  ** on the grounds that the GROUP BY will cause elements to come out
119618  ** in the correct order. It also may not - the GROUP BY might use a
119619  ** database index that causes rows to be grouped together as required
119620  ** but not actually sorted. Either way, record the fact that the
119621  ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
119622  ** variable. */
119623  if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
119624  orderByGrp = 1;
119625  }
119626 
119627  /* Create a label to jump to when we want to abort the query */
119628  addrEnd = sqlite3VdbeMakeLabel(v);
119629 
119630  /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
119631  ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
119632  ** SELECT statement.
119633  */
119634  memset(&sNC, 0, sizeof(sNC));
119635  sNC.pParse = pParse;
119636  sNC.pSrcList = pTabList;
119637  sNC.pAggInfo = &sAggInfo;
119638  sAggInfo.mnReg = pParse->nMem+1;
119639  sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
119640  sAggInfo.pGroupBy = pGroupBy;
119641  sqlite3ExprAnalyzeAggList(&sNC, pEList);
119642  sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
119643  if( pHaving ){
119644  sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
119645  }
119646  sAggInfo.nAccumulator = sAggInfo.nColumn;
119647  for(i=0; i<sAggInfo.nFunc; i++){
119648  assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
119649  sNC.ncFlags |= NC_InAggFunc;
119650  sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
119651  sNC.ncFlags &= ~NC_InAggFunc;
119652  }
119653  sAggInfo.mxReg = pParse->nMem;
119654  if( db->mallocFailed ) goto select_end;
119655 
119656  /* Processing for aggregates with GROUP BY is very different and
119657  ** much more complex than aggregates without a GROUP BY.
119658  */
119659  if( pGroupBy ){
119660  KeyInfo *pKeyInfo; /* Keying information for the group by clause */
119661  int addr1; /* A-vs-B comparision jump */
119662  int addrOutputRow; /* Start of subroutine that outputs a result row */
119663  int regOutputRow; /* Return address register for output subroutine */
119664  int addrSetAbort; /* Set the abort flag and return */
119665  int addrTopOfLoop; /* Top of the input loop */
119666  int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
119667  int addrReset; /* Subroutine for resetting the accumulator */
119668  int regReset; /* Return address register for reset subroutine */
119669 
119670  /* If there is a GROUP BY clause we might need a sorting index to
119671  ** implement it. Allocate that sorting index now. If it turns out
119672  ** that we do not need it after all, the OP_SorterOpen instruction
119673  ** will be converted into a Noop.
119674  */
119675  sAggInfo.sortingIdx = pParse->nTab++;
119676  pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
119677  addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
119678  sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
119679  0, (char*)pKeyInfo, P4_KEYINFO);
119680 
119681  /* Initialize memory locations used by GROUP BY aggregate processing
119682  */
119683  iUseFlag = ++pParse->nMem;
119684  iAbortFlag = ++pParse->nMem;
119685  regOutputRow = ++pParse->nMem;
119686  addrOutputRow = sqlite3VdbeMakeLabel(v);
119687  regReset = ++pParse->nMem;
119688  addrReset = sqlite3VdbeMakeLabel(v);
119689  iAMem = pParse->nMem + 1;
119690  pParse->nMem += pGroupBy->nExpr;
119691  iBMem = pParse->nMem + 1;
119692  pParse->nMem += pGroupBy->nExpr;
119693  sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
119694  VdbeComment((v, "clear abort flag"));
119695  sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
119696  VdbeComment((v, "indicate accumulator empty"));
119697  sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
119698 
119699  /* Begin a loop that will extract all source rows in GROUP BY order.
119700  ** This might involve two separate loops with an OP_Sort in between, or
119701  ** it might be a single loop that uses an index to extract information
119702  ** in the right order to begin with.
119703  */
119704  sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
119705  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
119706  WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
119707  );
119708  if( pWInfo==0 ) goto select_end;
119709  if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
119710  /* The optimizer is able to deliver rows in group by order so
119711  ** we do not have to sort. The OP_OpenEphemeral table will be
119712  ** cancelled later because we still need to use the pKeyInfo
119713  */
119714  groupBySort = 0;
119715  }else{
119716  /* Rows are coming out in undetermined order. We have to push
119717  ** each row into a sorting index, terminate the first loop,
119718  ** then loop over the sorting index in order to get the output
119719  ** in sorted order
119720  */
119721  int regBase;
119722  int regRecord;
119723  int nCol;
119724  int nGroupBy;
119725 
119726  explainTempTable(pParse,
119727  (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
119728  "DISTINCT" : "GROUP BY");
119729 
119730  groupBySort = 1;
119731  nGroupBy = pGroupBy->nExpr;
119732  nCol = nGroupBy;
119733  j = nGroupBy;
119734  for(i=0; i<sAggInfo.nColumn; i++){
119735  if( sAggInfo.aCol[i].iSorterColumn>=j ){
119736  nCol++;
119737  j++;
119738  }
119739  }
119740  regBase = sqlite3GetTempRange(pParse, nCol);
119741  sqlite3ExprCacheClear(pParse);
119742  sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
119743  j = nGroupBy;
119744  for(i=0; i<sAggInfo.nColumn; i++){
119745  struct AggInfo_col *pCol = &sAggInfo.aCol[i];
119746  if( pCol->iSorterColumn>=j ){
119747  int r1 = j + regBase;
119749  pCol->pTab, pCol->iColumn, pCol->iTable, r1);
119750  j++;
119751  }
119752  }
119753  regRecord = sqlite3GetTempReg(pParse);
119754  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
119755  sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
119756  sqlite3ReleaseTempReg(pParse, regRecord);
119757  sqlite3ReleaseTempRange(pParse, regBase, nCol);
119758  sqlite3WhereEnd(pWInfo);
119759  sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
119760  sortOut = sqlite3GetTempReg(pParse);
119761  sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
119762  sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
119763  VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
119764  sAggInfo.useSortingIdx = 1;
119765  sqlite3ExprCacheClear(pParse);
119766 
119767  }
119768 
119769  /* If the index or temporary table used by the GROUP BY sort
119770  ** will naturally deliver rows in the order required by the ORDER BY
119771  ** clause, cancel the ephemeral table open coded earlier.
119772  **
119773  ** This is an optimization - the correct answer should result regardless.
119774  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
119775  ** disable this optimization for testing purposes. */
119776  if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
119777  && (groupBySort || sqlite3WhereIsSorted(pWInfo))
119778  ){
119779  sSort.pOrderBy = 0;
119781  }
119782 
119783  /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
119784  ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
119785  ** Then compare the current GROUP BY terms against the GROUP BY terms
119786  ** from the previous row currently stored in a0, a1, a2...
119787  */
119788  addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
119789  sqlite3ExprCacheClear(pParse);
119790  if( groupBySort ){
119792  sortOut, sortPTab);
119793  }
119794  for(j=0; j<pGroupBy->nExpr; j++){
119795  if( groupBySort ){
119796  sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
119797  }else{
119798  sAggInfo.directMode = 1;
119799  sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
119800  }
119801  }
119802  sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
119803  (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
119804  addr1 = sqlite3VdbeCurrentAddr(v);
119805  sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
119806 
119807  /* Generate code that runs whenever the GROUP BY changes.
119808  ** Changes in the GROUP BY are detected by the previous code
119809  ** block. If there were no changes, this block is skipped.
119810  **
119811  ** This code copies current group by terms in b0,b1,b2,...
119812  ** over to a0,a1,a2. It then calls the output subroutine
119813  ** and resets the aggregate accumulator registers in preparation
119814  ** for the next GROUP BY batch.
119815  */
119816  sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
119817  sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
119818  VdbeComment((v, "output one row"));
119819  sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
119820  VdbeComment((v, "check abort flag"));
119821  sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
119822  VdbeComment((v, "reset accumulator"));
119823 
119824  /* Update the aggregate accumulators based on the content of
119825  ** the current row
119826  */
119827  sqlite3VdbeJumpHere(v, addr1);
119828  updateAccumulator(pParse, &sAggInfo);
119829  sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
119830  VdbeComment((v, "indicate data in accumulator"));
119831 
119832  /* End of the loop
119833  */
119834  if( groupBySort ){
119835  sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
119836  VdbeCoverage(v);
119837  }else{
119838  sqlite3WhereEnd(pWInfo);
119839  sqlite3VdbeChangeToNoop(v, addrSortingIdx);
119840  }
119841 
119842  /* Output the final row of result
119843  */
119844  sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
119845  VdbeComment((v, "output final row"));
119846 
119847  /* Jump over the subroutines
119848  */
119849  sqlite3VdbeGoto(v, addrEnd);
119850 
119851  /* Generate a subroutine that outputs a single row of the result
119852  ** set. This subroutine first looks at the iUseFlag. If iUseFlag
119853  ** is less than or equal to zero, the subroutine is a no-op. If
119854  ** the processing calls for the query to abort, this subroutine
119855  ** increments the iAbortFlag memory location before returning in
119856  ** order to signal the caller to abort.
119857  */
119858  addrSetAbort = sqlite3VdbeCurrentAddr(v);
119859  sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
119860  VdbeComment((v, "set abort flag"));
119861  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119862  sqlite3VdbeResolveLabel(v, addrOutputRow);
119863  addrOutputRow = sqlite3VdbeCurrentAddr(v);
119864  sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
119865  VdbeCoverage(v);
119866  VdbeComment((v, "Groupby result generator entry point"));
119867  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119868  finalizeAggFunctions(pParse, &sAggInfo);
119869  sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
119870  selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
119871  &sDistinct, pDest,
119872  addrOutputRow+1, addrSetAbort);
119873  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119874  VdbeComment((v, "end groupby result generator"));
119875 
119876  /* Generate a subroutine that will reset the group-by accumulator
119877  */
119878  sqlite3VdbeResolveLabel(v, addrReset);
119879  resetAccumulator(pParse, &sAggInfo);
119880  sqlite3VdbeAddOp1(v, OP_Return, regReset);
119881 
119882  } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
119883  else {
119884  ExprList *pDel = 0;
119885 #ifndef SQLITE_OMIT_BTREECOUNT
119886  Table *pTab;
119887  if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
119888  /* If isSimpleCount() returns a pointer to a Table structure, then
119889  ** the SQL statement is of the form:
119890  **
119891  ** SELECT count(*) FROM <tbl>
119892  **
119893  ** where the Table structure returned represents table <tbl>.
119894  **
119895  ** This statement is so common that it is optimized specially. The
119896  ** OP_Count instruction is executed either on the intkey table that
119897  ** contains the data for table <tbl> or on one of its indexes. It
119898  ** is better to execute the op on an index, as indexes are almost
119899  ** always spread across less pages than their corresponding tables.
119900  */
119901  const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119902  const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
119903  Index *pIdx; /* Iterator variable */
119904  KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
119905  Index *pBest = 0; /* Best index found so far */
119906  int iRoot = pTab->tnum; /* Root page of scanned b-tree */
119907 
119908  sqlite3CodeVerifySchema(pParse, iDb);
119909  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
119910 
119911  /* Search for the index that has the lowest scan cost.
119912  **
119913  ** (2011-04-15) Do not do a full scan of an unordered index.
119914  **
119915  ** (2013-10-03) Do not count the entries in a partial index.
119916  **
119917  ** In practice the KeyInfo structure will not be used. It is only
119918  ** passed to keep OP_OpenRead happy.
119919  */
119920  if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
119921  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119922  if( pIdx->bUnordered==0
119923  && pIdx->szIdxRow<pTab->szTabRow
119924  && pIdx->pPartIdxWhere==0
119925  && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
119926  ){
119927  pBest = pIdx;
119928  }
119929  }
119930  if( pBest ){
119931  iRoot = pBest->tnum;
119932  pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
119933  }
119934 
119935  /* Open a read-only cursor, execute the OP_Count, close the cursor. */
119936  sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
119937  if( pKeyInfo ){
119938  sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
119939  }
119940  sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
119941  sqlite3VdbeAddOp1(v, OP_Close, iCsr);
119942  explainSimpleCount(pParse, pTab, pBest);
119943  }else
119944 #endif /* SQLITE_OMIT_BTREECOUNT */
119945  {
119946  /* Check if the query is of one of the following forms:
119947  **
119948  ** SELECT min(x) FROM ...
119949  ** SELECT max(x) FROM ...
119950  **
119951  ** If it is, then ask the code in where.c to attempt to sort results
119952  ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
119953  ** If where.c is able to produce results sorted in this order, then
119954  ** add vdbe code to break out of the processing loop after the
119955  ** first iteration (since the first iteration of the loop is
119956  ** guaranteed to operate on the row with the minimum or maximum
119957  ** value of x, the only row required).
119958  **
119959  ** A special flag must be passed to sqlite3WhereBegin() to slightly
119960  ** modify behavior as follows:
119961  **
119962  ** + If the query is a "SELECT min(x)", then the loop coded by
119963  ** where.c should not iterate over any values with a NULL value
119964  ** for x.
119965  **
119966  ** + The optimizer code in where.c (the thing that decides which
119967  ** index or indices to use) should place a different priority on
119968  ** satisfying the 'ORDER BY' clause than it does in other cases.
119969  ** Refer to code and comments in where.c for details.
119970  */
119971  ExprList *pMinMax = 0;
119972  u8 flag = WHERE_ORDERBY_NORMAL;
119973 
119974  assert( p->pGroupBy==0 );
119975  assert( flag==0 );
119976  if( p->pHaving==0 ){
119977  flag = minMaxQuery(&sAggInfo, &pMinMax);
119978  }
119979  assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
119980 
119981  if( flag ){
119982  pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
119983  pDel = pMinMax;
119984  assert( db->mallocFailed || pMinMax!=0 );
119985  if( !db->mallocFailed ){
119986  pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
119987  pMinMax->a[0].pExpr->op = TK_COLUMN;
119988  }
119989  }
119990 
119991  /* This case runs if the aggregate has no GROUP BY clause. The
119992  ** processing is much simpler since there is only a single row
119993  ** of output.
119994  */
119995  resetAccumulator(pParse, &sAggInfo);
119996  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
119997  if( pWInfo==0 ){
119998  sqlite3ExprListDelete(db, pDel);
119999  goto select_end;
120000  }
120001  updateAccumulator(pParse, &sAggInfo);
120002  assert( pMinMax==0 || pMinMax->nExpr==1 );
120003  if( sqlite3WhereIsOrdered(pWInfo)>0 ){
120005  VdbeComment((v, "%s() by index",
120006  (flag==WHERE_ORDERBY_MIN?"min":"max")));
120007  }
120008  sqlite3WhereEnd(pWInfo);
120009  finalizeAggFunctions(pParse, &sAggInfo);
120010  }
120011 
120012  sSort.pOrderBy = 0;
120013  sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
120014  selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
120015  pDest, addrEnd, addrEnd);
120016  sqlite3ExprListDelete(db, pDel);
120017  }
120018  sqlite3VdbeResolveLabel(v, addrEnd);
120019 
120020  } /* endif aggregate query */
120021 
120022  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
120023  explainTempTable(pParse, "DISTINCT");
120024  }
120025 
120026  /* If there is an ORDER BY clause, then we need to sort the results
120027  ** and send them to the callback one by one.
120028  */
120029  if( sSort.pOrderBy ){
120030  explainTempTable(pParse,
120031  sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
120032  generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
120033  }
120034 
120035  /* Jump here to skip this query
120036  */
120037  sqlite3VdbeResolveLabel(v, iEnd);
120038 
120039  /* The SELECT has been coded. If there is an error in the Parse structure,
120040  ** set the return code to 1. Otherwise 0. */
120041  rc = (pParse->nErr>0);
120042 
120043  /* Control jumps to here if an error is encountered above, or upon
120044  ** successful coding of the SELECT.
120045  */
120046 select_end:
120047  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
120048 
120049  /* Identify column names if results of the SELECT are to be output.
120050  */
120051  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
120052  generateColumnNames(pParse, pTabList, pEList);
120053  }
120054 
120055  sqlite3DbFree(db, sAggInfo.aCol);
120056  sqlite3DbFree(db, sAggInfo.aFunc);
120057 #if SELECTTRACE_ENABLED
120058  SELECTTRACE(1,pParse,p,("end processing\n"));
120059  pParse->nSelectIndent--;
120060 #endif
120061  return rc;
120062 }
120063 
120064 /************** End of select.c **********************************************/
120065 /************** Begin file table.c *******************************************/
120066 /*
120067 ** 2001 September 15
120068 **
120069 ** The author disclaims copyright to this source code. In place of
120070 ** a legal notice, here is a blessing:
120071 **
120072 ** May you do good and not evil.
120073 ** May you find forgiveness for yourself and forgive others.
120074 ** May you share freely, never taking more than you give.
120075 **
120076 *************************************************************************
120077 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
120078 ** interface routines. These are just wrappers around the main
120079 ** interface routine of sqlite3_exec().
120080 **
120081 ** These routines are in a separate files so that they will not be linked
120082 ** if they are not used.
120083 */
120084 /* #include "sqliteInt.h" */
120085 /* #include <stdlib.h> */
120086 /* #include <string.h> */
120087 
120088 #ifndef SQLITE_OMIT_GET_TABLE
120089 
120090 /*
120091 ** This structure is used to pass data from sqlite3_get_table() through
120092 ** to the callback function is uses to build the result.
120093 */
120094 typedef struct TabResult {
120095  char **azResult; /* Accumulated output */
120096  char *zErrMsg; /* Error message text, if an error occurs */
120097  u32 nAlloc; /* Slots allocated for azResult[] */
120098  u32 nRow; /* Number of rows in the result */
120099  u32 nColumn; /* Number of columns in the result */
120100  u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
120101  int rc; /* Return code from sqlite3_exec() */
120102 } TabResult;
120103 
120104 /*
120105 ** This routine is called once for each row in the result table. Its job
120106 ** is to fill in the TabResult structure appropriately, allocating new
120107 ** memory as necessary.
120108 */
120109 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
120110  TabResult *p = (TabResult*)pArg; /* Result accumulator */
120111  int need; /* Slots needed in p->azResult[] */
120112  int i; /* Loop counter */
120113  char *z; /* A single column of result */
120114 
120115  /* Make sure there is enough space in p->azResult to hold everything
120116  ** we need to remember from this invocation of the callback.
120117  */
120118  if( p->nRow==0 && argv!=0 ){
120119  need = nCol*2;
120120  }else{
120121  need = nCol;
120122  }
120123  if( p->nData + need > p->nAlloc ){
120124  char **azNew;
120125  p->nAlloc = p->nAlloc*2 + need;
120126  azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
120127  if( azNew==0 ) goto malloc_failed;
120128  p->azResult = azNew;
120129  }
120130 
120131  /* If this is the first row, then generate an extra row containing
120132  ** the names of all columns.
120133  */
120134  if( p->nRow==0 ){
120135  p->nColumn = nCol;
120136  for(i=0; i<nCol; i++){
120137  z = sqlite3_mprintf("%s", colv[i]);
120138  if( z==0 ) goto malloc_failed;
120139  p->azResult[p->nData++] = z;
120140  }
120141  }else if( (int)p->nColumn!=nCol ){
120142  sqlite3_free(p->zErrMsg);
120143  p->zErrMsg = sqlite3_mprintf(
120144  "sqlite3_get_table() called with two or more incompatible queries"
120145  );
120146  p->rc = SQLITE_ERROR;
120147  return 1;
120148  }
120149 
120150  /* Copy over the row data
120151  */
120152  if( argv!=0 ){
120153  for(i=0; i<nCol; i++){
120154  if( argv[i]==0 ){
120155  z = 0;
120156  }else{
120157  int n = sqlite3Strlen30(argv[i])+1;
120158  z = sqlite3_malloc64( n );
120159  if( z==0 ) goto malloc_failed;
120160  memcpy(z, argv[i], n);
120161  }
120162  p->azResult[p->nData++] = z;
120163  }
120164  p->nRow++;
120165  }
120166  return 0;
120167 
120168 malloc_failed:
120169  p->rc = SQLITE_NOMEM_BKPT;
120170  return 1;
120171 }
120172 
120173 /*
120174 ** Query the database. But instead of invoking a callback for each row,
120175 ** malloc() for space to hold the result and return the entire results
120176 ** at the conclusion of the call.
120177 **
120178 ** The result that is written to ***pazResult is held in memory obtained
120179 ** from malloc(). But the caller cannot free this memory directly.
120180 ** Instead, the entire table should be passed to sqlite3_free_table() when
120181 ** the calling procedure is finished using it.
120182 */
120184  sqlite3 *db, /* The database on which the SQL executes */
120185  const char *zSql, /* The SQL to be executed */
120186  char ***pazResult, /* Write the result table here */
120187  int *pnRow, /* Write the number of rows in the result here */
120188  int *pnColumn, /* Write the number of columns of result here */
120189  char **pzErrMsg /* Write error messages here */
120190 ){
120191  int rc;
120192  TabResult res;
120193 
120194 #ifdef SQLITE_ENABLE_API_ARMOR
120195  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
120196 #endif
120197  *pazResult = 0;
120198  if( pnColumn ) *pnColumn = 0;
120199  if( pnRow ) *pnRow = 0;
120200  if( pzErrMsg ) *pzErrMsg = 0;
120201  res.zErrMsg = 0;
120202  res.nRow = 0;
120203  res.nColumn = 0;
120204  res.nData = 1;
120205  res.nAlloc = 20;
120206  res.rc = SQLITE_OK;
120207  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
120208  if( res.azResult==0 ){
120209  db->errCode = SQLITE_NOMEM;
120210  return SQLITE_NOMEM_BKPT;
120211  }
120212  res.azResult[0] = 0;
120213  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
120214  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
120215  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
120216  if( (rc&0xff)==SQLITE_ABORT ){
120217  sqlite3_free_table(&res.azResult[1]);
120218  if( res.zErrMsg ){
120219  if( pzErrMsg ){
120220  sqlite3_free(*pzErrMsg);
120221  *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
120222  }
120223  sqlite3_free(res.zErrMsg);
120224  }
120225  db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
120226  return res.rc;
120227  }
120228  sqlite3_free(res.zErrMsg);
120229  if( rc!=SQLITE_OK ){
120230  sqlite3_free_table(&res.azResult[1]);
120231  return rc;
120232  }
120233  if( res.nAlloc>res.nData ){
120234  char **azNew;
120235  azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
120236  if( azNew==0 ){
120237  sqlite3_free_table(&res.azResult[1]);
120238  db->errCode = SQLITE_NOMEM;
120239  return SQLITE_NOMEM_BKPT;
120240  }
120241  res.azResult = azNew;
120242  }
120243  *pazResult = &res.azResult[1];
120244  if( pnColumn ) *pnColumn = res.nColumn;
120245  if( pnRow ) *pnRow = res.nRow;
120246  return rc;
120247 }
120248 
120249 /*
120250 ** This routine frees the space the sqlite3_get_table() malloced.
120251 */
120253  char **azResult /* Result returned from sqlite3_get_table() */
120254 ){
120255  if( azResult ){
120256  int i, n;
120257  azResult--;
120258  assert( azResult!=0 );
120259  n = SQLITE_PTR_TO_INT(azResult[0]);
120260  for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
120261  sqlite3_free(azResult);
120262  }
120263 }
120264 
120265 #endif /* SQLITE_OMIT_GET_TABLE */
120266 
120267 /************** End of table.c ***********************************************/
120268 /************** Begin file trigger.c *****************************************/
120269 /*
120270 **
120271 ** The author disclaims copyright to this source code. In place of
120272 ** a legal notice, here is a blessing:
120273 **
120274 ** May you do good and not evil.
120275 ** May you find forgiveness for yourself and forgive others.
120276 ** May you share freely, never taking more than you give.
120277 **
120278 *************************************************************************
120279 ** This file contains the implementation for TRIGGERs
120280 */
120281 /* #include "sqliteInt.h" */
120282 
120283 #ifndef SQLITE_OMIT_TRIGGER
120284 /*
120285 ** Delete a linked list of TriggerStep structures.
120286 */
120287 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
120288  while( pTriggerStep ){
120289  TriggerStep * pTmp = pTriggerStep;
120290  pTriggerStep = pTriggerStep->pNext;
120291 
120292  sqlite3ExprDelete(db, pTmp->pWhere);
120293  sqlite3ExprListDelete(db, pTmp->pExprList);
120294  sqlite3SelectDelete(db, pTmp->pSelect);
120295  sqlite3IdListDelete(db, pTmp->pIdList);
120296 
120297  sqlite3DbFree(db, pTmp);
120298  }
120299 }
120300 
120301 /*
120302 ** Given table pTab, return a list of all the triggers attached to
120303 ** the table. The list is connected by Trigger.pNext pointers.
120304 **
120305 ** All of the triggers on pTab that are in the same database as pTab
120306 ** are already attached to pTab->pTrigger. But there might be additional
120307 ** triggers on pTab in the TEMP schema. This routine prepends all
120308 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
120309 ** and returns the combined list.
120310 **
120311 ** To state it another way: This routine returns a list of all triggers
120312 ** that fire off of pTab. The list will include any TEMP triggers on
120313 ** pTab as well as the triggers lised in pTab->pTrigger.
120314 */
120316  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
120317  Trigger *pList = 0; /* List of triggers to return */
120318 
120319  if( pParse->disableTriggers ){
120320  return 0;
120321  }
120322 
120323  if( pTmpSchema!=pTab->pSchema ){
120324  HashElem *p;
120325  assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
120326  for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
120327  Trigger *pTrig = (Trigger *)sqliteHashData(p);
120328  if( pTrig->pTabSchema==pTab->pSchema
120329  && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
120330  ){
120331  pTrig->pNext = (pList ? pList : pTab->pTrigger);
120332  pList = pTrig;
120333  }
120334  }
120335  }
120336 
120337  return (pList ? pList : pTab->pTrigger);
120338 }
120339 
120340 /*
120341 ** This is called by the parser when it sees a CREATE TRIGGER statement
120342 ** up to the point of the BEGIN before the trigger actions. A Trigger
120343 ** structure is generated based on the information available and stored
120344 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
120345 ** sqlite3FinishTrigger() function is called to complete the trigger
120346 ** construction process.
120347 */
120349  Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
120350  Token *pName1, /* The name of the trigger */
120351  Token *pName2, /* The name of the trigger */
120352  int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
120353  int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
120354  IdList *pColumns, /* column list if this is an UPDATE OF trigger */
120355  SrcList *pTableName,/* The name of the table/view the trigger applies to */
120356  Expr *pWhen, /* WHEN clause */
120357  int isTemp, /* True if the TEMPORARY keyword is present */
120358  int noErr /* Suppress errors if the trigger already exists */
120359 ){
120360  Trigger *pTrigger = 0; /* The new trigger */
120361  Table *pTab; /* Table that the trigger fires off of */
120362  char *zName = 0; /* Name of the trigger */
120363  sqlite3 *db = pParse->db; /* The database connection */
120364  int iDb; /* The database to store the trigger in */
120365  Token *pName; /* The unqualified db name */
120366  DbFixer sFix; /* State vector for the DB fixer */
120367 
120368  assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
120369  assert( pName2!=0 );
120370  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
120371  assert( op>0 && op<0xff );
120372  if( isTemp ){
120373  /* If TEMP was specified, then the trigger name may not be qualified. */
120374  if( pName2->n>0 ){
120375  sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
120376  goto trigger_cleanup;
120377  }
120378  iDb = 1;
120379  pName = pName1;
120380  }else{
120381  /* Figure out the db that the trigger will be created in */
120382  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
120383  if( iDb<0 ){
120384  goto trigger_cleanup;
120385  }
120386  }
120387  if( !pTableName || db->mallocFailed ){
120388  goto trigger_cleanup;
120389  }
120390 
120391  /* A long-standing parser bug is that this syntax was allowed:
120392  **
120393  ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
120394  ** ^^^^^^^^
120395  **
120396  ** To maintain backwards compatibility, ignore the database
120397  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
120398  */
120399  if( db->init.busy && iDb!=1 ){
120400  sqlite3DbFree(db, pTableName->a[0].zDatabase);
120401  pTableName->a[0].zDatabase = 0;
120402  }
120403 
120404  /* If the trigger name was unqualified, and the table is a temp table,
120405  ** then set iDb to 1 to create the trigger in the temporary database.
120406  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
120407  ** exist, the error is caught by the block below.
120408  */
120409  pTab = sqlite3SrcListLookup(pParse, pTableName);
120410  if( db->init.busy==0 && pName2->n==0 && pTab
120411  && pTab->pSchema==db->aDb[1].pSchema ){
120412  iDb = 1;
120413  }
120414 
120415  /* Ensure the table name matches database name and that the table exists */
120416  if( db->mallocFailed ) goto trigger_cleanup;
120417  assert( pTableName->nSrc==1 );
120418  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
120419  if( sqlite3FixSrcList(&sFix, pTableName) ){
120420  goto trigger_cleanup;
120421  }
120422  pTab = sqlite3SrcListLookup(pParse, pTableName);
120423  if( !pTab ){
120424  /* The table does not exist. */
120425  if( db->init.iDb==1 ){
120426  /* Ticket #3810.
120427  ** Normally, whenever a table is dropped, all associated triggers are
120428  ** dropped too. But if a TEMP trigger is created on a non-TEMP table
120429  ** and the table is dropped by a different database connection, the
120430  ** trigger is not visible to the database connection that does the
120431  ** drop so the trigger cannot be dropped. This results in an
120432  ** "orphaned trigger" - a trigger whose associated table is missing.
120433  */
120434  db->init.orphanTrigger = 1;
120435  }
120436  goto trigger_cleanup;
120437  }
120438  if( IsVirtual(pTab) ){
120439  sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
120440  goto trigger_cleanup;
120441  }
120442 
120443  /* Check that the trigger name is not reserved and that no trigger of the
120444  ** specified name exists */
120445  zName = sqlite3NameFromToken(db, pName);
120446  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
120447  goto trigger_cleanup;
120448  }
120449  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120450  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
120451  if( !noErr ){
120452  sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
120453  }else{
120454  assert( !db->init.busy );
120455  sqlite3CodeVerifySchema(pParse, iDb);
120456  }
120457  goto trigger_cleanup;
120458  }
120459 
120460  /* Do not create a trigger on a system table */
120461  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
120462  sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
120463  goto trigger_cleanup;
120464  }
120465 
120466  /* INSTEAD of triggers are only for views and views only support INSTEAD
120467  ** of triggers.
120468  */
120469  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
120470  sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
120471  (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
120472  goto trigger_cleanup;
120473  }
120474  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
120475  sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
120476  " trigger on table: %S", pTableName, 0);
120477  goto trigger_cleanup;
120478  }
120479 
120480 #ifndef SQLITE_OMIT_AUTHORIZATION
120481  {
120482  int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
120483  int code = SQLITE_CREATE_TRIGGER;
120484  const char *zDb = db->aDb[iTabDb].zDbSName;
120485  const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
120486  if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
120487  if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
120488  goto trigger_cleanup;
120489  }
120490  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
120491  goto trigger_cleanup;
120492  }
120493  }
120494 #endif
120495 
120496  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
120497  ** cannot appear on views. So we might as well translate every
120498  ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
120499  ** elsewhere.
120500  */
120501  if (tr_tm == TK_INSTEAD){
120502  tr_tm = TK_BEFORE;
120503  }
120504 
120505  /* Build the Trigger object */
120506  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
120507  if( pTrigger==0 ) goto trigger_cleanup;
120508  pTrigger->zName = zName;
120509  zName = 0;
120510  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
120511  pTrigger->pSchema = db->aDb[iDb].pSchema;
120512  pTrigger->pTabSchema = pTab->pSchema;
120513  pTrigger->op = (u8)op;
120514  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
120515  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
120516  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
120517  assert( pParse->pNewTrigger==0 );
120518  pParse->pNewTrigger = pTrigger;
120519 
120520 trigger_cleanup:
120521  sqlite3DbFree(db, zName);
120522  sqlite3SrcListDelete(db, pTableName);
120523  sqlite3IdListDelete(db, pColumns);
120524  sqlite3ExprDelete(db, pWhen);
120525  if( !pParse->pNewTrigger ){
120526  sqlite3DeleteTrigger(db, pTrigger);
120527  }else{
120528  assert( pParse->pNewTrigger==pTrigger );
120529  }
120530 }
120531 
120532 /*
120533 ** This routine is called after all of the trigger actions have been parsed
120534 ** in order to complete the process of building the trigger.
120535 */
120537  Parse *pParse, /* Parser context */
120538  TriggerStep *pStepList, /* The triggered program */
120539  Token *pAll /* Token that describes the complete CREATE TRIGGER */
120540 ){
120541  Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
120542  char *zName; /* Name of trigger */
120543  sqlite3 *db = pParse->db; /* The database */
120544  DbFixer sFix; /* Fixer object */
120545  int iDb; /* Database containing the trigger */
120546  Token nameToken; /* Trigger name for error reporting */
120547 
120548  pParse->pNewTrigger = 0;
120549  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
120550  zName = pTrig->zName;
120551  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
120552  pTrig->step_list = pStepList;
120553  while( pStepList ){
120554  pStepList->pTrig = pTrig;
120555  pStepList = pStepList->pNext;
120556  }
120557  sqlite3TokenInit(&nameToken, pTrig->zName);
120558  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
120559  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
120560  || sqlite3FixExpr(&sFix, pTrig->pWhen)
120561  ){
120562  goto triggerfinish_cleanup;
120563  }
120564 
120565  /* if we are not initializing,
120566  ** build the sqlite_master entry
120567  */
120568  if( !db->init.busy ){
120569  Vdbe *v;
120570  char *z;
120571 
120572  /* Make an entry in the sqlite_master table */
120573  v = sqlite3GetVdbe(pParse);
120574  if( v==0 ) goto triggerfinish_cleanup;
120575  sqlite3BeginWriteOperation(pParse, 0, iDb);
120576  z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
120577  sqlite3NestedParse(pParse,
120578  "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
120579  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), zName,
120580  pTrig->table, z);
120581  sqlite3DbFree(db, z);
120582  sqlite3ChangeCookie(pParse, iDb);
120584  sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
120585  }
120586 
120587  if( db->init.busy ){
120588  Trigger *pLink = pTrig;
120589  Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
120590  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120591  pTrig = sqlite3HashInsert(pHash, zName, pTrig);
120592  if( pTrig ){
120593  sqlite3OomFault(db);
120594  }else if( pLink->pSchema==pLink->pTabSchema ){
120595  Table *pTab;
120596  pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
120597  assert( pTab!=0 );
120598  pLink->pNext = pTab->pTrigger;
120599  pTab->pTrigger = pLink;
120600  }
120601  }
120602 
120603 triggerfinish_cleanup:
120604  sqlite3DeleteTrigger(db, pTrig);
120605  assert( !pParse->pNewTrigger );
120606  sqlite3DeleteTriggerStep(db, pStepList);
120607 }
120608 
120609 /*
120610 ** Turn a SELECT statement (that the pSelect parameter points to) into
120611 ** a trigger step. Return a pointer to a TriggerStep structure.
120612 **
120613 ** The parser calls this routine when it finds a SELECT statement in
120614 ** body of a TRIGGER.
120615 */
120617  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
120618  if( pTriggerStep==0 ) {
120619  sqlite3SelectDelete(db, pSelect);
120620  return 0;
120621  }
120622  pTriggerStep->op = TK_SELECT;
120623  pTriggerStep->pSelect = pSelect;
120624  pTriggerStep->orconf = OE_Default;
120625  return pTriggerStep;
120626 }
120627 
120628 /*
120629 ** Allocate space to hold a new trigger step. The allocated space
120630 ** holds both the TriggerStep object and the TriggerStep.target.z string.
120631 **
120632 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
120633 */
120635  sqlite3 *db, /* Database connection */
120636  u8 op, /* Trigger opcode */
120637  Token *pName /* The target name */
120638 ){
120639  TriggerStep *pTriggerStep;
120640 
120641  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
120642  if( pTriggerStep ){
120643  char *z = (char*)&pTriggerStep[1];
120644  memcpy(z, pName->z, pName->n);
120645  sqlite3Dequote(z);
120646  pTriggerStep->zTarget = z;
120647  pTriggerStep->op = op;
120648  }
120649  return pTriggerStep;
120650 }
120651 
120652 /*
120653 ** Build a trigger step out of an INSERT statement. Return a pointer
120654 ** to the new trigger step.
120655 **
120656 ** The parser calls this routine when it sees an INSERT inside the
120657 ** body of a trigger.
120658 */
120660  sqlite3 *db, /* The database connection */
120661  Token *pTableName, /* Name of the table into which we insert */
120662  IdList *pColumn, /* List of columns in pTableName to insert into */
120663  Select *pSelect, /* A SELECT statement that supplies values */
120664  u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
120665 ){
120666  TriggerStep *pTriggerStep;
120667 
120668  assert(pSelect != 0 || db->mallocFailed);
120669 
120670  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
120671  if( pTriggerStep ){
120672  pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
120673  pTriggerStep->pIdList = pColumn;
120674  pTriggerStep->orconf = orconf;
120675  }else{
120676  sqlite3IdListDelete(db, pColumn);
120677  }
120678  sqlite3SelectDelete(db, pSelect);
120679 
120680  return pTriggerStep;
120681 }
120682 
120683 /*
120684 ** Construct a trigger step that implements an UPDATE statement and return
120685 ** a pointer to that trigger step. The parser calls this routine when it
120686 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
120687 */
120689  sqlite3 *db, /* The database connection */
120690  Token *pTableName, /* Name of the table to be updated */
120691  ExprList *pEList, /* The SET clause: list of column and new values */
120692  Expr *pWhere, /* The WHERE clause */
120693  u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
120694 ){
120695  TriggerStep *pTriggerStep;
120696 
120697  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
120698  if( pTriggerStep ){
120699  pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
120700  pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
120701  pTriggerStep->orconf = orconf;
120702  }
120703  sqlite3ExprListDelete(db, pEList);
120704  sqlite3ExprDelete(db, pWhere);
120705  return pTriggerStep;
120706 }
120707 
120708 /*
120709 ** Construct a trigger step that implements a DELETE statement and return
120710 ** a pointer to that trigger step. The parser calls this routine when it
120711 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
120712 */
120714  sqlite3 *db, /* Database connection */
120715  Token *pTableName, /* The table from which rows are deleted */
120716  Expr *pWhere /* The WHERE clause */
120717 ){
120718  TriggerStep *pTriggerStep;
120719 
120720  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
120721  if( pTriggerStep ){
120722  pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
120723  pTriggerStep->orconf = OE_Default;
120724  }
120725  sqlite3ExprDelete(db, pWhere);
120726  return pTriggerStep;
120727 }
120728 
120729 /*
120730 ** Recursively delete a Trigger structure
120731 */
120732 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
120733  if( pTrigger==0 ) return;
120734  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
120735  sqlite3DbFree(db, pTrigger->zName);
120736  sqlite3DbFree(db, pTrigger->table);
120737  sqlite3ExprDelete(db, pTrigger->pWhen);
120738  sqlite3IdListDelete(db, pTrigger->pColumns);
120739  sqlite3DbFree(db, pTrigger);
120740 }
120741 
120742 /*
120743 ** This function is called to drop a trigger from the database schema.
120744 **
120745 ** This may be called directly from the parser and therefore identifies
120746 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
120747 ** same job as this routine except it takes a pointer to the trigger
120748 ** instead of the trigger name.
120749 **/
120750 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
120751  Trigger *pTrigger = 0;
120752  int i;
120753  const char *zDb;
120754  const char *zName;
120755  sqlite3 *db = pParse->db;
120756 
120757  if( db->mallocFailed ) goto drop_trigger_cleanup;
120758  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
120759  goto drop_trigger_cleanup;
120760  }
120761 
120762  assert( pName->nSrc==1 );
120763  zDb = pName->a[0].zDatabase;
120764  zName = pName->a[0].zName;
120765  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
120766  for(i=OMIT_TEMPDB; i<db->nDb; i++){
120767  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
120768  if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
120769  assert( sqlite3SchemaMutexHeld(db, j, 0) );
120770  pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
120771  if( pTrigger ) break;
120772  }
120773  if( !pTrigger ){
120774  if( !noErr ){
120775  sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
120776  }else{
120777  sqlite3CodeVerifyNamedSchema(pParse, zDb);
120778  }
120779  pParse->checkSchema = 1;
120780  goto drop_trigger_cleanup;
120781  }
120782  sqlite3DropTriggerPtr(pParse, pTrigger);
120783 
120784 drop_trigger_cleanup:
120785  sqlite3SrcListDelete(db, pName);
120786 }
120787 
120788 /*
120789 ** Return a pointer to the Table structure for the table that a trigger
120790 ** is set on.
120791 */
120792 static Table *tableOfTrigger(Trigger *pTrigger){
120793  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
120794 }
120795 
120796 
120797 /*
120798 ** Drop a trigger given a pointer to that trigger.
120799 */
120801  Table *pTable;
120802  Vdbe *v;
120803  sqlite3 *db = pParse->db;
120804  int iDb;
120805 
120806  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
120807  assert( iDb>=0 && iDb<db->nDb );
120808  pTable = tableOfTrigger(pTrigger);
120809  assert( pTable );
120810  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
120811 #ifndef SQLITE_OMIT_AUTHORIZATION
120812  {
120813  int code = SQLITE_DROP_TRIGGER;
120814  const char *zDb = db->aDb[iDb].zDbSName;
120815  const char *zTab = SCHEMA_TABLE(iDb);
120816  if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
120817  if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
120818  sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
120819  return;
120820  }
120821  }
120822 #endif
120823 
120824  /* Generate code to destroy the database record of the trigger.
120825  */
120826  assert( pTable!=0 );
120827  if( (v = sqlite3GetVdbe(pParse))!=0 ){
120828  sqlite3NestedParse(pParse,
120829  "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
120830  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb), pTrigger->zName
120831  );
120832  sqlite3ChangeCookie(pParse, iDb);
120833  sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
120834  }
120835 }
120836 
120837 /*
120838 ** Remove a trigger from the hash tables of the sqlite* pointer.
120839 */
120840 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
120841  Trigger *pTrigger;
120842  Hash *pHash;
120843 
120844  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
120845  pHash = &(db->aDb[iDb].pSchema->trigHash);
120846  pTrigger = sqlite3HashInsert(pHash, zName, 0);
120847  if( ALWAYS(pTrigger) ){
120848  if( pTrigger->pSchema==pTrigger->pTabSchema ){
120849  Table *pTab = tableOfTrigger(pTrigger);
120850  Trigger **pp;
120851  for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
120852  *pp = (*pp)->pNext;
120853  }
120854  sqlite3DeleteTrigger(db, pTrigger);
120855  db->flags |= SQLITE_InternChanges;
120856  }
120857 }
120858 
120859 /*
120860 ** pEList is the SET clause of an UPDATE statement. Each entry
120861 ** in pEList is of the format <id>=<expr>. If any of the entries
120862 ** in pEList have an <id> which matches an identifier in pIdList,
120863 ** then return TRUE. If pIdList==NULL, then it is considered a
120864 ** wildcard that matches anything. Likewise if pEList==NULL then
120865 ** it matches anything so always return true. Return false only
120866 ** if there is no match.
120867 */
120868 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
120869  int e;
120870  if( pIdList==0 || NEVER(pEList==0) ) return 1;
120871  for(e=0; e<pEList->nExpr; e++){
120872  if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
120873  }
120874  return 0;
120875 }
120876 
120877 /*
120878 ** Return a list of all triggers on table pTab if there exists at least
120879 ** one trigger that must be fired when an operation of type 'op' is
120880 ** performed on the table, and, if that operation is an UPDATE, if at
120881 ** least one of the columns in pChanges is being modified.
120882 */
120884  Parse *pParse, /* Parse context */
120885  Table *pTab, /* The table the contains the triggers */
120886  int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
120887  ExprList *pChanges, /* Columns that change in an UPDATE statement */
120888  int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120889 ){
120890  int mask = 0;
120891  Trigger *pList = 0;
120892  Trigger *p;
120893 
120894  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
120895  pList = sqlite3TriggerList(pParse, pTab);
120896  }
120897  assert( pList==0 || IsVirtual(pTab)==0 );
120898  for(p=pList; p; p=p->pNext){
120899  if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
120900  mask |= p->tr_tm;
120901  }
120902  }
120903  if( pMask ){
120904  *pMask = mask;
120905  }
120906  return (mask ? pList : 0);
120907 }
120908 
120909 /*
120910 ** Convert the pStep->zTarget string into a SrcList and return a pointer
120911 ** to that SrcList.
120912 **
120913 ** This routine adds a specific database name, if needed, to the target when
120914 ** forming the SrcList. This prevents a trigger in one database from
120915 ** referring to a target in another database. An exception is when the
120916 ** trigger is in TEMP in which case it can refer to any other database it
120917 ** wants.
120918 */
120920  Parse *pParse, /* The parsing context */
120921  TriggerStep *pStep /* The trigger containing the target token */
120922 ){
120923  sqlite3 *db = pParse->db;
120924  int iDb; /* Index of the database to use */
120925  SrcList *pSrc; /* SrcList to be returned */
120926 
120927  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
120928  if( pSrc ){
120929  assert( pSrc->nSrc>0 );
120930  pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
120931  iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
120932  if( iDb==0 || iDb>=2 ){
120933  const char *zDb;
120934  assert( iDb<db->nDb );
120935  zDb = db->aDb[iDb].zDbSName;
120936  pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
120937  }
120938  }
120939  return pSrc;
120940 }
120941 
120942 /*
120943 ** Generate VDBE code for the statements inside the body of a single
120944 ** trigger.
120945 */
120947  Parse *pParse, /* The parser context */
120948  TriggerStep *pStepList, /* List of statements inside the trigger body */
120949  int orconf /* Conflict algorithm. (OE_Abort, etc) */
120950 ){
120951  TriggerStep *pStep;
120952  Vdbe *v = pParse->pVdbe;
120953  sqlite3 *db = pParse->db;
120954 
120955  assert( pParse->pTriggerTab && pParse->pToplevel );
120956  assert( pStepList );
120957  assert( v!=0 );
120958  for(pStep=pStepList; pStep; pStep=pStep->pNext){
120959  /* Figure out the ON CONFLICT policy that will be used for this step
120960  ** of the trigger program. If the statement that caused this trigger
120961  ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
120962  ** the ON CONFLICT policy that was specified as part of the trigger
120963  ** step statement. Example:
120964  **
120965  ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
120966  ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
120967  ** END;
120968  **
120969  ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
120970  ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
120971  */
120972  pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
120973  assert( pParse->okConstFactor==0 );
120974 
120975  switch( pStep->op ){
120976  case TK_UPDATE: {
120977  sqlite3Update(pParse,
120978  targetSrcList(pParse, pStep),
120979  sqlite3ExprListDup(db, pStep->pExprList, 0),
120980  sqlite3ExprDup(db, pStep->pWhere, 0),
120981  pParse->eOrconf
120982  );
120983  break;
120984  }
120985  case TK_INSERT: {
120986  sqlite3Insert(pParse,
120987  targetSrcList(pParse, pStep),
120988  sqlite3SelectDup(db, pStep->pSelect, 0),
120989  sqlite3IdListDup(db, pStep->pIdList),
120990  pParse->eOrconf
120991  );
120992  break;
120993  }
120994  case TK_DELETE: {
120995  sqlite3DeleteFrom(pParse,
120996  targetSrcList(pParse, pStep),
120997  sqlite3ExprDup(db, pStep->pWhere, 0)
120998  );
120999  break;
121000  }
121001  default: assert( pStep->op==TK_SELECT ); {
121002  SelectDest sDest;
121003  Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
121004  sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
121005  sqlite3Select(pParse, pSelect, &sDest);
121006  sqlite3SelectDelete(db, pSelect);
121007  break;
121008  }
121009  }
121010  if( pStep->op!=TK_SELECT ){
121012  }
121013  }
121014 
121015  return 0;
121016 }
121017 
121018 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
121019 /*
121020 ** This function is used to add VdbeComment() annotations to a VDBE
121021 ** program. It is not used in production code, only for debugging.
121022 */
121023 static const char *onErrorText(int onError){
121024  switch( onError ){
121025  case OE_Abort: return "abort";
121026  case OE_Rollback: return "rollback";
121027  case OE_Fail: return "fail";
121028  case OE_Replace: return "replace";
121029  case OE_Ignore: return "ignore";
121030  case OE_Default: return "default";
121031  }
121032  return "n/a";
121033 }
121034 #endif
121035 
121036 /*
121037 ** Parse context structure pFrom has just been used to create a sub-vdbe
121038 ** (trigger program). If an error has occurred, transfer error information
121039 ** from pFrom to pTo.
121040 */
121041 static void transferParseError(Parse *pTo, Parse *pFrom){
121042  assert( pFrom->zErrMsg==0 || pFrom->nErr );
121043  assert( pTo->zErrMsg==0 || pTo->nErr );
121044  if( pTo->nErr==0 ){
121045  pTo->zErrMsg = pFrom->zErrMsg;
121046  pTo->nErr = pFrom->nErr;
121047  pTo->rc = pFrom->rc;
121048  }else{
121049  sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
121050  }
121051 }
121052 
121053 /*
121054 ** Create and populate a new TriggerPrg object with a sub-program
121055 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
121056 */
121058  Parse *pParse, /* Current parse context */
121059  Trigger *pTrigger, /* Trigger to code */
121060  Table *pTab, /* The table pTrigger is attached to */
121061  int orconf /* ON CONFLICT policy to code trigger program with */
121062 ){
121063  Parse *pTop = sqlite3ParseToplevel(pParse);
121064  sqlite3 *db = pParse->db; /* Database handle */
121065  TriggerPrg *pPrg; /* Value to return */
121066  Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
121067  Vdbe *v; /* Temporary VM */
121068  NameContext sNC; /* Name context for sub-vdbe */
121069  SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
121070  Parse *pSubParse; /* Parse context for sub-vdbe */
121071  int iEndTrigger = 0; /* Label to jump to if WHEN is false */
121072 
121073  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
121074  assert( pTop->pVdbe );
121075 
121076  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
121077  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
121078  ** list of the top-level Parse object sooner rather than later. */
121079  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
121080  if( !pPrg ) return 0;
121081  pPrg->pNext = pTop->pTriggerPrg;
121082  pTop->pTriggerPrg = pPrg;
121083  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
121084  if( !pProgram ) return 0;
121085  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
121086  pPrg->pTrigger = pTrigger;
121087  pPrg->orconf = orconf;
121088  pPrg->aColmask[0] = 0xffffffff;
121089  pPrg->aColmask[1] = 0xffffffff;
121090 
121091  /* Allocate and populate a new Parse context to use for coding the
121092  ** trigger sub-program. */
121093  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
121094  if( !pSubParse ) return 0;
121095  memset(&sNC, 0, sizeof(sNC));
121096  sNC.pParse = pSubParse;
121097  pSubParse->db = db;
121098  pSubParse->pTriggerTab = pTab;
121099  pSubParse->pToplevel = pTop;
121100  pSubParse->zAuthContext = pTrigger->zName;
121101  pSubParse->eTriggerOp = pTrigger->op;
121102  pSubParse->nQueryLoop = pParse->nQueryLoop;
121103 
121104  v = sqlite3GetVdbe(pSubParse);
121105  if( v ){
121106  VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
121107  pTrigger->zName, onErrorText(orconf),
121108  (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
121109  (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
121110  (pTrigger->op==TK_INSERT ? "INSERT" : ""),
121111  (pTrigger->op==TK_DELETE ? "DELETE" : ""),
121112  pTab->zName
121113  ));
121114 #ifndef SQLITE_OMIT_TRACE
121115  sqlite3VdbeChangeP4(v, -1,
121116  sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
121117  );
121118 #endif
121119 
121120  /* If one was specified, code the WHEN clause. If it evaluates to false
121121  ** (or NULL) the sub-vdbe is immediately halted by jumping to the
121122  ** OP_Halt inserted at the end of the program. */
121123  if( pTrigger->pWhen ){
121124  pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
121125  if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
121126  && db->mallocFailed==0
121127  ){
121128  iEndTrigger = sqlite3VdbeMakeLabel(v);
121129  sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
121130  }
121131  sqlite3ExprDelete(db, pWhen);
121132  }
121133 
121134  /* Code the trigger program into the sub-vdbe. */
121135  codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
121136 
121137  /* Insert an OP_Halt at the end of the sub-program. */
121138  if( iEndTrigger ){
121139  sqlite3VdbeResolveLabel(v, iEndTrigger);
121140  }
121142  VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
121143 
121144  transferParseError(pParse, pSubParse);
121145  if( db->mallocFailed==0 ){
121146  pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
121147  }
121148  pProgram->nMem = pSubParse->nMem;
121149  pProgram->nCsr = pSubParse->nTab;
121150  pProgram->token = (void *)pTrigger;
121151  pPrg->aColmask[0] = pSubParse->oldmask;
121152  pPrg->aColmask[1] = pSubParse->newmask;
121153  sqlite3VdbeDelete(v);
121154  }
121155 
121156  assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
121157  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
121158  sqlite3ParserReset(pSubParse);
121159  sqlite3StackFree(db, pSubParse);
121160 
121161  return pPrg;
121162 }
121163 
121164 /*
121165 ** Return a pointer to a TriggerPrg object containing the sub-program for
121166 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
121167 ** TriggerPrg object exists, a new object is allocated and populated before
121168 ** being returned.
121169 */
121171  Parse *pParse, /* Current parse context */
121172  Trigger *pTrigger, /* Trigger to code */
121173  Table *pTab, /* The table trigger pTrigger is attached to */
121174  int orconf /* ON CONFLICT algorithm. */
121175 ){
121176  Parse *pRoot = sqlite3ParseToplevel(pParse);
121177  TriggerPrg *pPrg;
121178 
121179  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
121180 
121181  /* It may be that this trigger has already been coded (or is in the
121182  ** process of being coded). If this is the case, then an entry with
121183  ** a matching TriggerPrg.pTrigger field will be present somewhere
121184  ** in the Parse.pTriggerPrg list. Search for such an entry. */
121185  for(pPrg=pRoot->pTriggerPrg;
121186  pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
121187  pPrg=pPrg->pNext
121188  );
121189 
121190  /* If an existing TriggerPrg could not be located, create a new one. */
121191  if( !pPrg ){
121192  pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
121193  }
121194 
121195  return pPrg;
121196 }
121197 
121198 /*
121199 ** Generate code for the trigger program associated with trigger p on
121200 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
121201 ** function are the same as those described in the header function for
121202 ** sqlite3CodeRowTrigger()
121203 */
121205  Parse *pParse, /* Parse context */
121206  Trigger *p, /* Trigger to code */
121207  Table *pTab, /* The table to code triggers from */
121208  int reg, /* Reg array containing OLD.* and NEW.* values */
121209  int orconf, /* ON CONFLICT policy */
121210  int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
121211 ){
121212  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
121213  TriggerPrg *pPrg;
121214  pPrg = getRowTrigger(pParse, p, pTab, orconf);
121215  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
121216 
121217  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
121218  ** is a pointer to the sub-vdbe containing the trigger program. */
121219  if( pPrg ){
121220  int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
121221 
121222  sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
121223  (const char *)pPrg->pProgram, P4_SUBPROGRAM);
121224  VdbeComment(
121225  (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
121226 
121227  /* Set the P5 operand of the OP_Program instruction to non-zero if
121228  ** recursive invocation of this trigger program is disallowed. Recursive
121229  ** invocation is disallowed if (a) the sub-program is really a trigger,
121230  ** not a foreign key action, and (b) the flag to enable recursive triggers
121231  ** is clear. */
121232  sqlite3VdbeChangeP5(v, (u8)bRecursive);
121233  }
121234 }
121235 
121236 /*
121237 ** This is called to code the required FOR EACH ROW triggers for an operation
121238 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
121239 ** is given by the op parameter. The tr_tm parameter determines whether the
121240 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
121241 ** parameter pChanges is passed the list of columns being modified.
121242 **
121243 ** If there are no triggers that fire at the specified time for the specified
121244 ** operation on pTab, this function is a no-op.
121245 **
121246 ** The reg argument is the address of the first in an array of registers
121247 ** that contain the values substituted for the new.* and old.* references
121248 ** in the trigger program. If N is the number of columns in table pTab
121249 ** (a copy of pTab->nCol), then registers are populated as follows:
121250 **
121251 ** Register Contains
121252 ** ------------------------------------------------------
121253 ** reg+0 OLD.rowid
121254 ** reg+1 OLD.* value of left-most column of pTab
121255 ** ... ...
121256 ** reg+N OLD.* value of right-most column of pTab
121257 ** reg+N+1 NEW.rowid
121258 ** reg+N+2 OLD.* value of left-most column of pTab
121259 ** ... ...
121260 ** reg+N+N+1 NEW.* value of right-most column of pTab
121261 **
121262 ** For ON DELETE triggers, the registers containing the NEW.* values will
121263 ** never be accessed by the trigger program, so they are not allocated or
121264 ** populated by the caller (there is no data to populate them with anyway).
121265 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
121266 ** are never accessed, and so are not allocated by the caller. So, for an
121267 ** ON INSERT trigger, the value passed to this function as parameter reg
121268 ** is not a readable register, although registers (reg+N) through
121269 ** (reg+N+N+1) are.
121270 **
121271 ** Parameter orconf is the default conflict resolution algorithm for the
121272 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
121273 ** is the instruction that control should jump to if a trigger program
121274 ** raises an IGNORE exception.
121275 */
121277  Parse *pParse, /* Parse context */
121278  Trigger *pTrigger, /* List of triggers on table pTab */
121279  int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
121280  ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
121281  int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
121282  Table *pTab, /* The table to code triggers from */
121283  int reg, /* The first in an array of registers (see above) */
121284  int orconf, /* ON CONFLICT policy */
121285  int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
121286 ){
121287  Trigger *p; /* Used to iterate through pTrigger list */
121288 
121289  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
121290  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
121291  assert( (op==TK_UPDATE)==(pChanges!=0) );
121292 
121293  for(p=pTrigger; p; p=p->pNext){
121294 
121295  /* Sanity checking: The schema for the trigger and for the table are
121296  ** always defined. The trigger must be in the same schema as the table
121297  ** or else it must be a TEMP trigger. */
121298  assert( p->pSchema!=0 );
121299  assert( p->pTabSchema!=0 );
121300  assert( p->pSchema==p->pTabSchema
121301  || p->pSchema==pParse->db->aDb[1].pSchema );
121302 
121303  /* Determine whether we should code this trigger */
121304  if( p->op==op
121305  && p->tr_tm==tr_tm
121306  && checkColumnOverlap(p->pColumns, pChanges)
121307  ){
121308  sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
121309  }
121310  }
121311 }
121312 
121313 /*
121314 ** Triggers may access values stored in the old.* or new.* pseudo-table.
121315 ** This function returns a 32-bit bitmask indicating which columns of the
121316 ** old.* or new.* tables actually are used by triggers. This information
121317 ** may be used by the caller, for example, to avoid having to load the entire
121318 ** old.* record into memory when executing an UPDATE or DELETE command.
121319 **
121320 ** Bit 0 of the returned mask is set if the left-most column of the
121321 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
121322 ** the second leftmost column value is required, and so on. If there
121323 ** are more than 32 columns in the table, and at least one of the columns
121324 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
121325 **
121326 ** It is not possible to determine if the old.rowid or new.rowid column is
121327 ** accessed by triggers. The caller must always assume that it is.
121328 **
121329 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
121330 ** applies to the old.* table. If 1, the new.* table.
121331 **
121332 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
121333 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
121334 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
121335 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
121336 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
121337 */
121339  Parse *pParse, /* Parse context */
121340  Trigger *pTrigger, /* List of triggers on table pTab */
121341  ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
121342  int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
121343  int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
121344  Table *pTab, /* The table to code triggers from */
121345  int orconf /* Default ON CONFLICT policy for trigger steps */
121346 ){
121347  const int op = pChanges ? TK_UPDATE : TK_DELETE;
121348  u32 mask = 0;
121349  Trigger *p;
121350 
121351  assert( isNew==1 || isNew==0 );
121352  for(p=pTrigger; p; p=p->pNext){
121353  if( p->op==op && (tr_tm&p->tr_tm)
121354  && checkColumnOverlap(p->pColumns,pChanges)
121355  ){
121356  TriggerPrg *pPrg;
121357  pPrg = getRowTrigger(pParse, p, pTab, orconf);
121358  if( pPrg ){
121359  mask |= pPrg->aColmask[isNew];
121360  }
121361  }
121362  }
121363 
121364  return mask;
121365 }
121366 
121367 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
121368 
121369 /************** End of trigger.c *********************************************/
121370 /************** Begin file update.c ******************************************/
121371 /*
121372 ** 2001 September 15
121373 **
121374 ** The author disclaims copyright to this source code. In place of
121375 ** a legal notice, here is a blessing:
121376 **
121377 ** May you do good and not evil.
121378 ** May you find forgiveness for yourself and forgive others.
121379 ** May you share freely, never taking more than you give.
121380 **
121381 *************************************************************************
121382 ** This file contains C code routines that are called by the parser
121383 ** to handle UPDATE statements.
121384 */
121385 /* #include "sqliteInt.h" */
121386 
121387 #ifndef SQLITE_OMIT_VIRTUALTABLE
121388 /* Forward declaration */
121389 static void updateVirtualTable(
121390  Parse *pParse, /* The parsing context */
121391  SrcList *pSrc, /* The virtual table to be modified */
121392  Table *pTab, /* The virtual table */
121393  ExprList *pChanges, /* The columns to change in the UPDATE statement */
121394  Expr *pRowidExpr, /* Expression used to recompute the rowid */
121395  int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
121396  Expr *pWhere, /* WHERE clause of the UPDATE statement */
121397  int onError /* ON CONFLICT strategy */
121398 );
121399 #endif /* SQLITE_OMIT_VIRTUALTABLE */
121400 
121401 /*
121402 ** The most recently coded instruction was an OP_Column to retrieve the
121403 ** i-th column of table pTab. This routine sets the P4 parameter of the
121404 ** OP_Column to the default value, if any.
121405 **
121406 ** The default value of a column is specified by a DEFAULT clause in the
121407 ** column definition. This was either supplied by the user when the table
121408 ** was created, or added later to the table definition by an ALTER TABLE
121409 ** command. If the latter, then the row-records in the table btree on disk
121410 ** may not contain a value for the column and the default value, taken
121411 ** from the P4 parameter of the OP_Column instruction, is returned instead.
121412 ** If the former, then all row-records are guaranteed to include a value
121413 ** for the column and the P4 value is not required.
121414 **
121415 ** Column definitions created by an ALTER TABLE command may only have
121416 ** literal default values specified: a number, null or a string. (If a more
121417 ** complicated default expression value was provided, it is evaluated
121418 ** when the ALTER TABLE is executed and one of the literal values written
121419 ** into the sqlite_master table.)
121420 **
121421 ** Therefore, the P4 parameter is only required if the default value for
121422 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
121423 ** function is capable of transforming these types of expressions into
121424 ** sqlite3_value objects.
121425 **
121426 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
121427 ** on register iReg. This is used when an equivalent integer value is
121428 ** stored in place of an 8-byte floating point value in order to save
121429 ** space.
121430 */
121431 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
121432  assert( pTab!=0 );
121433  if( !pTab->pSelect ){
121434  sqlite3_value *pValue = 0;
121435  u8 enc = ENC(sqlite3VdbeDb(v));
121436  Column *pCol = &pTab->aCol[i];
121437  VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
121438  assert( i<pTab->nCol );
121439  sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
121440  pCol->affinity, &pValue);
121441  if( pValue ){
121442  sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
121443  }
121444 #ifndef SQLITE_OMIT_FLOATING_POINT
121445  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
121447  }
121448 #endif
121449  }
121450 }
121451 
121452 /*
121453 ** Process an UPDATE statement.
121454 **
121455 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
121456 ** \_______/ \________/ \______/ \________________/
121457 * onError pTabList pChanges pWhere
121458 */
121460  Parse *pParse, /* The parser context */
121461  SrcList *pTabList, /* The table in which we should change things */
121462  ExprList *pChanges, /* Things to be changed */
121463  Expr *pWhere, /* The WHERE clause. May be null */
121464  int onError /* How to handle constraint errors */
121465 ){
121466  int i, j; /* Loop counters */
121467  Table *pTab; /* The table to be updated */
121468  int addrTop = 0; /* VDBE instruction address of the start of the loop */
121469  WhereInfo *pWInfo; /* Information about the WHERE clause */
121470  Vdbe *v; /* The virtual database engine */
121471  Index *pIdx; /* For looping over indices */
121472  Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
121473  int nIdx; /* Number of indices that need updating */
121474  int iBaseCur; /* Base cursor number */
121475  int iDataCur; /* Cursor for the canonical data btree */
121476  int iIdxCur; /* Cursor for the first index */
121477  sqlite3 *db; /* The database structure */
121478  int *aRegIdx = 0; /* One register assigned to each index to be updated */
121479  int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
121480  ** an expression for the i-th column of the table.
121481  ** aXRef[i]==-1 if the i-th column is not changed. */
121482  u8 *aToOpen; /* 1 for tables and indices to be opened */
121483  u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
121484  u8 chngRowid; /* Rowid changed in a normal table */
121485  u8 chngKey; /* Either chngPk or chngRowid */
121486  Expr *pRowidExpr = 0; /* Expression defining the new record number */
121487  AuthContext sContext; /* The authorization context */
121488  NameContext sNC; /* The name-context to resolve expressions in */
121489  int iDb; /* Database containing the table being updated */
121490  int okOnePass; /* True for one-pass algorithm without the FIFO */
121491  int hasFK; /* True if foreign key processing is required */
121492  int labelBreak; /* Jump here to break out of UPDATE loop */
121493  int labelContinue; /* Jump here to continue next step of UPDATE loop */
121494 
121495 #ifndef SQLITE_OMIT_TRIGGER
121496  int isView; /* True when updating a view (INSTEAD OF trigger) */
121497  Trigger *pTrigger; /* List of triggers on pTab, if required */
121498  int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
121499 #endif
121500  int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
121501  int iEph = 0; /* Ephemeral table holding all primary key values */
121502  int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
121503  int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
121504 
121505  /* Register Allocations */
121506  int regRowCount = 0; /* A count of rows changed */
121507  int regOldRowid = 0; /* The old rowid */
121508  int regNewRowid = 0; /* The new rowid */
121509  int regNew = 0; /* Content of the NEW.* table in triggers */
121510  int regOld = 0; /* Content of OLD.* table in triggers */
121511  int regRowSet = 0; /* Rowset of rows to be updated */
121512  int regKey = 0; /* composite PRIMARY KEY value */
121513 
121514  memset(&sContext, 0, sizeof(sContext));
121515  db = pParse->db;
121516  if( pParse->nErr || db->mallocFailed ){
121517  goto update_cleanup;
121518  }
121519  assert( pTabList->nSrc==1 );
121520 
121521  /* Locate the table which we want to update.
121522  */
121523  pTab = sqlite3SrcListLookup(pParse, pTabList);
121524  if( pTab==0 ) goto update_cleanup;
121525  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
121526 
121527  /* Figure out if we have any triggers and if the table being
121528  ** updated is a view.
121529  */
121530 #ifndef SQLITE_OMIT_TRIGGER
121531  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
121532  isView = pTab->pSelect!=0;
121533  assert( pTrigger || tmask==0 );
121534 #else
121535 # define pTrigger 0
121536 # define isView 0
121537 # define tmask 0
121538 #endif
121539 #ifdef SQLITE_OMIT_VIEW
121540 # undef isView
121541 # define isView 0
121542 #endif
121543 
121544  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
121545  goto update_cleanup;
121546  }
121547  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
121548  goto update_cleanup;
121549  }
121550 
121551  /* Allocate a cursors for the main database table and for all indices.
121552  ** The index cursors might not be used, but if they are used they
121553  ** need to occur right after the database cursor. So go ahead and
121554  ** allocate enough space, just in case.
121555  */
121556  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
121557  iIdxCur = iDataCur+1;
121558  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
121559  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
121560  if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
121561  iDataCur = pParse->nTab;
121562  pTabList->a[0].iCursor = iDataCur;
121563  }
121564  pParse->nTab++;
121565  }
121566 
121567  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
121568  ** Initialize aXRef[] and aToOpen[] to their default values.
121569  */
121570  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
121571  if( aXRef==0 ) goto update_cleanup;
121572  aRegIdx = aXRef+pTab->nCol;
121573  aToOpen = (u8*)(aRegIdx+nIdx);
121574  memset(aToOpen, 1, nIdx+1);
121575  aToOpen[nIdx+1] = 0;
121576  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
121577 
121578  /* Initialize the name-context */
121579  memset(&sNC, 0, sizeof(sNC));
121580  sNC.pParse = pParse;
121581  sNC.pSrcList = pTabList;
121582 
121583  /* Resolve the column names in all the expressions of the
121584  ** of the UPDATE statement. Also find the column index
121585  ** for each column to be updated in the pChanges array. For each
121586  ** column to be updated, make sure we have authorization to change
121587  ** that column.
121588  */
121589  chngRowid = chngPk = 0;
121590  for(i=0; i<pChanges->nExpr; i++){
121591  if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
121592  goto update_cleanup;
121593  }
121594  for(j=0; j<pTab->nCol; j++){
121595  if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
121596  if( j==pTab->iPKey ){
121597  chngRowid = 1;
121598  pRowidExpr = pChanges->a[i].pExpr;
121599  }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
121600  chngPk = 1;
121601  }
121602  aXRef[j] = i;
121603  break;
121604  }
121605  }
121606  if( j>=pTab->nCol ){
121607  if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
121608  j = -1;
121609  chngRowid = 1;
121610  pRowidExpr = pChanges->a[i].pExpr;
121611  }else{
121612  sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
121613  pParse->checkSchema = 1;
121614  goto update_cleanup;
121615  }
121616  }
121617 #ifndef SQLITE_OMIT_AUTHORIZATION
121618  {
121619  int rc;
121620  rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
121621  j<0 ? "ROWID" : pTab->aCol[j].zName,
121622  db->aDb[iDb].zDbSName);
121623  if( rc==SQLITE_DENY ){
121624  goto update_cleanup;
121625  }else if( rc==SQLITE_IGNORE ){
121626  aXRef[j] = -1;
121627  }
121628  }
121629 #endif
121630  }
121631  assert( (chngRowid & chngPk)==0 );
121632  assert( chngRowid==0 || chngRowid==1 );
121633  assert( chngPk==0 || chngPk==1 );
121634  chngKey = chngRowid + chngPk;
121635 
121636  /* The SET expressions are not actually used inside the WHERE loop.
121637  ** So reset the colUsed mask. Unless this is a virtual table. In that
121638  ** case, set all bits of the colUsed mask (to ensure that the virtual
121639  ** table implementation makes all columns available).
121640  */
121641  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
121642 
121643  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
121644 
121645  /* There is one entry in the aRegIdx[] array for each index on the table
121646  ** being updated. Fill in aRegIdx[] with a register number that will hold
121647  ** the key for accessing each index.
121648  **
121649  ** FIXME: Be smarter about omitting indexes that use expressions.
121650  */
121651  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
121652  int reg;
121653  if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
121654  reg = ++pParse->nMem;
121655  }else{
121656  reg = 0;
121657  for(i=0; i<pIdx->nKeyCol; i++){
121658  i16 iIdxCol = pIdx->aiColumn[i];
121659  if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
121660  reg = ++pParse->nMem;
121661  break;
121662  }
121663  }
121664  }
121665  if( reg==0 ) aToOpen[j+1] = 0;
121666  aRegIdx[j] = reg;
121667  }
121668 
121669  /* Begin generating code. */
121670  v = sqlite3GetVdbe(pParse);
121671  if( v==0 ) goto update_cleanup;
121672  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
121673  sqlite3BeginWriteOperation(pParse, 1, iDb);
121674 
121675  /* Allocate required registers. */
121676  if( !IsVirtual(pTab) ){
121677  regRowSet = ++pParse->nMem;
121678  regOldRowid = regNewRowid = ++pParse->nMem;
121679  if( chngPk || pTrigger || hasFK ){
121680  regOld = pParse->nMem + 1;
121681  pParse->nMem += pTab->nCol;
121682  }
121683  if( chngKey || pTrigger || hasFK ){
121684  regNewRowid = ++pParse->nMem;
121685  }
121686  regNew = pParse->nMem + 1;
121687  pParse->nMem += pTab->nCol;
121688  }
121689 
121690  /* Start the view context. */
121691  if( isView ){
121692  sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
121693  }
121694 
121695  /* If we are trying to update a view, realize that view into
121696  ** an ephemeral table.
121697  */
121698 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
121699  if( isView ){
121700  sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
121701  }
121702 #endif
121703 
121704  /* Resolve the column names in all the expressions in the
121705  ** WHERE clause.
121706  */
121707  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
121708  goto update_cleanup;
121709  }
121710 
121711 #ifndef SQLITE_OMIT_VIRTUALTABLE
121712  /* Virtual tables must be handled separately */
121713  if( IsVirtual(pTab) ){
121714  updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
121715  pWhere, onError);
121716  goto update_cleanup;
121717  }
121718 #endif
121719 
121720  /* Begin the database scan
121721  */
121722  if( HasRowid(pTab) ){
121723  sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
121724  pWInfo = sqlite3WhereBegin(
121725  pParse, pTabList, pWhere, 0, 0,
121727  );
121728  if( pWInfo==0 ) goto update_cleanup;
121729  okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
121730 
121731  /* Remember the rowid of every item to be updated.
121732  */
121733  sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
121734  if( !okOnePass ){
121735  sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
121736  }
121737 
121738  /* End the database scan loop.
121739  */
121740  sqlite3WhereEnd(pWInfo);
121741  }else{
121742  int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
121743  i16 nPk; /* Number of components of the PRIMARY KEY */
121744  int addrOpen; /* Address of the OpenEphemeral instruction */
121745 
121746  assert( pPk!=0 );
121747  nPk = pPk->nKeyCol;
121748  iPk = pParse->nMem+1;
121749  pParse->nMem += nPk;
121750  regKey = ++pParse->nMem;
121751  iEph = pParse->nTab++;
121752  sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
121753  addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
121754  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
121755  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
121756  WHERE_ONEPASS_DESIRED, iIdxCur);
121757  if( pWInfo==0 ) goto update_cleanup;
121758  okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
121759  for(i=0; i<nPk; i++){
121760  assert( pPk->aiColumn[i]>=0 );
121761  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
121762  iPk+i);
121763  }
121764  if( okOnePass ){
121765  sqlite3VdbeChangeToNoop(v, addrOpen);
121766  nKey = nPk;
121767  regKey = iPk;
121768  }else{
121769  sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
121770  sqlite3IndexAffinityStr(db, pPk), nPk);
121771  sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
121772  }
121773  sqlite3WhereEnd(pWInfo);
121774  }
121775 
121776  /* Initialize the count of updated rows
121777  */
121778  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
121779  regRowCount = ++pParse->nMem;
121780  sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
121781  }
121782 
121783  labelBreak = sqlite3VdbeMakeLabel(v);
121784  if( !isView ){
121785  /*
121786  ** Open every index that needs updating. Note that if any
121787  ** index could potentially invoke a REPLACE conflict resolution
121788  ** action, then we need to open all indices because we might need
121789  ** to be deleting some records.
121790  */
121791  if( onError==OE_Replace ){
121792  memset(aToOpen, 1, nIdx+1);
121793  }else{
121794  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121795  if( pIdx->onError==OE_Replace ){
121796  memset(aToOpen, 1, nIdx+1);
121797  break;
121798  }
121799  }
121800  }
121801  if( okOnePass ){
121802  if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
121803  if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
121804  }
121805  sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
121806  0, 0);
121807  }
121808 
121809  /* Top of the update loop */
121810  if( okOnePass ){
121811  if( aToOpen[iDataCur-iBaseCur] && !isView ){
121812  assert( pPk );
121813  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
121815  }
121816  labelContinue = labelBreak;
121817  sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
121818  VdbeCoverageIf(v, pPk==0);
121819  VdbeCoverageIf(v, pPk!=0);
121820  }else if( pPk ){
121821  labelContinue = sqlite3VdbeMakeLabel(v);
121822  sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
121823  addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
121824  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
121825  VdbeCoverage(v);
121826  }else{
121827  labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
121828  regOldRowid);
121829  VdbeCoverage(v);
121830  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
121831  VdbeCoverage(v);
121832  }
121833 
121834  /* If the record number will change, set register regNewRowid to
121835  ** contain the new value. If the record number is not being modified,
121836  ** then regNewRowid is the same register as regOldRowid, which is
121837  ** already populated. */
121838  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
121839  if( chngRowid ){
121840  sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
121841  sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
121842  }
121843 
121844  /* Compute the old pre-UPDATE content of the row being changed, if that
121845  ** information is needed */
121846  if( chngPk || hasFK || pTrigger ){
121847  u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
121848  oldmask |= sqlite3TriggerColmask(pParse,
121849  pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
121850  );
121851  for(i=0; i<pTab->nCol; i++){
121852  if( oldmask==0xffffffff
121853  || (i<32 && (oldmask & MASKBIT32(i))!=0)
121854  || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
121855  ){
121856  testcase( oldmask!=0xffffffff && i==31 );
121857  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
121858  }else{
121859  sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
121860  }
121861  }
121862  if( chngRowid==0 && pPk==0 ){
121863  sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
121864  }
121865  }
121866 
121867  /* Populate the array of registers beginning at regNew with the new
121868  ** row data. This array is used to check constants, create the new
121869  ** table and index records, and as the values for any new.* references
121870  ** made by triggers.
121871  **
121872  ** If there are one or more BEFORE triggers, then do not populate the
121873  ** registers associated with columns that are (a) not modified by
121874  ** this UPDATE statement and (b) not accessed by new.* references. The
121875  ** values for registers not modified by the UPDATE must be reloaded from
121876  ** the database after the BEFORE triggers are fired anyway (as the trigger
121877  ** may have modified them). So not loading those that are not going to
121878  ** be used eliminates some redundant opcodes.
121879  */
121880  newmask = sqlite3TriggerColmask(
121881  pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
121882  );
121883  for(i=0; i<pTab->nCol; i++){
121884  if( i==pTab->iPKey ){
121885  sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121886  }else{
121887  j = aXRef[i];
121888  if( j>=0 ){
121889  sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
121890  }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
121891  /* This branch loads the value of a column that will not be changed
121892  ** into a register. This is done if there are no BEFORE triggers, or
121893  ** if there are one or more BEFORE triggers that use this value via
121894  ** a new.* reference in a trigger program.
121895  */
121896  testcase( i==31 );
121897  testcase( i==32 );
121898  sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
121899  }else{
121900  sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121901  }
121902  }
121903  }
121904 
121905  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
121906  ** verified. One could argue that this is wrong.
121907  */
121908  if( tmask&TRIGGER_BEFORE ){
121909  sqlite3TableAffinity(v, pTab, regNew);
121910  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
121911  TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
121912 
121913  /* The row-trigger may have deleted the row being updated. In this
121914  ** case, jump to the next row. No updates or AFTER triggers are
121915  ** required. This behavior - what happens when the row being updated
121916  ** is deleted or renamed by a BEFORE trigger - is left undefined in the
121917  ** documentation.
121918  */
121919  if( pPk ){
121920  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
121921  VdbeCoverage(v);
121922  }else{
121923  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
121924  VdbeCoverage(v);
121925  }
121926 
121927  /* If it did not delete it, the row-trigger may still have modified
121928  ** some of the columns of the row being updated. Load the values for
121929  ** all columns not modified by the update statement into their
121930  ** registers in case this has happened.
121931  */
121932  for(i=0; i<pTab->nCol; i++){
121933  if( aXRef[i]<0 && i!=pTab->iPKey ){
121934  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
121935  }
121936  }
121937  }
121938 
121939  if( !isView ){
121940  int addr1 = 0; /* Address of jump instruction */
121941  int bReplace = 0; /* True if REPLACE conflict resolution might happen */
121942 
121943  /* Do constraint checks. */
121944  assert( regOldRowid>0 );
121945  sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
121946  regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
121947  aXRef);
121948 
121949  /* Do FK constraint checks. */
121950  if( hasFK ){
121951  sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
121952  }
121953 
121954  /* Delete the index entries associated with the current record. */
121955  if( bReplace || chngKey ){
121956  if( pPk ){
121957  addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
121958  }else{
121959  addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
121960  }
121962  }
121963  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
121964 
121965  /* If changing the rowid value, or if there are foreign key constraints
121966  ** to process, delete the old record. Otherwise, add a noop OP_Delete
121967  ** to invoke the pre-update hook.
121968  **
121969  ** That (regNew==regnewRowid+1) is true is also important for the
121970  ** pre-update hook. If the caller invokes preupdate_new(), the returned
121971  ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
121972  ** is the column index supplied by the user.
121973  */
121974  assert( regNew==regNewRowid+1 );
121975 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
121976  sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
121977  OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
121978  regNewRowid
121979  );
121980  if( !pParse->nested ){
121981  sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
121982  }
121983 #else
121984  if( hasFK || chngKey || pPk!=0 ){
121985  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
121986  }
121987 #endif
121988  if( bReplace || chngKey ){
121989  sqlite3VdbeJumpHere(v, addr1);
121990  }
121991 
121992  if( hasFK ){
121993  sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
121994  }
121995 
121996  /* Insert the new index entries and the new record. */
121997  sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
121998  regNewRowid, aRegIdx, 1, 0, 0);
121999 
122000  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
122001  ** handle rows (possibly in other tables) that refer via a foreign key
122002  ** to the row just updated. */
122003  if( hasFK ){
122004  sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
122005  }
122006  }
122007 
122008  /* Increment the row counter
122009  */
122010  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
122011  sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
122012  }
122013 
122014  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
122015  TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
122016 
122017  /* Repeat the above with the next record to be updated, until
122018  ** all record selected by the WHERE clause have been updated.
122019  */
122020  if( okOnePass ){
122021  /* Nothing to do at end-of-loop for a single-pass */
122022  }else if( pPk ){
122023  sqlite3VdbeResolveLabel(v, labelContinue);
122024  sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
122025  }else{
122026  sqlite3VdbeGoto(v, labelContinue);
122027  }
122028  sqlite3VdbeResolveLabel(v, labelBreak);
122029 
122030  /* Close all tables */
122031  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
122032  assert( aRegIdx );
122033  if( aToOpen[i+1] ){
122034  sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
122035  }
122036  }
122037  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
122038 
122039  /* Update the sqlite_sequence table by storing the content of the
122040  ** maximum rowid counter values recorded while inserting into
122041  ** autoincrement tables.
122042  */
122043  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
122044  sqlite3AutoincrementEnd(pParse);
122045  }
122046 
122047  /*
122048  ** Return the number of rows that were changed. If this routine is
122049  ** generating code because of a call to sqlite3NestedParse(), do not
122050  ** invoke the callback function.
122051  */
122052  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
122053  sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
122054  sqlite3VdbeSetNumCols(v, 1);
122055  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
122056  }
122057 
122058 update_cleanup:
122059  sqlite3AuthContextPop(&sContext);
122060  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
122061  sqlite3SrcListDelete(db, pTabList);
122062  sqlite3ExprListDelete(db, pChanges);
122063  sqlite3ExprDelete(db, pWhere);
122064  return;
122065 }
122066 /* Make sure "isView" and other macros defined above are undefined. Otherwise
122067 ** they may interfere with compilation of other functions in this file
122068 ** (or in another file, if this file becomes part of the amalgamation). */
122069 #ifdef isView
122070  #undef isView
122071 #endif
122072 #ifdef pTrigger
122073  #undef pTrigger
122074 #endif
122075 
122076 #ifndef SQLITE_OMIT_VIRTUALTABLE
122077 /*
122078 ** Generate code for an UPDATE of a virtual table.
122079 **
122080 ** There are two possible strategies - the default and the special
122081 ** "onepass" strategy. Onepass is only used if the virtual table
122082 ** implementation indicates that pWhere may match at most one row.
122083 **
122084 ** The default strategy is to create an ephemeral table that contains
122085 ** for each row to be changed:
122086 **
122087 ** (A) The original rowid of that row.
122088 ** (B) The revised rowid for the row.
122089 ** (C) The content of every column in the row.
122090 **
122091 ** Then loop through the contents of this ephemeral table executing a
122092 ** VUpdate for each row. When finished, drop the ephemeral table.
122093 **
122094 ** The "onepass" strategy does not use an ephemeral table. Instead, it
122095 ** stores the same values (A, B and C above) in a register array and
122096 ** makes a single invocation of VUpdate.
122097 */
122099  Parse *pParse, /* The parsing context */
122100  SrcList *pSrc, /* The virtual table to be modified */
122101  Table *pTab, /* The virtual table */
122102  ExprList *pChanges, /* The columns to change in the UPDATE statement */
122103  Expr *pRowid, /* Expression used to recompute the rowid */
122104  int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
122105  Expr *pWhere, /* WHERE clause of the UPDATE statement */
122106  int onError /* ON CONFLICT strategy */
122107 ){
122108  Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
122109  int ephemTab; /* Table holding the result of the SELECT */
122110  int i; /* Loop counter */
122111  sqlite3 *db = pParse->db; /* Database connection */
122112  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
122113  WhereInfo *pWInfo;
122114  int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
122115  int regArg; /* First register in VUpdate arg array */
122116  int regRec; /* Register in which to assemble record */
122117  int regRowid; /* Register for ephem table rowid */
122118  int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
122119  int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
122120  int bOnePass; /* True to use onepass strategy */
122121  int addr; /* Address of OP_OpenEphemeral */
122122 
122123  /* Allocate nArg registers to martial the arguments to VUpdate. Then
122124  ** create and open the ephemeral table in which the records created from
122125  ** these arguments will be temporarily stored. */
122126  assert( v );
122127  ephemTab = pParse->nTab++;
122128  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
122129  regArg = pParse->nMem + 1;
122130  pParse->nMem += nArg;
122131  regRec = ++pParse->nMem;
122132  regRowid = ++pParse->nMem;
122133 
122134  /* Start scanning the virtual table */
122135  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
122136  if( pWInfo==0 ) return;
122137 
122138  /* Populate the argument registers. */
122139  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
122140  if( pRowid ){
122141  sqlite3ExprCode(pParse, pRowid, regArg+1);
122142  }else{
122143  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
122144  }
122145  for(i=0; i<pTab->nCol; i++){
122146  if( aXRef[i]>=0 ){
122147  sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
122148  }else{
122149  sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
122150  }
122151  }
122152 
122153  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
122154 
122155  if( bOnePass ){
122156  /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
122157  ** above. Also, if this is a top-level parse (not a trigger), clear the
122158  ** multi-write flag so that the VM does not open a statement journal */
122159  sqlite3VdbeChangeToNoop(v, addr);
122160  if( sqlite3IsToplevel(pParse) ){
122161  pParse->isMultiWrite = 0;
122162  }
122163  }else{
122164  /* Create a record from the argument register contents and insert it into
122165  ** the ephemeral table. */
122166  sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
122167  sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
122168  sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
122169  }
122170 
122171 
122172  if( bOnePass==0 ){
122173  /* End the virtual table scan */
122174  sqlite3WhereEnd(pWInfo);
122175 
122176  /* Begin scannning through the ephemeral table. */
122177  addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
122178 
122179  /* Extract arguments from the current row of the ephemeral table and
122180  ** invoke the VUpdate method. */
122181  for(i=0; i<nArg; i++){
122182  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
122183  }
122184  }
122185  sqlite3VtabMakeWritable(pParse, pTab);
122186  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
122187  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
122188  sqlite3MayAbort(pParse);
122189 
122190  /* End of the ephemeral table scan. Or, if using the onepass strategy,
122191  ** jump to here if the scan visited zero rows. */
122192  if( bOnePass==0 ){
122193  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
122194  sqlite3VdbeJumpHere(v, addr);
122195  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
122196  }else{
122197  sqlite3WhereEnd(pWInfo);
122198  }
122199 }
122200 #endif /* SQLITE_OMIT_VIRTUALTABLE */
122201 
122202 /************** End of update.c **********************************************/
122203 /************** Begin file vacuum.c ******************************************/
122204 /*
122205 ** 2003 April 6
122206 **
122207 ** The author disclaims copyright to this source code. In place of
122208 ** a legal notice, here is a blessing:
122209 **
122210 ** May you do good and not evil.
122211 ** May you find forgiveness for yourself and forgive others.
122212 ** May you share freely, never taking more than you give.
122213 **
122214 *************************************************************************
122215 ** This file contains code used to implement the VACUUM command.
122216 **
122217 ** Most of the code in this file may be omitted by defining the
122218 ** SQLITE_OMIT_VACUUM macro.
122219 */
122220 /* #include "sqliteInt.h" */
122221 /* #include "vdbeInt.h" */
122222 
122223 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
122224 
122225 /*
122226 ** Execute zSql on database db.
122227 **
122228 ** If zSql returns rows, then each row will have exactly one
122229 ** column. (This will only happen if zSql begins with "SELECT".)
122230 ** Take each row of result and call execSql() again recursively.
122231 **
122232 ** The execSqlF() routine does the same thing, except it accepts
122233 ** a format string as its third argument
122234 */
122235 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
122236  sqlite3_stmt *pStmt;
122237  int rc;
122238 
122239  /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
122240  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
122241  if( rc!=SQLITE_OK ) return rc;
122242  while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
122243  const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
122244  assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
122245  if( zSubSql ){
122246  assert( zSubSql[0]!='S' );
122247  rc = execSql(db, pzErrMsg, zSubSql);
122248  if( rc!=SQLITE_OK ) break;
122249  }
122250  }
122251  assert( rc!=SQLITE_ROW );
122252  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
122253  if( rc ){
122254  sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
122255  }
122256  (void)sqlite3_finalize(pStmt);
122257  return rc;
122258 }
122259 static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
122260  char *z;
122261  va_list ap;
122262  int rc;
122263  va_start(ap, zSql);
122264  z = sqlite3VMPrintf(db, zSql, ap);
122265  va_end(ap);
122266  if( z==0 ) return SQLITE_NOMEM;
122267  rc = execSql(db, pzErrMsg, z);
122268  sqlite3DbFree(db, z);
122269  return rc;
122270 }
122271 
122272 /*
122273 ** The VACUUM command is used to clean up the database,
122274 ** collapse free space, etc. It is modelled after the VACUUM command
122275 ** in PostgreSQL. The VACUUM command works as follows:
122276 **
122277 ** (1) Create a new transient database file
122278 ** (2) Copy all content from the database being vacuumed into
122279 ** the new transient database file
122280 ** (3) Copy content from the transient database back into the
122281 ** original database.
122282 **
122283 ** The transient database requires temporary disk space approximately
122284 ** equal to the size of the original database. The copy operation of
122285 ** step (3) requires additional temporary disk space approximately equal
122286 ** to the size of the original database for the rollback journal.
122287 ** Hence, temporary disk space that is approximately 2x the size of the
122288 ** original database is required. Every page of the database is written
122289 ** approximately 3 times: Once for step (2) and twice for step (3).
122290 ** Two writes per page are required in step (3) because the original
122291 ** database content must be written into the rollback journal prior to
122292 ** overwriting the database with the vacuumed content.
122293 **
122294 ** Only 1x temporary space and only 1x writes would be required if
122295 ** the copy of step (3) were replaced by deleting the original database
122296 ** and renaming the transient database as the original. But that will
122297 ** not work if other processes are attached to the original database.
122298 ** And a power loss in between deleting the original and renaming the
122299 ** transient would cause the database file to appear to be deleted
122300 ** following reboot.
122301 */
122303  Vdbe *v = sqlite3GetVdbe(pParse);
122304  int iDb = pNm ? sqlite3TwoPartName(pParse, pNm, pNm, &pNm) : 0;
122305  if( v && (iDb>=2 || iDb==0) ){
122306  sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
122307  sqlite3VdbeUsesBtree(v, iDb);
122308  }
122309  return;
122310 }
122311 
122312 /*
122313 ** This routine implements the OP_Vacuum opcode of the VDBE.
122314 */
122315 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
122316  int rc = SQLITE_OK; /* Return code from service routines */
122317  Btree *pMain; /* The database being vacuumed */
122318  Btree *pTemp; /* The temporary database we vacuum into */
122319  int saved_flags; /* Saved value of the db->flags */
122320  int saved_nChange; /* Saved value of db->nChange */
122321  int saved_nTotalChange; /* Saved value of db->nTotalChange */
122322  u8 saved_mTrace; /* Saved trace settings */
122323  Db *pDb = 0; /* Database to detach at end of vacuum */
122324  int isMemDb; /* True if vacuuming a :memory: database */
122325  int nRes; /* Bytes of reserved space at the end of each page */
122326  int nDb; /* Number of attached databases */
122327  const char *zDbMain; /* Schema name of database to vacuum */
122328 
122329  if( !db->autoCommit ){
122330  sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
122331  return SQLITE_ERROR;
122332  }
122333  if( db->nVdbeActive>1 ){
122334  sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
122335  return SQLITE_ERROR;
122336  }
122337 
122338  /* Save the current value of the database flags so that it can be
122339  ** restored before returning. Then set the writable-schema flag, and
122340  ** disable CHECK and foreign key constraints. */
122341  saved_flags = db->flags;
122342  saved_nChange = db->nChange;
122343  saved_nTotalChange = db->nTotalChange;
122344  saved_mTrace = db->mTrace;
122348  db->mTrace = 0;
122349 
122350  zDbMain = db->aDb[iDb].zDbSName;
122351  pMain = db->aDb[iDb].pBt;
122352  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
122353 
122354  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
122355  ** can be set to 'off' for this file, as it is not recovered if a crash
122356  ** occurs anyway. The integrity of the database is maintained by a
122357  ** (possibly synchronous) transaction opened on the main database before
122358  ** sqlite3BtreeCopyFile() is called.
122359  **
122360  ** An optimisation would be to use a non-journaled pager.
122361  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
122362  ** that actually made the VACUUM run slower. Very little journalling
122363  ** actually occurs when doing a vacuum since the vacuum_db is initially
122364  ** empty. Only the journal header is written. Apparently it takes more
122365  ** time to parse and run the PRAGMA to turn journalling off than it does
122366  ** to write the journal header file.
122367  */
122368  nDb = db->nDb;
122369  rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
122370  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122371  assert( (db->nDb-1)==nDb );
122372  pDb = &db->aDb[nDb];
122373  assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
122374  pTemp = pDb->pBt;
122375 
122376  /* The call to execSql() to attach the temp database has left the file
122377  ** locked (as there was more than one active statement when the transaction
122378  ** to read the schema was concluded. Unlock it here so that this doesn't
122379  ** cause problems for the call to BtreeSetPageSize() below. */
122380  sqlite3BtreeCommit(pTemp);
122381 
122382  nRes = sqlite3BtreeGetOptimalReserve(pMain);
122383 
122384  /* A VACUUM cannot change the pagesize of an encrypted database. */
122385 #ifdef SQLITE_HAS_CODEC
122386  if( db->nextPagesize ){
122387  extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
122388  int nKey;
122389  char *zKey;
122390  sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
122391  if( nKey ) db->nextPagesize = 0;
122392  }
122393 #endif
122394 
122395  sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
122398 
122399  /* Begin a transaction and take an exclusive lock on the main database
122400  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
122401  ** to ensure that we do not try to change the page-size on a WAL database.
122402  */
122403  rc = execSql(db, pzErrMsg, "BEGIN");
122404  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122405  rc = sqlite3BtreeBeginTrans(pMain, 2);
122406  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122407 
122408  /* Do not attempt to change the page size for a WAL database */
122410  ==PAGER_JOURNALMODE_WAL ){
122411  db->nextPagesize = 0;
122412  }
122413 
122414  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
122415  || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
122416  || NEVER(db->mallocFailed)
122417  ){
122418  rc = SQLITE_NOMEM_BKPT;
122419  goto end_of_vacuum;
122420  }
122421 
122422 #ifndef SQLITE_OMIT_AUTOVACUUM
122423  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
122424  sqlite3BtreeGetAutoVacuum(pMain));
122425 #endif
122426 
122427  /* Query the schema of the main database. Create a mirror schema
122428  ** in the temporary database.
122429  */
122430  db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
122431  rc = execSqlF(db, pzErrMsg,
122432  "SELECT sql FROM \"%w\".sqlite_master"
122433  " WHERE type='table'AND name<>'sqlite_sequence'"
122434  " AND coalesce(rootpage,1)>0",
122435  zDbMain
122436  );
122437  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122438  rc = execSqlF(db, pzErrMsg,
122439  "SELECT sql FROM \"%w\".sqlite_master"
122440  " WHERE type='index' AND length(sql)>10",
122441  zDbMain
122442  );
122443  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122444  db->init.iDb = 0;
122445 
122446  /* Loop through the tables in the main database. For each, do
122447  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
122448  ** the contents to the temporary database.
122449  */
122450  rc = execSqlF(db, pzErrMsg,
122451  "SELECT'INSERT INTO vacuum_db.'||quote(name)"
122452  "||' SELECT*FROM\"%w\".'||quote(name)"
122453  "FROM vacuum_db.sqlite_master "
122454  "WHERE type='table'AND coalesce(rootpage,1)>0",
122455  zDbMain
122456  );
122457  assert( (db->flags & SQLITE_Vacuum)!=0 );
122458  db->flags &= ~SQLITE_Vacuum;
122459  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122460 
122461  /* Copy the triggers, views, and virtual tables from the main database
122462  ** over to the temporary database. None of these objects has any
122463  ** associated storage, so all we have to do is copy their entries
122464  ** from the SQLITE_MASTER table.
122465  */
122466  rc = execSqlF(db, pzErrMsg,
122467  "INSERT INTO vacuum_db.sqlite_master"
122468  " SELECT*FROM \"%w\".sqlite_master"
122469  " WHERE type IN('view','trigger')"
122470  " OR(type='table'AND rootpage=0)",
122471  zDbMain
122472  );
122473  if( rc ) goto end_of_vacuum;
122474 
122475  /* At this point, there is a write transaction open on both the
122476  ** vacuum database and the main database. Assuming no error occurs,
122477  ** both transactions are closed by this block - the main database
122478  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
122479  ** call to sqlite3BtreeCommit().
122480  */
122481  {
122482  u32 meta;
122483  int i;
122484 
122485  /* This array determines which meta meta values are preserved in the
122486  ** vacuum. Even entries are the meta value number and odd entries
122487  ** are an increment to apply to the meta value after the vacuum.
122488  ** The increment is used to increase the schema cookie so that other
122489  ** connections to the same database will know to reread the schema.
122490  */
122491  static const unsigned char aCopy[] = {
122492  BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
122493  BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
122494  BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
122495  BTREE_USER_VERSION, 0, /* Preserve the user version */
122496  BTREE_APPLICATION_ID, 0, /* Preserve the application id */
122497  };
122498 
122499  assert( 1==sqlite3BtreeIsInTrans(pTemp) );
122500  assert( 1==sqlite3BtreeIsInTrans(pMain) );
122501 
122502  /* Copy Btree meta values */
122503  for(i=0; i<ArraySize(aCopy); i+=2){
122504  /* GetMeta() and UpdateMeta() cannot fail in this context because
122505  ** we already have page 1 loaded into cache and marked dirty. */
122506  sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
122507  rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
122508  if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
122509  }
122510 
122511  rc = sqlite3BtreeCopyFile(pMain, pTemp);
122512  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122513  rc = sqlite3BtreeCommit(pTemp);
122514  if( rc!=SQLITE_OK ) goto end_of_vacuum;
122515 #ifndef SQLITE_OMIT_AUTOVACUUM
122517 #endif
122518  }
122519 
122520  assert( rc==SQLITE_OK );
122521  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
122522 
122523 end_of_vacuum:
122524  /* Restore the original value of db->flags */
122525  db->init.iDb = 0;
122526  db->flags = saved_flags;
122527  db->nChange = saved_nChange;
122528  db->nTotalChange = saved_nTotalChange;
122529  db->mTrace = saved_mTrace;
122530  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
122531 
122532  /* Currently there is an SQL level transaction open on the vacuum
122533  ** database. No locks are held on any other files (since the main file
122534  ** was committed at the btree level). So it safe to end the transaction
122535  ** by manually setting the autoCommit flag to true and detaching the
122536  ** vacuum database. The vacuum_db journal file is deleted when the pager
122537  ** is closed by the DETACH.
122538  */
122539  db->autoCommit = 1;
122540 
122541  if( pDb ){
122542  sqlite3BtreeClose(pDb->pBt);
122543  pDb->pBt = 0;
122544  pDb->pSchema = 0;
122545  }
122546 
122547  /* This both clears the schemas and reduces the size of the db->aDb[]
122548  ** array. */
122550 
122551  return rc;
122552 }
122553 
122554 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
122555 
122556 /************** End of vacuum.c **********************************************/
122557 /************** Begin file vtab.c ********************************************/
122558 /*
122559 ** 2006 June 10
122560 **
122561 ** The author disclaims copyright to this source code. In place of
122562 ** a legal notice, here is a blessing:
122563 **
122564 ** May you do good and not evil.
122565 ** May you find forgiveness for yourself and forgive others.
122566 ** May you share freely, never taking more than you give.
122567 **
122568 *************************************************************************
122569 ** This file contains code used to help implement virtual tables.
122570 */
122571 #ifndef SQLITE_OMIT_VIRTUALTABLE
122572 /* #include "sqliteInt.h" */
122573 
122574 /*
122575 ** Before a virtual table xCreate() or xConnect() method is invoked, the
122576 ** sqlite3.pVtabCtx member variable is set to point to an instance of
122577 ** this struct allocated on the stack. It is used by the implementation of
122578 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
122579 ** are invoked only from within xCreate and xConnect methods.
122580 */
122581 struct VtabCtx {
122582  VTable *pVTable; /* The virtual table being constructed */
122583  Table *pTab; /* The Table object to which the virtual table belongs */
122584  VtabCtx *pPrior; /* Parent context (if any) */
122585  int bDeclared; /* True after sqlite3_declare_vtab() is called */
122586 };
122587 
122588 /*
122589 ** The actual function that does the work of creating a new module.
122590 ** This function implements the sqlite3_create_module() and
122591 ** sqlite3_create_module_v2() interfaces.
122592 */
122593 static int createModule(
122594  sqlite3 *db, /* Database in which module is registered */
122595  const char *zName, /* Name assigned to this module */
122596  const sqlite3_module *pModule, /* The definition of the module */
122597  void *pAux, /* Context pointer for xCreate/xConnect */
122598  void (*xDestroy)(void *) /* Module destructor function */
122599 ){
122600  int rc = SQLITE_OK;
122601  int nName;
122602 
122603  sqlite3_mutex_enter(db->mutex);
122604  nName = sqlite3Strlen30(zName);
122605  if( sqlite3HashFind(&db->aModule, zName) ){
122606  rc = SQLITE_MISUSE_BKPT;
122607  }else{
122608  Module *pMod;
122609  pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
122610  if( pMod ){
122611  Module *pDel;
122612  char *zCopy = (char *)(&pMod[1]);
122613  memcpy(zCopy, zName, nName+1);
122614  pMod->zName = zCopy;
122615  pMod->pModule = pModule;
122616  pMod->pAux = pAux;
122617  pMod->xDestroy = xDestroy;
122618  pMod->pEpoTab = 0;
122619  pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
122620  assert( pDel==0 || pDel==pMod );
122621  if( pDel ){
122622  sqlite3OomFault(db);
122623  sqlite3DbFree(db, pDel);
122624  }
122625  }
122626  }
122627  rc = sqlite3ApiExit(db, rc);
122628  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
122629 
122630  sqlite3_mutex_leave(db->mutex);
122631  return rc;
122632 }
122633 
122634 
122635 /*
122636 ** External API function used to create a new virtual-table module.
122637 */
122639  sqlite3 *db, /* Database in which module is registered */
122640  const char *zName, /* Name assigned to this module */
122641  const sqlite3_module *pModule, /* The definition of the module */
122642  void *pAux /* Context pointer for xCreate/xConnect */
122643 ){
122644 #ifdef SQLITE_ENABLE_API_ARMOR
122645  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
122646 #endif
122647  return createModule(db, zName, pModule, pAux, 0);
122648 }
122649 
122650 /*
122651 ** External API function used to create a new virtual-table module.
122652 */
122654  sqlite3 *db, /* Database in which module is registered */
122655  const char *zName, /* Name assigned to this module */
122656  const sqlite3_module *pModule, /* The definition of the module */
122657  void *pAux, /* Context pointer for xCreate/xConnect */
122658  void (*xDestroy)(void *) /* Module destructor function */
122659 ){
122660 #ifdef SQLITE_ENABLE_API_ARMOR
122661  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
122662 #endif
122663  return createModule(db, zName, pModule, pAux, xDestroy);
122664 }
122665 
122666 /*
122667 ** Lock the virtual table so that it cannot be disconnected.
122668 ** Locks nest. Every lock should have a corresponding unlock.
122669 ** If an unlock is omitted, resources leaks will occur.
122670 **
122671 ** If a disconnect is attempted while a virtual table is locked,
122672 ** the disconnect is deferred until all locks have been removed.
122673 */
122675  pVTab->nRef++;
122676 }
122677 
122678 
122679 /*
122680 ** pTab is a pointer to a Table structure representing a virtual-table.
122681 ** Return a pointer to the VTable object used by connection db to access
122682 ** this virtual-table, if one has been created, or NULL otherwise.
122683 */
122685  VTable *pVtab;
122686  assert( IsVirtual(pTab) );
122687  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
122688  return pVtab;
122689 }
122690 
122691 /*
122692 ** Decrement the ref-count on a virtual table object. When the ref-count
122693 ** reaches zero, call the xDisconnect() method to delete the object.
122694 */
122696  sqlite3 *db = pVTab->db;
122697 
122698  assert( db );
122699  assert( pVTab->nRef>0 );
122700  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
122701 
122702  pVTab->nRef--;
122703  if( pVTab->nRef==0 ){
122704  sqlite3_vtab *p = pVTab->pVtab;
122705  if( p ){
122706  p->pModule->xDisconnect(p);
122707  }
122708  sqlite3DbFree(db, pVTab);
122709  }
122710 }
122711 
122712 /*
122713 ** Table p is a virtual table. This function moves all elements in the
122714 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
122715 ** database connections to be disconnected at the next opportunity.
122716 ** Except, if argument db is not NULL, then the entry associated with
122717 ** connection db is left in the p->pVTable list.
122718 */
122719 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
122720  VTable *pRet = 0;
122721  VTable *pVTable = p->pVTable;
122722  p->pVTable = 0;
122723 
122724  /* Assert that the mutex (if any) associated with the BtShared database
122725  ** that contains table p is held by the caller. See header comments
122726  ** above function sqlite3VtabUnlockList() for an explanation of why
122727  ** this makes it safe to access the sqlite3.pDisconnect list of any
122728  ** database connection that may have an entry in the p->pVTable list.
122729  */
122730  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
122731 
122732  while( pVTable ){
122733  sqlite3 *db2 = pVTable->db;
122734  VTable *pNext = pVTable->pNext;
122735  assert( db2 );
122736  if( db2==db ){
122737  pRet = pVTable;
122738  p->pVTable = pRet;
122739  pRet->pNext = 0;
122740  }else{
122741  pVTable->pNext = db2->pDisconnect;
122742  db2->pDisconnect = pVTable;
122743  }
122744  pVTable = pNext;
122745  }
122746 
122747  assert( !db || pRet );
122748  return pRet;
122749 }
122750 
122751 /*
122752 ** Table *p is a virtual table. This function removes the VTable object
122753 ** for table *p associated with database connection db from the linked
122754 ** list in p->pVTab. It also decrements the VTable ref count. This is
122755 ** used when closing database connection db to free all of its VTable
122756 ** objects without disturbing the rest of the Schema object (which may
122757 ** be being used by other shared-cache connections).
122758 */
122760  VTable **ppVTab;
122761 
122762  assert( IsVirtual(p) );
122763  assert( sqlite3BtreeHoldsAllMutexes(db) );
122764  assert( sqlite3_mutex_held(db->mutex) );
122765 
122766  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
122767  if( (*ppVTab)->db==db ){
122768  VTable *pVTab = *ppVTab;
122769  *ppVTab = pVTab->pNext;
122770  sqlite3VtabUnlock(pVTab);
122771  break;
122772  }
122773  }
122774 }
122775 
122776 
122777 /*
122778 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
122779 **
122780 ** This function may only be called when the mutexes associated with all
122781 ** shared b-tree databases opened using connection db are held by the
122782 ** caller. This is done to protect the sqlite3.pDisconnect list. The
122783 ** sqlite3.pDisconnect list is accessed only as follows:
122784 **
122785 ** 1) By this function. In this case, all BtShared mutexes and the mutex
122786 ** associated with the database handle itself must be held.
122787 **
122788 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
122789 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
122790 ** associated with the database the virtual table is stored in is held
122791 ** or, if the virtual table is stored in a non-sharable database, then
122792 ** the database handle mutex is held.
122793 **
122794 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
122795 ** by multiple threads. It is thread-safe.
122796 */
122798  VTable *p = db->pDisconnect;
122799  db->pDisconnect = 0;
122800 
122801  assert( sqlite3BtreeHoldsAllMutexes(db) );
122802  assert( sqlite3_mutex_held(db->mutex) );
122803 
122804  if( p ){
122806  do {
122807  VTable *pNext = p->pNext;
122808  sqlite3VtabUnlock(p);
122809  p = pNext;
122810  }while( p );
122811  }
122812 }
122813 
122814 /*
122815 ** Clear any and all virtual-table information from the Table record.
122816 ** This routine is called, for example, just before deleting the Table
122817 ** record.
122818 **
122819 ** Since it is a virtual-table, the Table structure contains a pointer
122820 ** to the head of a linked list of VTable structures. Each VTable
122821 ** structure is associated with a single sqlite3* user of the schema.
122822 ** The reference count of the VTable structure associated with database
122823 ** connection db is decremented immediately (which may lead to the
122824 ** structure being xDisconnected and free). Any other VTable structures
122825 ** in the list are moved to the sqlite3.pDisconnect list of the associated
122826 ** database connection.
122827 */
122829  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
122830  if( p->azModuleArg ){
122831  int i;
122832  for(i=0; i<p->nModuleArg; i++){
122833  if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
122834  }
122835  sqlite3DbFree(db, p->azModuleArg);
122836  }
122837 }
122838 
122839 /*
122840 ** Add a new module argument to pTable->azModuleArg[].
122841 ** The string is not copied - the pointer is stored. The
122842 ** string will be freed automatically when the table is
122843 ** deleted.
122844 */
122845 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
122846  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
122847  char **azModuleArg;
122848  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
122849  if( azModuleArg==0 ){
122850  sqlite3DbFree(db, zArg);
122851  }else{
122852  int i = pTable->nModuleArg++;
122853  azModuleArg[i] = zArg;
122854  azModuleArg[i+1] = 0;
122855  pTable->azModuleArg = azModuleArg;
122856  }
122857 }
122858 
122859 /*
122860 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
122861 ** statement. The module name has been parsed, but the optional list
122862 ** of parameters that follow the module name are still pending.
122863 */
122865  Parse *pParse, /* Parsing context */
122866  Token *pName1, /* Name of new table, or database name */
122867  Token *pName2, /* Name of new table or NULL */
122868  Token *pModuleName, /* Name of the module for the virtual table */
122869  int ifNotExists /* No error if the table already exists */
122870 ){
122871  int iDb; /* The database the table is being created in */
122872  Table *pTable; /* The new virtual table */
122873  sqlite3 *db; /* Database connection */
122874 
122875  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
122876  pTable = pParse->pNewTable;
122877  if( pTable==0 ) return;
122878  assert( 0==pTable->pIndex );
122879 
122880  db = pParse->db;
122881  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
122882  assert( iDb>=0 );
122883 
122884  pTable->tabFlags |= TF_Virtual;
122885  pTable->nModuleArg = 0;
122886  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
122887  addModuleArgument(db, pTable, 0);
122888  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
122889  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
122890  || (pParse->sNameToken.z==pName1->z && pName2->z==0)
122891  );
122892  pParse->sNameToken.n = (int)(
122893  &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
122894  );
122895 
122896 #ifndef SQLITE_OMIT_AUTHORIZATION
122897  /* Creating a virtual table invokes the authorization callback twice.
122898  ** The first invocation, to obtain permission to INSERT a row into the
122899  ** sqlite_master table, has already been made by sqlite3StartTable().
122900  ** The second call, to obtain permission to create the table, is made now.
122901  */
122902  if( pTable->azModuleArg ){
122903  sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
122904  pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
122905  }
122906 #endif
122907 }
122908 
122909 /*
122910 ** This routine takes the module argument that has been accumulating
122911 ** in pParse->zArg[] and appends it to the list of arguments on the
122912 ** virtual table currently under construction in pParse->pTable.
122913 */
122914 static void addArgumentToVtab(Parse *pParse){
122915  if( pParse->sArg.z && pParse->pNewTable ){
122916  const char *z = (const char*)pParse->sArg.z;
122917  int n = pParse->sArg.n;
122918  sqlite3 *db = pParse->db;
122919  addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
122920  }
122921 }
122922 
122923 /*
122924 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
122925 ** has been completely parsed.
122926 */
122928  Table *pTab = pParse->pNewTable; /* The table being constructed */
122929  sqlite3 *db = pParse->db; /* The database connection */
122930 
122931  if( pTab==0 ) return;
122932  addArgumentToVtab(pParse);
122933  pParse->sArg.z = 0;
122934  if( pTab->nModuleArg<1 ) return;
122935 
122936  /* If the CREATE VIRTUAL TABLE statement is being entered for the
122937  ** first time (in other words if the virtual table is actually being
122938  ** created now instead of just being read out of sqlite_master) then
122939  ** do additional initialization work and store the statement text
122940  ** in the sqlite_master table.
122941  */
122942  if( !db->init.busy ){
122943  char *zStmt;
122944  char *zWhere;
122945  int iDb;
122946  int iReg;
122947  Vdbe *v;
122948 
122949  /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
122950  if( pEnd ){
122951  pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
122952  }
122953  zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
122954 
122955  /* A slot for the record has already been allocated in the
122956  ** SQLITE_MASTER table. We just need to update that slot with all
122957  ** the information we've collected.
122958  **
122959  ** The VM register number pParse->regRowid holds the rowid of an
122960  ** entry in the sqlite_master table tht was created for this vtab
122961  ** by sqlite3StartTable().
122962  */
122963  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122964  sqlite3NestedParse(pParse,
122965  "UPDATE %Q.%s "
122966  "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
122967  "WHERE rowid=#%d",
122968  db->aDb[iDb].zDbSName, SCHEMA_TABLE(iDb),
122969  pTab->zName,
122970  pTab->zName,
122971  zStmt,
122972  pParse->regRowid
122973  );
122974  sqlite3DbFree(db, zStmt);
122975  v = sqlite3GetVdbe(pParse);
122976  sqlite3ChangeCookie(pParse, iDb);
122977 
122979  zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
122980  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
122981 
122982  iReg = ++pParse->nMem;
122983  sqlite3VdbeLoadString(v, iReg, pTab->zName);
122984  sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
122985  }
122986 
122987  /* If we are rereading the sqlite_master table create the in-memory
122988  ** record of the table. The xConnect() method is not called until
122989  ** the first time the virtual table is used in an SQL statement. This
122990  ** allows a schema that contains virtual tables to be loaded before
122991  ** the required virtual table implementations are registered. */
122992  else {
122993  Table *pOld;
122994  Schema *pSchema = pTab->pSchema;
122995  const char *zName = pTab->zName;
122996  assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
122997  pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
122998  if( pOld ){
122999  sqlite3OomFault(db);
123000  assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
123001  return;
123002  }
123003  pParse->pNewTable = 0;
123004  }
123005 }
123006 
123007 /*
123008 ** The parser calls this routine when it sees the first token
123009 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
123010 */
123012  addArgumentToVtab(pParse);
123013  pParse->sArg.z = 0;
123014  pParse->sArg.n = 0;
123015 }
123016 
123017 /*
123018 ** The parser calls this routine for each token after the first token
123019 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
123020 */
123022  Token *pArg = &pParse->sArg;
123023  if( pArg->z==0 ){
123024  pArg->z = p->z;
123025  pArg->n = p->n;
123026  }else{
123027  assert(pArg->z <= p->z);
123028  pArg->n = (int)(&p->z[p->n] - pArg->z);
123029  }
123030 }
123031 
123032 /*
123033 ** Invoke a virtual table constructor (either xCreate or xConnect). The
123034 ** pointer to the function to invoke is passed as the fourth parameter
123035 ** to this procedure.
123036 */
123038  sqlite3 *db,
123039  Table *pTab,
123040  Module *pMod,
123041  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
123042  char **pzErr
123043 ){
123044  VtabCtx sCtx;
123045  VTable *pVTable;
123046  int rc;
123047  const char *const*azArg = (const char *const*)pTab->azModuleArg;
123048  int nArg = pTab->nModuleArg;
123049  char *zErr = 0;
123050  char *zModuleName;
123051  int iDb;
123052  VtabCtx *pCtx;
123053 
123054  /* Check that the virtual-table is not already being initialized */
123055  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
123056  if( pCtx->pTab==pTab ){
123057  *pzErr = sqlite3MPrintf(db,
123058  "vtable constructor called recursively: %s", pTab->zName
123059  );
123060  return SQLITE_LOCKED;
123061  }
123062  }
123063 
123064  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
123065  if( !zModuleName ){
123066  return SQLITE_NOMEM_BKPT;
123067  }
123068 
123069  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
123070  if( !pVTable ){
123071  sqlite3DbFree(db, zModuleName);
123072  return SQLITE_NOMEM_BKPT;
123073  }
123074  pVTable->db = db;
123075  pVTable->pMod = pMod;
123076 
123077  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
123078  pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
123079 
123080  /* Invoke the virtual table constructor */
123081  assert( &db->pVtabCtx );
123082  assert( xConstruct );
123083  sCtx.pTab = pTab;
123084  sCtx.pVTable = pVTable;
123085  sCtx.pPrior = db->pVtabCtx;
123086  sCtx.bDeclared = 0;
123087  db->pVtabCtx = &sCtx;
123088  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
123089  db->pVtabCtx = sCtx.pPrior;
123090  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
123091  assert( sCtx.pTab==pTab );
123092 
123093  if( SQLITE_OK!=rc ){
123094  if( zErr==0 ){
123095  *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
123096  }else {
123097  *pzErr = sqlite3MPrintf(db, "%s", zErr);
123098  sqlite3_free(zErr);
123099  }
123100  sqlite3DbFree(db, pVTable);
123101  }else if( ALWAYS(pVTable->pVtab) ){
123102  /* Justification of ALWAYS(): A correct vtab constructor must allocate
123103  ** the sqlite3_vtab object if successful. */
123104  memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
123105  pVTable->pVtab->pModule = pMod->pModule;
123106  pVTable->nRef = 1;
123107  if( sCtx.bDeclared==0 ){
123108  const char *zFormat = "vtable constructor did not declare schema: %s";
123109  *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
123110  sqlite3VtabUnlock(pVTable);
123111  rc = SQLITE_ERROR;
123112  }else{
123113  int iCol;
123114  u8 oooHidden = 0;
123115  /* If everything went according to plan, link the new VTable structure
123116  ** into the linked list headed by pTab->pVTable. Then loop through the
123117  ** columns of the table to see if any of them contain the token "hidden".
123118  ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
123119  ** the type string. */
123120  pVTable->pNext = pTab->pVTable;
123121  pTab->pVTable = pVTable;
123122 
123123  for(iCol=0; iCol<pTab->nCol; iCol++){
123124  char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
123125  int nType;
123126  int i = 0;
123127  nType = sqlite3Strlen30(zType);
123128  for(i=0; i<nType; i++){
123129  if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
123130  && (i==0 || zType[i-1]==' ')
123131  && (zType[i+6]=='\0' || zType[i+6]==' ')
123132  ){
123133  break;
123134  }
123135  }
123136  if( i<nType ){
123137  int j;
123138  int nDel = 6 + (zType[i+6] ? 1 : 0);
123139  for(j=i; (j+nDel)<=nType; j++){
123140  zType[j] = zType[j+nDel];
123141  }
123142  if( zType[i]=='\0' && i>0 ){
123143  assert(zType[i-1]==' ');
123144  zType[i-1] = '\0';
123145  }
123146  pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
123147  oooHidden = TF_OOOHidden;
123148  }else{
123149  pTab->tabFlags |= oooHidden;
123150  }
123151  }
123152  }
123153  }
123154 
123155  sqlite3DbFree(db, zModuleName);
123156  return rc;
123157 }
123158 
123159 /*
123160 ** This function is invoked by the parser to call the xConnect() method
123161 ** of the virtual table pTab. If an error occurs, an error code is returned
123162 ** and an error left in pParse.
123163 **
123164 ** This call is a no-op if table pTab is not a virtual table.
123165 */
123167  sqlite3 *db = pParse->db;
123168  const char *zMod;
123169  Module *pMod;
123170  int rc;
123171 
123172  assert( pTab );
123173  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
123174  return SQLITE_OK;
123175  }
123176 
123177  /* Locate the required virtual table module */
123178  zMod = pTab->azModuleArg[0];
123179  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
123180 
123181  if( !pMod ){
123182  const char *zModule = pTab->azModuleArg[0];
123183  sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
123184  rc = SQLITE_ERROR;
123185  }else{
123186  char *zErr = 0;
123187  rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
123188  if( rc!=SQLITE_OK ){
123189  sqlite3ErrorMsg(pParse, "%s", zErr);
123190  }
123191  sqlite3DbFree(db, zErr);
123192  }
123193 
123194  return rc;
123195 }
123196 /*
123197 ** Grow the db->aVTrans[] array so that there is room for at least one
123198 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
123199 */
123200 static int growVTrans(sqlite3 *db){
123201  const int ARRAY_INCR = 5;
123202 
123203  /* Grow the sqlite3.aVTrans array if required */
123204  if( (db->nVTrans%ARRAY_INCR)==0 ){
123205  VTable **aVTrans;
123206  int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
123207  aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
123208  if( !aVTrans ){
123209  return SQLITE_NOMEM_BKPT;
123210  }
123211  memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
123212  db->aVTrans = aVTrans;
123213  }
123214 
123215  return SQLITE_OK;
123216 }
123217 
123218 /*
123219 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
123220 ** have already been reserved using growVTrans().
123221 */
123222 static void addToVTrans(sqlite3 *db, VTable *pVTab){
123223  /* Add pVtab to the end of sqlite3.aVTrans */
123224  db->aVTrans[db->nVTrans++] = pVTab;
123225  sqlite3VtabLock(pVTab);
123226 }
123227 
123228 /*
123229 ** This function is invoked by the vdbe to call the xCreate method
123230 ** of the virtual table named zTab in database iDb.
123231 **
123232 ** If an error occurs, *pzErr is set to point to an English language
123233 ** description of the error and an SQLITE_XXX error code is returned.
123234 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
123235 */
123236 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
123237  int rc = SQLITE_OK;
123238  Table *pTab;
123239  Module *pMod;
123240  const char *zMod;
123241 
123242  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
123243  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
123244 
123245  /* Locate the required virtual table module */
123246  zMod = pTab->azModuleArg[0];
123247  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
123248 
123249  /* If the module has been registered and includes a Create method,
123250  ** invoke it now. If the module has not been registered, return an
123251  ** error. Otherwise, do nothing.
123252  */
123253  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
123254  *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
123255  rc = SQLITE_ERROR;
123256  }else{
123257  rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
123258  }
123259 
123260  /* Justification of ALWAYS(): The xConstructor method is required to
123261  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
123262  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
123263  rc = growVTrans(db);
123264  if( rc==SQLITE_OK ){
123265  addToVTrans(db, sqlite3GetVTable(db, pTab));
123266  }
123267  }
123268 
123269  return rc;
123270 }
123271 
123272 /*
123273 ** This function is used to set the schema of a virtual table. It is only
123274 ** valid to call this function from within the xCreate() or xConnect() of a
123275 ** virtual table module.
123276 */
123277 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
123278  VtabCtx *pCtx;
123279  Parse *pParse;
123280  int rc = SQLITE_OK;
123281  Table *pTab;
123282  char *zErr = 0;
123283 
123284 #ifdef SQLITE_ENABLE_API_ARMOR
123285  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
123286  return SQLITE_MISUSE_BKPT;
123287  }
123288 #endif
123289  sqlite3_mutex_enter(db->mutex);
123290  pCtx = db->pVtabCtx;
123291  if( !pCtx || pCtx->bDeclared ){
123293  sqlite3_mutex_leave(db->mutex);
123294  return SQLITE_MISUSE_BKPT;
123295  }
123296  pTab = pCtx->pTab;
123297  assert( (pTab->tabFlags & TF_Virtual)!=0 );
123298 
123299  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
123300  if( pParse==0 ){
123301  rc = SQLITE_NOMEM_BKPT;
123302  }else{
123303  pParse->declareVtab = 1;
123304  pParse->db = db;
123305  pParse->nQueryLoop = 1;
123306 
123307  if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
123308  && pParse->pNewTable
123309  && !db->mallocFailed
123310  && !pParse->pNewTable->pSelect
123311  && (pParse->pNewTable->tabFlags & TF_Virtual)==0
123312  ){
123313  if( !pTab->aCol ){
123314  Table *pNew = pParse->pNewTable;
123315  Index *pIdx;
123316  pTab->aCol = pNew->aCol;
123317  pTab->nCol = pNew->nCol;
123318  pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
123319  pNew->nCol = 0;
123320  pNew->aCol = 0;
123321  assert( pTab->pIndex==0 );
123322  if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
123323  rc = SQLITE_ERROR;
123324  }
123325  pIdx = pNew->pIndex;
123326  if( pIdx ){
123327  assert( pIdx->pNext==0 );
123328  pTab->pIndex = pIdx;
123329  pNew->pIndex = 0;
123330  pIdx->pTable = pTab;
123331  }
123332  }
123333  pCtx->bDeclared = 1;
123334  }else{
123335  sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
123336  sqlite3DbFree(db, zErr);
123337  rc = SQLITE_ERROR;
123338  }
123339  pParse->declareVtab = 0;
123340 
123341  if( pParse->pVdbe ){
123342  sqlite3VdbeFinalize(pParse->pVdbe);
123343  }
123344  sqlite3DeleteTable(db, pParse->pNewTable);
123345  sqlite3ParserReset(pParse);
123346  sqlite3StackFree(db, pParse);
123347  }
123348 
123349  assert( (rc&0xff)==rc );
123350  rc = sqlite3ApiExit(db, rc);
123351  sqlite3_mutex_leave(db->mutex);
123352  return rc;
123353 }
123354 
123355 /*
123356 ** This function is invoked by the vdbe to call the xDestroy method
123357 ** of the virtual table named zTab in database iDb. This occurs
123358 ** when a DROP TABLE is mentioned.
123359 **
123360 ** This call is a no-op if zTab is not a virtual table.
123361 */
123362 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
123363  int rc = SQLITE_OK;
123364  Table *pTab;
123365 
123366  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
123367  if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
123368  VTable *p;
123369  int (*xDestroy)(sqlite3_vtab *);
123370  for(p=pTab->pVTable; p; p=p->pNext){
123371  assert( p->pVtab );
123372  if( p->pVtab->nRef>0 ){
123373  return SQLITE_LOCKED;
123374  }
123375  }
123376  p = vtabDisconnectAll(db, pTab);
123377  xDestroy = p->pMod->pModule->xDestroy;
123378  assert( xDestroy!=0 ); /* Checked before the virtual table is created */
123379  rc = xDestroy(p->pVtab);
123380  /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
123381  if( rc==SQLITE_OK ){
123382  assert( pTab->pVTable==p && p->pNext==0 );
123383  p->pVtab = 0;
123384  pTab->pVTable = 0;
123385  sqlite3VtabUnlock(p);
123386  }
123387  }
123388 
123389  return rc;
123390 }
123391 
123392 /*
123393 ** This function invokes either the xRollback or xCommit method
123394 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
123395 ** called is identified by the second argument, "offset", which is
123396 ** the offset of the method to call in the sqlite3_module structure.
123397 **
123398 ** The array is cleared after invoking the callbacks.
123399 */
123400 static void callFinaliser(sqlite3 *db, int offset){
123401  int i;
123402  if( db->aVTrans ){
123403  VTable **aVTrans = db->aVTrans;
123404  db->aVTrans = 0;
123405  for(i=0; i<db->nVTrans; i++){
123406  VTable *pVTab = aVTrans[i];
123407  sqlite3_vtab *p = pVTab->pVtab;
123408  if( p ){
123409  int (*x)(sqlite3_vtab *);
123410  x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
123411  if( x ) x(p);
123412  }
123413  pVTab->iSavepoint = 0;
123414  sqlite3VtabUnlock(pVTab);
123415  }
123416  sqlite3DbFree(db, aVTrans);
123417  db->nVTrans = 0;
123418  }
123419 }
123420 
123421 /*
123422 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
123423 ** array. Return the error code for the first error that occurs, or
123424 ** SQLITE_OK if all xSync operations are successful.
123425 **
123426 ** If an error message is available, leave it in p->zErrMsg.
123427 */
123428 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
123429  int i;
123430  int rc = SQLITE_OK;
123431  VTable **aVTrans = db->aVTrans;
123432 
123433  db->aVTrans = 0;
123434  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
123435  int (*x)(sqlite3_vtab *);
123436  sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
123437  if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
123438  rc = x(pVtab);
123439  sqlite3VtabImportErrmsg(p, pVtab);
123440  }
123441  }
123442  db->aVTrans = aVTrans;
123443  return rc;
123444 }
123445 
123446 /*
123447 ** Invoke the xRollback method of all virtual tables in the
123448 ** sqlite3.aVTrans array. Then clear the array itself.
123449 */
123451  callFinaliser(db, offsetof(sqlite3_module,xRollback));
123452  return SQLITE_OK;
123453 }
123454 
123455 /*
123456 ** Invoke the xCommit method of all virtual tables in the
123457 ** sqlite3.aVTrans array. Then clear the array itself.
123458 */
123460  callFinaliser(db, offsetof(sqlite3_module,xCommit));
123461  return SQLITE_OK;
123462 }
123463 
123464 /*
123465 ** If the virtual table pVtab supports the transaction interface
123466 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
123467 ** not currently open, invoke the xBegin method now.
123468 **
123469 ** If the xBegin call is successful, place the sqlite3_vtab pointer
123470 ** in the sqlite3.aVTrans array.
123471 */
123472 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
123473  int rc = SQLITE_OK;
123474  const sqlite3_module *pModule;
123475 
123476  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
123477  ** than zero, then this function is being called from within a
123478  ** virtual module xSync() callback. It is illegal to write to
123479  ** virtual module tables in this case, so return SQLITE_LOCKED.
123480  */
123481  if( sqlite3VtabInSync(db) ){
123482  return SQLITE_LOCKED;
123483  }
123484  if( !pVTab ){
123485  return SQLITE_OK;
123486  }
123487  pModule = pVTab->pVtab->pModule;
123488 
123489  if( pModule->xBegin ){
123490  int i;
123491 
123492  /* If pVtab is already in the aVTrans array, return early */
123493  for(i=0; i<db->nVTrans; i++){
123494  if( db->aVTrans[i]==pVTab ){
123495  return SQLITE_OK;
123496  }
123497  }
123498 
123499  /* Invoke the xBegin method. If successful, add the vtab to the
123500  ** sqlite3.aVTrans[] array. */
123501  rc = growVTrans(db);
123502  if( rc==SQLITE_OK ){
123503  rc = pModule->xBegin(pVTab->pVtab);
123504  if( rc==SQLITE_OK ){
123505  int iSvpt = db->nStatement + db->nSavepoint;
123506  addToVTrans(db, pVTab);
123507  if( iSvpt && pModule->xSavepoint ){
123508  pVTab->iSavepoint = iSvpt;
123509  rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
123510  }
123511  }
123512  }
123513  }
123514  return rc;
123515 }
123516 
123517 /*
123518 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
123519 ** virtual tables that currently have an open transaction. Pass iSavepoint
123520 ** as the second argument to the virtual table method invoked.
123521 **
123522 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
123523 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
123524 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
123525 ** an open transaction is invoked.
123526 **
123527 ** If any virtual table method returns an error code other than SQLITE_OK,
123528 ** processing is abandoned and the error returned to the caller of this
123529 ** function immediately. If all calls to virtual table methods are successful,
123530 ** SQLITE_OK is returned.
123531 */
123532 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
123533  int rc = SQLITE_OK;
123534 
123535  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
123536  assert( iSavepoint>=-1 );
123537  if( db->aVTrans ){
123538  int i;
123539  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
123540  VTable *pVTab = db->aVTrans[i];
123541  const sqlite3_module *pMod = pVTab->pMod->pModule;
123542  if( pVTab->pVtab && pMod->iVersion>=2 ){
123543  int (*xMethod)(sqlite3_vtab *, int);
123544  switch( op ){
123545  case SAVEPOINT_BEGIN:
123546  xMethod = pMod->xSavepoint;
123547  pVTab->iSavepoint = iSavepoint+1;
123548  break;
123549  case SAVEPOINT_ROLLBACK:
123550  xMethod = pMod->xRollbackTo;
123551  break;
123552  default:
123553  xMethod = pMod->xRelease;
123554  break;
123555  }
123556  if( xMethod && pVTab->iSavepoint>iSavepoint ){
123557  rc = xMethod(pVTab->pVtab, iSavepoint);
123558  }
123559  }
123560  }
123561  }
123562  return rc;
123563 }
123564 
123565 /*
123566 ** The first parameter (pDef) is a function implementation. The
123567 ** second parameter (pExpr) is the first argument to this function.
123568 ** If pExpr is a column in a virtual table, then let the virtual
123569 ** table implementation have an opportunity to overload the function.
123570 **
123571 ** This routine is used to allow virtual table implementations to
123572 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
123573 **
123574 ** Return either the pDef argument (indicating no change) or a
123575 ** new FuncDef structure that is marked as ephemeral using the
123576 ** SQLITE_FUNC_EPHEM flag.
123577 */
123579  sqlite3 *db, /* Database connection for reporting malloc problems */
123580  FuncDef *pDef, /* Function to possibly overload */
123581  int nArg, /* Number of arguments to the function */
123582  Expr *pExpr /* First argument to the function */
123583 ){
123584  Table *pTab;
123585  sqlite3_vtab *pVtab;
123586  sqlite3_module *pMod;
123587  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
123588  void *pArg = 0;
123589  FuncDef *pNew;
123590  int rc = 0;
123591  char *zLowerName;
123592  unsigned char *z;
123593 
123594 
123595  /* Check to see the left operand is a column in a virtual table */
123596  if( NEVER(pExpr==0) ) return pDef;
123597  if( pExpr->op!=TK_COLUMN ) return pDef;
123598  pTab = pExpr->pTab;
123599  if( NEVER(pTab==0) ) return pDef;
123600  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
123601  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
123602  assert( pVtab!=0 );
123603  assert( pVtab->pModule!=0 );
123604  pMod = (sqlite3_module *)pVtab->pModule;
123605  if( pMod->xFindFunction==0 ) return pDef;
123606 
123607  /* Call the xFindFunction method on the virtual table implementation
123608  ** to see if the implementation wants to overload this function
123609  */
123610  zLowerName = sqlite3DbStrDup(db, pDef->zName);
123611  if( zLowerName ){
123612  for(z=(unsigned char*)zLowerName; *z; z++){
123613  *z = sqlite3UpperToLower[*z];
123614  }
123615  rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
123616  sqlite3DbFree(db, zLowerName);
123617  }
123618  if( rc==0 ){
123619  return pDef;
123620  }
123621 
123622  /* Create a new ephemeral function definition for the overloaded
123623  ** function */
123624  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
123625  + sqlite3Strlen30(pDef->zName) + 1);
123626  if( pNew==0 ){
123627  return pDef;
123628  }
123629  *pNew = *pDef;
123630  pNew->zName = (const char*)&pNew[1];
123631  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
123632  pNew->xSFunc = xSFunc;
123633  pNew->pUserData = pArg;
123634  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
123635  return pNew;
123636 }
123637 
123638 /*
123639 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
123640 ** array so that an OP_VBegin will get generated for it. Add pTab to the
123641 ** array if it is missing. If pTab is already in the array, this routine
123642 ** is a no-op.
123643 */
123645  Parse *pToplevel = sqlite3ParseToplevel(pParse);
123646  int i, n;
123647  Table **apVtabLock;
123648 
123649  assert( IsVirtual(pTab) );
123650  for(i=0; i<pToplevel->nVtabLock; i++){
123651  if( pTab==pToplevel->apVtabLock[i] ) return;
123652  }
123653  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
123654  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
123655  if( apVtabLock ){
123656  pToplevel->apVtabLock = apVtabLock;
123657  pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
123658  }else{
123659  sqlite3OomFault(pToplevel->db);
123660  }
123661 }
123662 
123663 /*
123664 ** Check to see if virtual table module pMod can be have an eponymous
123665 ** virtual table instance. If it can, create one if one does not already
123666 ** exist. Return non-zero if the eponymous virtual table instance exists
123667 ** when this routine returns, and return zero if it does not exist.
123668 **
123669 ** An eponymous virtual table instance is one that is named after its
123670 ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
123671 ** statement in order to come into existance. Eponymous virtual table
123672 ** instances always exist. They cannot be DROP-ed.
123673 **
123674 ** Any virtual table module for which xConnect and xCreate are the same
123675 ** method can have an eponymous virtual table instance.
123676 */
123678  const sqlite3_module *pModule = pMod->pModule;
123679  Table *pTab;
123680  char *zErr = 0;
123681  int rc;
123682  sqlite3 *db = pParse->db;
123683  if( pMod->pEpoTab ) return 1;
123684  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
123685  pTab = sqlite3DbMallocZero(db, sizeof(Table));
123686  if( pTab==0 ) return 0;
123687  pTab->zName = sqlite3DbStrDup(db, pMod->zName);
123688  if( pTab->zName==0 ){
123689  sqlite3DbFree(db, pTab);
123690  return 0;
123691  }
123692  pMod->pEpoTab = pTab;
123693  pTab->nRef = 1;
123694  pTab->pSchema = db->aDb[0].pSchema;
123695  pTab->tabFlags |= TF_Virtual;
123696  pTab->nModuleArg = 0;
123697  pTab->iPKey = -1;
123698  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
123699  addModuleArgument(db, pTab, 0);
123700  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
123701  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
123702  if( rc ){
123703  sqlite3ErrorMsg(pParse, "%s", zErr);
123704  sqlite3DbFree(db, zErr);
123705  sqlite3VtabEponymousTableClear(db, pMod);
123706  return 0;
123707  }
123708  return 1;
123709 }
123710 
123711 /*
123712 ** Erase the eponymous virtual table instance associated with
123713 ** virtual table module pMod, if it exists.
123714 */
123716  Table *pTab = pMod->pEpoTab;
123717  if( pTab!=0 ){
123718  /* Mark the table as Ephemeral prior to deleting it, so that the
123719  ** sqlite3DeleteTable() routine will know that it is not stored in
123720  ** the schema. */
123721  pTab->tabFlags |= TF_Ephemeral;
123722  sqlite3DeleteTable(db, pTab);
123723  pMod->pEpoTab = 0;
123724  }
123725 }
123726 
123727 /*
123728 ** Return the ON CONFLICT resolution mode in effect for the virtual
123729 ** table update operation currently in progress.
123730 **
123731 ** The results of this routine are undefined unless it is called from
123732 ** within an xUpdate method.
123733 */
123735  static const unsigned char aMap[] = {
123737  };
123738 #ifdef SQLITE_ENABLE_API_ARMOR
123739  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
123740 #endif
123741  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
123742  assert( OE_Ignore==4 && OE_Replace==5 );
123743  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
123744  return (int)aMap[db->vtabOnConflict-1];
123745 }
123746 
123747 /*
123748 ** Call from within the xCreate() or xConnect() methods to provide
123749 ** the SQLite core with additional information about the behavior
123750 ** of the virtual table being implemented.
123751 */
123752 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
123753  va_list ap;
123754  int rc = SQLITE_OK;
123755 
123756 #ifdef SQLITE_ENABLE_API_ARMOR
123757  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
123758 #endif
123759  sqlite3_mutex_enter(db->mutex);
123760  va_start(ap, op);
123761  switch( op ){
123763  VtabCtx *p = db->pVtabCtx;
123764  if( !p ){
123765  rc = SQLITE_MISUSE_BKPT;
123766  }else{
123767  assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
123768  p->pVTable->bConstraint = (u8)va_arg(ap, int);
123769  }
123770  break;
123771  }
123772  default:
123773  rc = SQLITE_MISUSE_BKPT;
123774  break;
123775  }
123776  va_end(ap);
123777 
123778  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
123779  sqlite3_mutex_leave(db->mutex);
123780  return rc;
123781 }
123782 
123783 #endif /* SQLITE_OMIT_VIRTUALTABLE */
123784 
123785 /************** End of vtab.c ************************************************/
123786 /************** Begin file wherecode.c ***************************************/
123787 /*
123788 ** 2015-06-06
123789 **
123790 ** The author disclaims copyright to this source code. In place of
123791 ** a legal notice, here is a blessing:
123792 **
123793 ** May you do good and not evil.
123794 ** May you find forgiveness for yourself and forgive others.
123795 ** May you share freely, never taking more than you give.
123796 **
123797 *************************************************************************
123798 ** This module contains C code that generates VDBE code used to process
123799 ** the WHERE clause of SQL statements.
123800 **
123801 ** This file was split off from where.c on 2015-06-06 in order to reduce the
123802 ** size of where.c and make it easier to edit. This file contains the routines
123803 ** that actually generate the bulk of the WHERE loop code. The original where.c
123804 ** file retains the code that does query planning and analysis.
123805 */
123806 /* #include "sqliteInt.h" */
123807 /************** Include whereInt.h in the middle of wherecode.c **************/
123808 /************** Begin file whereInt.h ****************************************/
123809 /*
123810 ** 2013-11-12
123811 **
123812 ** The author disclaims copyright to this source code. In place of
123813 ** a legal notice, here is a blessing:
123814 **
123815 ** May you do good and not evil.
123816 ** May you find forgiveness for yourself and forgive others.
123817 ** May you share freely, never taking more than you give.
123818 **
123819 *************************************************************************
123820 **
123821 ** This file contains structure and macro definitions for the query
123822 ** planner logic in "where.c". These definitions are broken out into
123823 ** a separate source file for easier editing.
123824 */
123825 
123826 /*
123827 ** Trace output macros
123828 */
123829 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
123830 /***/ int sqlite3WhereTrace;
123831 #endif
123832 #if defined(SQLITE_DEBUG) \
123833  && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
123834 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
123835 # define WHERETRACE_ENABLED 1
123836 #else
123837 # define WHERETRACE(K,X)
123838 #endif
123839 
123840 /* Forward references
123841 */
123842 typedef struct WhereClause WhereClause;
123844 typedef struct WhereOrInfo WhereOrInfo;
123846 typedef struct WhereLevel WhereLevel;
123847 typedef struct WhereLoop WhereLoop;
123848 typedef struct WherePath WherePath;
123849 typedef struct WhereTerm WhereTerm;
123851 typedef struct WhereScan WhereScan;
123852 typedef struct WhereOrCost WhereOrCost;
123853 typedef struct WhereOrSet WhereOrSet;
123854 
123855 /*
123856 ** This object contains information needed to implement a single nested
123857 ** loop in WHERE clause.
123858 **
123859 ** Contrast this object with WhereLoop. This object describes the
123860 ** implementation of the loop. WhereLoop describes the algorithm.
123861 ** This object contains a pointer to the WhereLoop algorithm as one of
123862 ** its elements.
123863 **
123864 ** The WhereInfo object contains a single instance of this object for
123865 ** each term in the FROM clause (which is to say, for each of the
123866 ** nested loops as implemented). The order of WhereLevel objects determines
123867 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
123868 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
123869 */
123870 struct WhereLevel {
123871  int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
123872  int iTabCur; /* The VDBE cursor used to access the table */
123873  int iIdxCur; /* The VDBE cursor used to access pIdx */
123874  int addrBrk; /* Jump here to break out of the loop */
123875  int addrNxt; /* Jump here to start the next IN combination */
123876  int addrSkip; /* Jump here for next iteration of skip-scan */
123877  int addrCont; /* Jump here to continue with the next loop cycle */
123878  int addrFirst; /* First instruction of interior of the loop */
123879  int addrBody; /* Beginning of the body of this loop */
123880 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123881  u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
123882  int addrLikeRep; /* LIKE range processing address */
123883 #endif
123884  u8 iFrom; /* Which entry in the FROM clause */
123885  u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
123886  int p1, p2; /* Operands of the opcode used to ends the loop */
123887  union { /* Information that depends on pWLoop->wsFlags */
123888  struct {
123889  int nIn; /* Number of entries in aInLoop[] */
123890  struct InLoop {
123891  int iCur; /* The VDBE cursor used by this IN operator */
123892  int addrInTop; /* Top of the IN loop */
123893  u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
123894  } *aInLoop; /* Information about each nested IN operator */
123895  } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
123896  Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
123897  } u;
123898  struct WhereLoop *pWLoop; /* The selected WhereLoop object */
123899  Bitmask notReady; /* FROM entries not usable at this level */
123900 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123901  int addrVisit; /* Address at which row is visited */
123902 #endif
123903 };
123904 
123905 /*
123906 ** Each instance of this object represents an algorithm for evaluating one
123907 ** term of a join. Every term of the FROM clause will have at least
123908 ** one corresponding WhereLoop object (unless INDEXED BY constraints
123909 ** prevent a query solution - which is an error) and many terms of the
123910 ** FROM clause will have multiple WhereLoop objects, each describing a
123911 ** potential way of implementing that FROM-clause term, together with
123912 ** dependencies and cost estimates for using the chosen algorithm.
123913 **
123914 ** Query planning consists of building up a collection of these WhereLoop
123915 ** objects, then computing a particular sequence of WhereLoop objects, with
123916 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
123917 ** and that minimize the overall cost.
123918 */
123919 struct WhereLoop {
123920  Bitmask prereq; /* Bitmask of other loops that must run first */
123921  Bitmask maskSelf; /* Bitmask identifying table iTab */
123922 #ifdef SQLITE_DEBUG
123923  char cId; /* Symbolic ID of this loop for debugging use */
123924 #endif
123925  u8 iTab; /* Position in FROM clause of table for this loop */
123926  u8 iSortIdx; /* Sorting index number. 0==None */
123927  LogEst rSetup; /* One-time setup cost (ex: create transient index) */
123928  LogEst rRun; /* Cost of running each loop */
123929  LogEst nOut; /* Estimated number of output rows */
123930  union {
123931  struct { /* Information for internal btree tables */
123932  u16 nEq; /* Number of equality constraints */
123933  u16 nBtm; /* Size of BTM vector */
123934  u16 nTop; /* Size of TOP vector */
123935  Index *pIndex; /* Index used, or NULL */
123936  } btree;
123937  struct { /* Information for virtual tables */
123938  int idxNum; /* Index number */
123939  u8 needFree; /* True if sqlite3_free(idxStr) is needed */
123940  i8 isOrdered; /* True if satisfies ORDER BY */
123941  u16 omitMask; /* Terms that may be omitted */
123942  char *idxStr; /* Index identifier string */
123943  } vtab;
123944  } u;
123945  u32 wsFlags; /* WHERE_* flags describing the plan */
123946  u16 nLTerm; /* Number of entries in aLTerm[] */
123947  u16 nSkip; /* Number of NULL aLTerm[] entries */
123948  /**** whereLoopXfer() copies fields above ***********************/
123949 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
123950  u16 nLSlot; /* Number of slots allocated for aLTerm[] */
123951  WhereTerm **aLTerm; /* WhereTerms used */
123952  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
123953  WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
123954 };
123955 
123956 /* This object holds the prerequisites and the cost of running a
123957 ** subquery on one operand of an OR operator in the WHERE clause.
123958 ** See WhereOrSet for additional information
123959 */
123961  Bitmask prereq; /* Prerequisites */
123962  LogEst rRun; /* Cost of running this subquery */
123963  LogEst nOut; /* Number of outputs for this subquery */
123964 };
123965 
123966 /* The WhereOrSet object holds a set of possible WhereOrCosts that
123967 ** correspond to the subquery(s) of OR-clause processing. Only the
123968 ** best N_OR_COST elements are retained.
123969 */
123970 #define N_OR_COST 3
123971 struct WhereOrSet {
123972  u16 n; /* Number of valid a[] entries */
123973  WhereOrCost a[N_OR_COST]; /* Set of best costs */
123974 };
123975 
123976 /*
123977 ** Each instance of this object holds a sequence of WhereLoop objects
123978 ** that implement some or all of a query plan.
123979 **
123980 ** Think of each WhereLoop object as a node in a graph with arcs
123981 ** showing dependencies and costs for travelling between nodes. (That is
123982 ** not a completely accurate description because WhereLoop costs are a
123983 ** vector, not a scalar, and because dependencies are many-to-one, not
123984 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
123985 ** Then a WherePath object is a path through the graph that visits some
123986 ** or all of the WhereLoop objects once.
123987 **
123988 ** The "solver" works by creating the N best WherePath objects of length
123989 ** 1. Then using those as a basis to compute the N best WherePath objects
123990 ** of length 2. And so forth until the length of WherePaths equals the
123991 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
123992 ** at the end is the chosen query plan.
123993 */
123994 struct WherePath {
123995  Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
123996  Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
123997  LogEst nRow; /* Estimated number of rows generated by this path */
123998  LogEst rCost; /* Total cost of this path */
123999  LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
124000  i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
124001  WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
124002 };
124003 
124004 /*
124005 ** The query generator uses an array of instances of this structure to
124006 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
124007 ** clause subexpression is separated from the others by AND operators,
124008 ** usually, or sometimes subexpressions separated by OR.
124009 **
124010 ** All WhereTerms are collected into a single WhereClause structure.
124011 ** The following identity holds:
124012 **
124013 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
124014 **
124015 ** When a term is of the form:
124016 **
124017 ** X <op> <expr>
124018 **
124019 ** where X is a column name and <op> is one of certain operators,
124020 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
124021 ** cursor number and column number for X. WhereTerm.eOperator records
124022 ** the <op> using a bitmask encoding defined by WO_xxx below. The
124023 ** use of a bitmask encoding for the operator allows us to search
124024 ** quickly for terms that match any of several different operators.
124025 **
124026 ** A WhereTerm might also be two or more subterms connected by OR:
124027 **
124028 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
124029 **
124030 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
124031 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
124032 ** is collected about the OR clause.
124033 **
124034 ** If a term in the WHERE clause does not match either of the two previous
124035 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
124036 ** to the original subexpression content and wtFlags is set up appropriately
124037 ** but no other fields in the WhereTerm object are meaningful.
124038 **
124039 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
124040 ** but they do so indirectly. A single WhereMaskSet structure translates
124041 ** cursor number into bits and the translated bit is stored in the prereq
124042 ** fields. The translation is used in order to maximize the number of
124043 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
124044 ** spread out over the non-negative integers. For example, the cursor
124045 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
124046 ** translates these sparse cursor numbers into consecutive integers
124047 ** beginning with 0 in order to make the best possible use of the available
124048 ** bits in the Bitmask. So, in the example above, the cursor numbers
124049 ** would be mapped into integers 0 through 7.
124050 **
124051 ** The number of terms in a join is limited by the number of bits
124052 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
124053 ** is only able to process joins with 64 or fewer tables.
124054 */
124055 struct WhereTerm {
124056  Expr *pExpr; /* Pointer to the subexpression that is this term */
124057  WhereClause *pWC; /* The clause this term is part of */
124058  LogEst truthProb; /* Probability of truth for this expression */
124059  u16 wtFlags; /* TERM_xxx bit flags. See below */
124060  u16 eOperator; /* A WO_xx value describing <op> */
124061  u8 nChild; /* Number of children that must disable us */
124062  u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
124063  int iParent; /* Disable pWC->a[iParent] when this term disabled */
124064  int leftCursor; /* Cursor number of X in "X <op> <expr>" */
124065  int iField; /* Field in (?,?,?) IN (SELECT...) vector */
124066  union {
124067  int leftColumn; /* Column number of X in "X <op> <expr>" */
124068  WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
124069  WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
124070  } u;
124071  Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
124072  Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
124073 };
124074 
124075 /*
124076 ** Allowed values of WhereTerm.wtFlags
124077 */
124078 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
124079 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
124080 #define TERM_CODED 0x04 /* This term is already coded */
124081 #define TERM_COPIED 0x08 /* Has a child */
124082 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
124083 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
124084 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
124085 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
124086 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
124087 #else
124088 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
124089 #endif
124090 #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
124091 #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
124092 #define TERM_LIKE 0x400 /* The original LIKE operator */
124093 #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
124094 
124095 /*
124096 ** An instance of the WhereScan object is used as an iterator for locating
124097 ** terms in the WHERE clause that are useful to the query planner.
124098 */
124099 struct WhereScan {
124100  WhereClause *pOrigWC; /* Original, innermost WhereClause */
124101  WhereClause *pWC; /* WhereClause currently being scanned */
124102  const char *zCollName; /* Required collating sequence, if not NULL */
124103  Expr *pIdxExpr; /* Search for this index expression */
124104  char idxaff; /* Must match this affinity, if zCollName!=NULL */
124105  unsigned char nEquiv; /* Number of entries in aEquiv[] */
124106  unsigned char iEquiv; /* Next unused slot in aEquiv[] */
124107  u32 opMask; /* Acceptable operators */
124108  int k; /* Resume scanning at this->pWC->a[this->k] */
124109  int aiCur[11]; /* Cursors in the equivalence class */
124110  i16 aiColumn[11]; /* Corresponding column number in the eq-class */
124111 };
124112 
124113 /*
124114 ** An instance of the following structure holds all information about a
124115 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
124116 **
124117 ** Explanation of pOuter: For a WHERE clause of the form
124118 **
124119 ** a AND ((b AND c) OR (d AND e)) AND f
124120 **
124121 ** There are separate WhereClause objects for the whole clause and for
124122 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
124123 ** subclauses points to the WhereClause object for the whole clause.
124124 */
124126  WhereInfo *pWInfo; /* WHERE clause processing context */
124127  WhereClause *pOuter; /* Outer conjunction */
124128  u8 op; /* Split operator. TK_AND or TK_OR */
124129  int nTerm; /* Number of terms */
124130  int nSlot; /* Number of entries in a[] */
124131  WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
124132 #if defined(SQLITE_SMALL_STACK)
124133  WhereTerm aStatic[1]; /* Initial static space for a[] */
124134 #else
124135  WhereTerm aStatic[8]; /* Initial static space for a[] */
124136 #endif
124137 };
124138 
124139 /*
124140 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
124141 ** a dynamically allocated instance of the following structure.
124142 */
124144  WhereClause wc; /* Decomposition into subterms */
124145  Bitmask indexable; /* Bitmask of all indexable tables in the clause */
124146 };
124147 
124148 /*
124149 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
124150 ** a dynamically allocated instance of the following structure.
124151 */
124153  WhereClause wc; /* The subexpression broken out */
124154 };
124155 
124156 /*
124157 ** An instance of the following structure keeps track of a mapping
124158 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
124159 **
124160 ** The VDBE cursor numbers are small integers contained in
124161 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
124162 ** clause, the cursor numbers might not begin with 0 and they might
124163 ** contain gaps in the numbering sequence. But we want to make maximum
124164 ** use of the bits in our bitmasks. This structure provides a mapping
124165 ** from the sparse cursor numbers into consecutive integers beginning
124166 ** with 0.
124167 **
124168 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
124169 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
124170 **
124171 ** For example, if the WHERE clause expression used these VDBE
124172 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
124173 ** would map those cursor numbers into bits 0 through 5.
124174 **
124175 ** Note that the mapping is not necessarily ordered. In the example
124176 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
124177 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
124178 ** does not really matter. What is important is that sparse cursor
124179 ** numbers all get mapped into bit numbers that begin with 0 and contain
124180 ** no gaps.
124181 */
124183  int n; /* Number of assigned cursor values */
124184  int ix[BMS]; /* Cursor assigned to each bit */
124185 };
124186 
124187 /*
124188 ** Initialize a WhereMaskSet object
124189 */
124190 #define initMaskSet(P) (P)->n=0
124191 
124192 /*
124193 ** This object is a convenience wrapper holding all information needed
124194 ** to construct WhereLoop objects for a particular query.
124195 */
124197  WhereInfo *pWInfo; /* Information about this WHERE */
124198  WhereClause *pWC; /* WHERE clause terms */
124199  ExprList *pOrderBy; /* ORDER BY clause */
124200  WhereLoop *pNew; /* Template WhereLoop */
124201  WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
124202 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
124203  UnpackedRecord *pRec; /* Probe for stat4 (if required) */
124204  int nRecValid; /* Number of valid fields currently in pRec */
124205 #endif
124206 };
124207 
124208 /*
124209 ** The WHERE clause processing routine has two halves. The
124210 ** first part does the start of the WHERE loop and the second
124211 ** half does the tail of the WHERE loop. An instance of
124212 ** this structure is returned by the first half and passed
124213 ** into the second half to give some continuity.
124214 **
124215 ** An instance of this object holds the complete state of the query
124216 ** planner.
124217 */
124218 struct WhereInfo {
124219  Parse *pParse; /* Parsing and code generating context */
124220  SrcList *pTabList; /* List of tables in the join */
124221  ExprList *pOrderBy; /* The ORDER BY clause or NULL */
124222  ExprList *pDistinctSet; /* DISTINCT over all these values */
124223  LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
124224  int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
124225  int iContinue; /* Jump here to continue with next record */
124226  int iBreak; /* Jump here to break out of the loop */
124227  int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
124228  u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
124229  u8 nLevel; /* Number of nested loop */
124230  i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
124231  u8 sorted; /* True if really sorted (not just grouped) */
124232  u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
124233  u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
124234  u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
124235  u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
124236  int iTop; /* The very beginning of the WHERE loop */
124237  WhereLoop *pLoops; /* List of all WhereLoop objects */
124238  Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
124239  LogEst nRowOut; /* Estimated number of output rows */
124240  WhereClause sWC; /* Decomposition of the WHERE clause */
124241  WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
124242  WhereLevel a[1]; /* Information about each nest loop in WHERE */
124243 };
124244 
124245 /*
124246 ** Private interfaces - callable only by other where.c routines.
124247 **
124248 ** where.c:
124249 */
124251 #ifdef WHERETRACE_ENABLED
124252 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
124253 #endif
124255  WhereClause *pWC, /* The WHERE clause to be searched */
124256  int iCur, /* Cursor number of LHS */
124257  int iColumn, /* Column number of LHS */
124258  Bitmask notReady, /* RHS must not overlap with this mask */
124259  u32 op, /* Mask of WO_xx values describing operator */
124260  Index *pIdx /* Must be compatible with this index, if not NULL */
124261 );
124262 
124263 /* wherecode.c: */
124264 #ifndef SQLITE_OMIT_EXPLAIN
124266  Parse *pParse, /* Parse context */
124267  SrcList *pTabList, /* Table list this loop refers to */
124268  WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
124269  int iLevel, /* Value for "level" column of output */
124270  int iFrom, /* Value for "from" column of output */
124271  u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
124272 );
124273 #else
124274 # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
124275 #endif /* SQLITE_OMIT_EXPLAIN */
124276 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
124278  Vdbe *v, /* Vdbe to add scanstatus entry to */
124279  SrcList *pSrclist, /* FROM clause pLvl reads data from */
124280  WhereLevel *pLvl, /* Level to add scanstatus() entry for */
124281  int addrExplain /* Address of OP_Explain (or 0) */
124282 );
124283 #else
124284 # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
124285 #endif
124287  WhereInfo *pWInfo, /* Complete information about the WHERE clause */
124288  int iLevel, /* Which level of pWInfo->a[] should be coded */
124289  Bitmask notReady /* Which tables are currently available */
124290 );
124291 
124292 /* whereexpr.c: */
124299 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
124300 
124301 
124302 
124303 
124304 
124305 /*
124306 ** Bitmasks for the operators on WhereTerm objects. These are all
124307 ** operators that are of interest to the query planner. An
124308 ** OR-ed combination of these values can be used when searching for
124309 ** particular WhereTerms within a WhereClause.
124310 **
124311 ** Value constraints:
124312 ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
124313 ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
124314 ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
124315 ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
124316 ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
124317 ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
124318 */
124319 #define WO_IN 0x0001
124320 #define WO_EQ 0x0002
124321 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
124322 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
124323 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
124324 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
124325 #define WO_MATCH 0x0040
124326 #define WO_IS 0x0080
124327 #define WO_ISNULL 0x0100
124328 #define WO_OR 0x0200 /* Two or more OR-connected terms */
124329 #define WO_AND 0x0400 /* Two or more AND-connected terms */
124330 #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
124331 #define WO_NOOP 0x1000 /* This term does not restrict search space */
124332 
124333 #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
124334 #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
124335 
124336 /*
124337 ** These are definitions of bits in the WhereLoop.wsFlags field.
124338 ** The particular combination of bits in each WhereLoop help to
124339 ** determine the algorithm that WhereLoop represents.
124340 */
124341 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
124342 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
124343 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
124344 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
124345 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
124346 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
124347 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
124348 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
124349 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
124350 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
124351 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
124352 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
124353 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
124354 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
124355 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
124356 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
124357 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
124358 #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
124359 #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
124360 
124361 /************** End of whereInt.h ********************************************/
124362 /************** Continuing where we left off in wherecode.c ******************/
124363 
124364 #ifndef SQLITE_OMIT_EXPLAIN
124365 
124366 /*
124367 ** Return the name of the i-th column of the pIdx index.
124368 */
124369 static const char *explainIndexColumnName(Index *pIdx, int i){
124370  i = pIdx->aiColumn[i];
124371  if( i==XN_EXPR ) return "<expr>";
124372  if( i==XN_ROWID ) return "rowid";
124373  return pIdx->pTable->aCol[i].zName;
124374 }
124375 
124376 /*
124377 ** This routine is a helper for explainIndexRange() below
124378 **
124379 ** pStr holds the text of an expression that we are building up one term
124380 ** at a time. This routine adds a new term to the end of the expression.
124381 ** Terms are separated by AND so add the "AND" text for second and subsequent
124382 ** terms only.
124383 */
124385  StrAccum *pStr, /* The text expression being built */
124386  Index *pIdx, /* Index to read column names from */
124387  int nTerm, /* Number of terms */
124388  int iTerm, /* Zero-based index of first term. */
124389  int bAnd, /* Non-zero to append " AND " */
124390  const char *zOp /* Name of the operator */
124391 ){
124392  int i;
124393 
124394  assert( nTerm>=1 );
124395  if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
124396 
124397  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
124398  for(i=0; i<nTerm; i++){
124399  if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
124400  sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
124401  }
124402  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
124403 
124404  sqlite3StrAccumAppend(pStr, zOp, 1);
124405 
124406  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
124407  for(i=0; i<nTerm; i++){
124408  if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
124409  sqlite3StrAccumAppend(pStr, "?", 1);
124410  }
124411  if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
124412 }
124413 
124414 /*
124415 ** Argument pLevel describes a strategy for scanning table pTab. This
124416 ** function appends text to pStr that describes the subset of table
124417 ** rows scanned by the strategy in the form of an SQL expression.
124418 **
124419 ** For example, if the query:
124420 **
124421 ** SELECT * FROM t1 WHERE a=1 AND b>2;
124422 **
124423 ** is run and there is an index on (a, b), then this function returns a
124424 ** string similar to:
124425 **
124426 ** "a=? AND b>?"
124427 */
124428 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
124429  Index *pIndex = pLoop->u.btree.pIndex;
124430  u16 nEq = pLoop->u.btree.nEq;
124431  u16 nSkip = pLoop->nSkip;
124432  int i, j;
124433 
124434  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
124435  sqlite3StrAccumAppend(pStr, " (", 2);
124436  for(i=0; i<nEq; i++){
124437  const char *z = explainIndexColumnName(pIndex, i);
124438  if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
124439  sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
124440  }
124441 
124442  j = i;
124443  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
124444  explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
124445  i = 1;
124446  }
124447  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
124448  explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
124449  }
124450  sqlite3StrAccumAppend(pStr, ")", 1);
124451 }
124452 
124453 /*
124454 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
124455 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
124456 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
124457 ** is added to the output to describe the table scan strategy in pLevel.
124458 **
124459 ** If an OP_Explain opcode is added to the VM, its address is returned.
124460 ** Otherwise, if no OP_Explain is coded, zero is returned.
124461 */
124463  Parse *pParse, /* Parse context */
124464  SrcList *pTabList, /* Table list this loop refers to */
124465  WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
124466  int iLevel, /* Value for "level" column of output */
124467  int iFrom, /* Value for "from" column of output */
124468  u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
124469 ){
124470  int ret = 0;
124471 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
124472  if( pParse->explain==2 )
124473 #endif
124474  {
124475  struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
124476  Vdbe *v = pParse->pVdbe; /* VM being constructed */
124477  sqlite3 *db = pParse->db; /* Database handle */
124478  int iId = pParse->iSelectId; /* Select id (left-most output column) */
124479  int isSearch; /* True for a SEARCH. False for SCAN. */
124480  WhereLoop *pLoop; /* The controlling WhereLoop object */
124481  u32 flags; /* Flags that describe this loop */
124482  char *zMsg; /* Text to add to EQP output */
124483  StrAccum str; /* EQP output string */
124484  char zBuf[100]; /* Initial space for EQP output string */
124485 
124486  pLoop = pLevel->pWLoop;
124487  flags = pLoop->wsFlags;
124488  if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
124489 
124490  isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
124491  || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
124492  || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
124493 
124494  sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
124495  sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
124496  if( pItem->pSelect ){
124497  sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
124498  }else{
124499  sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
124500  }
124501 
124502  if( pItem->zAlias ){
124503  sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
124504  }
124505  if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
124506  const char *zFmt = 0;
124507  Index *pIdx;
124508 
124509  assert( pLoop->u.btree.pIndex!=0 );
124510  pIdx = pLoop->u.btree.pIndex;
124511  assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
124512  if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
124513  if( isSearch ){
124514  zFmt = "PRIMARY KEY";
124515  }
124516  }else if( flags & WHERE_PARTIALIDX ){
124517  zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
124518  }else if( flags & WHERE_AUTO_INDEX ){
124519  zFmt = "AUTOMATIC COVERING INDEX";
124520  }else if( flags & WHERE_IDX_ONLY ){
124521  zFmt = "COVERING INDEX %s";
124522  }else{
124523  zFmt = "INDEX %s";
124524  }
124525  if( zFmt ){
124526  sqlite3StrAccumAppend(&str, " USING ", 7);
124527  sqlite3XPrintf(&str, zFmt, pIdx->zName);
124528  explainIndexRange(&str, pLoop);
124529  }
124530  }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
124531  const char *zRangeOp;
124532  if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
124533  zRangeOp = "=";
124534  }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
124535  zRangeOp = ">? AND rowid<";
124536  }else if( flags&WHERE_BTM_LIMIT ){
124537  zRangeOp = ">";
124538  }else{
124539  assert( flags&WHERE_TOP_LIMIT);
124540  zRangeOp = "<";
124541  }
124542  sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
124543  }
124544 #ifndef SQLITE_OMIT_VIRTUALTABLE
124545  else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
124546  sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
124547  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
124548  }
124549 #endif
124550 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
124551  if( pLoop->nOut>=10 ){
124552  sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
124553  }else{
124554  sqlite3StrAccumAppend(&str, " (~1 row)", 9);
124555  }
124556 #endif
124557  zMsg = sqlite3StrAccumFinish(&str);
124558  ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
124559  }
124560  return ret;
124561 }
124562 #endif /* SQLITE_OMIT_EXPLAIN */
124563 
124564 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
124565 /*
124566 ** Configure the VM passed as the first argument with an
124567 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
124568 ** implement level pLvl. Argument pSrclist is a pointer to the FROM
124569 ** clause that the scan reads data from.
124570 **
124571 ** If argument addrExplain is not 0, it must be the address of an
124572 ** OP_Explain instruction that describes the same loop.
124573 */
124575  Vdbe *v, /* Vdbe to add scanstatus entry to */
124576  SrcList *pSrclist, /* FROM clause pLvl reads data from */
124577  WhereLevel *pLvl, /* Level to add scanstatus() entry for */
124578  int addrExplain /* Address of OP_Explain (or 0) */
124579 ){
124580  const char *zObj = 0;
124581  WhereLoop *pLoop = pLvl->pWLoop;
124582  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
124583  zObj = pLoop->u.btree.pIndex->zName;
124584  }else{
124585  zObj = pSrclist->a[pLvl->iFrom].zName;
124586  }
124588  v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
124589  );
124590 }
124591 #endif
124592 
124593 
124594 /*
124595 ** Disable a term in the WHERE clause. Except, do not disable the term
124596 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
124597 ** or USING clause of that join.
124598 **
124599 ** Consider the term t2.z='ok' in the following queries:
124600 **
124601 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
124602 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
124603 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
124604 **
124605 ** The t2.z='ok' is disabled in the in (2) because it originates
124606 ** in the ON clause. The term is disabled in (3) because it is not part
124607 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
124608 **
124609 ** Disabling a term causes that term to not be tested in the inner loop
124610 ** of the join. Disabling is an optimization. When terms are satisfied
124611 ** by indices, we disable them to prevent redundant tests in the inner
124612 ** loop. We would get the correct results if nothing were ever disabled,
124613 ** but joins might run a little slower. The trick is to disable as much
124614 ** as we can without disabling too much. If we disabled in (1), we'd get
124615 ** the wrong answer. See ticket #813.
124616 **
124617 ** If all the children of a term are disabled, then that term is also
124618 ** automatically disabled. In this way, terms get disabled if derived
124619 ** virtual terms are tested first. For example:
124620 **
124621 ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
124622 ** \___________/ \______/ \_____/
124623 ** parent child1 child2
124624 **
124625 ** Only the parent term was in the original WHERE clause. The child1
124626 ** and child2 terms were added by the LIKE optimization. If both of
124627 ** the virtual child terms are valid, then testing of the parent can be
124628 ** skipped.
124629 **
124630 ** Usually the parent term is marked as TERM_CODED. But if the parent
124631 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
124632 ** The TERM_LIKECOND marking indicates that the term should be coded inside
124633 ** a conditional such that is only evaluated on the second pass of a
124634 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
124635 */
124636 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
124637  int nLoop = 0;
124638  while( ALWAYS(pTerm!=0)
124639  && (pTerm->wtFlags & TERM_CODED)==0
124640  && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
124641  && (pLevel->notReady & pTerm->prereqAll)==0
124642  ){
124643  if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
124644  pTerm->wtFlags |= TERM_LIKECOND;
124645  }else{
124646  pTerm->wtFlags |= TERM_CODED;
124647  }
124648  if( pTerm->iParent<0 ) break;
124649  pTerm = &pTerm->pWC->a[pTerm->iParent];
124650  pTerm->nChild--;
124651  if( pTerm->nChild!=0 ) break;
124652  nLoop++;
124653  }
124654 }
124655 
124656 /*
124657 ** Code an OP_Affinity opcode to apply the column affinity string zAff
124658 ** to the n registers starting at base.
124659 **
124660 ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
124661 ** beginning and end of zAff are ignored. If all entries in zAff are
124662 ** SQLITE_AFF_BLOB, then no code gets generated.
124663 **
124664 ** This routine makes its own copy of zAff so that the caller is free
124665 ** to modify zAff after this routine returns.
124666 */
124667 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
124668  Vdbe *v = pParse->pVdbe;
124669  if( zAff==0 ){
124670  assert( pParse->db->mallocFailed );
124671  return;
124672  }
124673  assert( v!=0 );
124674 
124675  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
124676  ** and end of the affinity string.
124677  */
124678  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
124679  n--;
124680  base++;
124681  zAff++;
124682  }
124683  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
124684  n--;
124685  }
124686 
124687  /* Code the OP_Affinity opcode if there is anything left to do. */
124688  if( n>0 ){
124689  sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
124690  sqlite3ExprCacheAffinityChange(pParse, base, n);
124691  }
124692 }
124693 
124694 /*
124695 ** Expression pRight, which is the RHS of a comparison operation, is
124696 ** either a vector of n elements or, if n==1, a scalar expression.
124697 ** Before the comparison operation, affinity zAff is to be applied
124698 ** to the pRight values. This function modifies characters within the
124699 ** affinity string to SQLITE_AFF_BLOB if either:
124700 **
124701 ** * the comparison will be performed with no affinity, or
124702 ** * the affinity change in zAff is guaranteed not to change the value.
124703 */
124705  Expr *pRight, /* RHS of comparison */
124706  int n, /* Number of vector elements in comparison */
124707  char *zAff /* Affinity string to modify */
124708 ){
124709  int i;
124710  for(i=0; i<n; i++){
124711  Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
124712  if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
124713  || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
124714  ){
124715  zAff[i] = SQLITE_AFF_BLOB;
124716  }
124717  }
124718 }
124719 
124720 /*
124721 ** Generate code for a single equality term of the WHERE clause. An equality
124722 ** term can be either X=expr or X IN (...). pTerm is the term to be
124723 ** coded.
124724 **
124725 ** The current value for the constraint is left in a register, the index
124726 ** of which is returned. An attempt is made store the result in iTarget but
124727 ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
124728 ** constraint is a TK_EQ or TK_IS, then the current value might be left in
124729 ** some other register and it is the caller's responsibility to compensate.
124730 **
124731 ** For a constraint of the form X=expr, the expression is evaluated in
124732 ** straight-line code. For constraints of the form X IN (...)
124733 ** this routine sets up a loop that will iterate over all values of X.
124734 */
124736  Parse *pParse, /* The parsing context */
124737  WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
124738  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
124739  int iEq, /* Index of the equality term within this level */
124740  int bRev, /* True for reverse-order IN operations */
124741  int iTarget /* Attempt to leave results in this register */
124742 ){
124743  Expr *pX = pTerm->pExpr;
124744  Vdbe *v = pParse->pVdbe;
124745  int iReg; /* Register holding results */
124746 
124747  assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
124748  assert( iTarget>0 );
124749  if( pX->op==TK_EQ || pX->op==TK_IS ){
124750  iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
124751  }else if( pX->op==TK_ISNULL ){
124752  iReg = iTarget;
124753  sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
124754 #ifndef SQLITE_OMIT_SUBQUERY
124755  }else{
124756  int eType = IN_INDEX_NOOP;
124757  int iTab;
124758  struct InLoop *pIn;
124759  WhereLoop *pLoop = pLevel->pWLoop;
124760  int i;
124761  int nEq = 0;
124762  int *aiMap = 0;
124763 
124764  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
124765  && pLoop->u.btree.pIndex!=0
124766  && pLoop->u.btree.pIndex->aSortOrder[iEq]
124767  ){
124768  testcase( iEq==0 );
124769  testcase( bRev );
124770  bRev = !bRev;
124771  }
124772  assert( pX->op==TK_IN );
124773  iReg = iTarget;
124774 
124775  for(i=0; i<iEq; i++){
124776  if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
124777  disableTerm(pLevel, pTerm);
124778  return iTarget;
124779  }
124780  }
124781  for(i=iEq;i<pLoop->nLTerm; i++){
124782  if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
124783  }
124784 
124785  if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
124786  eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
124787  }else{
124788  Select *pSelect = pX->x.pSelect;
124789  sqlite3 *db = pParse->db;
124790  u16 savedDbOptFlags = db->dbOptFlags;
124791  ExprList *pOrigRhs = pSelect->pEList;
124792  ExprList *pOrigLhs = pX->pLeft->x.pList;
124793  ExprList *pRhs = 0; /* New Select.pEList for RHS */
124794  ExprList *pLhs = 0; /* New pX->pLeft vector */
124795 
124796  for(i=iEq;i<pLoop->nLTerm; i++){
124797  if( pLoop->aLTerm[i]->pExpr==pX ){
124798  int iField = pLoop->aLTerm[i]->iField - 1;
124799  Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
124800  Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
124801 
124802  pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
124803  pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
124804  }
124805  }
124806  if( !db->mallocFailed ){
124807  Expr *pLeft = pX->pLeft;
124808 
124809  if( pSelect->pOrderBy ){
124810  /* If the SELECT statement has an ORDER BY clause, zero the
124811  ** iOrderByCol variables. These are set to non-zero when an
124812  ** ORDER BY term exactly matches one of the terms of the
124813  ** result-set. Since the result-set of the SELECT statement may
124814  ** have been modified or reordered, these variables are no longer
124815  ** set correctly. Since setting them is just an optimization,
124816  ** it's easiest just to zero them here. */
124817  ExprList *pOrderBy = pSelect->pOrderBy;
124818  for(i=0; i<pOrderBy->nExpr; i++){
124819  pOrderBy->a[i].u.x.iOrderByCol = 0;
124820  }
124821  }
124822 
124823  /* Take care here not to generate a TK_VECTOR containing only a
124824  ** single value. Since the parser never creates such a vector, some
124825  ** of the subroutines do not handle this case. */
124826  if( pLhs->nExpr==1 ){
124827  pX->pLeft = pLhs->a[0].pExpr;
124828  }else{
124829  pLeft->x.pList = pLhs;
124830  aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
124831  testcase( aiMap==0 );
124832  }
124833  pSelect->pEList = pRhs;
124835  eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
124836  db->dbOptFlags = savedDbOptFlags;
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 */
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 */
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 */
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);
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 */
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);
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 ){
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);
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){
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){
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
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);
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 */
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 */
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 */
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
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,
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  testcase( pTerm!=&pWC->a[idxTerm] );
127656  pTerm = &pWC->a[idxTerm];
127657  pTerm->prereqRight |= extraRight;
127658 }
127659 
127660 /***************************************************************************
127661 ** Routines with file scope above. Interface to the rest of the where.c
127662 ** subsystem follows.
127663 ***************************************************************************/
127664 
127665 /*
127666 ** This routine identifies subexpressions in the WHERE clause where
127667 ** each subexpression is separated by the AND operator or some other
127668 ** operator specified in the op parameter. The WhereClause structure
127669 ** is filled with pointers to subexpressions. For example:
127670 **
127671 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
127672 ** \________/ \_______________/ \________________/
127673 ** slot[0] slot[1] slot[2]
127674 **
127675 ** The original WHERE clause in pExpr is unaltered. All this routine
127676 ** does is make slot[] entries point to substructure within pExpr.
127677 **
127678 ** In the previous sentence and in the diagram, "slot[]" refers to
127679 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
127680 ** all terms of the WHERE clause.
127681 */
127683  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
127684  pWC->op = op;
127685  if( pE2==0 ) return;
127686  if( pE2->op!=op ){
127687  whereClauseInsert(pWC, pExpr, 0);
127688  }else{
127689  sqlite3WhereSplit(pWC, pE2->pLeft, op);
127690  sqlite3WhereSplit(pWC, pE2->pRight, op);
127691  }
127692 }
127693 
127694 /*
127695 ** Initialize a preallocated WhereClause structure.
127696 */
127698  WhereClause *pWC, /* The WhereClause to be initialized */
127699  WhereInfo *pWInfo /* The WHERE processing context */
127700 ){
127701  pWC->pWInfo = pWInfo;
127702  pWC->pOuter = 0;
127703  pWC->nTerm = 0;
127704  pWC->nSlot = ArraySize(pWC->aStatic);
127705  pWC->a = pWC->aStatic;
127706 }
127707 
127708 /*
127709 ** Deallocate a WhereClause structure. The WhereClause structure
127710 ** itself is not freed. This routine is the inverse of
127711 ** sqlite3WhereClauseInit().
127712 */
127714  int i;
127715  WhereTerm *a;
127716  sqlite3 *db = pWC->pWInfo->pParse->db;
127717  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
127718  if( a->wtFlags & TERM_DYNAMIC ){
127719  sqlite3ExprDelete(db, a->pExpr);
127720  }
127721  if( a->wtFlags & TERM_ORINFO ){
127722  whereOrInfoDelete(db, a->u.pOrInfo);
127723  }else if( a->wtFlags & TERM_ANDINFO ){
127724  whereAndInfoDelete(db, a->u.pAndInfo);
127725  }
127726  }
127727  if( pWC->a!=pWC->aStatic ){
127728  sqlite3DbFree(db, pWC->a);
127729  }
127730 }
127731 
127732 
127733 /*
127734 ** These routines walk (recursively) an expression tree and generate
127735 ** a bitmask indicating which tables are used in that expression
127736 ** tree.
127737 */
127739  Bitmask mask;
127740  if( p==0 ) return 0;
127741  if( p->op==TK_COLUMN ){
127742  mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
127743  return mask;
127744  }
127745  assert( !ExprHasProperty(p, EP_TokenOnly) );
127746  mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0;
127747  if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
127748  if( ExprHasProperty(p, EP_xIsSelect) ){
127749  mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
127750  }else if( p->x.pList ){
127751  mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
127752  }
127753  return mask;
127754 }
127756  int i;
127757  Bitmask mask = 0;
127758  if( pList ){
127759  for(i=0; i<pList->nExpr; i++){
127760  mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
127761  }
127762  }
127763  return mask;
127764 }
127765 
127766 
127767 /*
127768 ** Call exprAnalyze on all terms in a WHERE clause.
127769 **
127770 ** Note that exprAnalyze() might add new virtual terms onto the
127771 ** end of the WHERE clause. We do not want to analyze these new
127772 ** virtual terms, so start analyzing at the end and work forward
127773 ** so that the added virtual terms are never processed.
127774 */
127776  SrcList *pTabList, /* the FROM clause */
127777  WhereClause *pWC /* the WHERE clause to be analyzed */
127778 ){
127779  int i;
127780  for(i=pWC->nTerm-1; i>=0; i--){
127781  exprAnalyze(pTabList, pWC, i);
127782  }
127783 }
127784 
127785 /*
127786 ** For table-valued-functions, transform the function arguments into
127787 ** new WHERE clause terms.
127788 **
127789 ** Each function argument translates into an equality constraint against
127790 ** a HIDDEN column in the table.
127791 */
127793  Parse *pParse, /* Parsing context */
127794  struct SrcList_item *pItem, /* The FROM clause term to process */
127795  WhereClause *pWC /* Xfer function arguments to here */
127796 ){
127797  Table *pTab;
127798  int j, k;
127799  ExprList *pArgs;
127800  Expr *pColRef;
127801  Expr *pTerm;
127802  if( pItem->fg.isTabFunc==0 ) return;
127803  pTab = pItem->pTab;
127804  assert( pTab!=0 );
127805  pArgs = pItem->u1.pFuncArg;
127806  if( pArgs==0 ) return;
127807  for(j=k=0; j<pArgs->nExpr; j++){
127808  while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
127809  if( k>=pTab->nCol ){
127810  sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
127811  pTab->zName, j);
127812  return;
127813  }
127814  pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
127815  if( pColRef==0 ) return;
127816  pColRef->iTable = pItem->iCursor;
127817  pColRef->iColumn = k++;
127818  pColRef->pTab = pTab;
127819  pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
127820  sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
127821  whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
127822  }
127823 }
127824 
127825 /************** End of whereexpr.c *******************************************/
127826 /************** Begin file where.c *******************************************/
127827 /*
127828 ** 2001 September 15
127829 **
127830 ** The author disclaims copyright to this source code. In place of
127831 ** a legal notice, here is a blessing:
127832 **
127833 ** May you do good and not evil.
127834 ** May you find forgiveness for yourself and forgive others.
127835 ** May you share freely, never taking more than you give.
127836 **
127837 *************************************************************************
127838 ** This module contains C code that generates VDBE code used to process
127839 ** the WHERE clause of SQL statements. This module is responsible for
127840 ** generating the code that loops through a table looking for applicable
127841 ** rows. Indices are selected and used to speed the search when doing
127842 ** so is applicable. Because this module is responsible for selecting
127843 ** indices, you might also think of this module as the "query optimizer".
127844 */
127845 /* #include "sqliteInt.h" */
127846 /* #include "whereInt.h" */
127847 
127848 /* Forward declaration of methods */
127849 static int whereLoopResize(sqlite3*, WhereLoop*, int);
127850 
127851 /* Test variable that can be set to enable WHERE tracing */
127852 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
127853 /***/ int sqlite3WhereTrace = 0;
127854 #endif
127855 
127856 
127857 /*
127858 ** Return the estimated number of output rows from a WHERE clause
127859 */
127861  return pWInfo->nRowOut;
127862 }
127863 
127864 /*
127865 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
127866 ** WHERE clause returns outputs for DISTINCT processing.
127867 */
127869  return pWInfo->eDistinct;
127870 }
127871 
127872 /*
127873 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
127874 ** Return FALSE if the output needs to be sorted.
127875 */
127877  return pWInfo->nOBSat;
127878 }
127879 
127880 /*
127881 ** Return TRUE if the innermost loop of the WHERE clause implementation
127882 ** returns rows in ORDER BY order for complete run of the inner loop.
127883 **
127884 ** Across multiple iterations of outer loops, the output rows need not be
127885 ** sorted. As long as rows are sorted for just the innermost loop, this
127886 ** routine can return TRUE.
127887 */
127889  return pWInfo->bOrderedInnerLoop;
127890 }
127891 
127892 /*
127893 ** Return the VDBE address or label to jump to in order to continue
127894 ** immediately with the next row of a WHERE clause.
127895 */
127897  assert( pWInfo->iContinue!=0 );
127898  return pWInfo->iContinue;
127899 }
127900 
127901 /*
127902 ** Return the VDBE address or label to jump to in order to break
127903 ** out of a WHERE loop.
127904 */
127906  return pWInfo->iBreak;
127907 }
127908 
127909 /*
127910 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
127911 ** operate directly on the rowis returned by a WHERE clause. Return
127912 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
127913 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
127914 ** optimization can be used on multiple
127915 **
127916 ** If the ONEPASS optimization is used (if this routine returns true)
127917 ** then also write the indices of open cursors used by ONEPASS
127918 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
127919 ** table and iaCur[1] gets the cursor used by an auxiliary index.
127920 ** Either value may be -1, indicating that cursor is not used.
127921 ** Any cursors returned will have been opened for writing.
127922 **
127923 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
127924 ** unable to use the ONEPASS optimization.
127925 */
127927  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
127928 #ifdef WHERETRACE_ENABLED
127929  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
127930  sqlite3DebugPrintf("%s cursors: %d %d\n",
127931  pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
127932  aiCur[0], aiCur[1]);
127933  }
127934 #endif
127935  return pWInfo->eOnePass;
127936 }
127937 
127938 /*
127939 ** Move the content of pSrc into pDest
127940 */
127941 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
127942  pDest->n = pSrc->n;
127943  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
127944 }
127945 
127946 /*
127947 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
127948 **
127949 ** The new entry might overwrite an existing entry, or it might be
127950 ** appended, or it might be discarded. Do whatever is the right thing
127951 ** so that pSet keeps the N_OR_COST best entries seen so far.
127952 */
127953 static int whereOrInsert(
127954  WhereOrSet *pSet, /* The WhereOrSet to be updated */
127955  Bitmask prereq, /* Prerequisites of the new entry */
127956  LogEst rRun, /* Run-cost of the new entry */
127957  LogEst nOut /* Number of outputs for the new entry */
127958 ){
127959  u16 i;
127960  WhereOrCost *p;
127961  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
127962  if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
127963  goto whereOrInsert_done;
127964  }
127965  if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
127966  return 0;
127967  }
127968  }
127969  if( pSet->n<N_OR_COST ){
127970  p = &pSet->a[pSet->n++];
127971  p->nOut = nOut;
127972  }else{
127973  p = pSet->a;
127974  for(i=1; i<pSet->n; i++){
127975  if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
127976  }
127977  if( p->rRun<=rRun ) return 0;
127978  }
127979 whereOrInsert_done:
127980  p->prereq = prereq;
127981  p->rRun = rRun;
127982  if( p->nOut>nOut ) p->nOut = nOut;
127983  return 1;
127984 }
127985 
127986 /*
127987 ** Return the bitmask for the given cursor number. Return 0 if
127988 ** iCursor is not in the set.
127989 */
127990 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
127991  int i;
127992  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
127993  for(i=0; i<pMaskSet->n; i++){
127994  if( pMaskSet->ix[i]==iCursor ){
127995  return MASKBIT(i);
127996  }
127997  }
127998  return 0;
127999 }
128000 
128001 /*
128002 ** Create a new mask for cursor iCursor.
128003 **
128004 ** There is one cursor per table in the FROM clause. The number of
128005 ** tables in the FROM clause is limited by a test early in the
128006 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
128007 ** array will never overflow.
128008 */
128009 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
128010  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
128011  pMaskSet->ix[pMaskSet->n++] = iCursor;
128012 }
128013 
128014 /*
128015 ** Advance to the next WhereTerm that matches according to the criteria
128016 ** established when the pScan object was initialized by whereScanInit().
128017 ** Return NULL if there are no more matching WhereTerms.
128018 */
128020  int iCur; /* The cursor on the LHS of the term */
128021  i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
128022  Expr *pX; /* An expression being tested */
128023  WhereClause *pWC; /* Shorthand for pScan->pWC */
128024  WhereTerm *pTerm; /* The term being tested */
128025  int k = pScan->k; /* Where to start scanning */
128026 
128027  while( pScan->iEquiv<=pScan->nEquiv ){
128028  iCur = pScan->aiCur[pScan->iEquiv-1];
128029  iColumn = pScan->aiColumn[pScan->iEquiv-1];
128030  if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
128031  while( (pWC = pScan->pWC)!=0 ){
128032  for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
128033  if( pTerm->leftCursor==iCur
128034  && pTerm->u.leftColumn==iColumn
128035  && (iColumn!=XN_EXPR
128036  || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
128037  && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
128038  ){
128039  if( (pTerm->eOperator & WO_EQUIV)!=0
128040  && pScan->nEquiv<ArraySize(pScan->aiCur)
128041  && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
128042  ){
128043  int j;
128044  for(j=0; j<pScan->nEquiv; j++){
128045  if( pScan->aiCur[j]==pX->iTable
128046  && pScan->aiColumn[j]==pX->iColumn ){
128047  break;
128048  }
128049  }
128050  if( j==pScan->nEquiv ){
128051  pScan->aiCur[j] = pX->iTable;
128052  pScan->aiColumn[j] = pX->iColumn;
128053  pScan->nEquiv++;
128054  }
128055  }
128056  if( (pTerm->eOperator & pScan->opMask)!=0 ){
128057  /* Verify the affinity and collating sequence match */
128058  if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
128059  CollSeq *pColl;
128060  Parse *pParse = pWC->pWInfo->pParse;
128061  pX = pTerm->pExpr;
128062  if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
128063  continue;
128064  }
128065  assert(pX->pLeft);
128066  pColl = sqlite3BinaryCompareCollSeq(pParse,
128067  pX->pLeft, pX->pRight);
128068  if( pColl==0 ) pColl = pParse->db->pDfltColl;
128069  if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
128070  continue;
128071  }
128072  }
128073  if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
128074  && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
128075  && pX->iTable==pScan->aiCur[0]
128076  && pX->iColumn==pScan->aiColumn[0]
128077  ){
128078  testcase( pTerm->eOperator & WO_IS );
128079  continue;
128080  }
128081  pScan->k = k+1;
128082  return pTerm;
128083  }
128084  }
128085  }
128086  pScan->pWC = pScan->pWC->pOuter;
128087  k = 0;
128088  }
128089  pScan->pWC = pScan->pOrigWC;
128090  k = 0;
128091  pScan->iEquiv++;
128092  }
128093  return 0;
128094 }
128095 
128096 /*
128097 ** Initialize a WHERE clause scanner object. Return a pointer to the
128098 ** first match. Return NULL if there are no matches.
128099 **
128100 ** The scanner will be searching the WHERE clause pWC. It will look
128101 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
128102 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
128103 ** must be one of the indexes of table iCur.
128104 **
128105 ** The <op> must be one of the operators described by opMask.
128106 **
128107 ** If the search is for X and the WHERE clause contains terms of the
128108 ** form X=Y then this routine might also return terms of the form
128109 ** "Y <op> <expr>". The number of levels of transitivity is limited,
128110 ** but is enough to handle most commonly occurring SQL statements.
128111 **
128112 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
128113 ** index pIdx.
128114 */
128116  WhereScan *pScan, /* The WhereScan object being initialized */
128117  WhereClause *pWC, /* The WHERE clause to be scanned */
128118  int iCur, /* Cursor to scan for */
128119  int iColumn, /* Column to scan for */
128120  u32 opMask, /* Operator(s) to scan for */
128121  Index *pIdx /* Must be compatible with this index */
128122 ){
128123  int j = 0;
128124 
128125  /* memset(pScan, 0, sizeof(*pScan)); */
128126  pScan->pOrigWC = pWC;
128127  pScan->pWC = pWC;
128128  pScan->pIdxExpr = 0;
128129  if( pIdx ){
128130  j = iColumn;
128131  iColumn = pIdx->aiColumn[j];
128132  if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
128133  if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
128134  }
128135  if( pIdx && iColumn>=0 ){
128136  pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
128137  pScan->zCollName = pIdx->azColl[j];
128138  }else{
128139  pScan->idxaff = 0;
128140  pScan->zCollName = 0;
128141  }
128142  pScan->opMask = opMask;
128143  pScan->k = 0;
128144  pScan->aiCur[0] = iCur;
128145  pScan->aiColumn[0] = iColumn;
128146  pScan->nEquiv = 1;
128147  pScan->iEquiv = 1;
128148  return whereScanNext(pScan);
128149 }
128150 
128151 /*
128152 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
128153 ** where X is a reference to the iColumn of table iCur or of index pIdx
128154 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
128155 ** the op parameter. Return a pointer to the term. Return 0 if not found.
128156 **
128157 ** If pIdx!=0 then it must be one of the indexes of table iCur.
128158 ** Search for terms matching the iColumn-th column of pIdx
128159 ** rather than the iColumn-th column of table iCur.
128160 **
128161 ** The term returned might by Y=<expr> if there is another constraint in
128162 ** the WHERE clause that specifies that X=Y. Any such constraints will be
128163 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
128164 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
128165 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
128166 ** other equivalent values. Hence a search for X will return <expr> if X=A1
128167 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
128168 **
128169 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
128170 ** then try for the one with no dependencies on <expr> - in other words where
128171 ** <expr> is a constant expression of some kind. Only return entries of
128172 ** the form "X <op> Y" where Y is a column in another table if no terms of
128173 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
128174 ** exist, try to return a term that does not use WO_EQUIV.
128175 */
128177  WhereClause *pWC, /* The WHERE clause to be searched */
128178  int iCur, /* Cursor number of LHS */
128179  int iColumn, /* Column number of LHS */
128180  Bitmask notReady, /* RHS must not overlap with this mask */
128181  u32 op, /* Mask of WO_xx values describing operator */
128182  Index *pIdx /* Must be compatible with this index, if not NULL */
128183 ){
128184  WhereTerm *pResult = 0;
128185  WhereTerm *p;
128186  WhereScan scan;
128187 
128188  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
128189  op &= WO_EQ|WO_IS;
128190  while( p ){
128191  if( (p->prereqRight & notReady)==0 ){
128192  if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
128193  testcase( p->eOperator & WO_IS );
128194  return p;
128195  }
128196  if( pResult==0 ) pResult = p;
128197  }
128198  p = whereScanNext(&scan);
128199  }
128200  return pResult;
128201 }
128202 
128203 /*
128204 ** This function searches pList for an entry that matches the iCol-th column
128205 ** of index pIdx.
128206 **
128207 ** If such an expression is found, its index in pList->a[] is returned. If
128208 ** no expression is found, -1 is returned.
128209 */
128210 static int findIndexCol(
128211  Parse *pParse, /* Parse context */
128212  ExprList *pList, /* Expression list to search */
128213  int iBase, /* Cursor for table associated with pIdx */
128214  Index *pIdx, /* Index to match column of */
128215  int iCol /* Column of index to match */
128216 ){
128217  int i;
128218  const char *zColl = pIdx->azColl[iCol];
128219 
128220  for(i=0; i<pList->nExpr; i++){
128221  Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
128222  if( p->op==TK_COLUMN
128223  && p->iColumn==pIdx->aiColumn[iCol]
128224  && p->iTable==iBase
128225  ){
128226  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
128227  if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
128228  return i;
128229  }
128230  }
128231  }
128232 
128233  return -1;
128234 }
128235 
128236 /*
128237 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
128238 */
128239 static int indexColumnNotNull(Index *pIdx, int iCol){
128240  int j;
128241  assert( pIdx!=0 );
128242  assert( iCol>=0 && iCol<pIdx->nColumn );
128243  j = pIdx->aiColumn[iCol];
128244  if( j>=0 ){
128245  return pIdx->pTable->aCol[j].notNull;
128246  }else if( j==(-1) ){
128247  return 1;
128248  }else{
128249  assert( j==(-2) );
128250  return 0; /* Assume an indexed expression can always yield a NULL */
128251 
128252  }
128253 }
128254 
128255 /*
128256 ** Return true if the DISTINCT expression-list passed as the third argument
128257 ** is redundant.
128258 **
128259 ** A DISTINCT list is redundant if any subset of the columns in the
128260 ** DISTINCT list are collectively unique and individually non-null.
128261 */
128263  Parse *pParse, /* Parsing context */
128264  SrcList *pTabList, /* The FROM clause */
128265  WhereClause *pWC, /* The WHERE clause */
128266  ExprList *pDistinct /* The result set that needs to be DISTINCT */
128267 ){
128268  Table *pTab;
128269  Index *pIdx;
128270  int i;
128271  int iBase;
128272 
128273  /* If there is more than one table or sub-select in the FROM clause of
128274  ** this query, then it will not be possible to show that the DISTINCT
128275  ** clause is redundant. */
128276  if( pTabList->nSrc!=1 ) return 0;
128277  iBase = pTabList->a[0].iCursor;
128278  pTab = pTabList->a[0].pTab;
128279 
128280  /* If any of the expressions is an IPK column on table iBase, then return
128281  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
128282  ** current SELECT is a correlated sub-query.
128283  */
128284  for(i=0; i<pDistinct->nExpr; i++){
128285  Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
128286  if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
128287  }
128288 
128289  /* Loop through all indices on the table, checking each to see if it makes
128290  ** the DISTINCT qualifier redundant. It does so if:
128291  **
128292  ** 1. The index is itself UNIQUE, and
128293  **
128294  ** 2. All of the columns in the index are either part of the pDistinct
128295  ** list, or else the WHERE clause contains a term of the form "col=X",
128296  ** where X is a constant value. The collation sequences of the
128297  ** comparison and select-list expressions must match those of the index.
128298  **
128299  ** 3. All of those index columns for which the WHERE clause does not
128300  ** contain a "col=X" term are subject to a NOT NULL constraint.
128301  */
128302  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
128303  if( !IsUniqueIndex(pIdx) ) continue;
128304  for(i=0; i<pIdx->nKeyCol; i++){
128305  if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
128306  if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
128307  if( indexColumnNotNull(pIdx, i)==0 ) break;
128308  }
128309  }
128310  if( i==pIdx->nKeyCol ){
128311  /* This index implies that the DISTINCT qualifier is redundant. */
128312  return 1;
128313  }
128314  }
128315 
128316  return 0;
128317 }
128318 
128319 
128320 /*
128321 ** Estimate the logarithm of the input value to base 2.
128322 */
128323 static LogEst estLog(LogEst N){
128324  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
128325 }
128326 
128327 /*
128328 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
128329 **
128330 ** This routine runs over generated VDBE code and translates OP_Column
128331 ** opcodes into OP_Copy when the table is being accessed via co-routine
128332 ** instead of via table lookup.
128333 **
128334 ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
128335 ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
128336 ** then each OP_Rowid is transformed into an instruction to increment the
128337 ** value stored in its output register.
128338 */
128340  Vdbe *v, /* The VDBE containing code to translate */
128341  int iStart, /* Translate from this opcode to the end */
128342  int iTabCur, /* OP_Column/OP_Rowid references to this table */
128343  int iRegister, /* The first column is in this register */
128344  int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
128345 ){
128346  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
128347  int iEnd = sqlite3VdbeCurrentAddr(v);
128348  for(; iStart<iEnd; iStart++, pOp++){
128349  if( pOp->p1!=iTabCur ) continue;
128350  if( pOp->opcode==OP_Column ){
128351  pOp->opcode = OP_Copy;
128352  pOp->p1 = pOp->p2 + iRegister;
128353  pOp->p2 = pOp->p3;
128354  pOp->p3 = 0;
128355  }else if( pOp->opcode==OP_Rowid ){
128356  if( bIncrRowid ){
128357  /* Increment the value stored in the P2 operand of the OP_Rowid. */
128358  pOp->opcode = OP_AddImm;
128359  pOp->p1 = pOp->p2;
128360  pOp->p2 = 1;
128361  }else{
128362  pOp->opcode = OP_Null;
128363  pOp->p1 = 0;
128364  pOp->p3 = 0;
128365  }
128366  }
128367  }
128368 }
128369 
128370 /*
128371 ** Two routines for printing the content of an sqlite3_index_info
128372 ** structure. Used for testing and debugging only. If neither
128373 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
128374 ** are no-ops.
128375 */
128376 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
128377 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
128378  int i;
128379  if( !sqlite3WhereTrace ) return;
128380  for(i=0; i<p->nConstraint; i++){
128381  sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
128382  i,
128383  p->aConstraint[i].iColumn,
128384  p->aConstraint[i].iTermOffset,
128385  p->aConstraint[i].op,
128386  p->aConstraint[i].usable);
128387  }
128388  for(i=0; i<p->nOrderBy; i++){
128389  sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
128390  i,
128391  p->aOrderBy[i].iColumn,
128392  p->aOrderBy[i].desc);
128393  }
128394 }
128395 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
128396  int i;
128397  if( !sqlite3WhereTrace ) return;
128398  for(i=0; i<p->nConstraint; i++){
128399  sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
128400  i,
128401  p->aConstraintUsage[i].argvIndex,
128402  p->aConstraintUsage[i].omit);
128403  }
128404  sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
128405  sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
128406  sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
128407  sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
128408  sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
128409 }
128410 #else
128411 #define TRACE_IDX_INPUTS(A)
128412 #define TRACE_IDX_OUTPUTS(A)
128413 #endif
128414 
128415 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
128416 /*
128417 ** Return TRUE if the WHERE clause term pTerm is of a form where it
128418 ** could be used with an index to access pSrc, assuming an appropriate
128419 ** index existed.
128420 */
128422  WhereTerm *pTerm, /* WHERE clause term to check */
128423  struct SrcList_item *pSrc, /* Table we are trying to access */
128424  Bitmask notReady /* Tables in outer loops of the join */
128425 ){
128426  char aff;
128427  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
128428  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
128429  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
128430  if( pTerm->u.leftColumn<0 ) return 0;
128431  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
128432  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
128433  testcase( pTerm->pExpr->op==TK_IS );
128434  return 1;
128435 }
128436 #endif
128437 
128438 
128439 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
128440 /*
128441 ** Generate code to construct the Index object for an automatic index
128442 ** and to set up the WhereLevel object pLevel so that the code generator
128443 ** makes use of the automatic index.
128444 */
128446  Parse *pParse, /* The parsing context */
128447  WhereClause *pWC, /* The WHERE clause */
128448  struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
128449  Bitmask notReady, /* Mask of cursors that are not available */
128450  WhereLevel *pLevel /* Write new index here */
128451 ){
128452  int nKeyCol; /* Number of columns in the constructed index */
128453  WhereTerm *pTerm; /* A single term of the WHERE clause */
128454  WhereTerm *pWCEnd; /* End of pWC->a[] */
128455  Index *pIdx; /* Object describing the transient index */
128456  Vdbe *v; /* Prepared statement under construction */
128457  int addrInit; /* Address of the initialization bypass jump */
128458  Table *pTable; /* The table being indexed */
128459  int addrTop; /* Top of the index fill loop */
128460  int regRecord; /* Register holding an index record */
128461  int n; /* Column counter */
128462  int i; /* Loop counter */
128463  int mxBitCol; /* Maximum column in pSrc->colUsed */
128464  CollSeq *pColl; /* Collating sequence to on a column */
128465  WhereLoop *pLoop; /* The Loop object */
128466  char *zNotUsed; /* Extra space on the end of pIdx */
128467  Bitmask idxCols; /* Bitmap of columns used for indexing */
128468  Bitmask extraCols; /* Bitmap of additional columns */
128469  u8 sentWarning = 0; /* True if a warnning has been issued */
128470  Expr *pPartial = 0; /* Partial Index Expression */
128471  int iContinue = 0; /* Jump here to skip excluded rows */
128472  struct SrcList_item *pTabItem; /* FROM clause term being indexed */
128473  int addrCounter = 0; /* Address where integer counter is initialized */
128474  int regBase; /* Array of registers where record is assembled */
128475 
128476  /* Generate code to skip over the creation and initialization of the
128477  ** transient index on 2nd and subsequent iterations of the loop. */
128478  v = pParse->pVdbe;
128479  assert( v!=0 );
128480  addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
128481 
128482  /* Count the number of columns that will be added to the index
128483  ** and used to match WHERE clause constraints */
128484  nKeyCol = 0;
128485  pTable = pSrc->pTab;
128486  pWCEnd = &pWC->a[pWC->nTerm];
128487  pLoop = pLevel->pWLoop;
128488  idxCols = 0;
128489  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
128490  Expr *pExpr = pTerm->pExpr;
128491  assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
128492  || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
128493  || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
128494  if( pLoop->prereq==0
128495  && (pTerm->wtFlags & TERM_VIRTUAL)==0
128496  && !ExprHasProperty(pExpr, EP_FromJoin)
128497  && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
128498  pPartial = sqlite3ExprAnd(pParse->db, pPartial,
128499  sqlite3ExprDup(pParse->db, pExpr, 0));
128500  }
128501  if( termCanDriveIndex(pTerm, pSrc, notReady) ){
128502  int iCol = pTerm->u.leftColumn;
128503  Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
128504  testcase( iCol==BMS );
128505  testcase( iCol==BMS-1 );
128506  if( !sentWarning ){
128508  "automatic index on %s(%s)", pTable->zName,
128509  pTable->aCol[iCol].zName);
128510  sentWarning = 1;
128511  }
128512  if( (idxCols & cMask)==0 ){
128513  if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
128514  goto end_auto_index_create;
128515  }
128516  pLoop->aLTerm[nKeyCol++] = pTerm;
128517  idxCols |= cMask;
128518  }
128519  }
128520  }
128521  assert( nKeyCol>0 );
128522  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
128524  | WHERE_AUTO_INDEX;
128525 
128526  /* Count the number of additional columns needed to create a
128527  ** covering index. A "covering index" is an index that contains all
128528  ** columns that are needed by the query. With a covering index, the
128529  ** original table never needs to be accessed. Automatic indices must
128530  ** be a covering index because the index will not be updated if the
128531  ** original table changes and the index and table cannot both be used
128532  ** if they go out of sync.
128533  */
128534  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
128535  mxBitCol = MIN(BMS-1,pTable->nCol);
128536  testcase( pTable->nCol==BMS-1 );
128537  testcase( pTable->nCol==BMS-2 );
128538  for(i=0; i<mxBitCol; i++){
128539  if( extraCols & MASKBIT(i) ) nKeyCol++;
128540  }
128541  if( pSrc->colUsed & MASKBIT(BMS-1) ){
128542  nKeyCol += pTable->nCol - BMS + 1;
128543  }
128544 
128545  /* Construct the Index object to describe this index */
128546  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
128547  if( pIdx==0 ) goto end_auto_index_create;
128548  pLoop->u.btree.pIndex = pIdx;
128549  pIdx->zName = "auto-index";
128550  pIdx->pTable = pTable;
128551  n = 0;
128552  idxCols = 0;
128553  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
128554  if( termCanDriveIndex(pTerm, pSrc, notReady) ){
128555  int iCol = pTerm->u.leftColumn;
128556  Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
128557  testcase( iCol==BMS-1 );
128558  testcase( iCol==BMS );
128559  if( (idxCols & cMask)==0 ){
128560  Expr *pX = pTerm->pExpr;
128561  idxCols |= cMask;
128562  pIdx->aiColumn[n] = pTerm->u.leftColumn;
128563  pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
128564  pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
128565  n++;
128566  }
128567  }
128568  }
128569  assert( (u32)n==pLoop->u.btree.nEq );
128570 
128571  /* Add additional columns needed to make the automatic index into
128572  ** a covering index */
128573  for(i=0; i<mxBitCol; i++){
128574  if( extraCols & MASKBIT(i) ){
128575  pIdx->aiColumn[n] = i;
128576  pIdx->azColl[n] = sqlite3StrBINARY;
128577  n++;
128578  }
128579  }
128580  if( pSrc->colUsed & MASKBIT(BMS-1) ){
128581  for(i=BMS-1; i<pTable->nCol; i++){
128582  pIdx->aiColumn[n] = i;
128583  pIdx->azColl[n] = sqlite3StrBINARY;
128584  n++;
128585  }
128586  }
128587  assert( n==nKeyCol );
128588  pIdx->aiColumn[n] = XN_ROWID;
128589  pIdx->azColl[n] = sqlite3StrBINARY;
128590 
128591  /* Create the automatic index */
128592  assert( pLevel->iIdxCur>=0 );
128593  pLevel->iIdxCur = pParse->nTab++;
128594  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
128595  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
128596  VdbeComment((v, "for %s", pTable->zName));
128597 
128598  /* Fill the automatic index with content */
128599  sqlite3ExprCachePush(pParse);
128600  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
128601  if( pTabItem->fg.viaCoroutine ){
128602  int regYield = pTabItem->regReturn;
128603  addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
128604  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
128605  addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
128606  VdbeCoverage(v);
128607  VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
128608  }else{
128609  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
128610  }
128611  if( pPartial ){
128612  iContinue = sqlite3VdbeMakeLabel(v);
128613  sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
128614  pLoop->wsFlags |= WHERE_PARTIALIDX;
128615  }
128616  regRecord = sqlite3GetTempReg(pParse);
128617  regBase = sqlite3GenerateIndexKey(
128618  pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
128619  );
128620  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
128622  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
128623  if( pTabItem->fg.viaCoroutine ){
128624  sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
128625  translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
128626  sqlite3VdbeGoto(v, addrTop);
128627  pTabItem->fg.viaCoroutine = 0;
128628  }else{
128629  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
128630  }
128632  sqlite3VdbeJumpHere(v, addrTop);
128633  sqlite3ReleaseTempReg(pParse, regRecord);
128634  sqlite3ExprCachePop(pParse);
128635 
128636  /* Jump here when skipping the initialization */
128637  sqlite3VdbeJumpHere(v, addrInit);
128638 
128639 end_auto_index_create:
128640  sqlite3ExprDelete(pParse->db, pPartial);
128641 }
128642 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
128643 
128644 #ifndef SQLITE_OMIT_VIRTUALTABLE
128645 /*
128646 ** Allocate and populate an sqlite3_index_info structure. It is the
128647 ** responsibility of the caller to eventually release the structure
128648 ** by passing the pointer returned by this function to sqlite3_free().
128649 */
128651  Parse *pParse,
128652  WhereClause *pWC,
128653  Bitmask mUnusable, /* Ignore terms with these prereqs */
128654  struct SrcList_item *pSrc,
128655  ExprList *pOrderBy,
128656  u16 *pmNoOmit /* Mask of terms not to omit */
128657 ){
128658  int i, j;
128659  int nTerm;
128660  struct sqlite3_index_constraint *pIdxCons;
128661  struct sqlite3_index_orderby *pIdxOrderBy;
128662  struct sqlite3_index_constraint_usage *pUsage;
128663  WhereTerm *pTerm;
128664  int nOrderBy;
128665  sqlite3_index_info *pIdxInfo;
128666  u16 mNoOmit = 0;
128667 
128668  /* Count the number of possible WHERE clause constraints referring
128669  ** to this virtual table */
128670  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
128671  if( pTerm->leftCursor != pSrc->iCursor ) continue;
128672  if( pTerm->prereqRight & mUnusable ) continue;
128673  assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
128674  testcase( pTerm->eOperator & WO_IN );
128675  testcase( pTerm->eOperator & WO_ISNULL );
128676  testcase( pTerm->eOperator & WO_IS );
128677  testcase( pTerm->eOperator & WO_ALL );
128678  if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
128679  if( pTerm->wtFlags & TERM_VNULL ) continue;
128680  assert( pTerm->u.leftColumn>=(-1) );
128681  nTerm++;
128682  }
128683 
128684  /* If the ORDER BY clause contains only columns in the current
128685  ** virtual table then allocate space for the aOrderBy part of
128686  ** the sqlite3_index_info structure.
128687  */
128688  nOrderBy = 0;
128689  if( pOrderBy ){
128690  int n = pOrderBy->nExpr;
128691  for(i=0; i<n; i++){
128692  Expr *pExpr = pOrderBy->a[i].pExpr;
128693  if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
128694  }
128695  if( i==n){
128696  nOrderBy = n;
128697  }
128698  }
128699 
128700  /* Allocate the sqlite3_index_info structure
128701  */
128702  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
128703  + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
128704  + sizeof(*pIdxOrderBy)*nOrderBy );
128705  if( pIdxInfo==0 ){
128706  sqlite3ErrorMsg(pParse, "out of memory");
128707  return 0;
128708  }
128709 
128710  /* Initialize the structure. The sqlite3_index_info structure contains
128711  ** many fields that are declared "const" to prevent xBestIndex from
128712  ** changing them. We have to do some funky casting in order to
128713  ** initialize those fields.
128714  */
128715  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
128716  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
128717  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
128718  *(int*)&pIdxInfo->nConstraint = nTerm;
128719  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
128720  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
128721  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
128722  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
128723  pUsage;
128724 
128725  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
128726  u8 op;
128727  if( pTerm->leftCursor != pSrc->iCursor ) continue;
128728  if( pTerm->prereqRight & mUnusable ) continue;
128729  assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
128730  testcase( pTerm->eOperator & WO_IN );
128731  testcase( pTerm->eOperator & WO_IS );
128732  testcase( pTerm->eOperator & WO_ISNULL );
128733  testcase( pTerm->eOperator & WO_ALL );
128734  if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
128735  if( pTerm->wtFlags & TERM_VNULL ) continue;
128736  assert( pTerm->u.leftColumn>=(-1) );
128737  pIdxCons[j].iColumn = pTerm->u.leftColumn;
128738  pIdxCons[j].iTermOffset = i;
128739  op = (u8)pTerm->eOperator & WO_ALL;
128740  if( op==WO_IN ) op = WO_EQ;
128741  if( op==WO_MATCH ){
128742  op = pTerm->eMatchOp;
128743  }
128744  pIdxCons[j].op = op;
128745  /* The direct assignment in the previous line is possible only because
128746  ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
128747  ** following asserts verify this fact. */
128748  assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
128749  assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
128750  assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
128751  assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
128752  assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
128754  assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
128755 
128756  if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
128757  && sqlite3ExprIsVector(pTerm->pExpr->pRight)
128758  ){
128759  if( i<16 ) mNoOmit |= (1 << i);
128760  if( op==WO_LT ) pIdxCons[j].op = WO_LE;
128761  if( op==WO_GT ) pIdxCons[j].op = WO_GE;
128762  }
128763 
128764  j++;
128765  }
128766  for(i=0; i<nOrderBy; i++){
128767  Expr *pExpr = pOrderBy->a[i].pExpr;
128768  pIdxOrderBy[i].iColumn = pExpr->iColumn;
128769  pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
128770  }
128771 
128772  *pmNoOmit = mNoOmit;
128773  return pIdxInfo;
128774 }
128775 
128776 /*
128777 ** The table object reference passed as the second argument to this function
128778 ** must represent a virtual table. This function invokes the xBestIndex()
128779 ** method of the virtual table with the sqlite3_index_info object that
128780 ** comes in as the 3rd argument to this function.
128781 **
128782 ** If an error occurs, pParse is populated with an error message and a
128783 ** non-zero value is returned. Otherwise, 0 is returned and the output
128784 ** part of the sqlite3_index_info structure is left populated.
128785 **
128786 ** Whether or not an error is returned, it is the responsibility of the
128787 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
128788 ** that this is required.
128789 */
128790 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
128791  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
128792  int rc;
128793 
128794  TRACE_IDX_INPUTS(p);
128795  rc = pVtab->pModule->xBestIndex(pVtab, p);
128796  TRACE_IDX_OUTPUTS(p);
128797 
128798  if( rc!=SQLITE_OK ){
128799  if( rc==SQLITE_NOMEM ){
128800  sqlite3OomFault(pParse->db);
128801  }else if( !pVtab->zErrMsg ){
128802  sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
128803  }else{
128804  sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
128805  }
128806  }
128807  sqlite3_free(pVtab->zErrMsg);
128808  pVtab->zErrMsg = 0;
128809 
128810 #if 0
128811  /* This error is now caught by the caller.
128812  ** Search for "xBestIndex malfunction" below */
128813  for(i=0; i<p->nConstraint; i++){
128814  if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
128815  sqlite3ErrorMsg(pParse,
128816  "table %s: xBestIndex returned an invalid plan", pTab->zName);
128817  }
128818  }
128819 #endif
128820 
128821  return pParse->nErr;
128822 }
128823 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
128824 
128825 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128826 /*
128827 ** Estimate the location of a particular key among all keys in an
128828 ** index. Store the results in aStat as follows:
128829 **
128830 ** aStat[0] Est. number of rows less than pRec
128831 ** aStat[1] Est. number of rows equal to pRec
128832 **
128833 ** Return the index of the sample that is the smallest sample that
128834 ** is greater than or equal to pRec. Note that this index is not an index
128835 ** into the aSample[] array - it is an index into a virtual set of samples
128836 ** based on the contents of aSample[] and the number of fields in record
128837 ** pRec.
128838 */
128839 static int whereKeyStats(
128840  Parse *pParse, /* Database connection */
128841  Index *pIdx, /* Index to consider domain of */
128842  UnpackedRecord *pRec, /* Vector of values to consider */
128843  int roundUp, /* Round up if true. Round down if false */
128844  tRowcnt *aStat /* OUT: stats written here */
128845 ){
128846  IndexSample *aSample = pIdx->aSample;
128847  int iCol; /* Index of required stats in anEq[] etc. */
128848  int i; /* Index of first sample >= pRec */
128849  int iSample; /* Smallest sample larger than or equal to pRec */
128850  int iMin = 0; /* Smallest sample not yet tested */
128851  int iTest; /* Next sample to test */
128852  int res; /* Result of comparison operation */
128853  int nField; /* Number of fields in pRec */
128854  tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
128855 
128856 #ifndef SQLITE_DEBUG
128857  UNUSED_PARAMETER( pParse );
128858 #endif
128859  assert( pRec!=0 );
128860  assert( pIdx->nSample>0 );
128861  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
128862 
128863  /* Do a binary search to find the first sample greater than or equal
128864  ** to pRec. If pRec contains a single field, the set of samples to search
128865  ** is simply the aSample[] array. If the samples in aSample[] contain more
128866  ** than one fields, all fields following the first are ignored.
128867  **
128868  ** If pRec contains N fields, where N is more than one, then as well as the
128869  ** samples in aSample[] (truncated to N fields), the search also has to
128870  ** consider prefixes of those samples. For example, if the set of samples
128871  ** in aSample is:
128872  **
128873  ** aSample[0] = (a, 5)
128874  ** aSample[1] = (a, 10)
128875  ** aSample[2] = (b, 5)
128876  ** aSample[3] = (c, 100)
128877  ** aSample[4] = (c, 105)
128878  **
128879  ** Then the search space should ideally be the samples above and the
128880  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
128881  ** the code actually searches this set:
128882  **
128883  ** 0: (a)
128884  ** 1: (a, 5)
128885  ** 2: (a, 10)
128886  ** 3: (a, 10)
128887  ** 4: (b)
128888  ** 5: (b, 5)
128889  ** 6: (c)
128890  ** 7: (c, 100)
128891  ** 8: (c, 105)
128892  ** 9: (c, 105)
128893  **
128894  ** For each sample in the aSample[] array, N samples are present in the
128895  ** effective sample array. In the above, samples 0 and 1 are based on
128896  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
128897  **
128898  ** Often, sample i of each block of N effective samples has (i+1) fields.
128899  ** Except, each sample may be extended to ensure that it is greater than or
128900  ** equal to the previous sample in the array. For example, in the above,
128901  ** sample 2 is the first sample of a block of N samples, so at first it
128902  ** appears that it should be 1 field in size. However, that would make it
128903  ** smaller than sample 1, so the binary search would not work. As a result,
128904  ** it is extended to two fields. The duplicates that this creates do not
128905  ** cause any problems.
128906  */
128907  nField = pRec->nField;
128908  iCol = 0;
128909  iSample = pIdx->nSample * nField;
128910  do{
128911  int iSamp; /* Index in aSample[] of test sample */
128912  int n; /* Number of fields in test sample */
128913 
128914  iTest = (iMin+iSample)/2;
128915  iSamp = iTest / nField;
128916  if( iSamp>0 ){
128917  /* The proposed effective sample is a prefix of sample aSample[iSamp].
128918  ** Specifically, the shortest prefix of at least (1 + iTest%nField)
128919  ** fields that is greater than the previous effective sample. */
128920  for(n=(iTest % nField) + 1; n<nField; n++){
128921  if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
128922  }
128923  }else{
128924  n = iTest + 1;
128925  }
128926 
128927  pRec->nField = n;
128928  res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
128929  if( res<0 ){
128930  iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
128931  iMin = iTest+1;
128932  }else if( res==0 && n<nField ){
128933  iLower = aSample[iSamp].anLt[n-1];
128934  iMin = iTest+1;
128935  res = -1;
128936  }else{
128937  iSample = iTest;
128938  iCol = n-1;
128939  }
128940  }while( res && iMin<iSample );
128941  i = iSample / nField;
128942 
128943 #ifdef SQLITE_DEBUG
128944  /* The following assert statements check that the binary search code
128945  ** above found the right answer. This block serves no purpose other
128946  ** than to invoke the asserts. */
128947  if( pParse->db->mallocFailed==0 ){
128948  if( res==0 ){
128949  /* If (res==0) is true, then pRec must be equal to sample i. */
128950  assert( i<pIdx->nSample );
128951  assert( iCol==nField-1 );
128952  pRec->nField = nField;
128953  assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
128954  || pParse->db->mallocFailed
128955  );
128956  }else{
128957  /* Unless i==pIdx->nSample, indicating that pRec is larger than
128958  ** all samples in the aSample[] array, pRec must be smaller than the
128959  ** (iCol+1) field prefix of sample i. */
128960  assert( i<=pIdx->nSample && i>=0 );
128961  pRec->nField = iCol+1;
128962  assert( i==pIdx->nSample
128963  || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
128964  || pParse->db->mallocFailed );
128965 
128966  /* if i==0 and iCol==0, then record pRec is smaller than all samples
128967  ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
128968  ** be greater than or equal to the (iCol) field prefix of sample i.
128969  ** If (i>0), then pRec must also be greater than sample (i-1). */
128970  if( iCol>0 ){
128971  pRec->nField = iCol;
128972  assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
128973  || pParse->db->mallocFailed );
128974  }
128975  if( i>0 ){
128976  pRec->nField = nField;
128977  assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
128978  || pParse->db->mallocFailed );
128979  }
128980  }
128981  }
128982 #endif /* ifdef SQLITE_DEBUG */
128983 
128984  if( res==0 ){
128985  /* Record pRec is equal to sample i */
128986  assert( iCol==nField-1 );
128987  aStat[0] = aSample[i].anLt[iCol];
128988  aStat[1] = aSample[i].anEq[iCol];
128989  }else{
128990  /* At this point, the (iCol+1) field prefix of aSample[i] is the first
128991  ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
128992  ** is larger than all samples in the array. */
128993  tRowcnt iUpper, iGap;
128994  if( i>=pIdx->nSample ){
128995  iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
128996  }else{
128997  iUpper = aSample[i].anLt[iCol];
128998  }
128999 
129000  if( iLower>=iUpper ){
129001  iGap = 0;
129002  }else{
129003  iGap = iUpper - iLower;
129004  }
129005  if( roundUp ){
129006  iGap = (iGap*2)/3;
129007  }else{
129008  iGap = iGap/3;
129009  }
129010  aStat[0] = iLower + iGap;
129011  aStat[1] = pIdx->aAvgEq[iCol];
129012  }
129013 
129014  /* Restore the pRec->nField value before returning. */
129015  pRec->nField = nField;
129016  return i;
129017 }
129018 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129019 
129020 /*
129021 ** If it is not NULL, pTerm is a term that provides an upper or lower
129022 ** bound on a range scan. Without considering pTerm, it is estimated
129023 ** that the scan will visit nNew rows. This function returns the number
129024 ** estimated to be visited after taking pTerm into account.
129025 **
129026 ** If the user explicitly specified a likelihood() value for this term,
129027 ** then the return value is the likelihood multiplied by the number of
129028 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
129029 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
129030 */
129031 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
129032  LogEst nRet = nNew;
129033  if( pTerm ){
129034  if( pTerm->truthProb<=0 ){
129035  nRet += pTerm->truthProb;
129036  }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
129037  nRet -= 20; assert( 20==sqlite3LogEst(4) );
129038  }
129039  }
129040  return nRet;
129041 }
129042 
129043 
129044 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129045 /*
129046 ** Return the affinity for a single column of an index.
129047 */
129048 SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
129049  assert( iCol>=0 && iCol<pIdx->nColumn );
129050  if( !pIdx->zColAff ){
129051  if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
129052  }
129053  return pIdx->zColAff[iCol];
129054 }
129055 #endif
129056 
129057 
129058 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129059 /*
129060 ** This function is called to estimate the number of rows visited by a
129061 ** range-scan on a skip-scan index. For example:
129062 **
129063 ** CREATE INDEX i1 ON t1(a, b, c);
129064 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
129065 **
129066 ** Value pLoop->nOut is currently set to the estimated number of rows
129067 ** visited for scanning (a=? AND b=?). This function reduces that estimate
129068 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
129069 ** on the stat4 data for the index. this scan will be peformed multiple
129070 ** times (once for each (a,b) combination that matches a=?) is dealt with
129071 ** by the caller.
129072 **
129073 ** It does this by scanning through all stat4 samples, comparing values
129074 ** extracted from pLower and pUpper with the corresponding column in each
129075 ** sample. If L and U are the number of samples found to be less than or
129076 ** equal to the values extracted from pLower and pUpper respectively, and
129077 ** N is the total number of samples, the pLoop->nOut value is adjusted
129078 ** as follows:
129079 **
129080 ** nOut = nOut * ( min(U - L, 1) / N )
129081 **
129082 ** If pLower is NULL, or a value cannot be extracted from the term, L is
129083 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
129084 ** U is set to N.
129085 **
129086 ** Normally, this function sets *pbDone to 1 before returning. However,
129087 ** if no value can be extracted from either pLower or pUpper (and so the
129088 ** estimate of the number of rows delivered remains unchanged), *pbDone
129089 ** is left as is.
129090 **
129091 ** If an error occurs, an SQLite error code is returned. Otherwise,
129092 ** SQLITE_OK.
129093 */
129094 static int whereRangeSkipScanEst(
129095  Parse *pParse, /* Parsing & code generating context */
129096  WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
129097  WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
129098  WhereLoop *pLoop, /* Update the .nOut value of this loop */
129099  int *pbDone /* Set to true if at least one expr. value extracted */
129100 ){
129101  Index *p = pLoop->u.btree.pIndex;
129102  int nEq = pLoop->u.btree.nEq;
129103  sqlite3 *db = pParse->db;
129104  int nLower = -1;
129105  int nUpper = p->nSample+1;
129106  int rc = SQLITE_OK;
129107  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
129108  CollSeq *pColl;
129109 
129110  sqlite3_value *p1 = 0; /* Value extracted from pLower */
129111  sqlite3_value *p2 = 0; /* Value extracted from pUpper */
129112  sqlite3_value *pVal = 0; /* Value extracted from record */
129113 
129114  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
129115  if( pLower ){
129116  rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
129117  nLower = 0;
129118  }
129119  if( pUpper && rc==SQLITE_OK ){
129120  rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
129121  nUpper = p2 ? 0 : p->nSample;
129122  }
129123 
129124  if( p1 || p2 ){
129125  int i;
129126  int nDiff;
129127  for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
129128  rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
129129  if( rc==SQLITE_OK && p1 ){
129130  int res = sqlite3MemCompare(p1, pVal, pColl);
129131  if( res>=0 ) nLower++;
129132  }
129133  if( rc==SQLITE_OK && p2 ){
129134  int res = sqlite3MemCompare(p2, pVal, pColl);
129135  if( res>=0 ) nUpper++;
129136  }
129137  }
129138  nDiff = (nUpper - nLower);
129139  if( nDiff<=0 ) nDiff = 1;
129140 
129141  /* If there is both an upper and lower bound specified, and the
129142  ** comparisons indicate that they are close together, use the fallback
129143  ** method (assume that the scan visits 1/64 of the rows) for estimating
129144  ** the number of rows visited. Otherwise, estimate the number of rows
129145  ** using the method described in the header comment for this function. */
129146  if( nDiff!=1 || pUpper==0 || pLower==0 ){
129147  int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
129148  pLoop->nOut -= nAdjust;
129149  *pbDone = 1;
129150  WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
129151  nLower, nUpper, nAdjust*-1, pLoop->nOut));
129152  }
129153 
129154  }else{
129155  assert( *pbDone==0 );
129156  }
129157 
129158  sqlite3ValueFree(p1);
129159  sqlite3ValueFree(p2);
129160  sqlite3ValueFree(pVal);
129161 
129162  return rc;
129163 }
129164 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129165 
129166 /*
129167 ** This function is used to estimate the number of rows that will be visited
129168 ** by scanning an index for a range of values. The range may have an upper
129169 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
129170 ** and lower bounds are represented by pLower and pUpper respectively. For
129171 ** example, assuming that index p is on t1(a):
129172 **
129173 ** ... FROM t1 WHERE a > ? AND a < ? ...
129174 ** |_____| |_____|
129175 ** | |
129176 ** pLower pUpper
129177 **
129178 ** If either of the upper or lower bound is not present, then NULL is passed in
129179 ** place of the corresponding WhereTerm.
129180 **
129181 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
129182 ** column subject to the range constraint. Or, equivalently, the number of
129183 ** equality constraints optimized by the proposed index scan. For example,
129184 ** assuming index p is on t1(a, b), and the SQL query is:
129185 **
129186 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
129187 **
129188 ** then nEq is set to 1 (as the range restricted column, b, is the second
129189 ** left-most column of the index). Or, if the query is:
129190 **
129191 ** ... FROM t1 WHERE a > ? AND a < ? ...
129192 **
129193 ** then nEq is set to 0.
129194 **
129195 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
129196 ** number of rows that the index scan is expected to visit without
129197 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
129198 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
129199 ** to account for the range constraints pLower and pUpper.
129200 **
129201 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
129202 ** used, a single range inequality reduces the search space by a factor of 4.
129203 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
129204 ** rows visited by a factor of 64.
129205 */
129207  Parse *pParse, /* Parsing & code generating context */
129208  WhereLoopBuilder *pBuilder,
129209  WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
129210  WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
129211  WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
129212 ){
129213  int rc = SQLITE_OK;
129214  int nOut = pLoop->nOut;
129215  LogEst nNew;
129216 
129217 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129218  Index *p = pLoop->u.btree.pIndex;
129219  int nEq = pLoop->u.btree.nEq;
129220 
129221  if( p->nSample>0 && nEq<p->nSampleCol ){
129222  if( nEq==pBuilder->nRecValid ){
129223  UnpackedRecord *pRec = pBuilder->pRec;
129224  tRowcnt a[2];
129225  int nBtm = pLoop->u.btree.nBtm;
129226  int nTop = pLoop->u.btree.nTop;
129227 
129228  /* Variable iLower will be set to the estimate of the number of rows in
129229  ** the index that are less than the lower bound of the range query. The
129230  ** lower bound being the concatenation of $P and $L, where $P is the
129231  ** key-prefix formed by the nEq values matched against the nEq left-most
129232  ** columns of the index, and $L is the value in pLower.
129233  **
129234  ** Or, if pLower is NULL or $L cannot be extracted from it (because it
129235  ** is not a simple variable or literal value), the lower bound of the
129236  ** range is $P. Due to a quirk in the way whereKeyStats() works, even
129237  ** if $L is available, whereKeyStats() is called for both ($P) and
129238  ** ($P:$L) and the larger of the two returned values is used.
129239  **
129240  ** Similarly, iUpper is to be set to the estimate of the number of rows
129241  ** less than the upper bound of the range query. Where the upper bound
129242  ** is either ($P) or ($P:$U). Again, even if $U is available, both values
129243  ** of iUpper are requested of whereKeyStats() and the smaller used.
129244  **
129245  ** The number of rows between the two bounds is then just iUpper-iLower.
129246  */
129247  tRowcnt iLower; /* Rows less than the lower bound */
129248  tRowcnt iUpper; /* Rows less than the upper bound */
129249  int iLwrIdx = -2; /* aSample[] for the lower bound */
129250  int iUprIdx = -1; /* aSample[] for the upper bound */
129251 
129252  if( pRec ){
129253  testcase( pRec->nField!=pBuilder->nRecValid );
129254  pRec->nField = pBuilder->nRecValid;
129255  }
129256  /* Determine iLower and iUpper using ($P) only. */
129257  if( nEq==0 ){
129258  iLower = 0;
129259  iUpper = p->nRowEst0;
129260  }else{
129261  /* Note: this call could be optimized away - since the same values must
129262  ** have been requested when testing key $P in whereEqualScanEst(). */
129263  whereKeyStats(pParse, p, pRec, 0, a);
129264  iLower = a[0];
129265  iUpper = a[0] + a[1];
129266  }
129267 
129268  assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
129269  assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
129270  assert( p->aSortOrder!=0 );
129271  if( p->aSortOrder[nEq] ){
129272  /* The roles of pLower and pUpper are swapped for a DESC index */
129273  SWAP(WhereTerm*, pLower, pUpper);
129274  SWAP(int, nBtm, nTop);
129275  }
129276 
129277  /* If possible, improve on the iLower estimate using ($P:$L). */
129278  if( pLower ){
129279  int n; /* Values extracted from pExpr */
129280  Expr *pExpr = pLower->pExpr->pRight;
129281  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
129282  if( rc==SQLITE_OK && n ){
129283  tRowcnt iNew;
129284  u16 mask = WO_GT|WO_LE;
129285  if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
129286  iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
129287  iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
129288  if( iNew>iLower ) iLower = iNew;
129289  nOut--;
129290  pLower = 0;
129291  }
129292  }
129293 
129294  /* If possible, improve on the iUpper estimate using ($P:$U). */
129295  if( pUpper ){
129296  int n; /* Values extracted from pExpr */
129297  Expr *pExpr = pUpper->pExpr->pRight;
129298  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
129299  if( rc==SQLITE_OK && n ){
129300  tRowcnt iNew;
129301  u16 mask = WO_GT|WO_LE;
129302  if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
129303  iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
129304  iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
129305  if( iNew<iUpper ) iUpper = iNew;
129306  nOut--;
129307  pUpper = 0;
129308  }
129309  }
129310 
129311  pBuilder->pRec = pRec;
129312  if( rc==SQLITE_OK ){
129313  if( iUpper>iLower ){
129314  nNew = sqlite3LogEst(iUpper - iLower);
129315  /* TUNING: If both iUpper and iLower are derived from the same
129316  ** sample, then assume they are 4x more selective. This brings
129317  ** the estimated selectivity more in line with what it would be
129318  ** if estimated without the use of STAT3/4 tables. */
129319  if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
129320  }else{
129321  nNew = 10; assert( 10==sqlite3LogEst(2) );
129322  }
129323  if( nNew<nOut ){
129324  nOut = nNew;
129325  }
129326  WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
129327  (u32)iLower, (u32)iUpper, nOut));
129328  }
129329  }else{
129330  int bDone = 0;
129331  rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
129332  if( bDone ) return rc;
129333  }
129334  }
129335 #else
129336  UNUSED_PARAMETER(pParse);
129337  UNUSED_PARAMETER(pBuilder);
129338  assert( pLower || pUpper );
129339 #endif
129340  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
129341  nNew = whereRangeAdjust(pLower, nOut);
129342  nNew = whereRangeAdjust(pUpper, nNew);
129343 
129344  /* TUNING: If there is both an upper and lower limit and neither limit
129345  ** has an application-defined likelihood(), assume the range is
129346  ** reduced by an additional 75%. This means that, by default, an open-ended
129347  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
129348  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
129349  ** match 1/64 of the index. */
129350  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
129351  nNew -= 20;
129352  }
129353 
129354  nOut -= (pLower!=0) + (pUpper!=0);
129355  if( nNew<10 ) nNew = 10;
129356  if( nNew<nOut ) nOut = nNew;
129357 #if defined(WHERETRACE_ENABLED)
129358  if( pLoop->nOut>nOut ){
129359  WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
129360  pLoop->nOut, nOut));
129361  }
129362 #endif
129363  pLoop->nOut = (LogEst)nOut;
129364  return rc;
129365 }
129366 
129367 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129368 /*
129369 ** Estimate the number of rows that will be returned based on
129370 ** an equality constraint x=VALUE and where that VALUE occurs in
129371 ** the histogram data. This only works when x is the left-most
129372 ** column of an index and sqlite_stat3 histogram data is available
129373 ** for that index. When pExpr==NULL that means the constraint is
129374 ** "x IS NULL" instead of "x=VALUE".
129375 **
129376 ** Write the estimated row count into *pnRow and return SQLITE_OK.
129377 ** If unable to make an estimate, leave *pnRow unchanged and return
129378 ** non-zero.
129379 **
129380 ** This routine can fail if it is unable to load a collating sequence
129381 ** required for string comparison, or if unable to allocate memory
129382 ** for a UTF conversion required for comparison. The error is stored
129383 ** in the pParse structure.
129384 */
129385 static int whereEqualScanEst(
129386  Parse *pParse, /* Parsing & code generating context */
129387  WhereLoopBuilder *pBuilder,
129388  Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
129389  tRowcnt *pnRow /* Write the revised row estimate here */
129390 ){
129391  Index *p = pBuilder->pNew->u.btree.pIndex;
129392  int nEq = pBuilder->pNew->u.btree.nEq;
129393  UnpackedRecord *pRec = pBuilder->pRec;
129394  int rc; /* Subfunction return code */
129395  tRowcnt a[2]; /* Statistics */
129396  int bOk;
129397 
129398  assert( nEq>=1 );
129399  assert( nEq<=p->nColumn );
129400  assert( p->aSample!=0 );
129401  assert( p->nSample>0 );
129402  assert( pBuilder->nRecValid<nEq );
129403 
129404  /* If values are not available for all fields of the index to the left
129405  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
129406  if( pBuilder->nRecValid<(nEq-1) ){
129407  return SQLITE_NOTFOUND;
129408  }
129409 
129410  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
129411  ** below would return the same value. */
129412  if( nEq>=p->nColumn ){
129413  *pnRow = 1;
129414  return SQLITE_OK;
129415  }
129416 
129417  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
129418  pBuilder->pRec = pRec;
129419  if( rc!=SQLITE_OK ) return rc;
129420  if( bOk==0 ) return SQLITE_NOTFOUND;
129421  pBuilder->nRecValid = nEq;
129422 
129423  whereKeyStats(pParse, p, pRec, 0, a);
129424  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
129425  p->zName, nEq-1, (int)a[1]));
129426  *pnRow = a[1];
129427 
129428  return rc;
129429 }
129430 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129431 
129432 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129433 /*
129434 ** Estimate the number of rows that will be returned based on
129435 ** an IN constraint where the right-hand side of the IN operator
129436 ** is a list of values. Example:
129437 **
129438 ** WHERE x IN (1,2,3,4)
129439 **
129440 ** Write the estimated row count into *pnRow and return SQLITE_OK.
129441 ** If unable to make an estimate, leave *pnRow unchanged and return
129442 ** non-zero.
129443 **
129444 ** This routine can fail if it is unable to load a collating sequence
129445 ** required for string comparison, or if unable to allocate memory
129446 ** for a UTF conversion required for comparison. The error is stored
129447 ** in the pParse structure.
129448 */
129449 static int whereInScanEst(
129450  Parse *pParse, /* Parsing & code generating context */
129451  WhereLoopBuilder *pBuilder,
129452  ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
129453  tRowcnt *pnRow /* Write the revised row estimate here */
129454 ){
129455  Index *p = pBuilder->pNew->u.btree.pIndex;
129456  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
129457  int nRecValid = pBuilder->nRecValid;
129458  int rc = SQLITE_OK; /* Subfunction return code */
129459  tRowcnt nEst; /* Number of rows for a single term */
129460  tRowcnt nRowEst = 0; /* New estimate of the number of rows */
129461  int i; /* Loop counter */
129462 
129463  assert( p->aSample!=0 );
129464  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
129465  nEst = nRow0;
129466  rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
129467  nRowEst += nEst;
129468  pBuilder->nRecValid = nRecValid;
129469  }
129470 
129471  if( rc==SQLITE_OK ){
129472  if( nRowEst > nRow0 ) nRowEst = nRow0;
129473  *pnRow = nRowEst;
129474  WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
129475  }
129476  assert( pBuilder->nRecValid==nRecValid );
129477  return rc;
129478 }
129479 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
129480 
129481 
129482 #ifdef WHERETRACE_ENABLED
129483 /*
129484 ** Print the content of a WhereTerm object
129485 */
129486 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
129487  if( pTerm==0 ){
129488  sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
129489  }else{
129490  char zType[4];
129491  char zLeft[50];
129492  memcpy(zType, "...", 4);
129493  if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
129494  if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
129495  if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
129496  if( pTerm->eOperator & WO_SINGLE ){
129497  sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
129498  pTerm->leftCursor, pTerm->u.leftColumn);
129499  }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
129500  sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
129501  pTerm->u.pOrInfo->indexable);
129502  }else{
129503  sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
129504  }
129505  sqlite3DebugPrintf(
129506  "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
129507  iTerm, pTerm, zType, zLeft, pTerm->truthProb,
129508  pTerm->eOperator, pTerm->wtFlags);
129509  if( pTerm->iField ){
129510  sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
129511  }else{
129512  sqlite3DebugPrintf("\n");
129513  }
129514  sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
129515  }
129516 }
129517 #endif
129518 
129519 #ifdef WHERETRACE_ENABLED
129520 /*
129521 ** Show the complete content of a WhereClause
129522 */
129523 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
129524  int i;
129525  for(i=0; i<pWC->nTerm; i++){
129526  whereTermPrint(&pWC->a[i], i);
129527  }
129528 }
129529 #endif
129530 
129531 #ifdef WHERETRACE_ENABLED
129532 /*
129533 ** Print a WhereLoop object for debugging purposes
129534 */
129535 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
129536  WhereInfo *pWInfo = pWC->pWInfo;
129537  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
129538  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
129539  Table *pTab = pItem->pTab;
129540  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
129541  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
129542  p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
129543  sqlite3DebugPrintf(" %12s",
129544  pItem->zAlias ? pItem->zAlias : pTab->zName);
129545  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
129546  const char *zName;
129547  if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
129548  if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
129549  int i = sqlite3Strlen30(zName) - 1;
129550  while( zName[i]!='_' ) i--;
129551  zName += i;
129552  }
129553  sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
129554  }else{
129555  sqlite3DebugPrintf("%20s","");
129556  }
129557  }else{
129558  char *z;
129559  if( p->u.vtab.idxStr ){
129560  z = sqlite3_mprintf("(%d,\"%s\",%x)",
129561  p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
129562  }else{
129563  z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
129564  }
129565  sqlite3DebugPrintf(" %-19s", z);
129566  sqlite3_free(z);
129567  }
129568  if( p->wsFlags & WHERE_SKIPSCAN ){
129569  sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
129570  }else{
129571  sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
129572  }
129573  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
129574  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
129575  int i;
129576  for(i=0; i<p->nLTerm; i++){
129577  whereTermPrint(p->aLTerm[i], i);
129578  }
129579  }
129580 }
129581 #endif
129582 
129583 /*
129584 ** Convert bulk memory into a valid WhereLoop that can be passed
129585 ** to whereLoopClear harmlessly.
129586 */
129587 static void whereLoopInit(WhereLoop *p){
129588  p->aLTerm = p->aLTermSpace;
129589  p->nLTerm = 0;
129590  p->nLSlot = ArraySize(p->aLTermSpace);
129591  p->wsFlags = 0;
129592 }
129593 
129594 /*
129595 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
129596 */
129597 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
129599  if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
129600  sqlite3_free(p->u.vtab.idxStr);
129601  p->u.vtab.needFree = 0;
129602  p->u.vtab.idxStr = 0;
129603  }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
129604  sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
129605  sqlite3DbFree(db, p->u.btree.pIndex);
129606  p->u.btree.pIndex = 0;
129607  }
129608  }
129609 }
129610 
129611 /*
129612 ** Deallocate internal memory used by a WhereLoop object
129613 */
129614 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
129615  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
129616  whereLoopClearUnion(db, p);
129617  whereLoopInit(p);
129618 }
129619 
129620 /*
129621 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
129622 */
129623 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
129624  WhereTerm **paNew;
129625  if( p->nLSlot>=n ) return SQLITE_OK;
129626  n = (n+7)&~7;
129627  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
129628  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
129629  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
129630  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
129631  p->aLTerm = paNew;
129632  p->nLSlot = n;
129633  return SQLITE_OK;
129634 }
129635 
129636 /*
129637 ** Transfer content from the second pLoop into the first.
129638 */
129639 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
129640  whereLoopClearUnion(db, pTo);
129641  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
129642  memset(&pTo->u, 0, sizeof(pTo->u));
129643  return SQLITE_NOMEM_BKPT;
129644  }
129645  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
129646  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
129647  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
129648  pFrom->u.vtab.needFree = 0;
129649  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
129650  pFrom->u.btree.pIndex = 0;
129651  }
129652  return SQLITE_OK;
129653 }
129654 
129655 /*
129656 ** Delete a WhereLoop object
129657 */
129658 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
129659  whereLoopClear(db, p);
129660  sqlite3DbFree(db, p);
129661 }
129662 
129663 /*
129664 ** Free a WhereInfo structure
129665 */
129666 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
129667  if( ALWAYS(pWInfo) ){
129668  int i;
129669  for(i=0; i<pWInfo->nLevel; i++){
129670  WhereLevel *pLevel = &pWInfo->a[i];
129671  if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
129672  sqlite3DbFree(db, pLevel->u.in.aInLoop);
129673  }
129674  }
129675  sqlite3WhereClauseClear(&pWInfo->sWC);
129676  while( pWInfo->pLoops ){
129677  WhereLoop *p = pWInfo->pLoops;
129678  pWInfo->pLoops = p->pNextLoop;
129679  whereLoopDelete(db, p);
129680  }
129681  sqlite3DbFree(db, pWInfo);
129682  }
129683 }
129684 
129685 /*
129686 ** Return TRUE if all of the following are true:
129687 **
129688 ** (1) X has the same or lower cost that Y
129689 ** (2) X is a proper subset of Y
129690 ** (3) X skips at least as many columns as Y
129691 **
129692 ** By "proper subset" we mean that X uses fewer WHERE clause terms
129693 ** than Y and that every WHERE clause term used by X is also used
129694 ** by Y.
129695 **
129696 ** If X is a proper subset of Y then Y is a better choice and ought
129697 ** to have a lower cost. This routine returns TRUE when that cost
129698 ** relationship is inverted and needs to be adjusted. The third rule
129699 ** was added because if X uses skip-scan less than Y it still might
129700 ** deserve a lower cost even if it is a proper subset of Y.
129701 */
129703  const WhereLoop *pX, /* First WhereLoop to compare */
129704  const WhereLoop *pY /* Compare against this WhereLoop */
129705 ){
129706  int i, j;
129707  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
129708  return 0; /* X is not a subset of Y */
129709  }
129710  if( pY->nSkip > pX->nSkip ) return 0;
129711  if( pX->rRun >= pY->rRun ){
129712  if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
129713  if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
129714  }
129715  for(i=pX->nLTerm-1; i>=0; i--){
129716  if( pX->aLTerm[i]==0 ) continue;
129717  for(j=pY->nLTerm-1; j>=0; j--){
129718  if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
129719  }
129720  if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
129721  }
129722  return 1; /* All conditions meet */
129723 }
129724 
129725 /*
129726 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
129727 ** that:
129728 **
129729 ** (1) pTemplate costs less than any other WhereLoops that are a proper
129730 ** subset of pTemplate
129731 **
129732 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
129733 ** is a proper subset.
129734 **
129735 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
129736 ** WHERE clause terms than Y and that every WHERE clause term used by X is
129737 ** also used by Y.
129738 */
129739 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
129740  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
129741  for(; p; p=p->pNextLoop){
129742  if( p->iTab!=pTemplate->iTab ) continue;
129743  if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
129744  if( whereLoopCheaperProperSubset(p, pTemplate) ){
129745  /* Adjust pTemplate cost downward so that it is cheaper than its
129746  ** subset p. */
129747  WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
129748  pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
129749  pTemplate->rRun = p->rRun;
129750  pTemplate->nOut = p->nOut - 1;
129751  }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
129752  /* Adjust pTemplate cost upward so that it is costlier than p since
129753  ** pTemplate is a proper subset of p */
129754  WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
129755  pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
129756  pTemplate->rRun = p->rRun;
129757  pTemplate->nOut = p->nOut + 1;
129758  }
129759  }
129760 }
129761 
129762 /*
129763 ** Search the list of WhereLoops in *ppPrev looking for one that can be
129764 ** supplanted by pTemplate.
129765 **
129766 ** Return NULL if the WhereLoop list contains an entry that can supplant
129767 ** pTemplate, in other words if pTemplate does not belong on the list.
129768 **
129769 ** If pX is a WhereLoop that pTemplate can supplant, then return the
129770 ** link that points to pX.
129771 **
129772 ** If pTemplate cannot supplant any existing element of the list but needs
129773 ** to be added to the list, then return a pointer to the tail of the list.
129774 */
129776  WhereLoop **ppPrev,
129777  const WhereLoop *pTemplate
129778 ){
129779  WhereLoop *p;
129780  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
129781  if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
129782  /* If either the iTab or iSortIdx values for two WhereLoop are different
129783  ** then those WhereLoops need to be considered separately. Neither is
129784  ** a candidate to replace the other. */
129785  continue;
129786  }
129787  /* In the current implementation, the rSetup value is either zero
129788  ** or the cost of building an automatic index (NlogN) and the NlogN
129789  ** is the same for compatible WhereLoops. */
129790  assert( p->rSetup==0 || pTemplate->rSetup==0
129791  || p->rSetup==pTemplate->rSetup );
129792 
129793  /* whereLoopAddBtree() always generates and inserts the automatic index
129794  ** case first. Hence compatible candidate WhereLoops never have a larger
129795  ** rSetup. Call this SETUP-INVARIANT */
129796  assert( p->rSetup>=pTemplate->rSetup );
129797 
129798  /* Any loop using an appliation-defined index (or PRIMARY KEY or
129799  ** UNIQUE constraint) with one or more == constraints is better
129800  ** than an automatic index. Unless it is a skip-scan. */
129801  if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
129802  && (pTemplate->nSkip)==0
129803  && (pTemplate->wsFlags & WHERE_INDEXED)!=0
129804  && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
129805  && (p->prereq & pTemplate->prereq)==pTemplate->prereq
129806  ){
129807  break;
129808  }
129809 
129810  /* If existing WhereLoop p is better than pTemplate, pTemplate can be
129811  ** discarded. WhereLoop p is better if:
129812  ** (1) p has no more dependencies than pTemplate, and
129813  ** (2) p has an equal or lower cost than pTemplate
129814  */
129815  if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
129816  && p->rSetup<=pTemplate->rSetup /* (2a) */
129817  && p->rRun<=pTemplate->rRun /* (2b) */
129818  && p->nOut<=pTemplate->nOut /* (2c) */
129819  ){
129820  return 0; /* Discard pTemplate */
129821  }
129822 
129823  /* If pTemplate is always better than p, then cause p to be overwritten
129824  ** with pTemplate. pTemplate is better than p if:
129825  ** (1) pTemplate has no more dependences than p, and
129826  ** (2) pTemplate has an equal or lower cost than p.
129827  */
129828  if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
129829  && p->rRun>=pTemplate->rRun /* (2a) */
129830  && p->nOut>=pTemplate->nOut /* (2b) */
129831  ){
129832  assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
129833  break; /* Cause p to be overwritten by pTemplate */
129834  }
129835  }
129836  return ppPrev;
129837 }
129838 
129839 /*
129840 ** Insert or replace a WhereLoop entry using the template supplied.
129841 **
129842 ** An existing WhereLoop entry might be overwritten if the new template
129843 ** is better and has fewer dependencies. Or the template will be ignored
129844 ** and no insert will occur if an existing WhereLoop is faster and has
129845 ** fewer dependencies than the template. Otherwise a new WhereLoop is
129846 ** added based on the template.
129847 **
129848 ** If pBuilder->pOrSet is not NULL then we care about only the
129849 ** prerequisites and rRun and nOut costs of the N best loops. That
129850 ** information is gathered in the pBuilder->pOrSet object. This special
129851 ** processing mode is used only for OR clause processing.
129852 **
129853 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
129854 ** still might overwrite similar loops with the new template if the
129855 ** new template is better. Loops may be overwritten if the following
129856 ** conditions are met:
129857 **
129858 ** (1) They have the same iTab.
129859 ** (2) They have the same iSortIdx.
129860 ** (3) The template has same or fewer dependencies than the current loop
129861 ** (4) The template has the same or lower cost than the current loop
129862 */
129863 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
129864  WhereLoop **ppPrev, *p;
129865  WhereInfo *pWInfo = pBuilder->pWInfo;
129866  sqlite3 *db = pWInfo->pParse->db;
129867  int rc;
129868 
129869  /* If pBuilder->pOrSet is defined, then only keep track of the costs
129870  ** and prereqs.
129871  */
129872  if( pBuilder->pOrSet!=0 ){
129873  if( pTemplate->nLTerm ){
129874 #if WHERETRACE_ENABLED
129875  u16 n = pBuilder->pOrSet->n;
129876  int x =
129877 #endif
129878  whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
129879  pTemplate->nOut);
129880 #if WHERETRACE_ENABLED /* 0x8 */
129881  if( sqlite3WhereTrace & 0x8 ){
129882  sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
129883  whereLoopPrint(pTemplate, pBuilder->pWC);
129884  }
129885 #endif
129886  }
129887  return SQLITE_OK;
129888  }
129889 
129890  /* Look for an existing WhereLoop to replace with pTemplate
129891  */
129892  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
129893  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
129894 
129895  if( ppPrev==0 ){
129896  /* There already exists a WhereLoop on the list that is better
129897  ** than pTemplate, so just ignore pTemplate */
129898 #if WHERETRACE_ENABLED /* 0x8 */
129899  if( sqlite3WhereTrace & 0x8 ){
129900  sqlite3DebugPrintf(" skip: ");
129901  whereLoopPrint(pTemplate, pBuilder->pWC);
129902  }
129903 #endif
129904  return SQLITE_OK;
129905  }else{
129906  p = *ppPrev;
129907  }
129908 
129909  /* If we reach this point it means that either p[] should be overwritten
129910  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
129911  ** WhereLoop and insert it.
129912  */
129913 #if WHERETRACE_ENABLED /* 0x8 */
129914  if( sqlite3WhereTrace & 0x8 ){
129915  if( p!=0 ){
129916  sqlite3DebugPrintf("replace: ");
129917  whereLoopPrint(p, pBuilder->pWC);
129918  }
129919  sqlite3DebugPrintf(" add: ");
129920  whereLoopPrint(pTemplate, pBuilder->pWC);
129921  }
129922 #endif
129923  if( p==0 ){
129924  /* Allocate a new WhereLoop to add to the end of the list */
129925  *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
129926  if( p==0 ) return SQLITE_NOMEM_BKPT;
129927  whereLoopInit(p);
129928  p->pNextLoop = 0;
129929  }else{
129930  /* We will be overwriting WhereLoop p[]. But before we do, first
129931  ** go through the rest of the list and delete any other entries besides
129932  ** p[] that are also supplated by pTemplate */
129933  WhereLoop **ppTail = &p->pNextLoop;
129934  WhereLoop *pToDel;
129935  while( *ppTail ){
129936  ppTail = whereLoopFindLesser(ppTail, pTemplate);
129937  if( ppTail==0 ) break;
129938  pToDel = *ppTail;
129939  if( pToDel==0 ) break;
129940  *ppTail = pToDel->pNextLoop;
129941 #if WHERETRACE_ENABLED /* 0x8 */
129942  if( sqlite3WhereTrace & 0x8 ){
129943  sqlite3DebugPrintf(" delete: ");
129944  whereLoopPrint(pToDel, pBuilder->pWC);
129945  }
129946 #endif
129947  whereLoopDelete(db, pToDel);
129948  }
129949  }
129950  rc = whereLoopXfer(db, p, pTemplate);
129951  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
129952  Index *pIndex = p->u.btree.pIndex;
129953  if( pIndex && pIndex->tnum==0 ){
129954  p->u.btree.pIndex = 0;
129955  }
129956  }
129957  return rc;
129958 }
129959 
129960 /*
129961 ** Adjust the WhereLoop.nOut value downward to account for terms of the
129962 ** WHERE clause that reference the loop but which are not used by an
129963 ** index.
129964 *
129965 ** For every WHERE clause term that is not used by the index
129966 ** and which has a truth probability assigned by one of the likelihood(),
129967 ** likely(), or unlikely() SQL functions, reduce the estimated number
129968 ** of output rows by the probability specified.
129969 **
129970 ** TUNING: For every WHERE clause term that is not used by the index
129971 ** and which does not have an assigned truth probability, heuristics
129972 ** described below are used to try to estimate the truth probability.
129973 ** TODO --> Perhaps this is something that could be improved by better
129974 ** table statistics.
129975 **
129976 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
129977 ** value corresponds to -1 in LogEst notation, so this means decrement
129978 ** the WhereLoop.nOut field for every such WHERE clause term.
129979 **
129980 ** Heuristic 2: If there exists one or more WHERE clause terms of the
129981 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
129982 ** final output row estimate is no greater than 1/4 of the total number
129983 ** of rows in the table. In other words, assume that x==EXPR will filter
129984 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
129985 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
129986 ** on the "x" column and so in that case only cap the output row estimate
129987 ** at 1/2 instead of 1/4.
129988 */
129990  WhereClause *pWC, /* The WHERE clause */
129991  WhereLoop *pLoop, /* The loop to adjust downward */
129992  LogEst nRow /* Number of rows in the entire table */
129993 ){
129994  WhereTerm *pTerm, *pX;
129995  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
129996  int i, j, k;
129997  LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
129998 
129999  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
130000  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
130001  if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
130002  if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
130003  if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
130004  for(j=pLoop->nLTerm-1; j>=0; j--){
130005  pX = pLoop->aLTerm[j];
130006  if( pX==0 ) continue;
130007  if( pX==pTerm ) break;
130008  if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
130009  }
130010  if( j<0 ){
130011  if( pTerm->truthProb<=0 ){
130012  /* If a truth probability is specified using the likelihood() hints,
130013  ** then use the probability provided by the application. */
130014  pLoop->nOut += pTerm->truthProb;
130015  }else{
130016  /* In the absence of explicit truth probabilities, use heuristics to
130017  ** guess a reasonable truth probability. */
130018  pLoop->nOut--;
130019  if( pTerm->eOperator&(WO_EQ|WO_IS) ){
130020  Expr *pRight = pTerm->pExpr->pRight;
130021  testcase( pTerm->pExpr->op==TK_IS );
130022  if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
130023  k = 10;
130024  }else{
130025  k = 20;
130026  }
130027  if( iReduce<k ) iReduce = k;
130028  }
130029  }
130030  }
130031  }
130032  if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
130033 }
130034 
130035 /*
130036 ** Term pTerm is a vector range comparison operation. The first comparison
130037 ** in the vector can be optimized using column nEq of the index. This
130038 ** function returns the total number of vector elements that can be used
130039 ** as part of the range comparison.
130040 **
130041 ** For example, if the query is:
130042 **
130043 ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
130044 **
130045 ** and the index:
130046 **
130047 ** CREATE INDEX ... ON (a, b, c, d, e)
130048 **
130049 ** then this function would be invoked with nEq=1. The value returned in
130050 ** this case is 3.
130051 */
130053  Parse *pParse, /* Parsing context */
130054  int iCur, /* Cursor open on pIdx */
130055  Index *pIdx, /* The index to be used for a inequality constraint */
130056  int nEq, /* Number of prior equality constraints on same index */
130057  WhereTerm *pTerm /* The vector inequality constraint */
130058 ){
130059  int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
130060  int i;
130061 
130062  nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
130063  for(i=1; i<nCmp; i++){
130064  /* Test if comparison i of pTerm is compatible with column (i+nEq)
130065  ** of the index. If not, exit the loop. */
130066  char aff; /* Comparison affinity */
130067  char idxaff = 0; /* Indexed columns affinity */
130068  CollSeq *pColl; /* Comparison collation sequence */
130069  Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
130070  Expr *pRhs = pTerm->pExpr->pRight;
130071  if( pRhs->flags & EP_xIsSelect ){
130072  pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
130073  }else{
130074  pRhs = pRhs->x.pList->a[i].pExpr;
130075  }
130076 
130077  /* Check that the LHS of the comparison is a column reference to
130078  ** the right column of the right source table. And that the sort
130079  ** order of the index column is the same as the sort order of the
130080  ** leftmost index column. */
130081  if( pLhs->op!=TK_COLUMN
130082  || pLhs->iTable!=iCur
130083  || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
130084  || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
130085  ){
130086  break;
130087  }
130088 
130089  testcase( pLhs->iColumn==XN_ROWID );
130090  aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
130091  idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
130092  if( aff!=idxaff ) break;
130093 
130094  pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
130095  if( pColl==0 ) break;
130096  if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
130097  }
130098  return i;
130099 }
130100 
130101 /*
130102 ** Adjust the cost C by the costMult facter T. This only occurs if
130103 ** compiled with -DSQLITE_ENABLE_COSTMULT
130104 */
130105 #ifdef SQLITE_ENABLE_COSTMULT
130106 # define ApplyCostMultiplier(C,T) C += T
130107 #else
130108 # define ApplyCostMultiplier(C,T)
130109 #endif
130110 
130111 /*
130112 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
130113 ** index pIndex. Try to match one more.
130114 **
130115 ** When this function is called, pBuilder->pNew->nOut contains the
130116 ** number of rows expected to be visited by filtering using the nEq
130117 ** terms only. If it is modified, this value is restored before this
130118 ** function returns.
130119 **
130120 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
130121 ** INTEGER PRIMARY KEY.
130122 */
130124  WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
130125  struct SrcList_item *pSrc, /* FROM clause term being analyzed */
130126  Index *pProbe, /* An index on pSrc */
130127  LogEst nInMul /* log(Number of iterations due to IN) */
130128 ){
130129  WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
130130  Parse *pParse = pWInfo->pParse; /* Parsing context */
130131  sqlite3 *db = pParse->db; /* Database connection malloc context */
130132  WhereLoop *pNew; /* Template WhereLoop under construction */
130133  WhereTerm *pTerm; /* A WhereTerm under consideration */
130134  int opMask; /* Valid operators for constraints */
130135  WhereScan scan; /* Iterator for WHERE terms */
130136  Bitmask saved_prereq; /* Original value of pNew->prereq */
130137  u16 saved_nLTerm; /* Original value of pNew->nLTerm */
130138  u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
130139  u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
130140  u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
130141  u16 saved_nSkip; /* Original value of pNew->nSkip */
130142  u32 saved_wsFlags; /* Original value of pNew->wsFlags */
130143  LogEst saved_nOut; /* Original value of pNew->nOut */
130144  int rc = SQLITE_OK; /* Return code */
130145  LogEst rSize; /* Number of rows in the table */
130146  LogEst rLogSize; /* Logarithm of table size */
130147  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
130148 
130149  pNew = pBuilder->pNew;
130150  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
130151  WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
130152  pProbe->zName, pNew->u.btree.nEq));
130153 
130154  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
130155  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
130156  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
130157  opMask = WO_LT|WO_LE;
130158  }else{
130159  assert( pNew->u.btree.nBtm==0 );
130161  }
130162  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
130163 
130164  assert( pNew->u.btree.nEq<pProbe->nColumn );
130165 
130166  saved_nEq = pNew->u.btree.nEq;
130167  saved_nBtm = pNew->u.btree.nBtm;
130168  saved_nTop = pNew->u.btree.nTop;
130169  saved_nSkip = pNew->nSkip;
130170  saved_nLTerm = pNew->nLTerm;
130171  saved_wsFlags = pNew->wsFlags;
130172  saved_prereq = pNew->prereq;
130173  saved_nOut = pNew->nOut;
130174  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
130175  opMask, pProbe);
130176  pNew->rSetup = 0;
130177  rSize = pProbe->aiRowLogEst[0];
130178  rLogSize = estLog(rSize);
130179  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
130180  u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
130181  LogEst rCostIdx;
130182  LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
130183  int nIn = 0;
130184 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130185  int nRecValid = pBuilder->nRecValid;
130186 #endif
130187  if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
130188  && indexColumnNotNull(pProbe, saved_nEq)
130189  ){
130190  continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
130191  }
130192  if( pTerm->prereqRight & pNew->maskSelf ) continue;
130193 
130194  /* Do not allow the upper bound of a LIKE optimization range constraint
130195  ** to mix with a lower range bound from some other source */
130196  if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
130197 
130198  /* Do not allow IS constraints from the WHERE clause to be used by the
130199  ** right table of a LEFT JOIN. Only constraints in the ON clause are
130200  ** allowed */
130201  if( (pSrc->fg.jointype & JT_LEFT)!=0
130202  && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
130203  && (eOp & (WO_IS|WO_ISNULL))!=0
130204  ){
130205  testcase( eOp & WO_IS );
130206  testcase( eOp & WO_ISNULL );
130207  continue;
130208  }
130209 
130210  pNew->wsFlags = saved_wsFlags;
130211  pNew->u.btree.nEq = saved_nEq;
130212  pNew->u.btree.nBtm = saved_nBtm;
130213  pNew->u.btree.nTop = saved_nTop;
130214  pNew->nLTerm = saved_nLTerm;
130215  if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
130216  pNew->aLTerm[pNew->nLTerm++] = pTerm;
130217  pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
130218 
130219  assert( nInMul==0
130220  || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
130221  || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
130222  || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
130223  );
130224 
130225  if( eOp & WO_IN ){
130226  Expr *pExpr = pTerm->pExpr;
130227  pNew->wsFlags |= WHERE_COLUMN_IN;
130228  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
130229  /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
130230  int i;
130231  nIn = 46; assert( 46==sqlite3LogEst(25) );
130232 
130233  /* The expression may actually be of the form (x, y) IN (SELECT...).
130234  ** In this case there is a separate term for each of (x) and (y).
130235  ** However, the nIn multiplier should only be applied once, not once
130236  ** for each such term. The following loop checks that pTerm is the
130237  ** first such term in use, and sets nIn back to 0 if it is not. */
130238  for(i=0; i<pNew->nLTerm-1; i++){
130239  if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
130240  }
130241  }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
130242  /* "x IN (value, value, ...)" */
130243  nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
130244  assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
130245  ** changes "x IN (?)" into "x=?". */
130246  }
130247  }else if( eOp & (WO_EQ|WO_IS) ){
130248  int iCol = pProbe->aiColumn[saved_nEq];
130249  pNew->wsFlags |= WHERE_COLUMN_EQ;
130250  assert( saved_nEq==pNew->u.btree.nEq );
130251  if( iCol==XN_ROWID
130252  || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
130253  ){
130254  if( iCol>=0 && pProbe->uniqNotNull==0 ){
130255  pNew->wsFlags |= WHERE_UNQ_WANTED;
130256  }else{
130257  pNew->wsFlags |= WHERE_ONEROW;
130258  }
130259  }
130260  }else if( eOp & WO_ISNULL ){
130261  pNew->wsFlags |= WHERE_COLUMN_NULL;
130262  }else if( eOp & (WO_GT|WO_GE) ){
130263  testcase( eOp & WO_GT );
130264  testcase( eOp & WO_GE );
130266  pNew->u.btree.nBtm = whereRangeVectorLen(
130267  pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
130268  );
130269  pBtm = pTerm;
130270  pTop = 0;
130271  if( pTerm->wtFlags & TERM_LIKEOPT ){
130272  /* Range contraints that come from the LIKE optimization are
130273  ** always used in pairs. */
130274  pTop = &pTerm[1];
130275  assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
130276  assert( pTop->wtFlags & TERM_LIKEOPT );
130277  assert( pTop->eOperator==WO_LT );
130278  if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
130279  pNew->aLTerm[pNew->nLTerm++] = pTop;
130280  pNew->wsFlags |= WHERE_TOP_LIMIT;
130281  pNew->u.btree.nTop = 1;
130282  }
130283  }else{
130284  assert( eOp & (WO_LT|WO_LE) );
130285  testcase( eOp & WO_LT );
130286  testcase( eOp & WO_LE );
130288  pNew->u.btree.nTop = whereRangeVectorLen(
130289  pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
130290  );
130291  pTop = pTerm;
130292  pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
130293  pNew->aLTerm[pNew->nLTerm-2] : 0;
130294  }
130295 
130296  /* At this point pNew->nOut is set to the number of rows expected to
130297  ** be visited by the index scan before considering term pTerm, or the
130298  ** values of nIn and nInMul. In other words, assuming that all
130299  ** "x IN(...)" terms are replaced with "x = ?". This block updates
130300  ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
130301  assert( pNew->nOut==saved_nOut );
130302  if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
130303  /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
130304  ** data, using some other estimate. */
130305  whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
130306  }else{
130307  int nEq = ++pNew->u.btree.nEq;
130308  assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
130309 
130310  assert( pNew->nOut==saved_nOut );
130311  if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
130312  assert( (eOp & WO_IN) || nIn==0 );
130313  testcase( eOp & WO_IN );
130314  pNew->nOut += pTerm->truthProb;
130315  pNew->nOut -= nIn;
130316  }else{
130317 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130318  tRowcnt nOut = 0;
130319  if( nInMul==0
130320  && pProbe->nSample
130321  && pNew->u.btree.nEq<=pProbe->nSampleCol
130322  && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
130323  ){
130324  Expr *pExpr = pTerm->pExpr;
130325  if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
130326  testcase( eOp & WO_EQ );
130327  testcase( eOp & WO_IS );
130328  testcase( eOp & WO_ISNULL );
130329  rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
130330  }else{
130331  rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
130332  }
130333  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
130334  if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
130335  if( nOut ){
130336  pNew->nOut = sqlite3LogEst(nOut);
130337  if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
130338  pNew->nOut -= nIn;
130339  }
130340  }
130341  if( nOut==0 )
130342 #endif
130343  {
130344  pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
130345  if( eOp & WO_ISNULL ){
130346  /* TUNING: If there is no likelihood() value, assume that a
130347  ** "col IS NULL" expression matches twice as many rows
130348  ** as (col=?). */
130349  pNew->nOut += 10;
130350  }
130351  }
130352  }
130353  }
130354 
130355  /* Set rCostIdx to the cost of visiting selected rows in index. Add
130356  ** it to pNew->rRun, which is currently set to the cost of the index
130357  ** seek only. Then, if this is a non-covering index, add the cost of
130358  ** visiting the rows in the main table. */
130359  rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
130360  pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
130361  if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
130362  pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
130363  }
130364  ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
130365 
130366  nOutUnadjusted = pNew->nOut;
130367  pNew->rRun += nInMul + nIn;
130368  pNew->nOut += nInMul + nIn;
130369  whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
130370  rc = whereLoopInsert(pBuilder, pNew);
130371 
130372  if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
130373  pNew->nOut = saved_nOut;
130374  }else{
130375  pNew->nOut = nOutUnadjusted;
130376  }
130377 
130378  if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
130379  && pNew->u.btree.nEq<pProbe->nColumn
130380  ){
130381  whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
130382  }
130383  pNew->nOut = saved_nOut;
130384 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130385  pBuilder->nRecValid = nRecValid;
130386 #endif
130387  }
130388  pNew->prereq = saved_prereq;
130389  pNew->u.btree.nEq = saved_nEq;
130390  pNew->u.btree.nBtm = saved_nBtm;
130391  pNew->u.btree.nTop = saved_nTop;
130392  pNew->nSkip = saved_nSkip;
130393  pNew->wsFlags = saved_wsFlags;
130394  pNew->nOut = saved_nOut;
130395  pNew->nLTerm = saved_nLTerm;
130396 
130397  /* Consider using a skip-scan if there are no WHERE clause constraints
130398  ** available for the left-most terms of the index, and if the average
130399  ** number of repeats in the left-most terms is at least 18.
130400  **
130401  ** The magic number 18 is selected on the basis that scanning 17 rows
130402  ** is almost always quicker than an index seek (even though if the index
130403  ** contains fewer than 2^17 rows we assume otherwise in other parts of
130404  ** the code). And, even if it is not, it should not be too much slower.
130405  ** On the other hand, the extra seeks could end up being significantly
130406  ** more expensive. */
130407  assert( 42==sqlite3LogEst(18) );
130408  if( saved_nEq==saved_nSkip
130409  && saved_nEq+1<pProbe->nKeyCol
130410  && pProbe->noSkipScan==0
130411  && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
130412  && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
130413  ){
130414  LogEst nIter;
130415  pNew->u.btree.nEq++;
130416  pNew->nSkip++;
130417  pNew->aLTerm[pNew->nLTerm++] = 0;
130418  pNew->wsFlags |= WHERE_SKIPSCAN;
130419  nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
130420  pNew->nOut -= nIter;
130421  /* TUNING: Because uncertainties in the estimates for skip-scan queries,
130422  ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
130423  nIter += 5;
130424  whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
130425  pNew->nOut = saved_nOut;
130426  pNew->u.btree.nEq = saved_nEq;
130427  pNew->nSkip = saved_nSkip;
130428  pNew->wsFlags = saved_wsFlags;
130429  }
130430 
130431  WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
130432  pProbe->zName, saved_nEq, rc));
130433  return rc;
130434 }
130435 
130436 /*
130437 ** Return True if it is possible that pIndex might be useful in
130438 ** implementing the ORDER BY clause in pBuilder.
130439 **
130440 ** Return False if pBuilder does not contain an ORDER BY clause or
130441 ** if there is no way for pIndex to be useful in implementing that
130442 ** ORDER BY clause.
130443 */
130445  WhereLoopBuilder *pBuilder,
130446  Index *pIndex,
130447  int iCursor
130448 ){
130449  ExprList *pOB;
130450  ExprList *aColExpr;
130451  int ii, jj;
130452 
130453  if( pIndex->bUnordered ) return 0;
130454  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
130455  for(ii=0; ii<pOB->nExpr; ii++){
130456  Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
130457  if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
130458  if( pExpr->iColumn<0 ) return 1;
130459  for(jj=0; jj<pIndex->nKeyCol; jj++){
130460  if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
130461  }
130462  }else if( (aColExpr = pIndex->aColExpr)!=0 ){
130463  for(jj=0; jj<pIndex->nKeyCol; jj++){
130464  if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
130465  if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
130466  return 1;
130467  }
130468  }
130469  }
130470  }
130471  return 0;
130472 }
130473 
130474 /*
130475 ** Return a bitmask where 1s indicate that the corresponding column of
130476 ** the table is used by an index. Only the first 63 columns are considered.
130477 */
130478 static Bitmask columnsInIndex(Index *pIdx){
130479  Bitmask m = 0;
130480  int j;
130481  for(j=pIdx->nColumn-1; j>=0; j--){
130482  int x = pIdx->aiColumn[j];
130483  if( x>=0 ){
130484  testcase( x==BMS-1 );
130485  testcase( x==BMS-2 );
130486  if( x<BMS-1 ) m |= MASKBIT(x);
130487  }
130488  }
130489  return m;
130490 }
130491 
130492 /* Check to see if a partial index with pPartIndexWhere can be used
130493 ** in the current query. Return true if it can be and false if not.
130494 */
130495 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
130496  int i;
130497  WhereTerm *pTerm;
130498  while( pWhere->op==TK_AND ){
130499  if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
130500  pWhere = pWhere->pRight;
130501  }
130502  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
130503  Expr *pExpr = pTerm->pExpr;
130504  if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
130505  && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
130506  ){
130507  return 1;
130508  }
130509  }
130510  return 0;
130511 }
130512 
130513 /*
130514 ** Add all WhereLoop objects for a single table of the join where the table
130515 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
130516 ** a b-tree table, not a virtual table.
130517 **
130518 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
130519 ** are calculated as follows:
130520 **
130521 ** For a full scan, assuming the table (or index) contains nRow rows:
130522 **
130523 ** cost = nRow * 3.0 // full-table scan
130524 ** cost = nRow * K // scan of covering index
130525 ** cost = nRow * (K+3.0) // scan of non-covering index
130526 **
130527 ** where K is a value between 1.1 and 3.0 set based on the relative
130528 ** estimated average size of the index and table records.
130529 **
130530 ** For an index scan, where nVisit is the number of index rows visited
130531 ** by the scan, and nSeek is the number of seek operations required on
130532 ** the index b-tree:
130533 **
130534 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
130535 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
130536 **
130537 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
130538 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
130539 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
130540 **
130541 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
130542 ** of uncertainty. For this reason, scoring is designed to pick plans that
130543 ** "do the least harm" if the estimates are inaccurate. For example, a
130544 ** log(nRow) factor is omitted from a non-covering index scan in order to
130545 ** bias the scoring in favor of using an index, since the worst-case
130546 ** performance of using an index is far better than the worst-case performance
130547 ** of a full table scan.
130548 */
130550  WhereLoopBuilder *pBuilder, /* WHERE clause information */
130551  Bitmask mPrereq /* Extra prerequesites for using this table */
130552 ){
130553  WhereInfo *pWInfo; /* WHERE analysis context */
130554  Index *pProbe; /* An index we are evaluating */
130555  Index sPk; /* A fake index object for the primary key */
130556  LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
130557  i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
130558  SrcList *pTabList; /* The FROM clause */
130559  struct SrcList_item *pSrc; /* The FROM clause btree term to add */
130560  WhereLoop *pNew; /* Template WhereLoop object */
130561  int rc = SQLITE_OK; /* Return code */
130562  int iSortIdx = 1; /* Index number */
130563  int b; /* A boolean value */
130564  LogEst rSize; /* number of rows in the table */
130565  LogEst rLogSize; /* Logarithm of the number of rows in the table */
130566  WhereClause *pWC; /* The parsed WHERE clause */
130567  Table *pTab; /* Table being queried */
130568 
130569  pNew = pBuilder->pNew;
130570  pWInfo = pBuilder->pWInfo;
130571  pTabList = pWInfo->pTabList;
130572  pSrc = pTabList->a + pNew->iTab;
130573  pTab = pSrc->pTab;
130574  pWC = pBuilder->pWC;
130575  assert( !IsVirtual(pSrc->pTab) );
130576 
130577  if( pSrc->pIBIndex ){
130578  /* An INDEXED BY clause specifies a particular index to use */
130579  pProbe = pSrc->pIBIndex;
130580  }else if( !HasRowid(pTab) ){
130581  pProbe = pTab->pIndex;
130582  }else{
130583  /* There is no INDEXED BY clause. Create a fake Index object in local
130584  ** variable sPk to represent the rowid primary key index. Make this
130585  ** fake index the first in a chain of Index objects with all of the real
130586  ** indices to follow */
130587  Index *pFirst; /* First of real indices on the table */
130588  memset(&sPk, 0, sizeof(Index));
130589  sPk.nKeyCol = 1;
130590  sPk.nColumn = 1;
130591  sPk.aiColumn = &aiColumnPk;
130592  sPk.aiRowLogEst = aiRowEstPk;
130593  sPk.onError = OE_Replace;
130594  sPk.pTable = pTab;
130595  sPk.szIdxRow = pTab->szTabRow;
130596  aiRowEstPk[0] = pTab->nRowLogEst;
130597  aiRowEstPk[1] = 0;
130598  pFirst = pSrc->pTab->pIndex;
130599  if( pSrc->fg.notIndexed==0 ){
130600  /* The real indices of the table are only considered if the
130601  ** NOT INDEXED qualifier is omitted from the FROM clause */
130602  sPk.pNext = pFirst;
130603  }
130604  pProbe = &sPk;
130605  }
130606  rSize = pTab->nRowLogEst;
130607  rLogSize = estLog(rSize);
130608 
130609 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
130610  /* Automatic indexes */
130611  if( !pBuilder->pOrSet /* Not part of an OR optimization */
130612  && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
130613  && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
130614  && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
130615  && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
130616  && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
130617  && !pSrc->fg.isCorrelated /* Not a correlated subquery */
130618  && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
130619  ){
130620  /* Generate auto-index WhereLoops */
130621  WhereTerm *pTerm;
130622  WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
130623  for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
130624  if( pTerm->prereqRight & pNew->maskSelf ) continue;
130625  if( termCanDriveIndex(pTerm, pSrc, 0) ){
130626  pNew->u.btree.nEq = 1;
130627  pNew->nSkip = 0;
130628  pNew->u.btree.pIndex = 0;
130629  pNew->nLTerm = 1;
130630  pNew->aLTerm[0] = pTerm;
130631  /* TUNING: One-time cost for computing the automatic index is
130632  ** estimated to be X*N*log2(N) where N is the number of rows in
130633  ** the table being indexed and where X is 7 (LogEst=28) for normal
130634  ** tables or 1.375 (LogEst=4) for views and subqueries. The value
130635  ** of X is smaller for views and subqueries so that the query planner
130636  ** will be more aggressive about generating automatic indexes for
130637  ** those objects, since there is no opportunity to add schema
130638  ** indexes on subqueries and views. */
130639  pNew->rSetup = rLogSize + rSize + 4;
130640  if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
130641  pNew->rSetup += 24;
130642  }
130643  ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
130644  if( pNew->rSetup<0 ) pNew->rSetup = 0;
130645  /* TUNING: Each index lookup yields 20 rows in the table. This
130646  ** is more than the usual guess of 10 rows, since we have no way
130647  ** of knowing how selective the index will ultimately be. It would
130648  ** not be unreasonable to make this value much larger. */
130649  pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
130650  pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
130651  pNew->wsFlags = WHERE_AUTO_INDEX;
130652  pNew->prereq = mPrereq | pTerm->prereqRight;
130653  rc = whereLoopInsert(pBuilder, pNew);
130654  }
130655  }
130656  }
130657 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
130658 
130659  /* Loop over all indices
130660  */
130661  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
130662  if( pProbe->pPartIdxWhere!=0
130663  && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
130664  testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
130665  continue; /* Partial index inappropriate for this query */
130666  }
130667  rSize = pProbe->aiRowLogEst[0];
130668  pNew->u.btree.nEq = 0;
130669  pNew->u.btree.nBtm = 0;
130670  pNew->u.btree.nTop = 0;
130671  pNew->nSkip = 0;
130672  pNew->nLTerm = 0;
130673  pNew->iSortIdx = 0;
130674  pNew->rSetup = 0;
130675  pNew->prereq = mPrereq;
130676  pNew->nOut = rSize;
130677  pNew->u.btree.pIndex = pProbe;
130678  b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
130679  /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
130680  assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
130681  if( pProbe->tnum<=0 ){
130682  /* Integer primary key index */
130683  pNew->wsFlags = WHERE_IPK;
130684 
130685  /* Full table scan */
130686  pNew->iSortIdx = b ? iSortIdx : 0;
130687  /* TUNING: Cost of full table scan is (N*3.0). */
130688  pNew->rRun = rSize + 16;
130689  ApplyCostMultiplier(pNew->rRun, pTab->costMult);
130690  whereLoopOutputAdjust(pWC, pNew, rSize);
130691  rc = whereLoopInsert(pBuilder, pNew);
130692  pNew->nOut = rSize;
130693  if( rc ) break;
130694  }else{
130695  Bitmask m;
130696  if( pProbe->isCovering ){
130698  m = 0;
130699  }else{
130700  m = pSrc->colUsed & ~columnsInIndex(pProbe);
130701  pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
130702  }
130703 
130704  /* Full scan via index */
130705  if( b
130706  || !HasRowid(pTab)
130707  || pProbe->pPartIdxWhere!=0
130708  || ( m==0
130709  && pProbe->bUnordered==0
130710  && (pProbe->szIdxRow<pTab->szTabRow)
130711  && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
130712  && sqlite3GlobalConfig.bUseCis
130714  )
130715  ){
130716  pNew->iSortIdx = b ? iSortIdx : 0;
130717 
130718  /* The cost of visiting the index rows is N*K, where K is
130719  ** between 1.1 and 3.0, depending on the relative sizes of the
130720  ** index and table rows. */
130721  pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
130722  if( m!=0 ){
130723  /* If this is a non-covering index scan, add in the cost of
130724  ** doing table lookups. The cost will be 3x the number of
130725  ** lookups. Take into account WHERE clause terms that can be
130726  ** satisfied using just the index, and that do not require a
130727  ** table lookup. */
130728  LogEst nLookup = rSize + 16; /* Base cost: N*3 */
130729  int ii;
130730  int iCur = pSrc->iCursor;
130731  WhereClause *pWC2 = &pWInfo->sWC;
130732  for(ii=0; ii<pWC2->nTerm; ii++){
130733  WhereTerm *pTerm = &pWC2->a[ii];
130734  if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
130735  break;
130736  }
130737  /* pTerm can be evaluated using just the index. So reduce
130738  ** the expected number of table lookups accordingly */
130739  if( pTerm->truthProb<=0 ){
130740  nLookup += pTerm->truthProb;
130741  }else{
130742  nLookup--;
130743  if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
130744  }
130745  }
130746 
130747  pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
130748  }
130749  ApplyCostMultiplier(pNew->rRun, pTab->costMult);
130750  whereLoopOutputAdjust(pWC, pNew, rSize);
130751  rc = whereLoopInsert(pBuilder, pNew);
130752  pNew->nOut = rSize;
130753  if( rc ) break;
130754  }
130755  }
130756 
130757  rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
130758 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
130759  sqlite3Stat4ProbeFree(pBuilder->pRec);
130760  pBuilder->nRecValid = 0;
130761  pBuilder->pRec = 0;
130762 #endif
130763 
130764  /* If there was an INDEXED BY clause, then only that one index is
130765  ** considered. */
130766  if( pSrc->pIBIndex ) break;
130767  }
130768  return rc;
130769 }
130770 
130771 #ifndef SQLITE_OMIT_VIRTUALTABLE
130772 
130773 /*
130774 ** Argument pIdxInfo is already populated with all constraints that may
130775 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
130776 ** function marks a subset of those constraints usable, invokes the
130777 ** xBestIndex method and adds the returned plan to pBuilder.
130778 **
130779 ** A constraint is marked usable if:
130780 **
130781 ** * Argument mUsable indicates that its prerequisites are available, and
130782 **
130783 ** * It is not one of the operators specified in the mExclude mask passed
130784 ** as the fourth argument (which in practice is either WO_IN or 0).
130785 **
130786 ** Argument mPrereq is a mask of tables that must be scanned before the
130787 ** virtual table in question. These are added to the plans prerequisites
130788 ** before it is added to pBuilder.
130789 **
130790 ** Output parameter *pbIn is set to true if the plan added to pBuilder
130791 ** uses one or more WO_IN terms, or false otherwise.
130792 */
130794  WhereLoopBuilder *pBuilder,
130795  Bitmask mPrereq, /* Mask of tables that must be used. */
130796  Bitmask mUsable, /* Mask of usable tables */
130797  u16 mExclude, /* Exclude terms using these operators */
130798  sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
130799  u16 mNoOmit, /* Do not omit these constraints */
130800  int *pbIn /* OUT: True if plan uses an IN(...) op */
130801 ){
130802  WhereClause *pWC = pBuilder->pWC;
130803  struct sqlite3_index_constraint *pIdxCons;
130804  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
130805  int i;
130806  int mxTerm;
130807  int rc = SQLITE_OK;
130808  WhereLoop *pNew = pBuilder->pNew;
130809  Parse *pParse = pBuilder->pWInfo->pParse;
130810  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
130811  int nConstraint = pIdxInfo->nConstraint;
130812 
130813  assert( (mUsable & mPrereq)==mPrereq );
130814  *pbIn = 0;
130815  pNew->prereq = mPrereq;
130816 
130817  /* Set the usable flag on the subset of constraints identified by
130818  ** arguments mUsable and mExclude. */
130819  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
130820  for(i=0; i<nConstraint; i++, pIdxCons++){
130821  WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
130822  pIdxCons->usable = 0;
130823  if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
130824  && (pTerm->eOperator & mExclude)==0
130825  ){
130826  pIdxCons->usable = 1;
130827  }
130828  }
130829 
130830  /* Initialize the output fields of the sqlite3_index_info structure */
130831  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
130832  assert( pIdxInfo->needToFreeIdxStr==0 );
130833  pIdxInfo->idxStr = 0;
130834  pIdxInfo->idxNum = 0;
130835  pIdxInfo->orderByConsumed = 0;
130836  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
130837  pIdxInfo->estimatedRows = 25;
130838  pIdxInfo->idxFlags = 0;
130839  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
130840 
130841  /* Invoke the virtual table xBestIndex() method */
130842  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
130843  if( rc ) return rc;
130844 
130845  mxTerm = -1;
130846  assert( pNew->nLSlot>=nConstraint );
130847  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
130848  pNew->u.vtab.omitMask = 0;
130849  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
130850  for(i=0; i<nConstraint; i++, pIdxCons++){
130851  int iTerm;
130852  if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
130853  WhereTerm *pTerm;
130854  int j = pIdxCons->iTermOffset;
130855  if( iTerm>=nConstraint
130856  || j<0
130857  || j>=pWC->nTerm
130858  || pNew->aLTerm[iTerm]!=0
130859  || pIdxCons->usable==0
130860  ){
130861  rc = SQLITE_ERROR;
130862  sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
130863  return rc;
130864  }
130865  testcase( iTerm==nConstraint-1 );
130866  testcase( j==0 );
130867  testcase( j==pWC->nTerm-1 );
130868  pTerm = &pWC->a[j];
130869  pNew->prereq |= pTerm->prereqRight;
130870  assert( iTerm<pNew->nLSlot );
130871  pNew->aLTerm[iTerm] = pTerm;
130872  if( iTerm>mxTerm ) mxTerm = iTerm;
130873  testcase( iTerm==15 );
130874  testcase( iTerm==16 );
130875  if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
130876  if( (pTerm->eOperator & WO_IN)!=0 ){
130877  /* A virtual table that is constrained by an IN clause may not
130878  ** consume the ORDER BY clause because (1) the order of IN terms
130879  ** is not necessarily related to the order of output terms and
130880  ** (2) Multiple outputs from a single IN value will not merge
130881  ** together. */
130882  pIdxInfo->orderByConsumed = 0;
130883  pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
130884  *pbIn = 1; assert( (mExclude & WO_IN)==0 );
130885  }
130886  }
130887  }
130888  pNew->u.vtab.omitMask &= ~mNoOmit;
130889 
130890  pNew->nLTerm = mxTerm+1;
130891  assert( pNew->nLTerm<=pNew->nLSlot );
130892  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
130893  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
130894  pIdxInfo->needToFreeIdxStr = 0;
130895  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
130896  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
130897  pIdxInfo->nOrderBy : 0);
130898  pNew->rSetup = 0;
130899  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
130900  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
130901 
130902  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
130903  ** that the scan will visit at most one row. Clear it otherwise. */
130904  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
130905  pNew->wsFlags |= WHERE_ONEROW;
130906  }else{
130907  pNew->wsFlags &= ~WHERE_ONEROW;
130908  }
130909  rc = whereLoopInsert(pBuilder, pNew);
130910  if( pNew->u.vtab.needFree ){
130911  sqlite3_free(pNew->u.vtab.idxStr);
130912  pNew->u.vtab.needFree = 0;
130913  }
130914  WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
130915  *pbIn, (sqlite3_uint64)mPrereq,
130916  (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
130917 
130918  return rc;
130919 }
130920 
130921 
130922 /*
130923 ** Add all WhereLoop objects for a table of the join identified by
130924 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
130925 **
130926 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
130927 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
130928 ** entries that occur before the virtual table in the FROM clause and are
130929 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
130930 ** mUnusable mask contains all FROM clause entries that occur after the
130931 ** virtual table and are separated from it by at least one LEFT or
130932 ** CROSS JOIN.
130933 **
130934 ** For example, if the query were:
130935 **
130936 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
130937 **
130938 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
130939 **
130940 ** All the tables in mPrereq must be scanned before the current virtual
130941 ** table. So any terms for which all prerequisites are satisfied by
130942 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
130943 ** Conversely, all tables in mUnusable must be scanned after the current
130944 ** virtual table, so any terms for which the prerequisites overlap with
130945 ** mUnusable should always be configured as "not-usable" for xBestIndex.
130946 */
130948  WhereLoopBuilder *pBuilder, /* WHERE clause information */
130949  Bitmask mPrereq, /* Tables that must be scanned before this one */
130950  Bitmask mUnusable /* Tables that must be scanned after this one */
130951 ){
130952  int rc = SQLITE_OK; /* Return code */
130953  WhereInfo *pWInfo; /* WHERE analysis context */
130954  Parse *pParse; /* The parsing context */
130955  WhereClause *pWC; /* The WHERE clause */
130956  struct SrcList_item *pSrc; /* The FROM clause term to search */
130957  sqlite3_index_info *p; /* Object to pass to xBestIndex() */
130958  int nConstraint; /* Number of constraints in p */
130959  int bIn; /* True if plan uses IN(...) operator */
130960  WhereLoop *pNew;
130961  Bitmask mBest; /* Tables used by best possible plan */
130962  u16 mNoOmit;
130963 
130964  assert( (mPrereq & mUnusable)==0 );
130965  pWInfo = pBuilder->pWInfo;
130966  pParse = pWInfo->pParse;
130967  pWC = pBuilder->pWC;
130968  pNew = pBuilder->pNew;
130969  pSrc = &pWInfo->pTabList->a[pNew->iTab];
130970  assert( IsVirtual(pSrc->pTab) );
130971  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
130972  &mNoOmit);
130973  if( p==0 ) return SQLITE_NOMEM_BKPT;
130974  pNew->rSetup = 0;
130975  pNew->wsFlags = WHERE_VIRTUALTABLE;
130976  pNew->nLTerm = 0;
130977  pNew->u.vtab.needFree = 0;
130978  nConstraint = p->nConstraint;
130979  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
130980  sqlite3DbFree(pParse->db, p);
130981  return SQLITE_NOMEM_BKPT;
130982  }
130983 
130984  /* First call xBestIndex() with all constraints usable. */
130985  WHERETRACE(0x40, (" VirtualOne: all usable\n"));
130986  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
130987 
130988  /* If the call to xBestIndex() with all terms enabled produced a plan
130989  ** that does not require any source tables (IOW: a plan with mBest==0),
130990  ** then there is no point in making any further calls to xBestIndex()
130991  ** since they will all return the same result (if the xBestIndex()
130992  ** implementation is sane). */
130993  if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
130994  int seenZero = 0; /* True if a plan with no prereqs seen */
130995  int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
130996  Bitmask mPrev = 0;
130997  Bitmask mBestNoIn = 0;
130998 
130999  /* If the plan produced by the earlier call uses an IN(...) term, call
131000  ** xBestIndex again, this time with IN(...) terms disabled. */
131001  if( bIn ){
131002  WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
131003  rc = whereLoopAddVirtualOne(
131004  pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
131005  assert( bIn==0 );
131006  mBestNoIn = pNew->prereq & ~mPrereq;
131007  if( mBestNoIn==0 ){
131008  seenZero = 1;
131009  seenZeroNoIN = 1;
131010  }
131011  }
131012 
131013  /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
131014  ** in the set of terms that apply to the current virtual table. */
131015  while( rc==SQLITE_OK ){
131016  int i;
131017  Bitmask mNext = ALLBITS;
131018  assert( mNext>0 );
131019  for(i=0; i<nConstraint; i++){
131020  Bitmask mThis = (
131021  pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
131022  );
131023  if( mThis>mPrev && mThis<mNext ) mNext = mThis;
131024  }
131025  mPrev = mNext;
131026  if( mNext==ALLBITS ) break;
131027  if( mNext==mBest || mNext==mBestNoIn ) continue;
131028  WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
131029  (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
131030  rc = whereLoopAddVirtualOne(
131031  pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
131032  if( pNew->prereq==mPrereq ){
131033  seenZero = 1;
131034  if( bIn==0 ) seenZeroNoIN = 1;
131035  }
131036  }
131037 
131038  /* If the calls to xBestIndex() in the above loop did not find a plan
131039  ** that requires no source tables at all (i.e. one guaranteed to be
131040  ** usable), make a call here with all source tables disabled */
131041  if( rc==SQLITE_OK && seenZero==0 ){
131042  WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
131043  rc = whereLoopAddVirtualOne(
131044  pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
131045  if( bIn==0 ) seenZeroNoIN = 1;
131046  }
131047 
131048  /* If the calls to xBestIndex() have so far failed to find a plan
131049  ** that requires no source tables at all and does not use an IN(...)
131050  ** operator, make a final call to obtain one here. */
131051  if( rc==SQLITE_OK && seenZeroNoIN==0 ){
131052  WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
131053  rc = whereLoopAddVirtualOne(
131054  pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
131055  }
131056  }
131057 
131058  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
131059  sqlite3DbFree(pParse->db, p);
131060  return rc;
131061 }
131062 #endif /* SQLITE_OMIT_VIRTUALTABLE */
131063 
131064 /*
131065 ** Add WhereLoop entries to handle OR terms. This works for either
131066 ** btrees or virtual tables.
131067 */
131068 static int whereLoopAddOr(
131069  WhereLoopBuilder *pBuilder,
131070  Bitmask mPrereq,
131071  Bitmask mUnusable
131072 ){
131073  WhereInfo *pWInfo = pBuilder->pWInfo;
131074  WhereClause *pWC;
131075  WhereLoop *pNew;
131076  WhereTerm *pTerm, *pWCEnd;
131077  int rc = SQLITE_OK;
131078  int iCur;
131079  WhereClause tempWC;
131080  WhereLoopBuilder sSubBuild;
131081  WhereOrSet sSum, sCur;
131082  struct SrcList_item *pItem;
131083 
131084  pWC = pBuilder->pWC;
131085  pWCEnd = pWC->a + pWC->nTerm;
131086  pNew = pBuilder->pNew;
131087  memset(&sSum, 0, sizeof(sSum));
131088  pItem = pWInfo->pTabList->a + pNew->iTab;
131089  iCur = pItem->iCursor;
131090 
131091  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
131092  if( (pTerm->eOperator & WO_OR)!=0
131093  && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
131094  ){
131095  WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
131096  WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
131097  WhereTerm *pOrTerm;
131098  int once = 1;
131099  int i, j;
131100 
131101  sSubBuild = *pBuilder;
131102  sSubBuild.pOrderBy = 0;
131103  sSubBuild.pOrSet = &sCur;
131104 
131105  WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
131106  for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
131107  if( (pOrTerm->eOperator & WO_AND)!=0 ){
131108  sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
131109  }else if( pOrTerm->leftCursor==iCur ){
131110  tempWC.pWInfo = pWC->pWInfo;
131111  tempWC.pOuter = pWC;
131112  tempWC.op = TK_AND;
131113  tempWC.nTerm = 1;
131114  tempWC.a = pOrTerm;
131115  sSubBuild.pWC = &tempWC;
131116  }else{
131117  continue;
131118  }
131119  sCur.n = 0;
131120 #ifdef WHERETRACE_ENABLED
131121  WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
131122  (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
131123  if( sqlite3WhereTrace & 0x400 ){
131124  sqlite3WhereClausePrint(sSubBuild.pWC);
131125  }
131126 #endif
131127 #ifndef SQLITE_OMIT_VIRTUALTABLE
131128  if( IsVirtual(pItem->pTab) ){
131129  rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
131130  }else
131131 #endif
131132  {
131133  rc = whereLoopAddBtree(&sSubBuild, mPrereq);
131134  }
131135  if( rc==SQLITE_OK ){
131136  rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
131137  }
131138  assert( rc==SQLITE_OK || sCur.n==0 );
131139  if( sCur.n==0 ){
131140  sSum.n = 0;
131141  break;
131142  }else if( once ){
131143  whereOrMove(&sSum, &sCur);
131144  once = 0;
131145  }else{
131146  WhereOrSet sPrev;
131147  whereOrMove(&sPrev, &sSum);
131148  sSum.n = 0;
131149  for(i=0; i<sPrev.n; i++){
131150  for(j=0; j<sCur.n; j++){
131151  whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
131152  sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
131153  sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
131154  }
131155  }
131156  }
131157  }
131158  pNew->nLTerm = 1;
131159  pNew->aLTerm[0] = pTerm;
131160  pNew->wsFlags = WHERE_MULTI_OR;
131161  pNew->rSetup = 0;
131162  pNew->iSortIdx = 0;
131163  memset(&pNew->u, 0, sizeof(pNew->u));
131164  for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
131165  /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
131166  ** of all sub-scans required by the OR-scan. However, due to rounding
131167  ** errors, it may be that the cost of the OR-scan is equal to its
131168  ** most expensive sub-scan. Add the smallest possible penalty
131169  ** (equivalent to multiplying the cost by 1.07) to ensure that
131170  ** this does not happen. Otherwise, for WHERE clauses such as the
131171  ** following where there is an index on "y":
131172  **
131173  ** WHERE likelihood(x=?, 0.99) OR y=?
131174  **
131175  ** the planner may elect to "OR" together a full-table scan and an
131176  ** index lookup. And other similarly odd results. */
131177  pNew->rRun = sSum.a[i].rRun + 1;
131178  pNew->nOut = sSum.a[i].nOut;
131179  pNew->prereq = sSum.a[i].prereq;
131180  rc = whereLoopInsert(pBuilder, pNew);
131181  }
131182  WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
131183  }
131184  }
131185  return rc;
131186 }
131187 
131188 /*
131189 ** Add all WhereLoop objects for all tables
131190 */
131191 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
131192  WhereInfo *pWInfo = pBuilder->pWInfo;
131193  Bitmask mPrereq = 0;
131194  Bitmask mPrior = 0;
131195  int iTab;
131196  SrcList *pTabList = pWInfo->pTabList;
131197  struct SrcList_item *pItem;
131198  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
131199  sqlite3 *db = pWInfo->pParse->db;
131200  int rc = SQLITE_OK;
131201  WhereLoop *pNew;
131202  u8 priorJointype = 0;
131203 
131204  /* Loop over the tables in the join, from left to right */
131205  pNew = pBuilder->pNew;
131206  whereLoopInit(pNew);
131207  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
131208  Bitmask mUnusable = 0;
131209  pNew->iTab = iTab;
131210  pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
131211  if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
131212  /* This condition is true when pItem is the FROM clause term on the
131213  ** right-hand-side of a LEFT or CROSS JOIN. */
131214  mPrereq = mPrior;
131215  }
131216  priorJointype = pItem->fg.jointype;
131217 #ifndef SQLITE_OMIT_VIRTUALTABLE
131218  if( IsVirtual(pItem->pTab) ){
131219  struct SrcList_item *p;
131220  for(p=&pItem[1]; p<pEnd; p++){
131221  if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
131222  mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
131223  }
131224  }
131225  rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
131226  }else
131227 #endif /* SQLITE_OMIT_VIRTUALTABLE */
131228  {
131229  rc = whereLoopAddBtree(pBuilder, mPrereq);
131230  }
131231  if( rc==SQLITE_OK ){
131232  rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
131233  }
131234  mPrior |= pNew->maskSelf;
131235  if( rc || db->mallocFailed ) break;
131236  }
131237 
131238  whereLoopClear(db, pNew);
131239  return rc;
131240 }
131241 
131242 /*
131243 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
131244 ** parameters) to see if it outputs rows in the requested ORDER BY
131245 ** (or GROUP BY) without requiring a separate sort operation. Return N:
131246 **
131247 ** N>0: N terms of the ORDER BY clause are satisfied
131248 ** N==0: No terms of the ORDER BY clause are satisfied
131249 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
131250 **
131251 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
131252 ** strict. With GROUP BY and DISTINCT the only requirement is that
131253 ** equivalent rows appear immediately adjacent to one another. GROUP BY
131254 ** and DISTINCT do not require rows to appear in any particular order as long
131255 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
131256 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
131257 ** pOrderBy terms must be matched in strict left-to-right order.
131258 */
131260  WhereInfo *pWInfo, /* The WHERE clause */
131261  ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
131262  WherePath *pPath, /* The WherePath to check */
131263  u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
131264  u16 nLoop, /* Number of entries in pPath->aLoop[] */
131265  WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
131266  Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
131267 ){
131268  u8 revSet; /* True if rev is known */
131269  u8 rev; /* Composite sort order */
131270  u8 revIdx; /* Index sort order */
131271  u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
131272  u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
131273  u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
131274  u16 eqOpMask; /* Allowed equality operators */
131275  u16 nKeyCol; /* Number of key columns in pIndex */
131276  u16 nColumn; /* Total number of ordered columns in the index */
131277  u16 nOrderBy; /* Number terms in the ORDER BY clause */
131278  int iLoop; /* Index of WhereLoop in pPath being processed */
131279  int i, j; /* Loop counters */
131280  int iCur; /* Cursor number for current WhereLoop */
131281  int iColumn; /* A column number within table iCur */
131282  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
131283  WhereTerm *pTerm; /* A single term of the WHERE clause */
131284  Expr *pOBExpr; /* An expression from the ORDER BY clause */
131285  CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
131286  Index *pIndex; /* The index associated with pLoop */
131287  sqlite3 *db = pWInfo->pParse->db; /* Database connection */
131288  Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
131289  Bitmask obDone; /* Mask of all ORDER BY terms */
131290  Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
131291  Bitmask ready; /* Mask of inner loops */
131292 
131293  /*
131294  ** We say the WhereLoop is "one-row" if it generates no more than one
131295  ** row of output. A WhereLoop is one-row if all of the following are true:
131296  ** (a) All index columns match with WHERE_COLUMN_EQ.
131297  ** (b) The index is unique
131298  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
131299  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
131300  **
131301  ** We say the WhereLoop is "order-distinct" if the set of columns from
131302  ** that WhereLoop that are in the ORDER BY clause are different for every
131303  ** row of the WhereLoop. Every one-row WhereLoop is automatically
131304  ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
131305  ** is not order-distinct. To be order-distinct is not quite the same as being
131306  ** UNIQUE since a UNIQUE column or index can have multiple rows that
131307  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
131308  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
131309  **
131310  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
131311  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
131312  ** automatically order-distinct.
131313  */
131314 
131315  assert( pOrderBy!=0 );
131316  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
131317 
131318  nOrderBy = pOrderBy->nExpr;
131319  testcase( nOrderBy==BMS-1 );
131320  if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
131321  isOrderDistinct = 1;
131322  obDone = MASKBIT(nOrderBy)-1;
131323  orderDistinctMask = 0;
131324  ready = 0;
131325  eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
131326  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
131327  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
131328  if( iLoop>0 ) ready |= pLoop->maskSelf;
131329  if( iLoop<nLoop ){
131330  pLoop = pPath->aLoop[iLoop];
131331  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
131332  }else{
131333  pLoop = pLast;
131334  }
131335  if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
131336  if( pLoop->u.vtab.isOrdered ) obSat = obDone;
131337  break;
131338  }
131339  iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
131340 
131341  /* Mark off any ORDER BY term X that is a column in the table of
131342  ** the current loop for which there is term in the WHERE
131343  ** clause of the form X IS NULL or X=? that reference only outer
131344  ** loops.
131345  */
131346  for(i=0; i<nOrderBy; i++){
131347  if( MASKBIT(i) & obSat ) continue;
131348  pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
131349  if( pOBExpr->op!=TK_COLUMN ) continue;
131350  if( pOBExpr->iTable!=iCur ) continue;
131351  pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
131352  ~ready, eqOpMask, 0);
131353  if( pTerm==0 ) continue;
131354  if( pTerm->eOperator==WO_IN ){
131355  /* IN terms are only valid for sorting in the ORDER BY LIMIT
131356  ** optimization, and then only if they are actually used
131357  ** by the query plan */
131358  assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
131359  for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
131360  if( j>=pLoop->nLTerm ) continue;
131361  }
131362  if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
131363  const char *z1, *z2;
131364  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
131365  if( !pColl ) pColl = db->pDfltColl;
131366  z1 = pColl->zName;
131367  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
131368  if( !pColl ) pColl = db->pDfltColl;
131369  z2 = pColl->zName;
131370  if( sqlite3StrICmp(z1, z2)!=0 ) continue;
131371  testcase( pTerm->pExpr->op==TK_IS );
131372  }
131373  obSat |= MASKBIT(i);
131374  }
131375 
131376  if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
131377  if( pLoop->wsFlags & WHERE_IPK ){
131378  pIndex = 0;
131379  nKeyCol = 0;
131380  nColumn = 1;
131381  }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
131382  return 0;
131383  }else{
131384  nKeyCol = pIndex->nKeyCol;
131385  nColumn = pIndex->nColumn;
131386  assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
131387  assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
131388  || !HasRowid(pIndex->pTable));
131389  isOrderDistinct = IsUniqueIndex(pIndex);
131390  }
131391 
131392  /* Loop through all columns of the index and deal with the ones
131393  ** that are not constrained by == or IN.
131394  */
131395  rev = revSet = 0;
131396  distinctColumns = 0;
131397  for(j=0; j<nColumn; j++){
131398  u8 bOnce = 1; /* True to run the ORDER BY search loop */
131399 
131400  assert( j>=pLoop->u.btree.nEq
131401  || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
131402  );
131403  if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
131404  u16 eOp = pLoop->aLTerm[j]->eOperator;
131405 
131406  /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
131407  ** doing WHERE_ORDERBY_LIMIT processing).
131408  **
131409  ** If the current term is a column of an ((?,?) IN (SELECT...))
131410  ** expression for which the SELECT returns more than one column,
131411  ** check that it is the only column used by this loop. Otherwise,
131412  ** if it is one of two or more, none of the columns can be
131413  ** considered to match an ORDER BY term. */
131414  if( (eOp & eqOpMask)!=0 ){
131415  if( eOp & WO_ISNULL ){
131416  testcase( isOrderDistinct );
131417  isOrderDistinct = 0;
131418  }
131419  continue;
131420  }else if( ALWAYS(eOp & WO_IN) ){
131421  /* ALWAYS() justification: eOp is an equality operator due to the
131422  ** j<pLoop->u.btree.nEq constraint above. Any equality other
131423  ** than WO_IN is captured by the previous "if". So this one
131424  ** always has to be WO_IN. */
131425  Expr *pX = pLoop->aLTerm[j]->pExpr;
131426  for(i=j+1; i<pLoop->u.btree.nEq; i++){
131427  if( pLoop->aLTerm[i]->pExpr==pX ){
131428  assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
131429  bOnce = 0;
131430  break;
131431  }
131432  }
131433  }
131434  }
131435 
131436  /* Get the column number in the table (iColumn) and sort order
131437  ** (revIdx) for the j-th column of the index.
131438  */
131439  if( pIndex ){
131440  iColumn = pIndex->aiColumn[j];
131441  revIdx = pIndex->aSortOrder[j];
131442  if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
131443  }else{
131444  iColumn = XN_ROWID;
131445  revIdx = 0;
131446  }
131447 
131448  /* An unconstrained column that might be NULL means that this
131449  ** WhereLoop is not well-ordered
131450  */
131451  if( isOrderDistinct
131452  && iColumn>=0
131453  && j>=pLoop->u.btree.nEq
131454  && pIndex->pTable->aCol[iColumn].notNull==0
131455  ){
131456  isOrderDistinct = 0;
131457  }
131458 
131459  /* Find the ORDER BY term that corresponds to the j-th column
131460  ** of the index and mark that ORDER BY term off
131461  */
131462  isMatch = 0;
131463  for(i=0; bOnce && i<nOrderBy; i++){
131464  if( MASKBIT(i) & obSat ) continue;
131465  pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
131466  testcase( wctrlFlags & WHERE_GROUPBY );
131467  testcase( wctrlFlags & WHERE_DISTINCTBY );
131468  if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
131469  if( iColumn>=(-1) ){
131470  if( pOBExpr->op!=TK_COLUMN ) continue;
131471  if( pOBExpr->iTable!=iCur ) continue;
131472  if( pOBExpr->iColumn!=iColumn ) continue;
131473  }else{
131474  if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
131475  continue;
131476  }
131477  }
131478  if( iColumn>=0 ){
131479  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
131480  if( !pColl ) pColl = db->pDfltColl;
131481  if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
131482  }
131483  isMatch = 1;
131484  break;
131485  }
131486  if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
131487  /* Make sure the sort order is compatible in an ORDER BY clause.
131488  ** Sort order is irrelevant for a GROUP BY clause. */
131489  if( revSet ){
131490  if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
131491  }else{
131492  rev = revIdx ^ pOrderBy->a[i].sortOrder;
131493  if( rev ) *pRevMask |= MASKBIT(iLoop);
131494  revSet = 1;
131495  }
131496  }
131497  if( isMatch ){
131498  if( iColumn==XN_ROWID ){
131499  testcase( distinctColumns==0 );
131500  distinctColumns = 1;
131501  }
131502  obSat |= MASKBIT(i);
131503  }else{
131504  /* No match found */
131505  if( j==0 || j<nKeyCol ){
131506  testcase( isOrderDistinct!=0 );
131507  isOrderDistinct = 0;
131508  }
131509  break;
131510  }
131511  } /* end Loop over all index columns */
131512  if( distinctColumns ){
131513  testcase( isOrderDistinct==0 );
131514  isOrderDistinct = 1;
131515  }
131516  } /* end-if not one-row */
131517 
131518  /* Mark off any other ORDER BY terms that reference pLoop */
131519  if( isOrderDistinct ){
131520  orderDistinctMask |= pLoop->maskSelf;
131521  for(i=0; i<nOrderBy; i++){
131522  Expr *p;
131523  Bitmask mTerm;
131524  if( MASKBIT(i) & obSat ) continue;
131525  p = pOrderBy->a[i].pExpr;
131526  mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
131527  if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
131528  if( (mTerm&~orderDistinctMask)==0 ){
131529  obSat |= MASKBIT(i);
131530  }
131531  }
131532  }
131533  } /* End the loop over all WhereLoops from outer-most down to inner-most */
131534  if( obSat==obDone ) return (i8)nOrderBy;
131535  if( !isOrderDistinct ){
131536  for(i=nOrderBy-1; i>0; i--){
131537  Bitmask m = MASKBIT(i) - 1;
131538  if( (obSat&m)==m ) return i;
131539  }
131540  return 0;
131541  }
131542  return -1;
131543 }
131544 
131545 
131546 /*
131547 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
131548 ** the planner assumes that the specified pOrderBy list is actually a GROUP
131549 ** BY clause - and so any order that groups rows as required satisfies the
131550 ** request.
131551 **
131552 ** Normally, in this case it is not possible for the caller to determine
131553 ** whether or not the rows are really being delivered in sorted order, or
131554 ** just in some other order that provides the required grouping. However,
131555 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
131556 ** this function may be called on the returned WhereInfo object. It returns
131557 ** true if the rows really will be sorted in the specified order, or false
131558 ** otherwise.
131559 **
131560 ** For example, assuming:
131561 **
131562 ** CREATE INDEX i1 ON t1(x, Y);
131563 **
131564 ** then
131565 **
131566 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
131567 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
131568 */
131570  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
131571  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
131572  return pWInfo->sorted;
131573 }
131574 
131575 #ifdef WHERETRACE_ENABLED
131576 /* For debugging use only: */
131577 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
131578  static char zName[65];
131579  int i;
131580  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
131581  if( pLast ) zName[i++] = pLast->cId;
131582  zName[i] = 0;
131583  return zName;
131584 }
131585 #endif
131586 
131587 /*
131588 ** Return the cost of sorting nRow rows, assuming that the keys have
131589 ** nOrderby columns and that the first nSorted columns are already in
131590 ** order.
131591 */
131592 static LogEst whereSortingCost(
131593  WhereInfo *pWInfo,
131594  LogEst nRow,
131595  int nOrderBy,
131596  int nSorted
131597 ){
131598  /* TUNING: Estimated cost of a full external sort, where N is
131599  ** the number of rows to sort is:
131600  **
131601  ** cost = (3.0 * N * log(N)).
131602  **
131603  ** Or, if the order-by clause has X terms but only the last Y
131604  ** terms are out of order, then block-sorting will reduce the
131605  ** sorting cost to:
131606  **
131607  ** cost = (3.0 * N * log(N)) * (Y/X)
131608  **
131609  ** The (Y/X) term is implemented using stack variable rScale
131610  ** below. */
131611  LogEst rScale, rSortCost;
131612  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
131613  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
131614  rSortCost = nRow + rScale + 16;
131615 
131616  /* Multiple by log(M) where M is the number of output rows.
131617  ** Use the LIMIT for M if it is smaller */
131618  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
131619  nRow = pWInfo->iLimit;
131620  }
131621  rSortCost += estLog(nRow);
131622  return rSortCost;
131623 }
131624 
131625 /*
131626 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
131627 ** attempts to find the lowest cost path that visits each WhereLoop
131628 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
131629 **
131630 ** Assume that the total number of output rows that will need to be sorted
131631 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
131632 ** costs if nRowEst==0.
131633 **
131634 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
131635 ** error occurs.
131636 */
131637 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
131638  int mxChoice; /* Maximum number of simultaneous paths tracked */
131639  int nLoop; /* Number of terms in the join */
131640  Parse *pParse; /* Parsing context */
131641  sqlite3 *db; /* The database connection */
131642  int iLoop; /* Loop counter over the terms of the join */
131643  int ii, jj; /* Loop counters */
131644  int mxI = 0; /* Index of next entry to replace */
131645  int nOrderBy; /* Number of ORDER BY clause terms */
131646  LogEst mxCost = 0; /* Maximum cost of a set of paths */
131647  LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
131648  int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
131649  WherePath *aFrom; /* All nFrom paths at the previous level */
131650  WherePath *aTo; /* The nTo best paths at the current level */
131651  WherePath *pFrom; /* An element of aFrom[] that we are working on */
131652  WherePath *pTo; /* An element of aTo[] that we are working on */
131653  WhereLoop *pWLoop; /* One of the WhereLoop objects */
131654  WhereLoop **pX; /* Used to divy up the pSpace memory */
131655  LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
131656  char *pSpace; /* Temporary memory used by this routine */
131657  int nSpace; /* Bytes of space allocated at pSpace */
131658 
131659  pParse = pWInfo->pParse;
131660  db = pParse->db;
131661  nLoop = pWInfo->nLevel;
131662  /* TUNING: For simple queries, only the best path is tracked.
131663  ** For 2-way joins, the 5 best paths are followed.
131664  ** For joins of 3 or more tables, track the 10 best paths */
131665  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
131666  assert( nLoop<=pWInfo->pTabList->nSrc );
131667  WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
131668 
131669  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
131670  ** case the purpose of this call is to estimate the number of rows returned
131671  ** by the overall query. Once this estimate has been obtained, the caller
131672  ** will invoke this function a second time, passing the estimate as the
131673  ** nRowEst parameter. */
131674  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
131675  nOrderBy = 0;
131676  }else{
131677  nOrderBy = pWInfo->pOrderBy->nExpr;
131678  }
131679 
131680  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
131681  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
131682  nSpace += sizeof(LogEst) * nOrderBy;
131683  pSpace = sqlite3DbMallocRawNN(db, nSpace);
131684  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
131685  aTo = (WherePath*)pSpace;
131686  aFrom = aTo+mxChoice;
131687  memset(aFrom, 0, sizeof(aFrom[0]));
131688  pX = (WhereLoop**)(aFrom+mxChoice);
131689  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
131690  pFrom->aLoop = pX;
131691  }
131692  if( nOrderBy ){
131693  /* If there is an ORDER BY clause and it is not being ignored, set up
131694  ** space for the aSortCost[] array. Each element of the aSortCost array
131695  ** is either zero - meaning it has not yet been initialized - or the
131696  ** cost of sorting nRowEst rows of data where the first X terms of
131697  ** the ORDER BY clause are already in order, where X is the array
131698  ** index. */
131699  aSortCost = (LogEst*)pX;
131700  memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
131701  }
131702  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
131703  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
131704 
131705  /* Seed the search with a single WherePath containing zero WhereLoops.
131706  **
131707  ** TUNING: Do not let the number of iterations go above 28. If the cost
131708  ** of computing an automatic index is not paid back within the first 28
131709  ** rows, then do not use the automatic index. */
131710  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
131711  nFrom = 1;
131712  assert( aFrom[0].isOrdered==0 );
131713  if( nOrderBy ){
131714  /* If nLoop is zero, then there are no FROM terms in the query. Since
131715  ** in this case the query may return a maximum of one row, the results
131716  ** are already in the requested order. Set isOrdered to nOrderBy to
131717  ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
131718  ** -1, indicating that the result set may or may not be ordered,
131719  ** depending on the loops added to the current plan. */
131720  aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
131721  }
131722 
131723  /* Compute successively longer WherePaths using the previous generation
131724  ** of WherePaths as the basis for the next. Keep track of the mxChoice
131725  ** best paths at each generation */
131726  for(iLoop=0; iLoop<nLoop; iLoop++){
131727  nTo = 0;
131728  for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
131729  for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
131730  LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
131731  LogEst rCost; /* Cost of path (pFrom+pWLoop) */
131732  LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
131733  i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
131734  Bitmask maskNew; /* Mask of src visited by (..) */
131735  Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
131736 
131737  if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
131738  if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
131739  if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
131740  /* Do not use an automatic index if the this loop is expected
131741  ** to run less than 2 times. */
131742  assert( 10==sqlite3LogEst(2) );
131743  continue;
131744  }
131745  /* At this point, pWLoop is a candidate to be the next loop.
131746  ** Compute its cost */
131747  rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
131748  rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
131749  nOut = pFrom->nRow + pWLoop->nOut;
131750  maskNew = pFrom->maskLoop | pWLoop->maskSelf;
131751  if( isOrdered<0 ){
131752  isOrdered = wherePathSatisfiesOrderBy(pWInfo,
131753  pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
131754  iLoop, pWLoop, &revMask);
131755  }else{
131756  revMask = pFrom->revLoop;
131757  }
131758  if( isOrdered>=0 && isOrdered<nOrderBy ){
131759  if( aSortCost[isOrdered]==0 ){
131760  aSortCost[isOrdered] = whereSortingCost(
131761  pWInfo, nRowEst, nOrderBy, isOrdered
131762  );
131763  }
131764  rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
131765 
131766  WHERETRACE(0x002,
131767  ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
131768  aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
131769  rUnsorted, rCost));
131770  }else{
131771  rCost = rUnsorted;
131772  }
131773 
131774  /* Check to see if pWLoop should be added to the set of
131775  ** mxChoice best-so-far paths.
131776  **
131777  ** First look for an existing path among best-so-far paths
131778  ** that covers the same set of loops and has the same isOrdered
131779  ** setting as the current path candidate.
131780  **
131781  ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
131782  ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
131783  ** of legal values for isOrdered, -1..64.
131784  */
131785  for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
131786  if( pTo->maskLoop==maskNew
131787  && ((pTo->isOrdered^isOrdered)&0x80)==0
131788  ){
131789  testcase( jj==nTo-1 );
131790  break;
131791  }
131792  }
131793  if( jj>=nTo ){
131794  /* None of the existing best-so-far paths match the candidate. */
131795  if( nTo>=mxChoice
131796  && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
131797  ){
131798  /* The current candidate is no better than any of the mxChoice
131799  ** paths currently in the best-so-far buffer. So discard
131800  ** this candidate as not viable. */
131801 #ifdef WHERETRACE_ENABLED /* 0x4 */
131802  if( sqlite3WhereTrace&0x4 ){
131803  sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
131804  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131805  isOrdered>=0 ? isOrdered+'0' : '?');
131806  }
131807 #endif
131808  continue;
131809  }
131810  /* If we reach this points it means that the new candidate path
131811  ** needs to be added to the set of best-so-far paths. */
131812  if( nTo<mxChoice ){
131813  /* Increase the size of the aTo set by one */
131814  jj = nTo++;
131815  }else{
131816  /* New path replaces the prior worst to keep count below mxChoice */
131817  jj = mxI;
131818  }
131819  pTo = &aTo[jj];
131820 #ifdef WHERETRACE_ENABLED /* 0x4 */
131821  if( sqlite3WhereTrace&0x4 ){
131822  sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
131823  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131824  isOrdered>=0 ? isOrdered+'0' : '?');
131825  }
131826 #endif
131827  }else{
131828  /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
131829  ** same set of loops and has the sam isOrdered setting as the
131830  ** candidate path. Check to see if the candidate should replace
131831  ** pTo or if the candidate should be skipped */
131832  if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
131833 #ifdef WHERETRACE_ENABLED /* 0x4 */
131834  if( sqlite3WhereTrace&0x4 ){
131835  sqlite3DebugPrintf(
131836  "Skip %s cost=%-3d,%3d order=%c",
131837  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131838  isOrdered>=0 ? isOrdered+'0' : '?');
131839  sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
131840  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
131841  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
131842  }
131843 #endif
131844  /* Discard the candidate path from further consideration */
131845  testcase( pTo->rCost==rCost );
131846  continue;
131847  }
131848  testcase( pTo->rCost==rCost+1 );
131849  /* Control reaches here if the candidate path is better than the
131850  ** pTo path. Replace pTo with the candidate. */
131851 #ifdef WHERETRACE_ENABLED /* 0x4 */
131852  if( sqlite3WhereTrace&0x4 ){
131853  sqlite3DebugPrintf(
131854  "Update %s cost=%-3d,%3d order=%c",
131855  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
131856  isOrdered>=0 ? isOrdered+'0' : '?');
131857  sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
131858  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
131859  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
131860  }
131861 #endif
131862  }
131863  /* pWLoop is a winner. Add it to the set of best so far */
131864  pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
131865  pTo->revLoop = revMask;
131866  pTo->nRow = nOut;
131867  pTo->rCost = rCost;
131868  pTo->rUnsorted = rUnsorted;
131869  pTo->isOrdered = isOrdered;
131870  memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
131871  pTo->aLoop[iLoop] = pWLoop;
131872  if( nTo>=mxChoice ){
131873  mxI = 0;
131874  mxCost = aTo[0].rCost;
131875  mxUnsorted = aTo[0].nRow;
131876  for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
131877  if( pTo->rCost>mxCost
131878  || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
131879  ){
131880  mxCost = pTo->rCost;
131881  mxUnsorted = pTo->rUnsorted;
131882  mxI = jj;
131883  }
131884  }
131885  }
131886  }
131887  }
131888 
131889 #ifdef WHERETRACE_ENABLED /* >=2 */
131890  if( sqlite3WhereTrace & 0x02 ){
131891  sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
131892  for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
131893  sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
131894  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
131895  pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
131896  if( pTo->isOrdered>0 ){
131897  sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
131898  }else{
131899  sqlite3DebugPrintf("\n");
131900  }
131901  }
131902  }
131903 #endif
131904 
131905  /* Swap the roles of aFrom and aTo for the next generation */
131906  pFrom = aTo;
131907  aTo = aFrom;
131908  aFrom = pFrom;
131909  nFrom = nTo;
131910  }
131911 
131912  if( nFrom==0 ){
131913  sqlite3ErrorMsg(pParse, "no query solution");
131914  sqlite3DbFree(db, pSpace);
131915  return SQLITE_ERROR;
131916  }
131917 
131918  /* Find the lowest cost path. pFrom will be left pointing to that path */
131919  pFrom = aFrom;
131920  for(ii=1; ii<nFrom; ii++){
131921  if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
131922  }
131923  assert( pWInfo->nLevel==nLoop );
131924  /* Load the lowest cost path into pWInfo */
131925  for(iLoop=0; iLoop<nLoop; iLoop++){
131926  WhereLevel *pLevel = pWInfo->a + iLoop;
131927  pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
131928  pLevel->iFrom = pWLoop->iTab;
131929  pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
131930  }
131931  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
131932  && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
131933  && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
131934  && nRowEst
131935  ){
131936  Bitmask notUsed;
131937  int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
131938  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
131939  if( rc==pWInfo->pDistinctSet->nExpr ){
131940  pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
131941  }
131942  }
131943  if( pWInfo->pOrderBy ){
131944  if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
131945  if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
131946  pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
131947  }
131948  }else{
131949  pWInfo->nOBSat = pFrom->isOrdered;
131950  pWInfo->revMask = pFrom->revLoop;
131951  if( pWInfo->nOBSat<=0 ){
131952  pWInfo->nOBSat = 0;
131953  if( nLoop>0 ){
131954  u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
131955  if( (wsFlags & WHERE_ONEROW)==0
131957  ){
131958  Bitmask m = 0;
131959  int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
131960  WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
131961  testcase( wsFlags & WHERE_IPK );
131962  testcase( wsFlags & WHERE_COLUMN_IN );
131963  if( rc==pWInfo->pOrderBy->nExpr ){
131964  pWInfo->bOrderedInnerLoop = 1;
131965  pWInfo->revMask = m;
131966  }
131967  }
131968  }
131969  }
131970  }
131971  if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
131972  && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
131973  ){
131974  Bitmask revMask = 0;
131975  int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
131976  pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
131977  );
131978  assert( pWInfo->sorted==0 );
131979  if( nOrder==pWInfo->pOrderBy->nExpr ){
131980  pWInfo->sorted = 1;
131981  pWInfo->revMask = revMask;
131982  }
131983  }
131984  }
131985 
131986 
131987  pWInfo->nRowOut = pFrom->nRow;
131988 
131989  /* Free temporary memory and return success */
131990  sqlite3DbFree(db, pSpace);
131991  return SQLITE_OK;
131992 }
131993 
131994 /*
131995 ** Most queries use only a single table (they are not joins) and have
131996 ** simple == constraints against indexed fields. This routine attempts
131997 ** to plan those simple cases using much less ceremony than the
131998 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
131999 ** times for the common case.
132000 **
132001 ** Return non-zero on success, if this query can be handled by this
132002 ** no-frills query planner. Return zero if this query needs the
132003 ** general-purpose query planner.
132004 */
132005 static int whereShortCut(WhereLoopBuilder *pBuilder){
132006  WhereInfo *pWInfo;
132007  struct SrcList_item *pItem;
132008  WhereClause *pWC;
132009  WhereTerm *pTerm;
132010  WhereLoop *pLoop;
132011  int iCur;
132012  int j;
132013  Table *pTab;
132014  Index *pIdx;
132015 
132016  pWInfo = pBuilder->pWInfo;
132017  if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
132018  assert( pWInfo->pTabList->nSrc>=1 );
132019  pItem = pWInfo->pTabList->a;
132020  pTab = pItem->pTab;
132021  if( IsVirtual(pTab) ) return 0;
132022  if( pItem->fg.isIndexedBy ) return 0;
132023  iCur = pItem->iCursor;
132024  pWC = &pWInfo->sWC;
132025  pLoop = pBuilder->pNew;
132026  pLoop->wsFlags = 0;
132027  pLoop->nSkip = 0;
132028  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
132029  if( pTerm ){
132030  testcase( pTerm->eOperator & WO_IS );
132032  pLoop->aLTerm[0] = pTerm;
132033  pLoop->nLTerm = 1;
132034  pLoop->u.btree.nEq = 1;
132035  /* TUNING: Cost of a rowid lookup is 10 */
132036  pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
132037  }else{
132038  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
132039  int opMask;
132040  assert( pLoop->aLTermSpace==pLoop->aLTerm );
132041  if( !IsUniqueIndex(pIdx)
132042  || pIdx->pPartIdxWhere!=0
132043  || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
132044  ) continue;
132045  opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
132046  for(j=0; j<pIdx->nKeyCol; j++){
132047  pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
132048  if( pTerm==0 ) break;
132049  testcase( pTerm->eOperator & WO_IS );
132050  pLoop->aLTerm[j] = pTerm;
132051  }
132052  if( j!=pIdx->nKeyCol ) continue;
132054  if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
132055  pLoop->wsFlags |= WHERE_IDX_ONLY;
132056  }
132057  pLoop->nLTerm = j;
132058  pLoop->u.btree.nEq = j;
132059  pLoop->u.btree.pIndex = pIdx;
132060  /* TUNING: Cost of a unique index lookup is 15 */
132061  pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
132062  break;
132063  }
132064  }
132065  if( pLoop->wsFlags ){
132066  pLoop->nOut = (LogEst)1;
132067  pWInfo->a[0].pWLoop = pLoop;
132068  pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
132069  pWInfo->a[0].iTabCur = iCur;
132070  pWInfo->nRowOut = 1;
132071  if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
132072  if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
132073  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
132074  }
132075 #ifdef SQLITE_DEBUG
132076  pLoop->cId = '0';
132077 #endif
132078  return 1;
132079  }
132080  return 0;
132081 }
132082 
132083 /*
132084 ** Generate the beginning of the loop used for WHERE clause processing.
132085 ** The return value is a pointer to an opaque structure that contains
132086 ** information needed to terminate the loop. Later, the calling routine
132087 ** should invoke sqlite3WhereEnd() with the return value of this function
132088 ** in order to complete the WHERE clause processing.
132089 **
132090 ** If an error occurs, this routine returns NULL.
132091 **
132092 ** The basic idea is to do a nested loop, one loop for each table in
132093 ** the FROM clause of a select. (INSERT and UPDATE statements are the
132094 ** same as a SELECT with only a single table in the FROM clause.) For
132095 ** example, if the SQL is this:
132096 **
132097 ** SELECT * FROM t1, t2, t3 WHERE ...;
132098 **
132099 ** Then the code generated is conceptually like the following:
132100 **
132101 ** foreach row1 in t1 do \ Code generated
132102 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
132103 ** foreach row3 in t3 do /
132104 ** ...
132105 ** end \ Code generated
132106 ** end |-- by sqlite3WhereEnd()
132107 ** end /
132108 **
132109 ** Note that the loops might not be nested in the order in which they
132110 ** appear in the FROM clause if a different order is better able to make
132111 ** use of indices. Note also that when the IN operator appears in
132112 ** the WHERE clause, it might result in additional nested loops for
132113 ** scanning through all values on the right-hand side of the IN.
132114 **
132115 ** There are Btree cursors associated with each table. t1 uses cursor
132116 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
132117 ** And so forth. This routine generates code to open those VDBE cursors
132118 ** and sqlite3WhereEnd() generates the code to close them.
132119 **
132120 ** The code that sqlite3WhereBegin() generates leaves the cursors named
132121 ** in pTabList pointing at their appropriate entries. The [...] code
132122 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
132123 ** data from the various tables of the loop.
132124 **
132125 ** If the WHERE clause is empty, the foreach loops must each scan their
132126 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
132127 ** the tables have indices and there are terms in the WHERE clause that
132128 ** refer to those indices, a complete table scan can be avoided and the
132129 ** code will run much faster. Most of the work of this routine is checking
132130 ** to see if there are indices that can be used to speed up the loop.
132131 **
132132 ** Terms of the WHERE clause are also used to limit which rows actually
132133 ** make it to the "..." in the middle of the loop. After each "foreach",
132134 ** terms of the WHERE clause that use only terms in that loop and outer
132135 ** loops are evaluated and if false a jump is made around all subsequent
132136 ** inner loops (or around the "..." if the test occurs within the inner-
132137 ** most loop)
132138 **
132139 ** OUTER JOINS
132140 **
132141 ** An outer join of tables t1 and t2 is conceptally coded as follows:
132142 **
132143 ** foreach row1 in t1 do
132144 ** flag = 0
132145 ** foreach row2 in t2 do
132146 ** start:
132147 ** ...
132148 ** flag = 1
132149 ** end
132150 ** if flag==0 then
132151 ** move the row2 cursor to a null row
132152 ** goto start
132153 ** fi
132154 ** end
132155 **
132156 ** ORDER BY CLAUSE PROCESSING
132157 **
132158 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
132159 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
132160 ** if there is one. If there is no ORDER BY clause or if this routine
132161 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
132162 **
132163 ** The iIdxCur parameter is the cursor number of an index. If
132164 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
132165 ** to use for OR clause processing. The WHERE clause should use this
132166 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
132167 ** the first cursor in an array of cursors for all indices. iIdxCur should
132168 ** be used to compute the appropriate cursor depending on which index is
132169 ** used.
132170 */
132172  Parse *pParse, /* The parser context */
132173  SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
132174  Expr *pWhere, /* The WHERE clause */
132175  ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
132176  ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
132177  u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
132178  int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
132179  ** If WHERE_USE_LIMIT, then the limit amount */
132180 ){
132181  int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
132182  int nTabList; /* Number of elements in pTabList */
132183  WhereInfo *pWInfo; /* Will become the return value of this function */
132184  Vdbe *v = pParse->pVdbe; /* The virtual database engine */
132185  Bitmask notReady; /* Cursors that are not yet positioned */
132186  WhereLoopBuilder sWLB; /* The WhereLoop builder */
132187  WhereMaskSet *pMaskSet; /* The expression mask set */
132188  WhereLevel *pLevel; /* A single level in pWInfo->a[] */
132189  WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
132190  int ii; /* Loop counter */
132191  sqlite3 *db; /* Database connection */
132192  int rc; /* Return code */
132193  u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
132194 
132195  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
132196  (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
132197  && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
132198  ));
132199 
132200  /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
132201  assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
132202  || (wctrlFlags & WHERE_USE_LIMIT)==0 );
132203 
132204  /* Variable initialization */
132205  db = pParse->db;
132206  memset(&sWLB, 0, sizeof(sWLB));
132207 
132208  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
132209  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
132210  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
132211  sWLB.pOrderBy = pOrderBy;
132212 
132213  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
132214  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
132216  wctrlFlags &= ~WHERE_WANT_DISTINCT;
132217  }
132218 
132219  /* The number of tables in the FROM clause is limited by the number of
132220  ** bits in a Bitmask
132221  */
132222  testcase( pTabList->nSrc==BMS );
132223  if( pTabList->nSrc>BMS ){
132224  sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
132225  return 0;
132226  }
132227 
132228  /* This function normally generates a nested loop for all tables in
132229  ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
132230  ** only generate code for the first table in pTabList and assume that
132231  ** any cursors associated with subsequent tables are uninitialized.
132232  */
132233  nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
132234 
132235  /* Allocate and initialize the WhereInfo structure that will become the
132236  ** return value. A single allocation is used to store the WhereInfo
132237  ** struct, the contents of WhereInfo.a[], the WhereClause structure
132238  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
132239  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
132240  ** some architectures. Hence the ROUND8() below.
132241  */
132242  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
132243  pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
132244  if( db->mallocFailed ){
132245  sqlite3DbFree(db, pWInfo);
132246  pWInfo = 0;
132247  goto whereBeginError;
132248  }
132249  pWInfo->pParse = pParse;
132250  pWInfo->pTabList = pTabList;
132251  pWInfo->pOrderBy = pOrderBy;
132252  pWInfo->pDistinctSet = pDistinctSet;
132253  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
132254  pWInfo->nLevel = nTabList;
132255  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
132256  pWInfo->wctrlFlags = wctrlFlags;
132257  pWInfo->iLimit = iAuxArg;
132258  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
132259  memset(&pWInfo->nOBSat, 0,
132260  offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
132261  memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
132262  assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
132263  pMaskSet = &pWInfo->sMaskSet;
132264  sWLB.pWInfo = pWInfo;
132265  sWLB.pWC = &pWInfo->sWC;
132266  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
132267  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
132268  whereLoopInit(sWLB.pNew);
132269 #ifdef SQLITE_DEBUG
132270  sWLB.pNew->cId = '*';
132271 #endif
132272 
132273  /* Split the WHERE clause into separate subexpressions where each
132274  ** subexpression is separated by an AND operator.
132275  */
132276  initMaskSet(pMaskSet);
132277  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
132278  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
132279 
132280  /* Special case: a WHERE clause that is constant. Evaluate the
132281  ** expression and either jump over all of the code or fall thru.
132282  */
132283  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
132284  if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
132285  sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
132287  sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
132288  }
132289  }
132290 
132291  /* Special case: No FROM clause
132292  */
132293  if( nTabList==0 ){
132294  if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
132295  if( wctrlFlags & WHERE_WANT_DISTINCT ){
132296  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
132297  }
132298  }
132299 
132300  /* Assign a bit from the bitmask to every term in the FROM clause.
132301  **
132302  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
132303  **
132304  ** The rule of the previous sentence ensures thta if X is the bitmask for
132305  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
132306  ** Knowing the bitmask for all tables to the left of a left join is
132307  ** important. Ticket #3015.
132308  **
132309  ** Note that bitmasks are created for all pTabList->nSrc tables in
132310  ** pTabList, not just the first nTabList tables. nTabList is normally
132311  ** equal to pTabList->nSrc but might be shortened to 1 if the
132312  ** WHERE_OR_SUBCLAUSE flag is set.
132313  */
132314  for(ii=0; ii<pTabList->nSrc; ii++){
132315  createMask(pMaskSet, pTabList->a[ii].iCursor);
132316  sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
132317  }
132318 #ifdef SQLITE_DEBUG
132319  for(ii=0; ii<pTabList->nSrc; ii++){
132320  Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
132321  assert( m==MASKBIT(ii) );
132322  }
132323 #endif
132324 
132325  /* Analyze all of the subexpressions. */
132326  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
132327  if( db->mallocFailed ) goto whereBeginError;
132328 
132329  if( wctrlFlags & WHERE_WANT_DISTINCT ){
132330  if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
132331  /* The DISTINCT marking is pointless. Ignore it. */
132332  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
132333  }else if( pOrderBy==0 ){
132334  /* Try to ORDER BY the result set to make distinct processing easier */
132335  pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
132336  pWInfo->pOrderBy = pDistinctSet;
132337  }
132338  }
132339 
132340  /* Construct the WhereLoop objects */
132341 #if defined(WHERETRACE_ENABLED)
132342  if( sqlite3WhereTrace & 0xffff ){
132343  sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
132344  if( wctrlFlags & WHERE_USE_LIMIT ){
132345  sqlite3DebugPrintf(", limit: %d", iAuxArg);
132346  }
132347  sqlite3DebugPrintf(")\n");
132348  }
132349  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
132350  sqlite3WhereClausePrint(sWLB.pWC);
132351  }
132352 #endif
132353 
132354  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
132355  rc = whereLoopAddAll(&sWLB);
132356  if( rc ) goto whereBeginError;
132357 
132358 #ifdef WHERETRACE_ENABLED
132359  if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
132360  WhereLoop *p;
132361  int i;
132362  static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
132363  "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
132364  for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
132365  p->cId = zLabel[i%sizeof(zLabel)];
132366  whereLoopPrint(p, sWLB.pWC);
132367  }
132368  }
132369 #endif
132370 
132371  wherePathSolver(pWInfo, 0);
132372  if( db->mallocFailed ) goto whereBeginError;
132373  if( pWInfo->pOrderBy ){
132374  wherePathSolver(pWInfo, pWInfo->nRowOut+1);
132375  if( db->mallocFailed ) goto whereBeginError;
132376  }
132377  }
132378  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
132379  pWInfo->revMask = ALLBITS;
132380  }
132381  if( pParse->nErr || NEVER(db->mallocFailed) ){
132382  goto whereBeginError;
132383  }
132384 #ifdef WHERETRACE_ENABLED
132385  if( sqlite3WhereTrace ){
132386  sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
132387  if( pWInfo->nOBSat>0 ){
132388  sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
132389  }
132390  switch( pWInfo->eDistinct ){
132391  case WHERE_DISTINCT_UNIQUE: {
132392  sqlite3DebugPrintf(" DISTINCT=unique");
132393  break;
132394  }
132395  case WHERE_DISTINCT_ORDERED: {
132396  sqlite3DebugPrintf(" DISTINCT=ordered");
132397  break;
132398  }
132399  case WHERE_DISTINCT_UNORDERED: {
132400  sqlite3DebugPrintf(" DISTINCT=unordered");
132401  break;
132402  }
132403  }
132404  sqlite3DebugPrintf("\n");
132405  for(ii=0; ii<pWInfo->nLevel; ii++){
132406  whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
132407  }
132408  }
132409 #endif
132410  /* Attempt to omit tables from the join that do not effect the result */
132411  if( pWInfo->nLevel>=2
132412  && pDistinctSet!=0
132414  ){
132415  Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
132416  if( sWLB.pOrderBy ){
132417  tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
132418  }
132419  while( pWInfo->nLevel>=2 ){
132420  WhereTerm *pTerm, *pEnd;
132421  pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
132422  if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
132423  if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
132424  && (pLoop->wsFlags & WHERE_ONEROW)==0
132425  ){
132426  break;
132427  }
132428  if( (tabUsed & pLoop->maskSelf)!=0 ) break;
132429  pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
132430  for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
132431  if( (pTerm->prereqAll & pLoop->maskSelf)!=0
132432  && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
132433  ){
132434  break;
132435  }
132436  }
132437  if( pTerm<pEnd ) break;
132438  WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
132439  pWInfo->nLevel--;
132440  nTabList--;
132441  }
132442  }
132443  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
132444  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
132445 
132446  /* If the caller is an UPDATE or DELETE statement that is requesting
132447  ** to use a one-pass algorithm, determine if this is appropriate.
132448  */
132449  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
132450  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
132451  int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
132452  int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
132453  if( bOnerow
132454  || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
132455  && 0==(wsFlags & WHERE_VIRTUALTABLE))
132456  ){
132457  pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
132458  if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
132459  if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
132460  bFordelete = OPFLAG_FORDELETE;
132461  }
132462  pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
132463  }
132464  }
132465  }
132466 
132467  /* Open all tables in the pTabList and any indices selected for
132468  ** searching those tables.
132469  */
132470  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
132471  Table *pTab; /* Table to open */
132472  int iDb; /* Index of database containing table/index */
132473  struct SrcList_item *pTabItem;
132474 
132475  pTabItem = &pTabList->a[pLevel->iFrom];
132476  pTab = pTabItem->pTab;
132477  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
132478  pLoop = pLevel->pWLoop;
132479  if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
132480  /* Do nothing */
132481  }else
132482 #ifndef SQLITE_OMIT_VIRTUALTABLE
132483  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
132484  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
132485  int iCur = pTabItem->iCursor;
132486  sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
132487  }else if( IsVirtual(pTab) ){
132488  /* noop */
132489  }else
132490 #endif
132491  if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
132492  && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
132493  int op = OP_OpenRead;
132494  if( pWInfo->eOnePass!=ONEPASS_OFF ){
132495  op = OP_OpenWrite;
132496  pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
132497  };
132498  sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
132499  assert( pTabItem->iCursor==pLevel->iTabCur );
132500  testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
132501  testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
132502  if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
132503  Bitmask b = pTabItem->colUsed;
132504  int n = 0;
132505  for(; b; b=b>>1, n++){}
132507  assert( n<=pTab->nCol );
132508  }
132509 #ifdef SQLITE_ENABLE_CURSOR_HINTS
132510  if( pLoop->u.btree.pIndex!=0 ){
132511  sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
132512  }else
132513 #endif
132514  {
132515  sqlite3VdbeChangeP5(v, bFordelete);
132516  }
132517 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
132518  sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
132519  (const u8*)&pTabItem->colUsed, P4_INT64);
132520 #endif
132521  }else{
132522  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
132523  }
132524  if( pLoop->wsFlags & WHERE_INDEXED ){
132525  Index *pIx = pLoop->u.btree.pIndex;
132526  int iIndexCur;
132527  int op = OP_OpenRead;
132528  /* iAuxArg is always set if to a positive value if ONEPASS is possible */
132529  assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
132530  if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
132531  && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
132532  ){
132533  /* This is one term of an OR-optimization using the PRIMARY KEY of a
132534  ** WITHOUT ROWID table. No need for a separate index */
132535  iIndexCur = pLevel->iTabCur;
132536  op = 0;
132537  }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
132538  Index *pJ = pTabItem->pTab->pIndex;
132539  iIndexCur = iAuxArg;
132540  assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
132541  while( ALWAYS(pJ) && pJ!=pIx ){
132542  iIndexCur++;
132543  pJ = pJ->pNext;
132544  }
132545  op = OP_OpenWrite;
132546  pWInfo->aiCurOnePass[1] = iIndexCur;
132547  }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
132548  iIndexCur = iAuxArg;
132549  op = OP_ReopenIdx;
132550  }else{
132551  iIndexCur = pParse->nTab++;
132552  }
132553  pLevel->iIdxCur = iIndexCur;
132554  assert( pIx->pSchema==pTab->pSchema );
132555  assert( iIndexCur>=0 );
132556  if( op ){
132557  sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
132558  sqlite3VdbeSetP4KeyInfo(pParse, pIx);
132559  if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
132560  && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
132561  && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
132562  ){
132563  sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
132564  }
132565  VdbeComment((v, "%s", pIx->zName));
132566 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
132567  {
132568  u64 colUsed = 0;
132569  int ii, jj;
132570  for(ii=0; ii<pIx->nColumn; ii++){
132571  jj = pIx->aiColumn[ii];
132572  if( jj<0 ) continue;
132573  if( jj>63 ) jj = 63;
132574  if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
132575  colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
132576  }
132577  sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
132578  (u8*)&colUsed, P4_INT64);
132579  }
132580 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
132581  }
132582  }
132583  if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
132584  }
132585  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
132586  if( db->mallocFailed ) goto whereBeginError;
132587 
132588  /* Generate the code to do the search. Each iteration of the for
132589  ** loop below generates code for a single nested loop of the VM
132590  ** program.
132591  */
132592  notReady = ~(Bitmask)0;
132593  for(ii=0; ii<nTabList; ii++){
132594  int addrExplain;
132595  int wsFlags;
132596  pLevel = &pWInfo->a[ii];
132597  wsFlags = pLevel->pWLoop->wsFlags;
132598 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
132599  if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
132600  constructAutomaticIndex(pParse, &pWInfo->sWC,
132601  &pTabList->a[pLevel->iFrom], notReady, pLevel);
132602  if( db->mallocFailed ) goto whereBeginError;
132603  }
132604 #endif
132605  addrExplain = sqlite3WhereExplainOneScan(
132606  pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
132607  );
132608  pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
132609  notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
132610  pWInfo->iContinue = pLevel->addrCont;
132611  if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
132612  sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
132613  }
132614  }
132615 
132616  /* Done. */
132617  VdbeModuleComment((v, "Begin WHERE-core"));
132618  return pWInfo;
132619 
132620  /* Jump here if malloc fails */
132621 whereBeginError:
132622  if( pWInfo ){
132623  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
132624  whereInfoFree(db, pWInfo);
132625  }
132626  return 0;
132627 }
132628 
132629 /*
132630 ** Generate the end of the WHERE loop. See comments on
132631 ** sqlite3WhereBegin() for additional information.
132632 */
132634  Parse *pParse = pWInfo->pParse;
132635  Vdbe *v = pParse->pVdbe;
132636  int i;
132637  WhereLevel *pLevel;
132638  WhereLoop *pLoop;
132639  SrcList *pTabList = pWInfo->pTabList;
132640  sqlite3 *db = pParse->db;
132641 
132642  /* Generate loop termination code.
132643  */
132644  VdbeModuleComment((v, "End WHERE-core"));
132645  sqlite3ExprCacheClear(pParse);
132646  for(i=pWInfo->nLevel-1; i>=0; i--){
132647  int addr;
132648  pLevel = &pWInfo->a[i];
132649  pLoop = pLevel->pWLoop;
132650  sqlite3VdbeResolveLabel(v, pLevel->addrCont);
132651  if( pLevel->op!=OP_Noop ){
132652  sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
132653  sqlite3VdbeChangeP5(v, pLevel->p5);
132654  VdbeCoverage(v);
132655  VdbeCoverageIf(v, pLevel->op==OP_Next);
132656  VdbeCoverageIf(v, pLevel->op==OP_Prev);
132657  VdbeCoverageIf(v, pLevel->op==OP_VNext);
132658  }
132659  if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
132660  struct InLoop *pIn;
132661  int j;
132662  sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
132663  for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
132664  sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
132665  if( pIn->eEndLoopOp!=OP_Noop ){
132666  sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
132667  VdbeCoverage(v);
132668  VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
132669  VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
132670  }
132671  sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
132672  }
132673  }
132674  sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
132675  if( pLevel->addrSkip ){
132676  sqlite3VdbeGoto(v, pLevel->addrSkip);
132677  VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
132678  sqlite3VdbeJumpHere(v, pLevel->addrSkip);
132679  sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
132680  }
132681 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
132682  if( pLevel->addrLikeRep ){
132683  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
132684  pLevel->addrLikeRep);
132685  VdbeCoverage(v);
132686  }
132687 #endif
132688  if( pLevel->iLeftJoin ){
132689  int ws = pLoop->wsFlags;
132690  addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
132691  assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
132692  if( (ws & WHERE_IDX_ONLY)==0 ){
132693  sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
132694  }
132695  if( (ws & WHERE_INDEXED)
132696  || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
132697  ){
132698  sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
132699  }
132700  if( pLevel->op==OP_Return ){
132701  sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
132702  }else{
132703  sqlite3VdbeGoto(v, pLevel->addrFirst);
132704  }
132705  sqlite3VdbeJumpHere(v, addr);
132706  }
132707  VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
132708  pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
132709  }
132710 
132711  /* The "break" point is here, just past the end of the outer loop.
132712  ** Set it.
132713  */
132714  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
132715 
132716  assert( pWInfo->nLevel<=pTabList->nSrc );
132717  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
132718  int k, last;
132719  VdbeOp *pOp;
132720  Index *pIdx = 0;
132721  struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
132722  Table *pTab = pTabItem->pTab;
132723  assert( pTab!=0 );
132724  pLoop = pLevel->pWLoop;
132725 
132726  /* For a co-routine, change all OP_Column references to the table of
132727  ** the co-routine into OP_Copy of result contained in a register.
132728  ** OP_Rowid becomes OP_Null.
132729  */
132730  if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
132731  translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
132732  pTabItem->regResult, 0);
132733  continue;
132734  }
132735 
132736  /* Close all of the cursors that were opened by sqlite3WhereBegin.
132737  ** Except, do not close cursors that will be reused by the OR optimization
132738  ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors
132739  ** created for the ONEPASS optimization.
132740  */
132741  if( (pTab->tabFlags & TF_Ephemeral)==0
132742  && pTab->pSelect==0
132743  && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
132744  ){
132745  int ws = pLoop->wsFlags;
132746  if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
132747  sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
132748  }
132749  if( (ws & WHERE_INDEXED)!=0
132750  && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
132751  && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
132752  ){
132753  sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
132754  }
132755  }
132756 
132757  /* If this scan uses an index, make VDBE code substitutions to read data
132758  ** from the index instead of from the table where possible. In some cases
132759  ** this optimization prevents the table from ever being read, which can
132760  ** yield a significant performance boost.
132761  **
132762  ** Calls to the code generator in between sqlite3WhereBegin and
132763  ** sqlite3WhereEnd will have created code that references the table
132764  ** directly. This loop scans all that code looking for opcodes
132765  ** that reference the table and converts them into opcodes that
132766  ** reference the index.
132767  */
132768  if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
132769  pIdx = pLoop->u.btree.pIndex;
132770  }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
132771  pIdx = pLevel->u.pCovidx;
132772  }
132773  if( pIdx
132774  && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
132775  && !db->mallocFailed
132776  ){
132777  last = sqlite3VdbeCurrentAddr(v);
132778  k = pLevel->addrBody;
132779  pOp = sqlite3VdbeGetOp(v, k);
132780  for(; k<last; k++, pOp++){
132781  if( pOp->p1!=pLevel->iTabCur ) continue;
132782  if( pOp->opcode==OP_Column ){
132783  int x = pOp->p2;
132784  assert( pIdx->pTable==pTab );
132785  if( !HasRowid(pTab) ){
132786  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
132787  x = pPk->aiColumn[x];
132788  assert( x>=0 );
132789  }
132790  x = sqlite3ColumnOfIndex(pIdx, x);
132791  if( x>=0 ){
132792  pOp->p2 = x;
132793  pOp->p1 = pLevel->iIdxCur;
132794  }
132795  assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
132796  }else if( pOp->opcode==OP_Rowid ){
132797  pOp->p1 = pLevel->iIdxCur;
132798  pOp->opcode = OP_IdxRowid;
132799  }
132800  }
132801  }
132802  }
132803 
132804  /* Final cleanup
132805  */
132806  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
132807  whereInfoFree(db, pWInfo);
132808  return;
132809 }
132810 
132811 /************** End of where.c ***********************************************/
132812 /************** Begin file parse.c *******************************************/
132813 /*
132814 ** 2000-05-29
132815 **
132816 ** The author disclaims copyright to this source code. In place of
132817 ** a legal notice, here is a blessing:
132818 **
132819 ** May you do good and not evil.
132820 ** May you find forgiveness for yourself and forgive others.
132821 ** May you share freely, never taking more than you give.
132822 **
132823 *************************************************************************
132824 ** Driver template for the LEMON parser generator.
132825 **
132826 ** The "lemon" program processes an LALR(1) input grammar file, then uses
132827 ** this template to construct a parser. The "lemon" program inserts text
132828 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
132829 ** interstitial "-" characters) contained in this template is changed into
132830 ** the value of the %name directive from the grammar. Otherwise, the content
132831 ** of this template is copied straight through into the generate parser
132832 ** source file.
132833 **
132834 ** The following is the concatenation of all %include directives from the
132835 ** input grammar file:
132836 */
132837 /* #include <stdio.h> */
132838 /************ Begin %include sections from the grammar ************************/
132839 
132840 /* #include "sqliteInt.h" */
132841 
132842 /*
132843 ** Disable all error recovery processing in the parser push-down
132844 ** automaton.
132845 */
132846 #define YYNOERRORRECOVERY 1
132847 
132848 /*
132849 ** Make yytestcase() the same as testcase()
132850 */
132851 #define yytestcase(X) testcase(X)
132852 
132853 /*
132854 ** Indicate that sqlite3ParserFree() will never be called with a null
132855 ** pointer.
132856 */
132857 #define YYPARSEFREENEVERNULL 1
132858 
132859 /*
132860 ** Alternative datatype for the argument to the malloc() routine passed
132861 ** into sqlite3ParserAlloc(). The default is size_t.
132862 */
132863 #define YYMALLOCARGTYPE u64
132864 
132865 /*
132866 ** An instance of this structure holds information about the
132867 ** LIMIT clause of a SELECT statement.
132868 */
132869 struct LimitVal {
132870  Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
132871  Expr *pOffset; /* The OFFSET expression. NULL if there is none */
132872 };
132873 
132874 /*
132875 ** An instance of the following structure describes the event of a
132876 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
132877 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
132878 **
132879 ** UPDATE ON (a,b,c)
132880 **
132881 ** Then the "b" IdList records the list "a,b,c".
132882 */
132883 struct TrigEvent { int a; IdList * b; };
132884 
132885 /*
132886 ** Disable lookaside memory allocation for objects that might be
132887 ** shared across database connections.
132888 */
132889 static void disableLookaside(Parse *pParse){
132890  pParse->disableLookaside++;
132891  pParse->db->lookaside.bDisable++;
132892 }
132893 
132894 
132895  /*
132896  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
132897  ** all elements in the list. And make sure list length does not exceed
132898  ** SQLITE_LIMIT_COMPOUND_SELECT.
132899  */
132900  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
132901  if( p->pPrior ){
132902  Select *pNext = 0, *pLoop;
132903  int mxSelect, cnt = 0;
132904  for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
132905  pLoop->pNext = pNext;
132906  pLoop->selFlags |= SF_Compound;
132907  }
132908  if( (p->selFlags & SF_MultiValue)==0 &&
132909  (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
132910  cnt>mxSelect
132911  ){
132912  sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
132913  }
132914  }
132915  }
132916 
132917  /* This is a utility routine used to set the ExprSpan.zStart and
132918  ** ExprSpan.zEnd values of pOut so that the span covers the complete
132919  ** range of text beginning with pStart and going to the end of pEnd.
132920  */
132921  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
132922  pOut->zStart = pStart->z;
132923  pOut->zEnd = &pEnd->z[pEnd->n];
132924  }
132925 
132926  /* Construct a new Expr object from a single identifier. Use the
132927  ** new Expr to populate pOut. Set the span of pOut to be the identifier
132928  ** that created the expression.
132929  */
132930  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
132931  Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
132932  if( p ){
132933  memset(p, 0, sizeof(Expr));
132934  p->op = (u8)op;
132935  p->flags = EP_Leaf;
132936  p->iAgg = -1;
132937  p->u.zToken = (char*)&p[1];
132938  memcpy(p->u.zToken, t.z, t.n);
132939  p->u.zToken[t.n] = 0;
132940  if( sqlite3Isquote(p->u.zToken[0]) ){
132941  if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
132942  sqlite3Dequote(p->u.zToken);
132943  }
132944 #if SQLITE_MAX_EXPR_DEPTH>0
132945  p->nHeight = 1;
132946 #endif
132947  }
132948  pOut->pExpr = p;
132949  pOut->zStart = t.z;
132950  pOut->zEnd = &t.z[t.n];
132951  }
132952 
132953  /* This routine constructs a binary expression node out of two ExprSpan
132954  ** objects and uses the result to populate a new ExprSpan object.
132955  */
132956  static void spanBinaryExpr(
132957  Parse *pParse, /* The parsing context. Errors accumulate here */
132958  int op, /* The binary operation */
132959  ExprSpan *pLeft, /* The left operand, and output */
132960  ExprSpan *pRight /* The right operand */
132961  ){
132962  pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
132963  pLeft->zEnd = pRight->zEnd;
132964  }
132965 
132966  /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
132967  ** outside of *ppExpr.
132968  */
132969  static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
132970  if( doNot ){
132971  pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0);
132972  }
132973  }
132974 
132975  /* Construct an expression node for a unary postfix operator
132976  */
132977  static void spanUnaryPostfix(
132978  Parse *pParse, /* Parsing context to record errors */
132979  int op, /* The operator */
132980  ExprSpan *pOperand, /* The operand, and output */
132981  Token *pPostOp /* The operand token for setting the span */
132982  ){
132983  pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
132984  pOperand->zEnd = &pPostOp->z[pPostOp->n];
132985  }
132986 
132987  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
132988  ** unary TK_ISNULL or TK_NOTNULL expression. */
132989  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
132990  sqlite3 *db = pParse->db;
132991  if( pA && pY && pY->op==TK_NULL ){
132992  pA->op = (u8)op;
132993  sqlite3ExprDelete(db, pA->pRight);
132994  pA->pRight = 0;
132995  }
132996  }
132997 
132998  /* Construct an expression node for a unary prefix operator
132999  */
133000  static void spanUnaryPrefix(
133001  ExprSpan *pOut, /* Write the new expression node here */
133002  Parse *pParse, /* Parsing context to record errors */
133003  int op, /* The operator */
133004  ExprSpan *pOperand, /* The operand */
133005  Token *pPreOp /* The operand token for setting the span */
133006  ){
133007  pOut->zStart = pPreOp->z;
133008  pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
133009  pOut->zEnd = pOperand->zEnd;
133010  }
133011 
133012  /* Add a single new term to an ExprList that is used to store a
133013  ** list of identifiers. Report an error if the ID list contains
133014  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
133015  ** error while parsing a legacy schema.
133016  */
133018  Parse *pParse,
133019  ExprList *pPrior,
133020  Token *pIdToken,
133021  int hasCollate,
133022  int sortOrder
133023  ){
133024  ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
133025  if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
133026  && pParse->db->init.busy==0
133027  ){
133028  sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
133029  pIdToken->n, pIdToken->z);
133030  }
133031  sqlite3ExprListSetName(pParse, p, pIdToken, 1);
133032  return p;
133033  }
133034 /**************** End of %include directives **********************************/
133035 /* These constants specify the various numeric values for terminal symbols
133036 ** in a format understandable to "makeheaders". This section is blank unless
133037 ** "lemon" is run with the "-m" command-line option.
133038 ***************** Begin makeheaders token definitions *************************/
133039 /**************** End makeheaders token definitions ***************************/
133040 
133041 /* The next sections is a series of control #defines.
133042 ** various aspects of the generated parser.
133043 ** YYCODETYPE is the data type used to store the integer codes
133044 ** that represent terminal and non-terminal symbols.
133045 ** "unsigned char" is used if there are fewer than
133046 ** 256 symbols. Larger types otherwise.
133047 ** YYNOCODE is a number of type YYCODETYPE that is not used for
133048 ** any terminal or nonterminal symbol.
133049 ** YYFALLBACK If defined, this indicates that one or more tokens
133050 ** (also known as: "terminal symbols") have fall-back
133051 ** values which should be used if the original symbol
133052 ** would not parse. This permits keywords to sometimes
133053 ** be used as identifiers, for example.
133054 ** YYACTIONTYPE is the data type used for "action codes" - numbers
133055 ** that indicate what to do in response to the next
133056 ** token.
133057 ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
133058 ** symbols. Background: A "minor type" is a semantic
133059 ** value associated with a terminal or non-terminal
133060 ** symbols. For example, for an "ID" terminal symbol,
133061 ** the minor type might be the name of the identifier.
133062 ** Each non-terminal can have a different minor type.
133063 ** Terminal symbols all have the same minor type, though.
133064 ** This macros defines the minor type for terminal
133065 ** symbols.
133066 ** YYMINORTYPE is the data type used for all minor types.
133067 ** This is typically a union of many types, one of
133068 ** which is sqlite3ParserTOKENTYPE. The entry in the union
133069 ** for terminal symbols is called "yy0".
133070 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
133071 ** zero the stack is dynamically sized using realloc()
133072 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
133073 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
133074 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
133075 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
133076 ** YYERRORSYMBOL is the code number of the error symbol. If not
133077 ** defined, then do no error processing.
133078 ** YYNSTATE the combined number of states.
133079 ** YYNRULE the number of rules in the grammar
133080 ** YY_MAX_SHIFT Maximum value for shift actions
133081 ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
133082 ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
133083 ** YY_MIN_REDUCE Maximum value for reduce actions
133084 ** YY_ERROR_ACTION The yy_action[] code for syntax error
133085 ** YY_ACCEPT_ACTION The yy_action[] code for accept
133086 ** YY_NO_ACTION The yy_action[] code for no-op
133087 */
133088 #ifndef INTERFACE
133089 # define INTERFACE 1
133090 #endif
133091 /************* Begin control #defines *****************************************/
133092 #define YYCODETYPE unsigned char
133093 #define YYNOCODE 252
133094 #define YYACTIONTYPE unsigned short int
133095 #define YYWILDCARD 96
133096 #define sqlite3ParserTOKENTYPE Token
133097 typedef union {
133098  int yyinit;
133105  int yy194;
133109  struct TrigEvent yy332;
133110  struct LimitVal yy354;
133111  struct {int value; int mask;} yy497;
133112 } YYMINORTYPE;
133113 #ifndef YYSTACKDEPTH
133114 #define YYSTACKDEPTH 100
133115 #endif
133116 #define sqlite3ParserARG_SDECL Parse *pParse;
133117 #define sqlite3ParserARG_PDECL ,Parse *pParse
133118 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
133119 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
133120 #define YYFALLBACK 1
133121 #define YYNSTATE 456
133122 #define YYNRULE 332
133123 #define YY_MAX_SHIFT 455
133124 #define YY_MIN_SHIFTREDUCE 668
133125 #define YY_MAX_SHIFTREDUCE 999
133126 #define YY_MIN_REDUCE 1000
133127 #define YY_MAX_REDUCE 1331
133128 #define YY_ERROR_ACTION 1332
133129 #define YY_ACCEPT_ACTION 1333
133130 #define YY_NO_ACTION 1334
133131 /************* End control #defines *******************************************/
133132 
133133 /* Define the yytestcase() macro to be a no-op if is not already defined
133134 ** otherwise.
133135 **
133136 ** Applications can choose to define yytestcase() in the %include section
133137 ** to a macro that can assist in verifying code coverage. For production
133138 ** code the yytestcase() macro should be turned off. But it is useful
133139 ** for testing.
133140 */
133141 #ifndef yytestcase
133142 # define yytestcase(X)
133143 #endif
133144 
133145 
133146 /* Next are the tables used to determine what action to take based on the
133147 ** current state and lookahead token. These tables are used to implement
133148 ** functions that take a state number and lookahead value and return an
133149 ** action integer.
133150 **
133151 ** Suppose the action integer is N. Then the action is determined as
133152 ** follows
133153 **
133154 ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
133155 ** token onto the stack and goto state N.
133156 **
133157 ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
133158 ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
133159 **
133160 ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
133161 ** and YY_MAX_REDUCE
133162 **
133163 ** N == YY_ERROR_ACTION A syntax error has occurred.
133164 **
133165 ** N == YY_ACCEPT_ACTION The parser accepts its input.
133166 **
133167 ** N == YY_NO_ACTION No such action. Denotes unused
133168 ** slots in the yy_action[] table.
133169 **
133170 ** The action table is constructed as a single large table named yy_action[].
133171 ** Given state S and lookahead X, the action is computed as either:
133172 **
133173 ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
133174 ** (B) N = yy_default[S]
133175 **
133176 ** The (A) formula is preferred. The B formula is used instead if:
133177 ** (1) The yy_shift_ofst[S]+X value is out of range, or
133178 ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
133179 ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
133180 ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
133181 ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
133182 ** Hence only tests (1) and (2) need to be evaluated.)
133183 **
133184 ** The formulas above are for computing the action when the lookahead is
133185 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
133186 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
133187 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
133188 ** YY_SHIFT_USE_DFLT.
133189 **
133190 ** The following are the tables generated in this section:
133191 **
133192 ** yy_action[] A single table containing all actions.
133193 ** yy_lookahead[] A table containing the lookahead for each entry in
133194 ** yy_action. Used to detect hash collisions.
133195 ** yy_shift_ofst[] For each state, the offset into yy_action for
133196 ** shifting terminals.
133197 ** yy_reduce_ofst[] For each state, the offset into yy_action for
133198 ** shifting non-terminals after a reduce.
133199 ** yy_default[] Default action for each state.
133200 **
133201 *********** Begin parsing tables **********************************************/
133202 #define YY_ACTTAB_COUNT (1567)
133203 static const YYACTIONTYPE yy_action[] = {
133204  /* 0 */ 325, 832, 351, 825, 5, 203, 203, 819, 99, 100,
133205  /* 10 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98,
133206  /* 20 */ 98, 98, 98, 301, 96, 96, 96, 96, 95, 95,
133207  /* 30 */ 94, 94, 94, 93, 351, 325, 977, 977, 824, 824,
133208  /* 40 */ 826, 947, 354, 99, 100, 90, 842, 842, 854, 857,
133209  /* 50 */ 846, 846, 97, 97, 98, 98, 98, 98, 338, 96,
133210  /* 60 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
133211  /* 70 */ 95, 95, 94, 94, 94, 93, 351, 791, 977, 977,
133212  /* 80 */ 325, 94, 94, 94, 93, 351, 792, 75, 99, 100,
133213  /* 90 */ 90, 842, 842, 854, 857, 846, 846, 97, 97, 98,
133214  /* 100 */ 98, 98, 98, 450, 96, 96, 96, 96, 95, 95,
133215  /* 110 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 325,
133216  /* 120 */ 275, 146, 132, 52, 52, 93, 351, 99, 100, 90,
133217  /* 130 */ 842, 842, 854, 857, 846, 846, 97, 97, 98, 98,
133218  /* 140 */ 98, 98, 101, 96, 96, 96, 96, 95, 95, 94,
133219  /* 150 */ 94, 94, 93, 351, 958, 958, 325, 268, 428, 413,
133220  /* 160 */ 411, 61, 752, 752, 99, 100, 90, 842, 842, 854,
133221  /* 170 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 60,
133222  /* 180 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133223  /* 190 */ 351, 325, 270, 329, 273, 277, 959, 960, 250, 99,
133224  /* 200 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133225  /* 210 */ 98, 98, 98, 98, 301, 96, 96, 96, 96, 95,
133226  /* 220 */ 95, 94, 94, 94, 93, 351, 325, 938, 1326, 698,
133227  /* 230 */ 706, 1326, 242, 412, 99, 100, 90, 842, 842, 854,
133228  /* 240 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 347,
133229  /* 250 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133230  /* 260 */ 351, 325, 938, 1327, 384, 699, 1327, 381, 379, 99,
133231  /* 270 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133232  /* 280 */ 98, 98, 98, 98, 701, 96, 96, 96, 96, 95,
133233  /* 290 */ 95, 94, 94, 94, 93, 351, 325, 92, 89, 178,
133234  /* 300 */ 833, 936, 373, 700, 99, 100, 90, 842, 842, 854,
133235  /* 310 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 375,
133236  /* 320 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133237  /* 330 */ 351, 325, 1276, 947, 354, 818, 936, 739, 739, 99,
133238  /* 340 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133239  /* 350 */ 98, 98, 98, 98, 230, 96, 96, 96, 96, 95,
133240  /* 360 */ 95, 94, 94, 94, 93, 351, 325, 969, 227, 92,
133241  /* 370 */ 89, 178, 373, 300, 99, 100, 90, 842, 842, 854,
133242  /* 380 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 921,
133243  /* 390 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133244  /* 400 */ 351, 325, 449, 447, 447, 447, 147, 737, 737, 99,
133245  /* 410 */ 100, 90, 842, 842, 854, 857, 846, 846, 97, 97,
133246  /* 420 */ 98, 98, 98, 98, 296, 96, 96, 96, 96, 95,
133247  /* 430 */ 95, 94, 94, 94, 93, 351, 325, 419, 231, 958,
133248  /* 440 */ 958, 158, 25, 422, 99, 100, 90, 842, 842, 854,
133249  /* 450 */ 857, 846, 846, 97, 97, 98, 98, 98, 98, 450,
133250  /* 460 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133251  /* 470 */ 351, 443, 224, 224, 420, 958, 958, 962, 325, 52,
133252  /* 480 */ 52, 959, 960, 176, 415, 78, 99, 100, 90, 842,
133253  /* 490 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98,
133254  /* 500 */ 98, 379, 96, 96, 96, 96, 95, 95, 94, 94,
133255  /* 510 */ 94, 93, 351, 325, 428, 418, 298, 959, 960, 962,
133256  /* 520 */ 81, 99, 88, 90, 842, 842, 854, 857, 846, 846,
133257  /* 530 */ 97, 97, 98, 98, 98, 98, 717, 96, 96, 96,
133258  /* 540 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 843,
133259  /* 550 */ 843, 855, 858, 996, 318, 343, 379, 100, 90, 842,
133260  /* 560 */ 842, 854, 857, 846, 846, 97, 97, 98, 98, 98,
133261  /* 570 */ 98, 450, 96, 96, 96, 96, 95, 95, 94, 94,
133262  /* 580 */ 94, 93, 351, 325, 350, 350, 350, 260, 377, 340,
133263  /* 590 */ 929, 52, 52, 90, 842, 842, 854, 857, 846, 846,
133264  /* 600 */ 97, 97, 98, 98, 98, 98, 361, 96, 96, 96,
133265  /* 610 */ 96, 95, 95, 94, 94, 94, 93, 351, 86, 445,
133266  /* 620 */ 847, 3, 1203, 361, 360, 378, 344, 813, 958, 958,
133267  /* 630 */ 1300, 86, 445, 729, 3, 212, 169, 287, 405, 282,
133268  /* 640 */ 404, 199, 232, 450, 300, 760, 83, 84, 280, 245,
133269  /* 650 */ 262, 365, 251, 85, 352, 352, 92, 89, 178, 83,
133270  /* 660 */ 84, 242, 412, 52, 52, 448, 85, 352, 352, 246,
133271  /* 670 */ 959, 960, 194, 455, 670, 402, 399, 398, 448, 243,
133272  /* 680 */ 221, 114, 434, 776, 361, 450, 397, 268, 747, 224,
133273  /* 690 */ 224, 132, 132, 198, 832, 434, 452, 451, 428, 427,
133274  /* 700 */ 819, 415, 734, 713, 132, 52, 52, 832, 268, 452,
133275  /* 710 */ 451, 734, 194, 819, 363, 402, 399, 398, 450, 1271,
133276  /* 720 */ 1271, 23, 958, 958, 86, 445, 397, 3, 228, 429,
133277  /* 730 */ 895, 824, 824, 826, 827, 19, 203, 720, 52, 52,
133278  /* 740 */ 428, 408, 439, 249, 824, 824, 826, 827, 19, 229,
133279  /* 750 */ 403, 153, 83, 84, 761, 177, 241, 450, 721, 85,
133280  /* 760 */ 352, 352, 120, 157, 959, 960, 58, 977, 409, 355,
133281  /* 770 */ 330, 448, 268, 428, 430, 320, 790, 32, 32, 86,
133282  /* 780 */ 445, 776, 3, 341, 98, 98, 98, 98, 434, 96,
133283  /* 790 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
133284  /* 800 */ 832, 120, 452, 451, 813, 887, 819, 83, 84, 977,
133285  /* 810 */ 813, 132, 410, 920, 85, 352, 352, 132, 407, 789,
133286  /* 820 */ 958, 958, 92, 89, 178, 917, 448, 262, 370, 261,
133287  /* 830 */ 82, 914, 80, 262, 370, 261, 776, 824, 824, 826,
133288  /* 840 */ 827, 19, 934, 434, 96, 96, 96, 96, 95, 95,
133289  /* 850 */ 94, 94, 94, 93, 351, 832, 74, 452, 451, 958,
133290  /* 860 */ 958, 819, 959, 960, 120, 92, 89, 178, 945, 2,
133291  /* 870 */ 918, 965, 268, 1, 976, 76, 445, 762, 3, 708,
133292  /* 880 */ 901, 901, 387, 958, 958, 757, 919, 371, 740, 778,
133293  /* 890 */ 756, 257, 824, 824, 826, 827, 19, 417, 741, 450,
133294  /* 900 */ 24, 959, 960, 83, 84, 369, 958, 958, 177, 226,
133295  /* 910 */ 85, 352, 352, 885, 315, 314, 313, 215, 311, 10,
133296  /* 920 */ 10, 683, 448, 349, 348, 959, 960, 909, 777, 157,
133297  /* 930 */ 120, 958, 958, 337, 776, 416, 711, 310, 450, 434,
133298  /* 940 */ 450, 321, 450, 791, 103, 200, 175, 450, 959, 960,
133299  /* 950 */ 908, 832, 792, 452, 451, 9, 9, 819, 10, 10,
133300  /* 960 */ 52, 52, 51, 51, 180, 716, 248, 10, 10, 171,
133301  /* 970 */ 170, 167, 339, 959, 960, 247, 984, 702, 702, 450,
133302  /* 980 */ 715, 233, 686, 982, 889, 983, 182, 914, 824, 824,
133303  /* 990 */ 826, 827, 19, 183, 256, 423, 132, 181, 394, 10,
133304  /* 1000 */ 10, 889, 891, 749, 958, 958, 917, 268, 985, 198,
133305  /* 1010 */ 985, 349, 348, 425, 415, 299, 817, 832, 326, 825,
133306  /* 1020 */ 120, 332, 133, 819, 268, 98, 98, 98, 98, 91,
133307  /* 1030 */ 96, 96, 96, 96, 95, 95, 94, 94, 94, 93,
133308  /* 1040 */ 351, 157, 810, 371, 382, 359, 959, 960, 358, 268,
133309  /* 1050 */ 450, 918, 368, 324, 824, 824, 826, 450, 709, 450,
133310  /* 1060 */ 264, 380, 889, 450, 877, 746, 253, 919, 255, 433,
133311  /* 1070 */ 36, 36, 234, 450, 234, 120, 269, 37, 37, 12,
133312  /* 1080 */ 12, 334, 272, 27, 27, 450, 330, 118, 450, 162,
133313  /* 1090 */ 742, 280, 450, 38, 38, 450, 985, 356, 985, 450,
133314  /* 1100 */ 709, 1210, 450, 132, 450, 39, 39, 450, 40, 40,
133315  /* 1110 */ 450, 362, 41, 41, 450, 42, 42, 450, 254, 28,
133316  /* 1120 */ 28, 450, 29, 29, 31, 31, 450, 43, 43, 450,
133317  /* 1130 */ 44, 44, 450, 714, 45, 45, 450, 11, 11, 767,
133318  /* 1140 */ 450, 46, 46, 450, 268, 450, 105, 105, 450, 47,
133319  /* 1150 */ 47, 450, 48, 48, 450, 237, 33, 33, 450, 172,
133320  /* 1160 */ 49, 49, 450, 50, 50, 34, 34, 274, 122, 122,
133321  /* 1170 */ 450, 123, 123, 450, 124, 124, 450, 898, 56, 56,
133322  /* 1180 */ 450, 897, 35, 35, 450, 267, 450, 817, 450, 817,
133323  /* 1190 */ 106, 106, 450, 53, 53, 385, 107, 107, 450, 817,
133324  /* 1200 */ 108, 108, 817, 450, 104, 104, 121, 121, 119, 119,
133325  /* 1210 */ 450, 117, 112, 112, 450, 276, 450, 225, 111, 111,
133326  /* 1220 */ 450, 730, 450, 109, 109, 450, 673, 674, 675, 912,
133327  /* 1230 */ 110, 110, 317, 998, 55, 55, 57, 57, 692, 331,
133328  /* 1240 */ 54, 54, 26, 26, 696, 30, 30, 317, 937, 197,
133329  /* 1250 */ 196, 195, 335, 281, 336, 446, 331, 745, 689, 436,
133330  /* 1260 */ 440, 444, 120, 72, 386, 223, 175, 345, 757, 933,
133331  /* 1270 */ 20, 286, 319, 756, 815, 372, 374, 202, 202, 202,
133332  /* 1280 */ 263, 395, 285, 74, 208, 21, 696, 719, 718, 884,
133333  /* 1290 */ 120, 120, 120, 120, 120, 754, 278, 828, 77, 74,
133334  /* 1300 */ 726, 727, 785, 783, 880, 202, 999, 208, 894, 893,
133335  /* 1310 */ 894, 893, 694, 816, 763, 116, 774, 1290, 431, 432,
133336  /* 1320 */ 302, 999, 390, 303, 823, 697, 691, 680, 159, 289,
133337  /* 1330 */ 679, 884, 681, 952, 291, 218, 293, 7, 316, 828,
133338  /* 1340 */ 173, 805, 259, 364, 252, 911, 376, 713, 295, 435,
133339  /* 1350 */ 308, 168, 955, 993, 135, 400, 990, 284, 882, 881,
133340  /* 1360 */ 205, 928, 926, 59, 333, 62, 144, 156, 130, 72,
133341  /* 1370 */ 802, 366, 367, 393, 137, 185, 189, 160, 139, 383,
133342  /* 1380 */ 67, 896, 140, 141, 142, 148, 389, 812, 775, 266,
133343  /* 1390 */ 219, 190, 154, 391, 913, 876, 271, 406, 191, 322,
133344  /* 1400 */ 682, 733, 192, 342, 732, 724, 731, 711, 723, 421,
133345  /* 1410 */ 705, 71, 323, 6, 204, 771, 288, 79, 297, 346,
133346  /* 1420 */ 772, 704, 290, 283, 703, 770, 292, 294, 967, 239,
133347  /* 1430 */ 769, 102, 862, 438, 426, 240, 424, 442, 73, 213,
133348  /* 1440 */ 688, 238, 22, 453, 953, 214, 217, 216, 454, 677,
133349  /* 1450 */ 676, 671, 753, 125, 115, 235, 126, 669, 353, 166,
133350  /* 1460 */ 127, 244, 179, 357, 306, 304, 305, 307, 113, 892,
133351  /* 1470 */ 327, 890, 811, 328, 134, 128, 136, 138, 743, 258,
133352  /* 1480 */ 907, 184, 143, 129, 910, 186, 63, 64, 145, 187,
133353  /* 1490 */ 906, 65, 8, 66, 13, 188, 202, 899, 265, 149,
133354  /* 1500 */ 987, 388, 150, 685, 161, 392, 285, 193, 279, 396,
133355  /* 1510 */ 151, 401, 68, 14, 15, 722, 69, 236, 831, 131,
133356  /* 1520 */ 830, 860, 70, 751, 16, 414, 755, 4, 174, 220,
133357  /* 1530 */ 222, 784, 201, 152, 779, 77, 74, 17, 18, 875,
133358  /* 1540 */ 861, 859, 916, 864, 915, 207, 206, 942, 163, 437,
133359  /* 1550 */ 948, 943, 164, 209, 1002, 441, 863, 165, 210, 829,
133360  /* 1560 */ 695, 87, 312, 211, 1292, 1291, 309,
133361 };
133362 static const YYCODETYPE yy_lookahead[] = {
133363  /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28,
133364  /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
133365  /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
133366  /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133,
133367  /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33,
133368  /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 187, 43,
133369  /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
133370  /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97,
133371  /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28,
133372  /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
133373  /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
133374  /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19,
133375  /* 120 */ 16, 22, 92, 172, 173, 52, 53, 27, 28, 29,
133376  /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
133377  /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49,
133378  /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208,
133379  /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32,
133380  /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79,
133381  /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133382  /* 190 */ 53, 19, 88, 157, 90, 23, 97, 98, 193, 27,
133383  /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133384  /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
133385  /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172,
133386  /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32,
133387  /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
133388  /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133389  /* 260 */ 53, 19, 22, 23, 228, 23, 26, 231, 152, 27,
133390  /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133391  /* 280 */ 38, 39, 40, 41, 172, 43, 44, 45, 46, 47,
133392  /* 290 */ 48, 49, 50, 51, 52, 53, 19, 221, 222, 223,
133393  /* 300 */ 23, 96, 152, 172, 27, 28, 29, 30, 31, 32,
133394  /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152,
133395  /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133396  /* 330 */ 53, 19, 0, 1, 2, 23, 96, 190, 191, 27,
133397  /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133398  /* 350 */ 38, 39, 40, 41, 238, 43, 44, 45, 46, 47,
133399  /* 360 */ 48, 49, 50, 51, 52, 53, 19, 185, 218, 221,
133400  /* 370 */ 222, 223, 152, 152, 27, 28, 29, 30, 31, 32,
133401  /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 241,
133402  /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133403  /* 400 */ 53, 19, 152, 168, 169, 170, 22, 190, 191, 27,
133404  /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
133405  /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
133406  /* 430 */ 48, 49, 50, 51, 52, 53, 19, 19, 218, 55,
133407  /* 440 */ 56, 24, 22, 152, 27, 28, 29, 30, 31, 32,
133408  /* 450 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 152,
133409  /* 460 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133410  /* 470 */ 53, 250, 194, 195, 56, 55, 56, 55, 19, 172,
133411  /* 480 */ 173, 97, 98, 152, 206, 138, 27, 28, 29, 30,
133412  /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
133413  /* 500 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50,
133414  /* 510 */ 51, 52, 53, 19, 207, 208, 152, 97, 98, 97,
133415  /* 520 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35,
133416  /* 530 */ 36, 37, 38, 39, 40, 41, 181, 43, 44, 45,
133417  /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 30,
133418  /* 550 */ 31, 32, 33, 247, 248, 19, 152, 28, 29, 30,
133419  /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
133420  /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50,
133421  /* 580 */ 51, 52, 53, 19, 168, 169, 170, 238, 19, 53,
133422  /* 590 */ 152, 172, 173, 29, 30, 31, 32, 33, 34, 35,
133423  /* 600 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45,
133424  /* 610 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 20,
133425  /* 620 */ 101, 22, 23, 169, 170, 56, 207, 85, 55, 56,
133426  /* 630 */ 23, 19, 20, 26, 22, 99, 100, 101, 102, 103,
133427  /* 640 */ 104, 105, 238, 152, 152, 210, 47, 48, 112, 152,
133428  /* 650 */ 108, 109, 110, 54, 55, 56, 221, 222, 223, 47,
133429  /* 660 */ 48, 119, 120, 172, 173, 66, 54, 55, 56, 152,
133430  /* 670 */ 97, 98, 99, 148, 149, 102, 103, 104, 66, 154,
133431  /* 680 */ 23, 156, 83, 26, 230, 152, 113, 152, 163, 194,
133432  /* 690 */ 195, 92, 92, 30, 95, 83, 97, 98, 207, 208,
133433  /* 700 */ 101, 206, 179, 180, 92, 172, 173, 95, 152, 97,
133434  /* 710 */ 98, 188, 99, 101, 219, 102, 103, 104, 152, 119,
133435  /* 720 */ 120, 196, 55, 56, 19, 20, 113, 22, 193, 163,
133436  /* 730 */ 11, 132, 133, 134, 135, 136, 24, 65, 172, 173,
133437  /* 740 */ 207, 208, 250, 152, 132, 133, 134, 135, 136, 193,
133438  /* 750 */ 78, 84, 47, 48, 49, 98, 199, 152, 86, 54,
133439  /* 760 */ 55, 56, 196, 152, 97, 98, 209, 55, 163, 244,
133440  /* 770 */ 107, 66, 152, 207, 208, 164, 175, 172, 173, 19,
133441  /* 780 */ 20, 124, 22, 111, 38, 39, 40, 41, 83, 43,
133442  /* 790 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
133443  /* 800 */ 95, 196, 97, 98, 85, 152, 101, 47, 48, 97,
133444  /* 810 */ 85, 92, 207, 193, 54, 55, 56, 92, 49, 175,
133445  /* 820 */ 55, 56, 221, 222, 223, 12, 66, 108, 109, 110,
133446  /* 830 */ 137, 163, 139, 108, 109, 110, 26, 132, 133, 134,
133447  /* 840 */ 135, 136, 152, 83, 43, 44, 45, 46, 47, 48,
133448  /* 850 */ 49, 50, 51, 52, 53, 95, 26, 97, 98, 55,
133449  /* 860 */ 56, 101, 97, 98, 196, 221, 222, 223, 146, 147,
133450  /* 870 */ 57, 171, 152, 22, 26, 19, 20, 49, 22, 179,
133451  /* 880 */ 108, 109, 110, 55, 56, 116, 73, 219, 75, 124,
133452  /* 890 */ 121, 152, 132, 133, 134, 135, 136, 163, 85, 152,
133453  /* 900 */ 232, 97, 98, 47, 48, 237, 55, 56, 98, 5,
133454  /* 910 */ 54, 55, 56, 193, 10, 11, 12, 13, 14, 172,
133455  /* 920 */ 173, 17, 66, 47, 48, 97, 98, 152, 124, 152,
133456  /* 930 */ 196, 55, 56, 186, 124, 152, 106, 160, 152, 83,
133457  /* 940 */ 152, 164, 152, 61, 22, 211, 212, 152, 97, 98,
133458  /* 950 */ 152, 95, 70, 97, 98, 172, 173, 101, 172, 173,
133459  /* 960 */ 172, 173, 172, 173, 60, 181, 62, 172, 173, 47,
133460  /* 970 */ 48, 123, 186, 97, 98, 71, 100, 55, 56, 152,
133461  /* 980 */ 181, 186, 21, 107, 152, 109, 82, 163, 132, 133,
133462  /* 990 */ 134, 135, 136, 89, 16, 207, 92, 93, 19, 172,
133463  /* 1000 */ 173, 169, 170, 195, 55, 56, 12, 152, 132, 30,
133464  /* 1010 */ 134, 47, 48, 186, 206, 225, 152, 95, 114, 97,
133465  /* 1020 */ 196, 245, 246, 101, 152, 38, 39, 40, 41, 42,
133466  /* 1030 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
133467  /* 1040 */ 53, 152, 163, 219, 152, 141, 97, 98, 193, 152,
133468  /* 1050 */ 152, 57, 91, 164, 132, 133, 134, 152, 55, 152,
133469  /* 1060 */ 152, 237, 230, 152, 103, 193, 88, 73, 90, 75,
133470  /* 1070 */ 172, 173, 183, 152, 185, 196, 152, 172, 173, 172,
133471  /* 1080 */ 173, 217, 152, 172, 173, 152, 107, 22, 152, 24,
133472  /* 1090 */ 193, 112, 152, 172, 173, 152, 132, 242, 134, 152,
133473  /* 1100 */ 97, 140, 152, 92, 152, 172, 173, 152, 172, 173,
133474  /* 1110 */ 152, 100, 172, 173, 152, 172, 173, 152, 140, 172,
133475  /* 1120 */ 173, 152, 172, 173, 172, 173, 152, 172, 173, 152,
133476  /* 1130 */ 172, 173, 152, 152, 172, 173, 152, 172, 173, 213,
133477  /* 1140 */ 152, 172, 173, 152, 152, 152, 172, 173, 152, 172,
133478  /* 1150 */ 173, 152, 172, 173, 152, 210, 172, 173, 152, 26,
133479  /* 1160 */ 172, 173, 152, 172, 173, 172, 173, 152, 172, 173,
133480  /* 1170 */ 152, 172, 173, 152, 172, 173, 152, 59, 172, 173,
133481  /* 1180 */ 152, 63, 172, 173, 152, 193, 152, 152, 152, 152,
133482  /* 1190 */ 172, 173, 152, 172, 173, 77, 172, 173, 152, 152,
133483  /* 1200 */ 172, 173, 152, 152, 172, 173, 172, 173, 172, 173,
133484  /* 1210 */ 152, 22, 172, 173, 152, 152, 152, 22, 172, 173,
133485  /* 1220 */ 152, 152, 152, 172, 173, 152, 7, 8, 9, 163,
133486  /* 1230 */ 172, 173, 22, 23, 172, 173, 172, 173, 166, 167,
133487  /* 1240 */ 172, 173, 172, 173, 55, 172, 173, 22, 23, 108,
133488  /* 1250 */ 109, 110, 217, 152, 217, 166, 167, 163, 163, 163,
133489  /* 1260 */ 163, 163, 196, 130, 217, 211, 212, 217, 116, 23,
133490  /* 1270 */ 22, 101, 26, 121, 23, 23, 23, 26, 26, 26,
133491  /* 1280 */ 23, 23, 112, 26, 26, 37, 97, 100, 101, 55,
133492  /* 1290 */ 196, 196, 196, 196, 196, 23, 23, 55, 26, 26,
133493  /* 1300 */ 7, 8, 23, 152, 23, 26, 96, 26, 132, 132,
133494  /* 1310 */ 134, 134, 23, 152, 152, 26, 152, 122, 152, 191,
133495  /* 1320 */ 152, 96, 234, 152, 152, 152, 152, 152, 197, 210,
133496  /* 1330 */ 152, 97, 152, 152, 210, 233, 210, 198, 150, 97,
133497  /* 1340 */ 184, 201, 239, 214, 214, 201, 239, 180, 214, 227,
133498  /* 1350 */ 200, 198, 155, 67, 243, 176, 69, 175, 175, 175,
133499  /* 1360 */ 122, 159, 159, 240, 159, 240, 22, 220, 27, 130,
133500  /* 1370 */ 201, 18, 159, 18, 189, 158, 158, 220, 192, 159,
133501  /* 1380 */ 137, 236, 192, 192, 192, 189, 74, 189, 159, 235,
133502  /* 1390 */ 159, 158, 22, 177, 201, 201, 159, 107, 158, 177,
133503  /* 1400 */ 159, 174, 158, 76, 174, 182, 174, 106, 182, 125,
133504  /* 1410 */ 174, 107, 177, 22, 159, 216, 215, 137, 159, 53,
133505  /* 1420 */ 216, 176, 215, 174, 174, 216, 215, 215, 174, 229,
133506  /* 1430 */ 216, 129, 224, 177, 126, 229, 127, 177, 128, 25,
133507  /* 1440 */ 162, 226, 26, 161, 13, 153, 6, 153, 151, 151,
133508  /* 1450 */ 151, 151, 205, 165, 178, 178, 165, 4, 3, 22,
133509  /* 1460 */ 165, 142, 15, 94, 202, 204, 203, 201, 16, 23,
133510  /* 1470 */ 249, 23, 120, 249, 246, 111, 131, 123, 20, 16,
133511  /* 1480 */ 1, 125, 123, 111, 56, 64, 37, 37, 131, 122,
133512  /* 1490 */ 1, 37, 5, 37, 22, 107, 26, 80, 140, 80,
133513  /* 1500 */ 87, 72, 107, 20, 24, 19, 112, 105, 23, 79,
133514  /* 1510 */ 22, 79, 22, 22, 22, 58, 22, 79, 23, 68,
133515  /* 1520 */ 23, 23, 26, 116, 22, 26, 23, 22, 122, 23,
133516  /* 1530 */ 23, 56, 64, 22, 124, 26, 26, 64, 64, 23,
133517  /* 1540 */ 23, 23, 23, 11, 23, 22, 26, 23, 22, 24,
133518  /* 1550 */ 1, 23, 22, 26, 251, 24, 23, 22, 122, 23,
133519  /* 1560 */ 23, 22, 15, 122, 122, 122, 23,
133520 };
133521 #define YY_SHIFT_USE_DFLT (1567)
133522 #define YY_SHIFT_COUNT (455)
133523 #define YY_SHIFT_MIN (-94)
133524 #define YY_SHIFT_MAX (1549)
133525 static const short yy_shift_ofst[] = {
133526  /* 0 */ 40, 599, 904, 612, 760, 760, 760, 760, 725, -19,
133527  /* 10 */ 16, 16, 100, 760, 760, 760, 760, 760, 760, 760,
133528  /* 20 */ 876, 876, 573, 542, 719, 600, 61, 137, 172, 207,
133529  /* 30 */ 242, 277, 312, 347, 382, 417, 459, 459, 459, 459,
133530  /* 40 */ 459, 459, 459, 459, 459, 459, 459, 459, 459, 459,
133531  /* 50 */ 459, 459, 459, 494, 459, 529, 564, 564, 705, 760,
133532  /* 60 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133533  /* 70 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133534  /* 80 */ 760, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133535  /* 90 */ 856, 760, 760, 760, 760, 760, 760, 760, 760, 760,
133536  /* 100 */ 760, 760, 760, 760, 987, 746, 746, 746, 746, 746,
133537  /* 110 */ 801, 23, 32, 949, 961, 979, 964, 964, 949, 73,
133538  /* 120 */ 113, -51, 1567, 1567, 1567, 536, 536, 536, 99, 99,
133539  /* 130 */ 813, 813, 667, 205, 240, 949, 949, 949, 949, 949,
133540  /* 140 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949,
133541  /* 150 */ 949, 949, 949, 949, 949, 332, 1011, 422, 422, 113,
133542  /* 160 */ 30, 30, 30, 30, 30, 30, 1567, 1567, 1567, 922,
133543  /* 170 */ -94, -94, 384, 613, 828, 420, 765, 804, 851, 949,
133544  /* 180 */ 949, 949, 949, 949, 949, 949, 949, 949, 949, 949,
133545  /* 190 */ 949, 949, 949, 949, 949, 672, 672, 672, 949, 949,
133546  /* 200 */ 657, 949, 949, 949, -18, 949, 949, 994, 949, 949,
133547  /* 210 */ 949, 949, 949, 949, 949, 949, 949, 949, 772, 1118,
133548  /* 220 */ 712, 712, 712, 810, 45, 769, 1219, 1133, 418, 418,
133549  /* 230 */ 569, 1133, 569, 830, 607, 663, 882, 418, 693, 882,
133550  /* 240 */ 882, 848, 1152, 1065, 1286, 1238, 1238, 1287, 1287, 1238,
133551  /* 250 */ 1344, 1341, 1239, 1353, 1353, 1353, 1353, 1238, 1355, 1239,
133552  /* 260 */ 1344, 1341, 1341, 1239, 1238, 1355, 1243, 1312, 1238, 1238,
133553  /* 270 */ 1355, 1370, 1238, 1355, 1238, 1355, 1370, 1290, 1290, 1290,
133554  /* 280 */ 1327, 1370, 1290, 1301, 1290, 1327, 1290, 1290, 1284, 1304,
133555  /* 290 */ 1284, 1304, 1284, 1304, 1284, 1304, 1238, 1391, 1238, 1280,
133556  /* 300 */ 1370, 1366, 1366, 1370, 1302, 1308, 1310, 1309, 1239, 1414,
133557  /* 310 */ 1416, 1431, 1431, 1440, 1440, 1440, 1440, 1567, 1567, 1567,
133558  /* 320 */ 1567, 1567, 1567, 1567, 1567, 519, 978, 1210, 1225, 104,
133559  /* 330 */ 1141, 1189, 1246, 1248, 1251, 1252, 1253, 1257, 1258, 1273,
133560  /* 340 */ 1003, 1187, 1293, 1170, 1272, 1279, 1234, 1281, 1176, 1177,
133561  /* 350 */ 1289, 1242, 1195, 1453, 1455, 1437, 1319, 1447, 1369, 1452,
133562  /* 360 */ 1446, 1448, 1352, 1345, 1364, 1354, 1458, 1356, 1463, 1479,
133563  /* 370 */ 1359, 1357, 1449, 1450, 1454, 1456, 1372, 1428, 1421, 1367,
133564  /* 380 */ 1489, 1487, 1472, 1388, 1358, 1417, 1470, 1419, 1413, 1429,
133565  /* 390 */ 1395, 1480, 1483, 1486, 1394, 1402, 1488, 1430, 1490, 1491,
133566  /* 400 */ 1485, 1492, 1432, 1457, 1494, 1438, 1451, 1495, 1497, 1498,
133567  /* 410 */ 1496, 1407, 1502, 1503, 1505, 1499, 1406, 1506, 1507, 1475,
133568  /* 420 */ 1468, 1511, 1410, 1509, 1473, 1510, 1474, 1516, 1509, 1517,
133569  /* 430 */ 1518, 1519, 1520, 1521, 1523, 1532, 1524, 1526, 1525, 1527,
133570  /* 440 */ 1528, 1530, 1531, 1527, 1533, 1535, 1536, 1537, 1539, 1436,
133571  /* 450 */ 1441, 1442, 1443, 1543, 1547, 1549,
133572 };
133573 #define YY_REDUCE_USE_DFLT (-130)
133574 #define YY_REDUCE_COUNT (324)
133575 #define YY_REDUCE_MIN (-129)
133576 #define YY_REDUCE_MAX (1300)
133577 static const short yy_reduce_ofst[] = {
133578  /* 0 */ -29, 566, 525, 605, -49, 307, 491, 533, 668, 435,
133579  /* 10 */ 601, 644, 148, 747, 786, 795, 419, 788, 827, 790,
133580  /* 20 */ 454, 832, 889, 495, 824, 734, 76, 76, 76, 76,
133581  /* 30 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
133582  /* 40 */ 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
133583  /* 50 */ 76, 76, 76, 76, 76, 76, 76, 76, 783, 898,
133584  /* 60 */ 905, 907, 911, 921, 933, 936, 940, 943, 947, 950,
133585  /* 70 */ 952, 955, 958, 962, 965, 969, 974, 977, 980, 984,
133586  /* 80 */ 988, 991, 993, 996, 999, 1002, 1006, 1010, 1018, 1021,
133587  /* 90 */ 1024, 1028, 1032, 1034, 1036, 1040, 1046, 1051, 1058, 1062,
133588  /* 100 */ 1064, 1068, 1070, 1073, 76, 76, 76, 76, 76, 76,
133589  /* 110 */ 76, 76, 76, 855, 36, 523, 235, 416, 777, 76,
133590  /* 120 */ 278, 76, 76, 76, 76, 700, 700, 700, 150, 220,
133591  /* 130 */ 147, 217, 221, 306, 306, 611, 5, 535, 556, 620,
133592  /* 140 */ 720, 872, 897, 116, 864, 349, 1035, 1037, 404, 1047,
133593  /* 150 */ 992, -129, 1050, 492, 62, 722, 879, 1072, 1089, 808,
133594  /* 160 */ 1066, 1094, 1095, 1096, 1097, 1098, 776, 1054, 557, 57,
133595  /* 170 */ 112, 131, 167, 182, 250, 272, 291, 331, 364, 438,
133596  /* 180 */ 497, 517, 591, 653, 690, 739, 775, 798, 892, 908,
133597  /* 190 */ 924, 930, 1015, 1063, 1069, 355, 784, 799, 981, 1101,
133598  /* 200 */ 926, 1151, 1161, 1162, 945, 1164, 1166, 1128, 1168, 1171,
133599  /* 210 */ 1172, 250, 1173, 1174, 1175, 1178, 1180, 1181, 1088, 1102,
133600  /* 220 */ 1119, 1124, 1126, 926, 1131, 1139, 1188, 1140, 1129, 1130,
133601  /* 230 */ 1103, 1144, 1107, 1179, 1156, 1167, 1182, 1134, 1122, 1183,
133602  /* 240 */ 1184, 1150, 1153, 1197, 1111, 1202, 1203, 1123, 1125, 1205,
133603  /* 250 */ 1147, 1185, 1169, 1186, 1190, 1191, 1192, 1213, 1217, 1193,
133604  /* 260 */ 1157, 1196, 1198, 1194, 1220, 1218, 1145, 1154, 1229, 1231,
133605  /* 270 */ 1233, 1216, 1237, 1240, 1241, 1244, 1222, 1227, 1230, 1232,
133606  /* 280 */ 1223, 1235, 1236, 1245, 1249, 1226, 1250, 1254, 1199, 1201,
133607  /* 290 */ 1204, 1207, 1209, 1211, 1214, 1212, 1255, 1208, 1259, 1215,
133608  /* 300 */ 1256, 1200, 1206, 1260, 1247, 1261, 1263, 1262, 1266, 1278,
133609  /* 310 */ 1282, 1292, 1294, 1297, 1298, 1299, 1300, 1221, 1224, 1228,
133610  /* 320 */ 1288, 1291, 1276, 1277, 1295,
133611 };
133612 static const YYACTIONTYPE yy_default[] = {
133613  /* 0 */ 1281, 1271, 1271, 1271, 1203, 1203, 1203, 1203, 1271, 1096,
133614  /* 10 */ 1125, 1125, 1255, 1332, 1332, 1332, 1332, 1332, 1332, 1202,
133615  /* 20 */ 1332, 1332, 1332, 1332, 1271, 1100, 1131, 1332, 1332, 1332,
133616  /* 30 */ 1332, 1204, 1205, 1332, 1332, 1332, 1254, 1256, 1141, 1140,
133617  /* 40 */ 1139, 1138, 1237, 1112, 1136, 1129, 1133, 1204, 1198, 1199,
133618  /* 50 */ 1197, 1201, 1205, 1332, 1132, 1167, 1182, 1166, 1332, 1332,
133619  /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133620  /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133621  /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133622  /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133623  /* 100 */ 1332, 1332, 1332, 1332, 1176, 1181, 1188, 1180, 1177, 1169,
133624  /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172,
133625  /* 120 */ 1332, 1173, 1185, 1184, 1183, 1262, 1289, 1288, 1332, 1332,
133626  /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133627  /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133628  /* 150 */ 1332, 1332, 1332, 1332, 1332, 1281, 1271, 1025, 1025, 1332,
133629  /* 160 */ 1271, 1271, 1271, 1271, 1271, 1271, 1267, 1100, 1091, 1332,
133630  /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133631  /* 180 */ 1259, 1257, 1332, 1218, 1332, 1332, 1332, 1332, 1332, 1332,
133632  /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133633  /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332,
133634  /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1283, 1332, 1232,
133635  /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114,
133636  /* 230 */ 1321, 1135, 1321, 1042, 1303, 1039, 1125, 1114, 1200, 1125,
133637  /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105,
133638  /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135,
133639  /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1236, 1318, 1105, 1105,
133640  /* 270 */ 1016, 1211, 1105, 1016, 1105, 1016, 1211, 1068, 1068, 1068,
133641  /* 280 */ 1057, 1211, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113,
133642  /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1206, 1105, 1332,
133643  /* 300 */ 1211, 1215, 1215, 1211, 1130, 1119, 1128, 1126, 1135, 1022,
133644  /* 310 */ 1060, 1286, 1286, 1282, 1282, 1282, 1282, 1329, 1329, 1267,
133645  /* 320 */ 1298, 1298, 1044, 1044, 1298, 1332, 1332, 1332, 1332, 1332,
133646  /* 330 */ 1332, 1293, 1332, 1220, 1332, 1332, 1332, 1332, 1332, 1332,
133647  /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133648  /* 350 */ 1332, 1332, 1152, 1332, 1000, 1264, 1332, 1332, 1263, 1332,
133649  /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133650  /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320,
133651  /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1235, 1234, 1332, 1332,
133652  /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133653  /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
133654  /* 410 */ 1332, 1082, 1332, 1332, 1332, 1307, 1332, 1332, 1332, 1332,
133655  /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332,
133656  /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1273,
133657  /* 440 */ 1332, 1332, 1332, 1272, 1332, 1332, 1332, 1332, 1332, 1154,
133658  /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332,
133659 };
133660 /********** End of lemon-generated parsing tables *****************************/
133661 
133662 /* The next table maps tokens (terminal symbols) into fallback tokens.
133663 ** If a construct like the following:
133664 **
133665 ** %fallback ID X Y Z.
133666 **
133667 ** appears in the grammar, then ID becomes a fallback token for X, Y,
133668 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
133669 ** but it does not parse, the type of the token is changed to ID and
133670 ** the parse is retried before an error is thrown.
133671 **
133672 ** This feature can be used, for example, to cause some keywords in a language
133673 ** to revert to identifiers if they keyword does not apply in the context where
133674 ** it appears.
133675 */
133676 #ifdef YYFALLBACK
133677 static const YYCODETYPE yyFallback[] = {
133678  0, /* $ => nothing */
133679  0, /* SEMI => nothing */
133680  55, /* EXPLAIN => ID */
133681  55, /* QUERY => ID */
133682  55, /* PLAN => ID */
133683  55, /* BEGIN => ID */
133684  0, /* TRANSACTION => nothing */
133685  55, /* DEFERRED => ID */
133686  55, /* IMMEDIATE => ID */
133687  55, /* EXCLUSIVE => ID */
133688  0, /* COMMIT => nothing */
133689  55, /* END => ID */
133690  55, /* ROLLBACK => ID */
133691  55, /* SAVEPOINT => ID */
133692  55, /* RELEASE => ID */
133693  0, /* TO => nothing */
133694  0, /* TABLE => nothing */
133695  0, /* CREATE => nothing */
133696  55, /* IF => ID */
133697  0, /* NOT => nothing */
133698  0, /* EXISTS => nothing */
133699  55, /* TEMP => ID */
133700  0, /* LP => nothing */
133701  0, /* RP => nothing */
133702  0, /* AS => nothing */
133703  55, /* WITHOUT => ID */
133704  0, /* COMMA => nothing */
133705  0, /* OR => nothing */
133706  0, /* AND => nothing */
133707  0, /* IS => nothing */
133708  55, /* MATCH => ID */
133709  55, /* LIKE_KW => ID */
133710  0, /* BETWEEN => nothing */
133711  0, /* IN => nothing */
133712  0, /* ISNULL => nothing */
133713  0, /* NOTNULL => nothing */
133714  0, /* NE => nothing */
133715  0, /* EQ => nothing */
133716  0, /* GT => nothing */
133717  0, /* LE => nothing */
133718  0, /* LT => nothing */
133719  0, /* GE => nothing */
133720  0, /* ESCAPE => nothing */
133721  0, /* BITAND => nothing */
133722  0, /* BITOR => nothing */
133723  0, /* LSHIFT => nothing */
133724  0, /* RSHIFT => nothing */
133725  0, /* PLUS => nothing */
133726  0, /* MINUS => nothing */
133727  0, /* STAR => nothing */
133728  0, /* SLASH => nothing */
133729  0, /* REM => nothing */
133730  0, /* CONCAT => nothing */
133731  0, /* COLLATE => nothing */
133732  0, /* BITNOT => nothing */
133733  0, /* ID => nothing */
133734  0, /* INDEXED => nothing */
133735  55, /* ABORT => ID */
133736  55, /* ACTION => ID */
133737  55, /* AFTER => ID */
133738  55, /* ANALYZE => ID */
133739  55, /* ASC => ID */
133740  55, /* ATTACH => ID */
133741  55, /* BEFORE => ID */
133742  55, /* BY => ID */
133743  55, /* CASCADE => ID */
133744  55, /* CAST => ID */
133745  55, /* COLUMNKW => ID */
133746  55, /* CONFLICT => ID */
133747  55, /* DATABASE => ID */
133748  55, /* DESC => ID */
133749  55, /* DETACH => ID */
133750  55, /* EACH => ID */
133751  55, /* FAIL => ID */
133752  55, /* FOR => ID */
133753  55, /* IGNORE => ID */
133754  55, /* INITIALLY => ID */
133755  55, /* INSTEAD => ID */
133756  55, /* NO => ID */
133757  55, /* KEY => ID */
133758  55, /* OF => ID */
133759  55, /* OFFSET => ID */
133760  55, /* PRAGMA => ID */
133761  55, /* RAISE => ID */
133762  55, /* RECURSIVE => ID */
133763  55, /* REPLACE => ID */
133764  55, /* RESTRICT => ID */
133765  55, /* ROW => ID */
133766  55, /* TRIGGER => ID */
133767  55, /* VACUUM => ID */
133768  55, /* VIEW => ID */
133769  55, /* VIRTUAL => ID */
133770  55, /* WITH => ID */
133771  55, /* REINDEX => ID */
133772  55, /* RENAME => ID */
133773  55, /* CTIME_KW => ID */
133774 };
133775 #endif /* YYFALLBACK */
133776 
133777 /* The following structure represents a single element of the
133778 ** parser's stack. Information stored includes:
133779 **
133780 ** + The state number for the parser at this level of the stack.
133781 **
133782 ** + The value of the token stored at this level of the stack.
133783 ** (In other words, the "major" token.)
133784 **
133785 ** + The semantic value stored at this level of the stack. This is
133786 ** the information used by the action routines in the grammar.
133787 ** It is sometimes called the "minor" token.
133788 **
133789 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
133790 ** actually contains the reduce action for the second half of the
133791 ** SHIFTREDUCE.
133792 */
133794  YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
133795  YYCODETYPE major; /* The major token value. This is the code
133796  ** number for the token at this stack level */
133797  YYMINORTYPE minor; /* The user-supplied minor token value. This
133798  ** is the value of the token */
133799 };
133801 
133802 /* The state of the parser is completely contained in an instance of
133803 ** the following structure */
133804 struct yyParser {
133805  yyStackEntry *yytos; /* Pointer to top element of the stack */
133806 #ifdef YYTRACKMAXSTACKDEPTH
133807  int yyhwm; /* High-water mark of the stack */
133808 #endif
133809 #ifndef YYNOERRORRECOVERY
133810  int yyerrcnt; /* Shifts left before out of the error */
133811 #endif
133812  sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
133813 #if YYSTACKDEPTH<=0
133814  int yystksz; /* Current side of the stack */
133815  yyStackEntry *yystack; /* The parser's stack */
133816  yyStackEntry yystk0; /* First stack entry */
133817 #else
133818  yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
133819 #endif
133820 };
133821 typedef struct yyParser yyParser;
133822 
133823 #ifndef NDEBUG
133824 /* #include <stdio.h> */
133825 static FILE *yyTraceFILE = 0;
133826 static char *yyTracePrompt = 0;
133827 #endif /* NDEBUG */
133828 
133829 #ifndef NDEBUG
133830 /*
133831 ** Turn parser tracing on by giving a stream to which to write the trace
133832 ** and a prompt to preface each trace message. Tracing is turned off
133833 ** by making either argument NULL
133834 **
133835 ** Inputs:
133836 ** <ul>
133837 ** <li> A FILE* to which trace output should be written.
133838 ** If NULL, then tracing is turned off.
133839 ** <li> A prefix string written at the beginning of every
133840 ** line of trace output. If NULL, then tracing is
133841 ** turned off.
133842 ** </ul>
133843 **
133844 ** Outputs:
133845 ** None.
133846 */
133847 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
133848  yyTraceFILE = TraceFILE;
133849  yyTracePrompt = zTracePrompt;
133850  if( yyTraceFILE==0 ) yyTracePrompt = 0;
133851  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
133852 }
133853 #endif /* NDEBUG */
133854 
133855 #ifndef NDEBUG
133856 /* For tracing shifts, the names of all terminals and nonterminals
133857 ** are required. The following table supplies these names */
133858 static const char *const yyTokenName[] = {
133859  "$", "SEMI", "EXPLAIN", "QUERY",
133860  "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
133861  "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
133862  "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
133863  "TABLE", "CREATE", "IF", "NOT",
133864  "EXISTS", "TEMP", "LP", "RP",
133865  "AS", "WITHOUT", "COMMA", "OR",
133866  "AND", "IS", "MATCH", "LIKE_KW",
133867  "BETWEEN", "IN", "ISNULL", "NOTNULL",
133868  "NE", "EQ", "GT", "LE",
133869  "LT", "GE", "ESCAPE", "BITAND",
133870  "BITOR", "LSHIFT", "RSHIFT", "PLUS",
133871  "MINUS", "STAR", "SLASH", "REM",
133872  "CONCAT", "COLLATE", "BITNOT", "ID",
133873  "INDEXED", "ABORT", "ACTION", "AFTER",
133874  "ANALYZE", "ASC", "ATTACH", "BEFORE",
133875  "BY", "CASCADE", "CAST", "COLUMNKW",
133876  "CONFLICT", "DATABASE", "DESC", "DETACH",
133877  "EACH", "FAIL", "FOR", "IGNORE",
133878  "INITIALLY", "INSTEAD", "NO", "KEY",
133879  "OF", "OFFSET", "PRAGMA", "RAISE",
133880  "RECURSIVE", "REPLACE", "RESTRICT", "ROW",
133881  "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
133882  "WITH", "REINDEX", "RENAME", "CTIME_KW",
133883  "ANY", "STRING", "JOIN_KW", "CONSTRAINT",
133884  "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
133885  "CHECK", "REFERENCES", "AUTOINCR", "ON",
133886  "INSERT", "DELETE", "UPDATE", "SET",
133887  "DEFERRABLE", "FOREIGN", "DROP", "UNION",
133888  "ALL", "EXCEPT", "INTERSECT", "SELECT",
133889  "VALUES", "DISTINCT", "DOT", "FROM",
133890  "JOIN", "USING", "ORDER", "GROUP",
133891  "HAVING", "LIMIT", "WHERE", "INTO",
133892  "FLOAT", "BLOB", "INTEGER", "VARIABLE",
133893  "CASE", "WHEN", "THEN", "ELSE",
133894  "INDEX", "ALTER", "ADD", "error",
133895  "input", "cmdlist", "ecmd", "explain",
133896  "cmdx", "cmd", "transtype", "trans_opt",
133897  "nm", "savepoint_opt", "create_table", "create_table_args",
133898  "createkw", "temp", "ifnotexists", "dbnm",
133899  "columnlist", "conslist_opt", "table_options", "select",
133900  "columnname", "carglist", "typetoken", "typename",
133901  "signed", "plus_num", "minus_num", "ccons",
133902  "term", "expr", "onconf", "sortorder",
133903  "autoinc", "eidlist_opt", "refargs", "defer_subclause",
133904  "refarg", "refact", "init_deferred_pred_opt", "conslist",
133905  "tconscomma", "tcons", "sortlist", "eidlist",
133906  "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
133907  "ifexists", "fullname", "selectnowith", "oneselect",
133908  "with", "multiselect_op", "distinct", "selcollist",
133909  "from", "where_opt", "groupby_opt", "having_opt",
133910  "orderby_opt", "limit_opt", "values", "nexprlist",
133911  "exprlist", "sclp", "as", "seltablist",
133912  "stl_prefix", "joinop", "indexed_opt", "on_opt",
133913  "using_opt", "idlist", "setlist", "insert_cmd",
133914  "idlist_opt", "likeop", "between_op", "in_op",
133915  "paren_exprlist", "case_operand", "case_exprlist", "case_else",
133916  "uniqueflag", "collate", "nmnum", "trigger_decl",
133917  "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
133918  "when_clause", "trigger_cmd", "trnm", "tridxby",
133919  "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
133920  "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
133921  "lp", "anylist", "wqlist",
133922 };
133923 #endif /* NDEBUG */
133924 
133925 #ifndef NDEBUG
133926 /* For tracing reduce actions, the names of all rules are required.
133927 */
133928 static const char *const yyRuleName[] = {
133929  /* 0 */ "explain ::= EXPLAIN",
133930  /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
133931  /* 2 */ "cmdx ::= cmd",
133932  /* 3 */ "cmd ::= BEGIN transtype trans_opt",
133933  /* 4 */ "transtype ::=",
133934  /* 5 */ "transtype ::= DEFERRED",
133935  /* 6 */ "transtype ::= IMMEDIATE",
133936  /* 7 */ "transtype ::= EXCLUSIVE",
133937  /* 8 */ "cmd ::= COMMIT trans_opt",
133938  /* 9 */ "cmd ::= END trans_opt",
133939  /* 10 */ "cmd ::= ROLLBACK trans_opt",
133940  /* 11 */ "cmd ::= SAVEPOINT nm",
133941  /* 12 */ "cmd ::= RELEASE savepoint_opt nm",
133942  /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
133943  /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
133944  /* 15 */ "createkw ::= CREATE",
133945  /* 16 */ "ifnotexists ::=",
133946  /* 17 */ "ifnotexists ::= IF NOT EXISTS",
133947  /* 18 */ "temp ::= TEMP",
133948  /* 19 */ "temp ::=",
133949  /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
133950  /* 21 */ "create_table_args ::= AS select",
133951  /* 22 */ "table_options ::=",
133952  /* 23 */ "table_options ::= WITHOUT nm",
133953  /* 24 */ "columnname ::= nm typetoken",
133954  /* 25 */ "typetoken ::=",
133955  /* 26 */ "typetoken ::= typename LP signed RP",
133956  /* 27 */ "typetoken ::= typename LP signed COMMA signed RP",
133957  /* 28 */ "typename ::= typename ID|STRING",
133958  /* 29 */ "ccons ::= CONSTRAINT nm",
133959  /* 30 */ "ccons ::= DEFAULT term",
133960  /* 31 */ "ccons ::= DEFAULT LP expr RP",
133961  /* 32 */ "ccons ::= DEFAULT PLUS term",
133962  /* 33 */ "ccons ::= DEFAULT MINUS term",
133963  /* 34 */ "ccons ::= DEFAULT ID|INDEXED",
133964  /* 35 */ "ccons ::= NOT NULL onconf",
133965  /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
133966  /* 37 */ "ccons ::= UNIQUE onconf",
133967  /* 38 */ "ccons ::= CHECK LP expr RP",
133968  /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
133969  /* 40 */ "ccons ::= defer_subclause",
133970  /* 41 */ "ccons ::= COLLATE ID|STRING",
133971  /* 42 */ "autoinc ::=",
133972  /* 43 */ "autoinc ::= AUTOINCR",
133973  /* 44 */ "refargs ::=",
133974  /* 45 */ "refargs ::= refargs refarg",
133975  /* 46 */ "refarg ::= MATCH nm",
133976  /* 47 */ "refarg ::= ON INSERT refact",
133977  /* 48 */ "refarg ::= ON DELETE refact",
133978  /* 49 */ "refarg ::= ON UPDATE refact",
133979  /* 50 */ "refact ::= SET NULL",
133980  /* 51 */ "refact ::= SET DEFAULT",
133981  /* 52 */ "refact ::= CASCADE",
133982  /* 53 */ "refact ::= RESTRICT",
133983  /* 54 */ "refact ::= NO ACTION",
133984  /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
133985  /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
133986  /* 57 */ "init_deferred_pred_opt ::=",
133987  /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
133988  /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
133989  /* 60 */ "conslist_opt ::=",
133990  /* 61 */ "tconscomma ::= COMMA",
133991  /* 62 */ "tcons ::= CONSTRAINT nm",
133992  /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
133993  /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
133994  /* 65 */ "tcons ::= CHECK LP expr RP onconf",
133995  /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
133996  /* 67 */ "defer_subclause_opt ::=",
133997  /* 68 */ "onconf ::=",
133998  /* 69 */ "onconf ::= ON CONFLICT resolvetype",
133999  /* 70 */ "orconf ::=",
134000  /* 71 */ "orconf ::= OR resolvetype",
134001  /* 72 */ "resolvetype ::= IGNORE",
134002  /* 73 */ "resolvetype ::= REPLACE",
134003  /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
134004  /* 75 */ "ifexists ::= IF EXISTS",
134005  /* 76 */ "ifexists ::=",
134006  /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
134007  /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
134008  /* 79 */ "cmd ::= select",
134009  /* 80 */ "select ::= with selectnowith",
134010  /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
134011  /* 82 */ "multiselect_op ::= UNION",
134012  /* 83 */ "multiselect_op ::= UNION ALL",
134013  /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT",
134014  /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
134015  /* 86 */ "values ::= VALUES LP nexprlist RP",
134016  /* 87 */ "values ::= values COMMA LP exprlist RP",
134017  /* 88 */ "distinct ::= DISTINCT",
134018  /* 89 */ "distinct ::= ALL",
134019  /* 90 */ "distinct ::=",
134020  /* 91 */ "sclp ::=",
134021  /* 92 */ "selcollist ::= sclp expr as",
134022  /* 93 */ "selcollist ::= sclp STAR",
134023  /* 94 */ "selcollist ::= sclp nm DOT STAR",
134024  /* 95 */ "as ::= AS nm",
134025  /* 96 */ "as ::=",
134026  /* 97 */ "from ::=",
134027  /* 98 */ "from ::= FROM seltablist",
134028  /* 99 */ "stl_prefix ::= seltablist joinop",
134029  /* 100 */ "stl_prefix ::=",
134030  /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
134031  /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
134032  /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
134033  /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
134034  /* 105 */ "dbnm ::=",
134035  /* 106 */ "dbnm ::= DOT nm",
134036  /* 107 */ "fullname ::= nm dbnm",
134037  /* 108 */ "joinop ::= COMMA|JOIN",
134038  /* 109 */ "joinop ::= JOIN_KW JOIN",
134039  /* 110 */ "joinop ::= JOIN_KW nm JOIN",
134040  /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
134041  /* 112 */ "on_opt ::= ON expr",
134042  /* 113 */ "on_opt ::=",
134043  /* 114 */ "indexed_opt ::=",
134044  /* 115 */ "indexed_opt ::= INDEXED BY nm",
134045  /* 116 */ "indexed_opt ::= NOT INDEXED",
134046  /* 117 */ "using_opt ::= USING LP idlist RP",
134047  /* 118 */ "using_opt ::=",
134048  /* 119 */ "orderby_opt ::=",
134049  /* 120 */ "orderby_opt ::= ORDER BY sortlist",
134050  /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
134051  /* 122 */ "sortlist ::= expr sortorder",
134052  /* 123 */ "sortorder ::= ASC",
134053  /* 124 */ "sortorder ::= DESC",
134054  /* 125 */ "sortorder ::=",
134055  /* 126 */ "groupby_opt ::=",
134056  /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
134057  /* 128 */ "having_opt ::=",
134058  /* 129 */ "having_opt ::= HAVING expr",
134059  /* 130 */ "limit_opt ::=",
134060  /* 131 */ "limit_opt ::= LIMIT expr",
134061  /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
134062  /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
134063  /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
134064  /* 135 */ "where_opt ::=",
134065  /* 136 */ "where_opt ::= WHERE expr",
134066  /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
134067  /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
134068  /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
134069  /* 140 */ "setlist ::= nm EQ expr",
134070  /* 141 */ "setlist ::= LP idlist RP EQ expr",
134071  /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
134072  /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
134073  /* 144 */ "insert_cmd ::= INSERT orconf",
134074  /* 145 */ "insert_cmd ::= REPLACE",
134075  /* 146 */ "idlist_opt ::=",
134076  /* 147 */ "idlist_opt ::= LP idlist RP",
134077  /* 148 */ "idlist ::= idlist COMMA nm",
134078  /* 149 */ "idlist ::= nm",
134079  /* 150 */ "expr ::= LP expr RP",
134080  /* 151 */ "term ::= NULL",
134081  /* 152 */ "expr ::= ID|INDEXED",
134082  /* 153 */ "expr ::= JOIN_KW",
134083  /* 154 */ "expr ::= nm DOT nm",
134084  /* 155 */ "expr ::= nm DOT nm DOT nm",
134085  /* 156 */ "term ::= FLOAT|BLOB",
134086  /* 157 */ "term ::= STRING",
134087  /* 158 */ "term ::= INTEGER",
134088  /* 159 */ "expr ::= VARIABLE",
134089  /* 160 */ "expr ::= expr COLLATE ID|STRING",
134090  /* 161 */ "expr ::= CAST LP expr AS typetoken RP",
134091  /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
134092  /* 163 */ "expr ::= ID|INDEXED LP STAR RP",
134093  /* 164 */ "term ::= CTIME_KW",
134094  /* 165 */ "expr ::= LP nexprlist COMMA expr RP",
134095  /* 166 */ "expr ::= expr AND expr",
134096  /* 167 */ "expr ::= expr OR expr",
134097  /* 168 */ "expr ::= expr LT|GT|GE|LE expr",
134098  /* 169 */ "expr ::= expr EQ|NE expr",
134099  /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
134100  /* 171 */ "expr ::= expr PLUS|MINUS expr",
134101  /* 172 */ "expr ::= expr STAR|SLASH|REM expr",
134102  /* 173 */ "expr ::= expr CONCAT expr",
134103  /* 174 */ "likeop ::= LIKE_KW|MATCH",
134104  /* 175 */ "likeop ::= NOT LIKE_KW|MATCH",
134105  /* 176 */ "expr ::= expr likeop expr",
134106  /* 177 */ "expr ::= expr likeop expr ESCAPE expr",
134107  /* 178 */ "expr ::= expr ISNULL|NOTNULL",
134108  /* 179 */ "expr ::= expr NOT NULL",
134109  /* 180 */ "expr ::= expr IS expr",
134110  /* 181 */ "expr ::= expr IS NOT expr",
134111  /* 182 */ "expr ::= NOT expr",
134112  /* 183 */ "expr ::= BITNOT expr",
134113  /* 184 */ "expr ::= MINUS expr",
134114  /* 185 */ "expr ::= PLUS expr",
134115  /* 186 */ "between_op ::= BETWEEN",
134116  /* 187 */ "between_op ::= NOT BETWEEN",
134117  /* 188 */ "expr ::= expr between_op expr AND expr",
134118  /* 189 */ "in_op ::= IN",
134119  /* 190 */ "in_op ::= NOT IN",
134120  /* 191 */ "expr ::= expr in_op LP exprlist RP",
134121  /* 192 */ "expr ::= LP select RP",
134122  /* 193 */ "expr ::= expr in_op LP select RP",
134123  /* 194 */ "expr ::= expr in_op nm dbnm paren_exprlist",
134124  /* 195 */ "expr ::= EXISTS LP select RP",
134125  /* 196 */ "expr ::= CASE case_operand case_exprlist case_else END",
134126  /* 197 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
134127  /* 198 */ "case_exprlist ::= WHEN expr THEN expr",
134128  /* 199 */ "case_else ::= ELSE expr",
134129  /* 200 */ "case_else ::=",
134130  /* 201 */ "case_operand ::= expr",
134131  /* 202 */ "case_operand ::=",
134132  /* 203 */ "exprlist ::=",
134133  /* 204 */ "nexprlist ::= nexprlist COMMA expr",
134134  /* 205 */ "nexprlist ::= expr",
134135  /* 206 */ "paren_exprlist ::=",
134136  /* 207 */ "paren_exprlist ::= LP exprlist RP",
134137  /* 208 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
134138  /* 209 */ "uniqueflag ::= UNIQUE",
134139  /* 210 */ "uniqueflag ::=",
134140  /* 211 */ "eidlist_opt ::=",
134141  /* 212 */ "eidlist_opt ::= LP eidlist RP",
134142  /* 213 */ "eidlist ::= eidlist COMMA nm collate sortorder",
134143  /* 214 */ "eidlist ::= nm collate sortorder",
134144  /* 215 */ "collate ::=",
134145  /* 216 */ "collate ::= COLLATE ID|STRING",
134146  /* 217 */ "cmd ::= DROP INDEX ifexists fullname",
134147  /* 218 */ "cmd ::= VACUUM",
134148  /* 219 */ "cmd ::= VACUUM nm",
134149  /* 220 */ "cmd ::= PRAGMA nm dbnm",
134150  /* 221 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
134151  /* 222 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
134152  /* 223 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
134153  /* 224 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
134154  /* 225 */ "plus_num ::= PLUS INTEGER|FLOAT",
134155  /* 226 */ "minus_num ::= MINUS INTEGER|FLOAT",
134156  /* 227 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
134157  /* 228 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
134158  /* 229 */ "trigger_time ::= BEFORE",
134159  /* 230 */ "trigger_time ::= AFTER",
134160  /* 231 */ "trigger_time ::= INSTEAD OF",
134161  /* 232 */ "trigger_time ::=",
134162  /* 233 */ "trigger_event ::= DELETE|INSERT",
134163  /* 234 */ "trigger_event ::= UPDATE",
134164  /* 235 */ "trigger_event ::= UPDATE OF idlist",
134165  /* 236 */ "when_clause ::=",
134166  /* 237 */ "when_clause ::= WHEN expr",
134167  /* 238 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
134168  /* 239 */ "trigger_cmd_list ::= trigger_cmd SEMI",
134169  /* 240 */ "trnm ::= nm DOT nm",
134170  /* 241 */ "tridxby ::= INDEXED BY nm",
134171  /* 242 */ "tridxby ::= NOT INDEXED",
134172  /* 243 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
134173  /* 244 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
134174  /* 245 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
134175  /* 246 */ "trigger_cmd ::= select",
134176  /* 247 */ "expr ::= RAISE LP IGNORE RP",
134177  /* 248 */ "expr ::= RAISE LP raisetype COMMA nm RP",
134178  /* 249 */ "raisetype ::= ROLLBACK",
134179  /* 250 */ "raisetype ::= ABORT",
134180  /* 251 */ "raisetype ::= FAIL",
134181  /* 252 */ "cmd ::= DROP TRIGGER ifexists fullname",
134182  /* 253 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
134183  /* 254 */ "cmd ::= DETACH database_kw_opt expr",
134184  /* 255 */ "key_opt ::=",
134185  /* 256 */ "key_opt ::= KEY expr",
134186  /* 257 */ "cmd ::= REINDEX",
134187  /* 258 */ "cmd ::= REINDEX nm dbnm",
134188  /* 259 */ "cmd ::= ANALYZE",
134189  /* 260 */ "cmd ::= ANALYZE nm dbnm",
134190  /* 261 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
134191  /* 262 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
134192  /* 263 */ "add_column_fullname ::= fullname",
134193  /* 264 */ "cmd ::= create_vtab",
134194  /* 265 */ "cmd ::= create_vtab LP vtabarglist RP",
134195  /* 266 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
134196  /* 267 */ "vtabarg ::=",
134197  /* 268 */ "vtabargtoken ::= ANY",
134198  /* 269 */ "vtabargtoken ::= lp anylist RP",
134199  /* 270 */ "lp ::= LP",
134200  /* 271 */ "with ::=",
134201  /* 272 */ "with ::= WITH wqlist",
134202  /* 273 */ "with ::= WITH RECURSIVE wqlist",
134203  /* 274 */ "wqlist ::= nm eidlist_opt AS LP select RP",
134204  /* 275 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
134205  /* 276 */ "input ::= cmdlist",
134206  /* 277 */ "cmdlist ::= cmdlist ecmd",
134207  /* 278 */ "cmdlist ::= ecmd",
134208  /* 279 */ "ecmd ::= SEMI",
134209  /* 280 */ "ecmd ::= explain cmdx SEMI",
134210  /* 281 */ "explain ::=",
134211  /* 282 */ "trans_opt ::=",
134212  /* 283 */ "trans_opt ::= TRANSACTION",
134213  /* 284 */ "trans_opt ::= TRANSACTION nm",
134214  /* 285 */ "savepoint_opt ::= SAVEPOINT",
134215  /* 286 */ "savepoint_opt ::=",
134216  /* 287 */ "cmd ::= create_table create_table_args",
134217  /* 288 */ "columnlist ::= columnlist COMMA columnname carglist",
134218  /* 289 */ "columnlist ::= columnname carglist",
134219  /* 290 */ "nm ::= ID|INDEXED",
134220  /* 291 */ "nm ::= STRING",
134221  /* 292 */ "nm ::= JOIN_KW",
134222  /* 293 */ "typetoken ::= typename",
134223  /* 294 */ "typename ::= ID|STRING",
134224  /* 295 */ "signed ::= plus_num",
134225  /* 296 */ "signed ::= minus_num",
134226  /* 297 */ "carglist ::= carglist ccons",
134227  /* 298 */ "carglist ::=",
134228  /* 299 */ "ccons ::= NULL onconf",
134229  /* 300 */ "conslist_opt ::= COMMA conslist",
134230  /* 301 */ "conslist ::= conslist tconscomma tcons",
134231  /* 302 */ "conslist ::= tcons",
134232  /* 303 */ "tconscomma ::=",
134233  /* 304 */ "defer_subclause_opt ::= defer_subclause",
134234  /* 305 */ "resolvetype ::= raisetype",
134235  /* 306 */ "selectnowith ::= oneselect",
134236  /* 307 */ "oneselect ::= values",
134237  /* 308 */ "sclp ::= selcollist COMMA",
134238  /* 309 */ "as ::= ID|STRING",
134239  /* 310 */ "expr ::= term",
134240  /* 311 */ "exprlist ::= nexprlist",
134241  /* 312 */ "nmnum ::= plus_num",
134242  /* 313 */ "nmnum ::= nm",
134243  /* 314 */ "nmnum ::= ON",
134244  /* 315 */ "nmnum ::= DELETE",
134245  /* 316 */ "nmnum ::= DEFAULT",
134246  /* 317 */ "plus_num ::= INTEGER|FLOAT",
134247  /* 318 */ "foreach_clause ::=",
134248  /* 319 */ "foreach_clause ::= FOR EACH ROW",
134249  /* 320 */ "trnm ::= nm",
134250  /* 321 */ "tridxby ::=",
134251  /* 322 */ "database_kw_opt ::= DATABASE",
134252  /* 323 */ "database_kw_opt ::=",
134253  /* 324 */ "kwcolumn_opt ::=",
134254  /* 325 */ "kwcolumn_opt ::= COLUMNKW",
134255  /* 326 */ "vtabarglist ::= vtabarg",
134256  /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
134257  /* 328 */ "vtabarg ::= vtabarg vtabargtoken",
134258  /* 329 */ "anylist ::=",
134259  /* 330 */ "anylist ::= anylist LP anylist RP",
134260  /* 331 */ "anylist ::= anylist ANY",
134261 };
134262 #endif /* NDEBUG */
134263 
134264 
134265 #if YYSTACKDEPTH<=0
134266 /*
134267 ** Try to increase the size of the parser stack. Return the number
134268 ** of errors. Return 0 on success.
134269 */
134270 static int yyGrowStack(yyParser *p){
134271  int newSize;
134272  int idx;
134273  yyStackEntry *pNew;
134274 
134275  newSize = p->yystksz*2 + 100;
134276  idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
134277  if( p->yystack==&p->yystk0 ){
134278  pNew = malloc(newSize*sizeof(pNew[0]));
134279  if( pNew ) pNew[0] = p->yystk0;
134280  }else{
134281  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
134282  }
134283  if( pNew ){
134284  p->yystack = pNew;
134285  p->yytos = &p->yystack[idx];
134286 #ifndef NDEBUG
134287  if( yyTraceFILE ){
134288  fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
134289  yyTracePrompt, p->yystksz, newSize);
134290  }
134291 #endif
134292  p->yystksz = newSize;
134293  }
134294  return pNew==0;
134295 }
134296 #endif
134297 
134298 /* Datatype of the argument to the memory allocated passed as the
134299 ** second argument to sqlite3ParserAlloc() below. This can be changed by
134300 ** putting an appropriate #define in the %include section of the input
134301 ** grammar.
134302 */
134303 #ifndef YYMALLOCARGTYPE
134304 # define YYMALLOCARGTYPE size_t
134305 #endif
134306 
134307 /*
134308 ** This function allocates a new parser.
134309 ** The only argument is a pointer to a function which works like
134310 ** malloc.
134311 **
134312 ** Inputs:
134313 ** A pointer to the function used to allocate memory.
134314 **
134315 ** Outputs:
134316 ** A pointer to a parser. This pointer is used in subsequent calls
134317 ** to sqlite3Parser and sqlite3ParserFree.
134318 */
134320  yyParser *pParser;
134321  pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
134322  if( pParser ){
134323 #ifdef YYTRACKMAXSTACKDEPTH
134324  pParser->yyhwm = 0;
134325 #endif
134326 #if YYSTACKDEPTH<=0
134327  pParser->yytos = NULL;
134328  pParser->yystack = NULL;
134329  pParser->yystksz = 0;
134330  if( yyGrowStack(pParser) ){
134331  pParser->yystack = &pParser->yystk0;
134332  pParser->yystksz = 1;
134333  }
134334 #endif
134335 #ifndef YYNOERRORRECOVERY
134336  pParser->yyerrcnt = -1;
134337 #endif
134338  pParser->yytos = pParser->yystack;
134339  pParser->yystack[0].stateno = 0;
134340  pParser->yystack[0].major = 0;
134341  }
134342  return pParser;
134343 }
134344 
134345 /* The following function deletes the "minor type" or semantic value
134346 ** associated with a symbol. The symbol can be either a terminal
134347 ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
134348 ** a pointer to the value to be deleted. The code used to do the
134349 ** deletions is derived from the %destructor and/or %token_destructor
134350 ** directives of the input grammar.
134351 */
134352 static void yy_destructor(
134353  yyParser *yypParser, /* The parser */
134354  YYCODETYPE yymajor, /* Type code for object to destroy */
134355  YYMINORTYPE *yypminor /* The object to be destroyed */
134356 ){
134358  switch( yymajor ){
134359  /* Here is inserted the actions which take place when a
134360  ** terminal or non-terminal is destroyed. This can happen
134361  ** when the symbol is popped from the stack during a
134362  ** reduce or during error processing or when a parser is
134363  ** being destroyed before it is finished parsing.
134364  **
134365  ** Note: during a reduce, the only symbols destroyed are those
134366  ** which appear on the RHS of the rule, but which are *not* used
134367  ** inside the C code.
134368  */
134369 /********* Begin destructor definitions ***************************************/
134370  case 163: /* select */
134371  case 194: /* selectnowith */
134372  case 195: /* oneselect */
134373  case 206: /* values */
134374 {
134375 sqlite3SelectDelete(pParse->db, (yypminor->yy243));
134376 }
134377  break;
134378  case 172: /* term */
134379  case 173: /* expr */
134380 {
134381 sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
134382 }
134383  break;
134384  case 177: /* eidlist_opt */
134385  case 186: /* sortlist */
134386  case 187: /* eidlist */
134387  case 199: /* selcollist */
134388  case 202: /* groupby_opt */
134389  case 204: /* orderby_opt */
134390  case 207: /* nexprlist */
134391  case 208: /* exprlist */
134392  case 209: /* sclp */
134393  case 218: /* setlist */
134394  case 224: /* paren_exprlist */
134395  case 226: /* case_exprlist */
134396 {
134397 sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
134398 }
134399  break;
134400  case 193: /* fullname */
134401  case 200: /* from */
134402  case 211: /* seltablist */
134403  case 212: /* stl_prefix */
134404 {
134405 sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
134406 }
134407  break;
134408  case 196: /* with */
134409  case 250: /* wqlist */
134410 {
134411 sqlite3WithDelete(pParse->db, (yypminor->yy285));
134412 }
134413  break;
134414  case 201: /* where_opt */
134415  case 203: /* having_opt */
134416  case 215: /* on_opt */
134417  case 225: /* case_operand */
134418  case 227: /* case_else */
134419  case 236: /* when_clause */
134420  case 241: /* key_opt */
134421 {
134422 sqlite3ExprDelete(pParse->db, (yypminor->yy72));
134423 }
134424  break;
134425  case 216: /* using_opt */
134426  case 217: /* idlist */
134427  case 220: /* idlist_opt */
134428 {
134429 sqlite3IdListDelete(pParse->db, (yypminor->yy254));
134430 }
134431  break;
134432  case 232: /* trigger_cmd_list */
134433  case 237: /* trigger_cmd */
134434 {
134435 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
134436 }
134437  break;
134438  case 234: /* trigger_event */
134439 {
134440 sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
134441 }
134442  break;
134443 /********* End destructor definitions *****************************************/
134444  default: break; /* If no destructor action specified: do nothing */
134445  }
134446 }
134447 
134448 /*
134449 ** Pop the parser's stack once.
134450 **
134451 ** If there is a destructor routine associated with the token which
134452 ** is popped from the stack, then call it.
134453 */
134454 static void yy_pop_parser_stack(yyParser *pParser){
134455  yyStackEntry *yytos;
134456  assert( pParser->yytos!=0 );
134457  assert( pParser->yytos > pParser->yystack );
134458  yytos = pParser->yytos--;
134459 #ifndef NDEBUG
134460  if( yyTraceFILE ){
134461  fprintf(yyTraceFILE,"%sPopping %s\n",
134462  yyTracePrompt,
134463  yyTokenName[yytos->major]);
134464  }
134465 #endif
134466  yy_destructor(pParser, yytos->major, &yytos->minor);
134467 }
134468 
134469 /*
134470 ** Deallocate and destroy a parser. Destructors are called for
134471 ** all stack elements before shutting the parser down.
134472 **
134473 ** If the YYPARSEFREENEVERNULL macro exists (for example because it
134474 ** is defined in a %include section of the input grammar) then it is
134475 ** assumed that the input pointer is never NULL.
134476 */
134478  void *p, /* The parser to be deleted */
134479  void (*freeProc)(void*) /* Function used to reclaim memory */
134480 ){
134481  yyParser *pParser = (yyParser*)p;
134482 #ifndef YYPARSEFREENEVERNULL
134483  if( pParser==0 ) return;
134484 #endif
134485  while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
134486 #if YYSTACKDEPTH<=0
134487  if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
134488 #endif
134489  (*freeProc)((void*)pParser);
134490 }
134491 
134492 /*
134493 ** Return the peak depth of the stack for a parser.
134494 */
134495 #ifdef YYTRACKMAXSTACKDEPTH
134496 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
134497  yyParser *pParser = (yyParser*)p;
134498  return pParser->yyhwm;
134499 }
134500 #endif
134501 
134502 /*
134503 ** Find the appropriate action for a parser given the terminal
134504 ** look-ahead token iLookAhead.
134505 */
134506 static unsigned int yy_find_shift_action(
134507  yyParser *pParser, /* The parser */
134508  YYCODETYPE iLookAhead /* The look-ahead token */
134509 ){
134510  int i;
134511  int stateno = pParser->yytos->stateno;
134512 
134513  if( stateno>=YY_MIN_REDUCE ) return stateno;
134514  assert( stateno <= YY_SHIFT_COUNT );
134515  do{
134516  i = yy_shift_ofst[stateno];
134517  assert( iLookAhead!=YYNOCODE );
134518  i += iLookAhead;
134519  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
134520 #ifdef YYFALLBACK
134521  YYCODETYPE iFallback; /* Fallback token */
134522  if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
134523  && (iFallback = yyFallback[iLookAhead])!=0 ){
134524 #ifndef NDEBUG
134525  if( yyTraceFILE ){
134526  fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
134527  yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
134528  }
134529 #endif
134530  assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
134531  iLookAhead = iFallback;
134532  continue;
134533  }
134534 #endif
134535 #ifdef YYWILDCARD
134536  {
134537  int j = i - iLookAhead + YYWILDCARD;
134538  if(
134539 #if YY_SHIFT_MIN+YYWILDCARD<0
134540  j>=0 &&
134541 #endif
134542 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
134543  j<YY_ACTTAB_COUNT &&
134544 #endif
134545  yy_lookahead[j]==YYWILDCARD && iLookAhead>0
134546  ){
134547 #ifndef NDEBUG
134548  if( yyTraceFILE ){
134549  fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
134550  yyTracePrompt, yyTokenName[iLookAhead],
134551  yyTokenName[YYWILDCARD]);
134552  }
134553 #endif /* NDEBUG */
134554  return yy_action[j];
134555  }
134556  }
134557 #endif /* YYWILDCARD */
134558  return yy_default[stateno];
134559  }else{
134560  return yy_action[i];
134561  }
134562  }while(1);
134563 }
134564 
134565 /*
134566 ** Find the appropriate action for a parser given the non-terminal
134567 ** look-ahead token iLookAhead.
134568 */
134570  int stateno, /* Current state number */
134571  YYCODETYPE iLookAhead /* The look-ahead token */
134572 ){
134573  int i;
134574 #ifdef YYERRORSYMBOL
134575  if( stateno>YY_REDUCE_COUNT ){
134576  return yy_default[stateno];
134577  }
134578 #else
134579  assert( stateno<=YY_REDUCE_COUNT );
134580 #endif
134581  i = yy_reduce_ofst[stateno];
134582  assert( i!=YY_REDUCE_USE_DFLT );
134583  assert( iLookAhead!=YYNOCODE );
134584  i += iLookAhead;
134585 #ifdef YYERRORSYMBOL
134586  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
134587  return yy_default[stateno];
134588  }
134589 #else
134590  assert( i>=0 && i<YY_ACTTAB_COUNT );
134591  assert( yy_lookahead[i]==iLookAhead );
134592 #endif
134593  return yy_action[i];
134594 }
134595 
134596 /*
134597 ** The following routine is called if the stack overflows.
134598 */
134599 static void yyStackOverflow(yyParser *yypParser){
134601  yypParser->yytos--;
134602 #ifndef NDEBUG
134603  if( yyTraceFILE ){
134604  fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
134605  }
134606 #endif
134607  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
134608  /* Here code is inserted which will execute if the parser
134609  ** stack every overflows */
134610 /******** Begin %stack_overflow code ******************************************/
134611 
134612  sqlite3ErrorMsg(pParse, "parser stack overflow");
134613 /******** End %stack_overflow code ********************************************/
134614  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
134615 }
134616 
134617 /*
134618 ** Print tracing information for a SHIFT action
134619 */
134620 #ifndef NDEBUG
134621 static void yyTraceShift(yyParser *yypParser, int yyNewState){
134622  if( yyTraceFILE ){
134623  if( yyNewState<YYNSTATE ){
134624  fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
134625  yyTracePrompt,yyTokenName[yypParser->yytos->major],
134626  yyNewState);
134627  }else{
134628  fprintf(yyTraceFILE,"%sShift '%s'\n",
134629  yyTracePrompt,yyTokenName[yypParser->yytos->major]);
134630  }
134631  }
134632 }
134633 #else
134634 # define yyTraceShift(X,Y)
134635 #endif
134636 
134637 /*
134638 ** Perform a shift action.
134639 */
134640 static void yy_shift(
134641  yyParser *yypParser, /* The parser to be shifted */
134642  int yyNewState, /* The new state to shift in */
134643  int yyMajor, /* The major token to shift in */
134644  sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
134645 ){
134646  yyStackEntry *yytos;
134647  yypParser->yytos++;
134648 #ifdef YYTRACKMAXSTACKDEPTH
134649  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
134650  yypParser->yyhwm++;
134651  assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
134652  }
134653 #endif
134654 #if YYSTACKDEPTH>0
134655  if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
134656  yyStackOverflow(yypParser);
134657  return;
134658  }
134659 #else
134660  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
134661  if( yyGrowStack(yypParser) ){
134662  yyStackOverflow(yypParser);
134663  return;
134664  }
134665  }
134666 #endif
134667  if( yyNewState > YY_MAX_SHIFT ){
134668  yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
134669  }
134670  yytos = yypParser->yytos;
134671  yytos->stateno = (YYACTIONTYPE)yyNewState;
134672  yytos->major = (YYCODETYPE)yyMajor;
134673  yytos->minor.yy0 = yyMinor;
134674  yyTraceShift(yypParser, yyNewState);
134675 }
134676 
134677 /* The following table contains information about every rule that
134678 ** is used during the reduce.
134679 */
134680 static const struct {
134681  YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
134682  unsigned char nrhs; /* Number of right-hand side symbols in the rule */
134683 } yyRuleInfo[] = {
134684  { 147, 1 },
134685  { 147, 3 },
134686  { 148, 1 },
134687  { 149, 3 },
134688  { 150, 0 },
134689  { 150, 1 },
134690  { 150, 1 },
134691  { 150, 1 },
134692  { 149, 2 },
134693  { 149, 2 },
134694  { 149, 2 },
134695  { 149, 2 },
134696  { 149, 3 },
134697  { 149, 5 },
134698  { 154, 6 },
134699  { 156, 1 },
134700  { 158, 0 },
134701  { 158, 3 },
134702  { 157, 1 },
134703  { 157, 0 },
134704  { 155, 5 },
134705  { 155, 2 },
134706  { 162, 0 },
134707  { 162, 2 },
134708  { 164, 2 },
134709  { 166, 0 },
134710  { 166, 4 },
134711  { 166, 6 },
134712  { 167, 2 },
134713  { 171, 2 },
134714  { 171, 2 },
134715  { 171, 4 },
134716  { 171, 3 },
134717  { 171, 3 },
134718  { 171, 2 },
134719  { 171, 3 },
134720  { 171, 5 },
134721  { 171, 2 },
134722  { 171, 4 },
134723  { 171, 4 },
134724  { 171, 1 },
134725  { 171, 2 },
134726  { 176, 0 },
134727  { 176, 1 },
134728  { 178, 0 },
134729  { 178, 2 },
134730  { 180, 2 },
134731  { 180, 3 },
134732  { 180, 3 },
134733  { 180, 3 },
134734  { 181, 2 },
134735  { 181, 2 },
134736  { 181, 1 },
134737  { 181, 1 },
134738  { 181, 2 },
134739  { 179, 3 },
134740  { 179, 2 },
134741  { 182, 0 },
134742  { 182, 2 },
134743  { 182, 2 },
134744  { 161, 0 },
134745  { 184, 1 },
134746  { 185, 2 },
134747  { 185, 7 },
134748  { 185, 5 },
134749  { 185, 5 },
134750  { 185, 10 },
134751  { 188, 0 },
134752  { 174, 0 },
134753  { 174, 3 },
134754  { 189, 0 },
134755  { 189, 2 },
134756  { 190, 1 },
134757  { 190, 1 },
134758  { 149, 4 },
134759  { 192, 2 },
134760  { 192, 0 },
134761  { 149, 9 },
134762  { 149, 4 },
134763  { 149, 1 },
134764  { 163, 2 },
134765  { 194, 3 },
134766  { 197, 1 },
134767  { 197, 2 },
134768  { 197, 1 },
134769  { 195, 9 },
134770  { 206, 4 },
134771  { 206, 5 },
134772  { 198, 1 },
134773  { 198, 1 },
134774  { 198, 0 },
134775  { 209, 0 },
134776  { 199, 3 },
134777  { 199, 2 },
134778  { 199, 4 },
134779  { 210, 2 },
134780  { 210, 0 },
134781  { 200, 0 },
134782  { 200, 2 },
134783  { 212, 2 },
134784  { 212, 0 },
134785  { 211, 7 },
134786  { 211, 9 },
134787  { 211, 7 },
134788  { 211, 7 },
134789  { 159, 0 },
134790  { 159, 2 },
134791  { 193, 2 },
134792  { 213, 1 },
134793  { 213, 2 },
134794  { 213, 3 },
134795  { 213, 4 },
134796  { 215, 2 },
134797  { 215, 0 },
134798  { 214, 0 },
134799  { 214, 3 },
134800  { 214, 2 },
134801  { 216, 4 },
134802  { 216, 0 },
134803  { 204, 0 },
134804  { 204, 3 },
134805  { 186, 4 },
134806  { 186, 2 },
134807  { 175, 1 },
134808  { 175, 1 },
134809  { 175, 0 },
134810  { 202, 0 },
134811  { 202, 3 },
134812  { 203, 0 },
134813  { 203, 2 },
134814  { 205, 0 },
134815  { 205, 2 },
134816  { 205, 4 },
134817  { 205, 4 },
134818  { 149, 6 },
134819  { 201, 0 },
134820  { 201, 2 },
134821  { 149, 8 },
134822  { 218, 5 },
134823  { 218, 7 },
134824  { 218, 3 },
134825  { 218, 5 },
134826  { 149, 6 },
134827  { 149, 7 },
134828  { 219, 2 },
134829  { 219, 1 },
134830  { 220, 0 },
134831  { 220, 3 },
134832  { 217, 3 },
134833  { 217, 1 },
134834  { 173, 3 },
134835  { 172, 1 },
134836  { 173, 1 },
134837  { 173, 1 },
134838  { 173, 3 },
134839  { 173, 5 },
134840  { 172, 1 },
134841  { 172, 1 },
134842  { 172, 1 },
134843  { 173, 1 },
134844  { 173, 3 },
134845  { 173, 6 },
134846  { 173, 5 },
134847  { 173, 4 },
134848  { 172, 1 },
134849  { 173, 5 },
134850  { 173, 3 },
134851  { 173, 3 },
134852  { 173, 3 },
134853  { 173, 3 },
134854  { 173, 3 },
134855  { 173, 3 },
134856  { 173, 3 },
134857  { 173, 3 },
134858  { 221, 1 },
134859  { 221, 2 },
134860  { 173, 3 },
134861  { 173, 5 },
134862  { 173, 2 },
134863  { 173, 3 },
134864  { 173, 3 },
134865  { 173, 4 },
134866  { 173, 2 },
134867  { 173, 2 },
134868  { 173, 2 },
134869  { 173, 2 },
134870  { 222, 1 },
134871  { 222, 2 },
134872  { 173, 5 },
134873  { 223, 1 },
134874  { 223, 2 },
134875  { 173, 5 },
134876  { 173, 3 },
134877  { 173, 5 },
134878  { 173, 5 },
134879  { 173, 4 },
134880  { 173, 5 },
134881  { 226, 5 },
134882  { 226, 4 },
134883  { 227, 2 },
134884  { 227, 0 },
134885  { 225, 1 },
134886  { 225, 0 },
134887  { 208, 0 },
134888  { 207, 3 },
134889  { 207, 1 },
134890  { 224, 0 },
134891  { 224, 3 },
134892  { 149, 12 },
134893  { 228, 1 },
134894  { 228, 0 },
134895  { 177, 0 },
134896  { 177, 3 },
134897  { 187, 5 },
134898  { 187, 3 },
134899  { 229, 0 },
134900  { 229, 2 },
134901  { 149, 4 },
134902  { 149, 1 },
134903  { 149, 2 },
134904  { 149, 3 },
134905  { 149, 5 },
134906  { 149, 6 },
134907  { 149, 5 },
134908  { 149, 6 },
134909  { 169, 2 },
134910  { 170, 2 },
134911  { 149, 5 },
134912  { 231, 11 },
134913  { 233, 1 },
134914  { 233, 1 },
134915  { 233, 2 },
134916  { 233, 0 },
134917  { 234, 1 },
134918  { 234, 1 },
134919  { 234, 3 },
134920  { 236, 0 },
134921  { 236, 2 },
134922  { 232, 3 },
134923  { 232, 2 },
134924  { 238, 3 },
134925  { 239, 3 },
134926  { 239, 2 },
134927  { 237, 7 },
134928  { 237, 5 },
134929  { 237, 5 },
134930  { 237, 1 },
134931  { 173, 4 },
134932  { 173, 6 },
134933  { 191, 1 },
134934  { 191, 1 },
134935  { 191, 1 },
134936  { 149, 4 },
134937  { 149, 6 },
134938  { 149, 3 },
134939  { 241, 0 },
134940  { 241, 2 },
134941  { 149, 1 },
134942  { 149, 3 },
134943  { 149, 1 },
134944  { 149, 3 },
134945  { 149, 6 },
134946  { 149, 7 },
134947  { 242, 1 },
134948  { 149, 1 },
134949  { 149, 4 },
134950  { 244, 8 },
134951  { 246, 0 },
134952  { 247, 1 },
134953  { 247, 3 },
134954  { 248, 1 },
134955  { 196, 0 },
134956  { 196, 2 },
134957  { 196, 3 },
134958  { 250, 6 },
134959  { 250, 8 },
134960  { 144, 1 },
134961  { 145, 2 },
134962  { 145, 1 },
134963  { 146, 1 },
134964  { 146, 3 },
134965  { 147, 0 },
134966  { 151, 0 },
134967  { 151, 1 },
134968  { 151, 2 },
134969  { 153, 1 },
134970  { 153, 0 },
134971  { 149, 2 },
134972  { 160, 4 },
134973  { 160, 2 },
134974  { 152, 1 },
134975  { 152, 1 },
134976  { 152, 1 },
134977  { 166, 1 },
134978  { 167, 1 },
134979  { 168, 1 },
134980  { 168, 1 },
134981  { 165, 2 },
134982  { 165, 0 },
134983  { 171, 2 },
134984  { 161, 2 },
134985  { 183, 3 },
134986  { 183, 1 },
134987  { 184, 0 },
134988  { 188, 1 },
134989  { 190, 1 },
134990  { 194, 1 },
134991  { 195, 1 },
134992  { 209, 2 },
134993  { 210, 1 },
134994  { 173, 1 },
134995  { 208, 1 },
134996  { 230, 1 },
134997  { 230, 1 },
134998  { 230, 1 },
134999  { 230, 1 },
135000  { 230, 1 },
135001  { 169, 1 },
135002  { 235, 0 },
135003  { 235, 3 },
135004  { 238, 1 },
135005  { 239, 0 },
135006  { 240, 1 },
135007  { 240, 0 },
135008  { 243, 0 },
135009  { 243, 1 },
135010  { 245, 1 },
135011  { 245, 3 },
135012  { 246, 2 },
135013  { 249, 0 },
135014  { 249, 4 },
135015  { 249, 2 },
135016 };
135017 
135018 static void yy_accept(yyParser*); /* Forward Declaration */
135019 
135020 /*
135021 ** Perform a reduce action and the shift that must immediately
135022 ** follow the reduce.
135023 */
135024 static void yy_reduce(
135025  yyParser *yypParser, /* The parser */
135026  unsigned int yyruleno /* Number of the rule by which to reduce */
135027 ){
135028  int yygoto; /* The next state */
135029  int yyact; /* The next action */
135030  yyStackEntry *yymsp; /* The top of the parser's stack */
135031  int yysize; /* Amount to pop the stack */
135033  yymsp = yypParser->yytos;
135034 #ifndef NDEBUG
135035  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
135036  yysize = yyRuleInfo[yyruleno].nrhs;
135037  fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
135038  yyRuleName[yyruleno], yymsp[-yysize].stateno);
135039  }
135040 #endif /* NDEBUG */
135041 
135042  /* Check that the stack is large enough to grow by a single entry
135043  ** if the RHS of the rule is empty. This ensures that there is room
135044  ** enough on the stack to push the LHS value */
135045  if( yyRuleInfo[yyruleno].nrhs==0 ){
135046 #ifdef YYTRACKMAXSTACKDEPTH
135047  if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
135048  yypParser->yyhwm++;
135049  assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
135050  }
135051 #endif
135052 #if YYSTACKDEPTH>0
135053  if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
135054  yyStackOverflow(yypParser);
135055  return;
135056  }
135057 #else
135058  if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
135059  if( yyGrowStack(yypParser) ){
135060  yyStackOverflow(yypParser);
135061  return;
135062  }
135063  yymsp = yypParser->yytos;
135064  }
135065 #endif
135066  }
135067 
135068  switch( yyruleno ){
135069  /* Beginning here are the reduction cases. A typical example
135070  ** follows:
135071  ** case 0:
135072  ** #line <lineno> <grammarfile>
135073  ** { ... } // User supplied code
135074  ** #line <lineno> <thisfile>
135075  ** break;
135076  */
135077 /********** Begin reduce actions **********************************************/
135078  YYMINORTYPE yylhsminor;
135079  case 0: /* explain ::= EXPLAIN */
135080 { pParse->explain = 1; }
135081  break;
135082  case 1: /* explain ::= EXPLAIN QUERY PLAN */
135083 { pParse->explain = 2; }
135084  break;
135085  case 2: /* cmdx ::= cmd */
135086 { sqlite3FinishCoding(pParse); }
135087  break;
135088  case 3: /* cmd ::= BEGIN transtype trans_opt */
135089 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
135090  break;
135091  case 4: /* transtype ::= */
135092 {yymsp[1].minor.yy194 = TK_DEFERRED;}
135093  break;
135094  case 5: /* transtype ::= DEFERRED */
135095  case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
135096  case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
135097 {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
135098  break;
135099  case 8: /* cmd ::= COMMIT trans_opt */
135100  case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
135101 {sqlite3CommitTransaction(pParse);}
135102  break;
135103  case 10: /* cmd ::= ROLLBACK trans_opt */
135104 {sqlite3RollbackTransaction(pParse);}
135105  break;
135106  case 11: /* cmd ::= SAVEPOINT nm */
135107 {
135108  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
135109 }
135110  break;
135111  case 12: /* cmd ::= RELEASE savepoint_opt nm */
135112 {
135113  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
135114 }
135115  break;
135116  case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
135117 {
135118  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
135119 }
135120  break;
135121  case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
135122 {
135123  sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
135124 }
135125  break;
135126  case 15: /* createkw ::= CREATE */
135127 {disableLookaside(pParse);}
135128  break;
135129  case 16: /* ifnotexists ::= */
135130  case 19: /* temp ::= */ yytestcase(yyruleno==19);
135131  case 22: /* table_options ::= */ yytestcase(yyruleno==22);
135132  case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
135133  case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
135134  case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
135135  case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
135136  case 90: /* distinct ::= */ yytestcase(yyruleno==90);
135137  case 215: /* collate ::= */ yytestcase(yyruleno==215);
135138 {yymsp[1].minor.yy194 = 0;}
135139  break;
135140  case 17: /* ifnotexists ::= IF NOT EXISTS */
135141 {yymsp[-2].minor.yy194 = 1;}
135142  break;
135143  case 18: /* temp ::= TEMP */
135144  case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
135145 {yymsp[0].minor.yy194 = 1;}
135146  break;
135147  case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
135148 {
135149  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
135150 }
135151  break;
135152  case 21: /* create_table_args ::= AS select */
135153 {
135154  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
135155  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
135156 }
135157  break;
135158  case 23: /* table_options ::= WITHOUT nm */
135159 {
135160  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
135162  }else{
135163  yymsp[-1].minor.yy194 = 0;
135164  sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
135165  }
135166 }
135167  break;
135168  case 24: /* columnname ::= nm typetoken */
135169 {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
135170  break;
135171  case 25: /* typetoken ::= */
135172  case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
135173  case 96: /* as ::= */ yytestcase(yyruleno==96);
135174 {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
135175  break;
135176  case 26: /* typetoken ::= typename LP signed RP */
135177 {
135178  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
135179 }
135180  break;
135181  case 27: /* typetoken ::= typename LP signed COMMA signed RP */
135182 {
135183  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
135184 }
135185  break;
135186  case 28: /* typename ::= typename ID|STRING */
135187 {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
135188  break;
135189  case 29: /* ccons ::= CONSTRAINT nm */
135190  case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
135191 {pParse->constraintName = yymsp[0].minor.yy0;}
135192  break;
135193  case 30: /* ccons ::= DEFAULT term */
135194  case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
135195 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
135196  break;
135197  case 31: /* ccons ::= DEFAULT LP expr RP */
135198 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
135199  break;
135200  case 33: /* ccons ::= DEFAULT MINUS term */
135201 {
135202  ExprSpan v;
135203  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0, 0);
135204  v.zStart = yymsp[-1].minor.yy0.z;
135205  v.zEnd = yymsp[0].minor.yy190.zEnd;
135206  sqlite3AddDefaultValue(pParse,&v);
135207 }
135208  break;
135209  case 34: /* ccons ::= DEFAULT ID|INDEXED */
135210 {
135211  ExprSpan v;
135212  spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
135213  sqlite3AddDefaultValue(pParse,&v);
135214 }
135215  break;
135216  case 35: /* ccons ::= NOT NULL onconf */
135217 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
135218  break;
135219  case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
135220 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
135221  break;
135222  case 37: /* ccons ::= UNIQUE onconf */
135223 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
135225  break;
135226  case 38: /* ccons ::= CHECK LP expr RP */
135227 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
135228  break;
135229  case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
135230 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
135231  break;
135232  case 40: /* ccons ::= defer_subclause */
135233 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
135234  break;
135235  case 41: /* ccons ::= COLLATE ID|STRING */
135236 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
135237  break;
135238  case 44: /* refargs ::= */
135239 { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
135240  break;
135241  case 45: /* refargs ::= refargs refarg */
135242 { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
135243  break;
135244  case 46: /* refarg ::= MATCH nm */
135245 { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; }
135246  break;
135247  case 47: /* refarg ::= ON INSERT refact */
135248 { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; }
135249  break;
135250  case 48: /* refarg ::= ON DELETE refact */
135251 { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; }
135252  break;
135253  case 49: /* refarg ::= ON UPDATE refact */
135254 { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; }
135255  break;
135256  case 50: /* refact ::= SET NULL */
135257 { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */}
135258  break;
135259  case 51: /* refact ::= SET DEFAULT */
135260 { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */}
135261  break;
135262  case 52: /* refact ::= CASCADE */
135263 { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */}
135264  break;
135265  case 53: /* refact ::= RESTRICT */
135266 { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
135267  break;
135268  case 54: /* refact ::= NO ACTION */
135269 { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */}
135270  break;
135271  case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
135272 {yymsp[-2].minor.yy194 = 0;}
135273  break;
135274  case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
135275  case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
135276  case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144);
135277 {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
135278  break;
135279  case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
135280  case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
135281  case 187: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==187);
135282  case 190: /* in_op ::= NOT IN */ yytestcase(yyruleno==190);
135283  case 216: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==216);
135284 {yymsp[-1].minor.yy194 = 1;}
135285  break;
135286  case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
135287 {yymsp[-1].minor.yy194 = 0;}
135288  break;
135289  case 61: /* tconscomma ::= COMMA */
135290 {pParse->constraintName.n = 0;}
135291  break;
135292  case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
135293 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
135294  break;
135295  case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
135296 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
135298  break;
135299  case 65: /* tcons ::= CHECK LP expr RP onconf */
135300 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
135301  break;
135302  case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
135303 {
135304  sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
135305  sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
135306 }
135307  break;
135308  case 68: /* onconf ::= */
135309  case 70: /* orconf ::= */ yytestcase(yyruleno==70);
135310 {yymsp[1].minor.yy194 = OE_Default;}
135311  break;
135312  case 69: /* onconf ::= ON CONFLICT resolvetype */
135313 {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
135314  break;
135315  case 72: /* resolvetype ::= IGNORE */
135316 {yymsp[0].minor.yy194 = OE_Ignore;}
135317  break;
135318  case 73: /* resolvetype ::= REPLACE */
135319  case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145);
135320 {yymsp[0].minor.yy194 = OE_Replace;}
135321  break;
135322  case 74: /* cmd ::= DROP TABLE ifexists fullname */
135323 {
135324  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
135325 }
135326  break;
135327  case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
135328 {
135329  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);
135330 }
135331  break;
135332  case 78: /* cmd ::= DROP VIEW ifexists fullname */
135333 {
135334  sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
135335 }
135336  break;
135337  case 79: /* cmd ::= select */
135338 {
135339  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
135340  sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
135341  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
135342 }
135343  break;
135344  case 80: /* select ::= with selectnowith */
135345 {
135346  Select *p = yymsp[0].minor.yy243;
135347  if( p ){
135348  p->pWith = yymsp[-1].minor.yy285;
135349  parserDoubleLinkSelect(pParse, p);
135350  }else{
135351  sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
135352  }
135353  yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
135354 }
135355  break;
135356  case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
135357 {
135358  Select *pRhs = yymsp[0].minor.yy243;
135359  Select *pLhs = yymsp[-2].minor.yy243;
135360  if( pRhs && pRhs->pPrior ){
135361  SrcList *pFrom;
135362  Token x;
135363  x.n = 0;
135364  parserDoubleLinkSelect(pParse, pRhs);
135365  pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
135366  pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
135367  }
135368  if( pRhs ){
135369  pRhs->op = (u8)yymsp[-1].minor.yy194;
135370  pRhs->pPrior = pLhs;
135371  if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
135372  pRhs->selFlags &= ~SF_MultiValue;
135373  if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
135374  }else{
135375  sqlite3SelectDelete(pParse->db, pLhs);
135376  }
135377  yymsp[-2].minor.yy243 = pRhs;
135378 }
135379  break;
135380  case 82: /* multiselect_op ::= UNION */
135381  case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
135382 {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
135383  break;
135384  case 83: /* multiselect_op ::= UNION ALL */
135385 {yymsp[-1].minor.yy194 = TK_ALL;}
135386  break;
135387  case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
135388 {
135389 #if SELECTTRACE_ENABLED
135390  Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
135391 #endif
135392  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);
135393 #if SELECTTRACE_ENABLED
135394  /* Populate the Select.zSelName[] string that is used to help with
135395  ** query planner debugging, to differentiate between multiple Select
135396  ** objects in a complex query.
135397  **
135398  ** If the SELECT keyword is immediately followed by a C-style comment
135399  ** then extract the first few alphanumeric characters from within that
135400  ** comment to be the zSelName value. Otherwise, the label is #N where
135401  ** is an integer that is incremented with each SELECT statement seen.
135402  */
135403  if( yymsp[-8].minor.yy243!=0 ){
135404  const char *z = s.z+6;
135405  int i;
135406  sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
135407  ++pParse->nSelect);
135408  while( z[0]==' ' ) z++;
135409  if( z[0]=='/' && z[1]=='*' ){
135410  z += 2;
135411  while( z[0]==' ' ) z++;
135412  for(i=0; sqlite3Isalnum(z[i]); i++){}
135413  sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
135414  }
135415  }
135416 #endif /* SELECTRACE_ENABLED */
135417 }
135418  break;
135419  case 86: /* values ::= VALUES LP nexprlist RP */
135420 {
135421  yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
135422 }
135423  break;
135424  case 87: /* values ::= values COMMA LP exprlist RP */
135425 {
135426  Select *pRight, *pLeft = yymsp[-4].minor.yy243;
135427  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
135428  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
135429  if( pRight ){
135430  pRight->op = TK_ALL;
135431  pRight->pPrior = pLeft;
135432  yymsp[-4].minor.yy243 = pRight;
135433  }else{
135434  yymsp[-4].minor.yy243 = pLeft;
135435  }
135436 }
135437  break;
135438  case 88: /* distinct ::= DISTINCT */
135439 {yymsp[0].minor.yy194 = SF_Distinct;}
135440  break;
135441  case 89: /* distinct ::= ALL */
135442 {yymsp[0].minor.yy194 = SF_All;}
135443  break;
135444  case 91: /* sclp ::= */
135445  case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
135446  case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
135447  case 203: /* exprlist ::= */ yytestcase(yyruleno==203);
135448  case 206: /* paren_exprlist ::= */ yytestcase(yyruleno==206);
135449  case 211: /* eidlist_opt ::= */ yytestcase(yyruleno==211);
135450 {yymsp[1].minor.yy148 = 0;}
135451  break;
135452  case 92: /* selcollist ::= sclp expr as */
135453 {
135454  yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
135455  if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
135456  sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
135457 }
135458  break;
135459  case 93: /* selcollist ::= sclp STAR */
135460 {
135461  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
135462  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
135463 }
135464  break;
135465  case 94: /* selcollist ::= sclp nm DOT STAR */
135466 {
135467  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, 0);
135468  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
135469  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
135470  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
135471 }
135472  break;
135473  case 95: /* as ::= AS nm */
135474  case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
135475  case 225: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==225);
135476  case 226: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==226);
135477 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
135478  break;
135479  case 97: /* from ::= */
135480 {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
135481  break;
135482  case 98: /* from ::= FROM seltablist */
135483 {
135484  yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
135485  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
135486 }
135487  break;
135488  case 99: /* stl_prefix ::= seltablist joinop */
135489 {
135490  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;
135491 }
135492  break;
135493  case 100: /* stl_prefix ::= */
135494 {yymsp[1].minor.yy185 = 0;}
135495  break;
135496  case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
135497 {
135498  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);
135499  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
135500 }
135501  break;
135502  case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
135503 {
135504  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);
135505  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
135506 }
135507  break;
135508  case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
135509 {
135510  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);
135511  }
135512  break;
135513  case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
135514 {
135515  if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
135516  yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
135517  }else if( yymsp[-4].minor.yy185->nSrc==1 ){
135518  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);
135519  if( yymsp[-6].minor.yy185 ){
135520  struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
135521  struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
135522  pNew->zName = pOld->zName;
135523  pNew->zDatabase = pOld->zDatabase;
135524  pNew->pSelect = pOld->pSelect;
135525  pOld->zName = pOld->zDatabase = 0;
135526  pOld->pSelect = 0;
135527  }
135528  sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
135529  }else{
135530  Select *pSubquery;
135531  sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
135532  pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
135533  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);
135534  }
135535  }
135536  break;
135537  case 105: /* dbnm ::= */
135538  case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
135539 {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
135540  break;
135541  case 107: /* fullname ::= nm dbnm */
135542 {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
135543  break;
135544  case 108: /* joinop ::= COMMA|JOIN */
135545 { yymsp[0].minor.yy194 = JT_INNER; }
135546  break;
135547  case 109: /* joinop ::= JOIN_KW JOIN */
135548 {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
135549  break;
135550  case 110: /* joinop ::= JOIN_KW nm JOIN */
135551 {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
135552  break;
135553  case 111: /* joinop ::= JOIN_KW nm nm JOIN */
135554 {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
135555  break;
135556  case 112: /* on_opt ::= ON expr */
135557  case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
135558  case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
135559  case 199: /* case_else ::= ELSE expr */ yytestcase(yyruleno==199);
135560 {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
135561  break;
135562  case 113: /* on_opt ::= */
135563  case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
135564  case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
135565  case 200: /* case_else ::= */ yytestcase(yyruleno==200);
135566  case 202: /* case_operand ::= */ yytestcase(yyruleno==202);
135567 {yymsp[1].minor.yy72 = 0;}
135568  break;
135569  case 115: /* indexed_opt ::= INDEXED BY nm */
135570 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
135571  break;
135572  case 116: /* indexed_opt ::= NOT INDEXED */
135573 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
135574  break;
135575  case 117: /* using_opt ::= USING LP idlist RP */
135576 {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
135577  break;
135578  case 118: /* using_opt ::= */
135579  case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146);
135580 {yymsp[1].minor.yy254 = 0;}
135581  break;
135582  case 120: /* orderby_opt ::= ORDER BY sortlist */
135583  case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
135584 {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
135585  break;
135586  case 121: /* sortlist ::= sortlist COMMA expr sortorder */
135587 {
135588  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
135589  sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
135590 }
135591  break;
135592  case 122: /* sortlist ::= expr sortorder */
135593 {
135594  yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
135595  sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
135596 }
135597  break;
135598  case 123: /* sortorder ::= ASC */
135599 {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
135600  break;
135601  case 124: /* sortorder ::= DESC */
135602 {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
135603  break;
135604  case 125: /* sortorder ::= */
135605 {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
135606  break;
135607  case 130: /* limit_opt ::= */
135608 {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
135609  break;
135610  case 131: /* limit_opt ::= LIMIT expr */
135611 {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
135612  break;
135613  case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
135614 {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
135615  break;
135616  case 133: /* limit_opt ::= LIMIT expr COMMA expr */
135617 {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
135618  break;
135619  case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
135620 {
135621  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
135622  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
135623  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
135624 }
135625  break;
135626  case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
135627 {
135628  sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
135629  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
135630  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
135631  sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
135632 }
135633  break;
135634  case 138: /* setlist ::= setlist COMMA nm EQ expr */
135635 {
135636  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
135637  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
135638 }
135639  break;
135640  case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
135641 {
135642  yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
135643 }
135644  break;
135645  case 140: /* setlist ::= nm EQ expr */
135646 {
135647  yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
135648  sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
135649 }
135650  yymsp[-2].minor.yy148 = yylhsminor.yy148;
135651  break;
135652  case 141: /* setlist ::= LP idlist RP EQ expr */
135653 {
135654  yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
135655 }
135656  break;
135657  case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
135658 {
135659  sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
135660  sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
135661 }
135662  break;
135663  case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
135664 {
135665  sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
135666  sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
135667 }
135668  break;
135669  case 147: /* idlist_opt ::= LP idlist RP */
135670 {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
135671  break;
135672  case 148: /* idlist ::= idlist COMMA nm */
135673 {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
135674  break;
135675  case 149: /* idlist ::= nm */
135676 {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
135677  break;
135678  case 150: /* expr ::= LP expr RP */
135679 {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;}
135680  break;
135681  case 151: /* term ::= NULL */
135682  case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156);
135683  case 157: /* term ::= STRING */ yytestcase(yyruleno==157);
135684 {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
135685  break;
135686  case 152: /* expr ::= ID|INDEXED */
135687  case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153);
135688 {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
135689  break;
135690  case 154: /* expr ::= nm DOT nm */
135691 {
135692  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
135693  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
135694  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
135695  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
135696 }
135697  break;
135698  case 155: /* expr ::= nm DOT nm DOT nm */
135699 {
135700  Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
135701  Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
135702  Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
135703  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
135704  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
135705  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
135706 }
135707  break;
135708  case 158: /* term ::= INTEGER */
135709 {
135710  yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
135711  yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
135712  yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
135713  if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf;
135714 }
135715  yymsp[0].minor.yy190 = yylhsminor.yy190;
135716  break;
135717  case 159: /* expr ::= VARIABLE */
135718 {
135719  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
135720  u32 n = yymsp[0].minor.yy0.n;
135721  spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
135722  sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
135723  }else{
135724  /* When doing a nested parse, one can include terms in an expression
135725  ** that look like this: #1 #2 ... These terms refer to registers
135726  ** in the virtual machine. #N is the N-th register. */
135727  Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
135728  assert( t.n>=2 );
135729  spanSet(&yymsp[0].minor.yy190, &t, &t);
135730  if( pParse->nested==0 ){
135731  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
135732  yymsp[0].minor.yy190.pExpr = 0;
135733  }else{
135734  yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, 0);
135735  if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
135736  }
135737  }
135738 }
135739  break;
135740  case 160: /* expr ::= expr COLLATE ID|STRING */
135741 {
135742  yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
135743  yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
135744 }
135745  break;
135746  case 161: /* expr ::= CAST LP expr AS typetoken RP */
135747 {
135748  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
135749  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy190.pExpr, 0, &yymsp[-1].minor.yy0);
135750 }
135751  break;
135752  case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */
135753 {
135754  if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
135755  sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
135756  }
135757  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
135758  spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
135759  if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
135760  yylhsminor.yy190.pExpr->flags |= EP_Distinct;
135761  }
135762 }
135763  yymsp[-4].minor.yy190 = yylhsminor.yy190;
135764  break;
135765  case 163: /* expr ::= ID|INDEXED LP STAR RP */
135766 {
135767  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
135768  spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
135769 }
135770  yymsp[-3].minor.yy190 = yylhsminor.yy190;
135771  break;
135772  case 164: /* term ::= CTIME_KW */
135773 {
135774  yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
135775  spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
135776 }
135777  yymsp[0].minor.yy190 = yylhsminor.yy190;
135778  break;
135779  case 165: /* expr ::= LP nexprlist COMMA expr RP */
135780 {
135781  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
135782  yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0, 0);
135783  if( yylhsminor.yy190.pExpr ){
135784  yylhsminor.yy190.pExpr->x.pList = pList;
135785  spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
135786  }else{
135787  sqlite3ExprListDelete(pParse->db, pList);
135788  }
135789 }
135790  yymsp[-4].minor.yy190 = yylhsminor.yy190;
135791  break;
135792  case 166: /* expr ::= expr AND expr */
135793  case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167);
135794  case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168);
135795  case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169);
135796  case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170);
135797  case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171);
135798  case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172);
135799  case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173);
135800 {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
135801  break;
135802  case 174: /* likeop ::= LIKE_KW|MATCH */
135803 {yymsp[0].minor.yy0=yymsp[0].minor.yy0;/*A-overwrites-X*/}
135804  break;
135805  case 175: /* likeop ::= NOT LIKE_KW|MATCH */
135806 {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
135807  break;
135808  case 176: /* expr ::= expr likeop expr */
135809 {
135810  ExprList *pList;
135811  int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
135812  yymsp[-1].minor.yy0.n &= 0x7fffffff;
135813  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
135814  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
135815  yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
135816  exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
135817  yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
135818  if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
135819 }
135820  break;
135821  case 177: /* expr ::= expr likeop expr ESCAPE expr */
135822 {
135823  ExprList *pList;
135824  int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
135825  yymsp[-3].minor.yy0.n &= 0x7fffffff;
135826  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
135827  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
135828  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
135829  yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
135830  exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
135831  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
135832  if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
135833 }
135834  break;
135835  case 178: /* expr ::= expr ISNULL|NOTNULL */
135836 {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
135837  break;
135838  case 179: /* expr ::= expr NOT NULL */
135839 {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
135840  break;
135841  case 180: /* expr ::= expr IS expr */
135842 {
135843  spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
135844  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
135845 }
135846  break;
135847  case 181: /* expr ::= expr IS NOT expr */
135848 {
135849  spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
135850  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
135851 }
135852  break;
135853  case 182: /* expr ::= NOT expr */
135854  case 183: /* expr ::= BITNOT expr */ yytestcase(yyruleno==183);
135855 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
135856  break;
135857  case 184: /* expr ::= MINUS expr */
135858 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
135859  break;
135860  case 185: /* expr ::= PLUS expr */
135861 {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
135862  break;
135863  case 186: /* between_op ::= BETWEEN */
135864  case 189: /* in_op ::= IN */ yytestcase(yyruleno==189);
135865 {yymsp[0].minor.yy194 = 0;}
135866  break;
135867  case 188: /* expr ::= expr between_op expr AND expr */
135868 {
135869  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
135870  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
135871  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135872  if( yymsp[-4].minor.yy190.pExpr ){
135873  yymsp[-4].minor.yy190.pExpr->x.pList = pList;
135874  }else{
135875  sqlite3ExprListDelete(pParse->db, pList);
135876  }
135877  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135878  yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
135879 }
135880  break;
135881  case 191: /* expr ::= expr in_op LP exprlist RP */
135882 {
135883  if( yymsp[-1].minor.yy148==0 ){
135884  /* Expressions of the form
135885  **
135886  ** expr1 IN ()
135887  ** expr1 NOT IN ()
135888  **
135889  ** simplify to constants 0 (false) and 1 (true), respectively,
135890  ** regardless of the value of expr1.
135891  */
135892  sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
135893  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy194]);
135894  }else if( yymsp[-1].minor.yy148->nExpr==1 ){
135895  /* Expressions of the form:
135896  **
135897  ** expr1 IN (?1)
135898  ** expr1 NOT IN (?2)
135899  **
135900  ** with exactly one value on the RHS can be simplified to something
135901  ** like this:
135902  **
135903  ** expr1 == ?1
135904  ** expr1 <> ?2
135905  **
135906  ** But, the RHS of the == or <> is marked with the EP_Generic flag
135907  ** so that it may not contribute to the computation of comparison
135908  ** affinity or the collating sequence to use for comparison. Otherwise,
135909  ** the semantics would be subtly different from IN or NOT IN.
135910  */
135911  Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
135912  yymsp[-1].minor.yy148->a[0].pExpr = 0;
135913  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
135914  /* pRHS cannot be NULL because a malloc error would have been detected
135915  ** before now and control would have never reached this point */
135916  if( ALWAYS(pRHS) ){
135917  pRHS->flags &= ~EP_Collate;
135918  pRHS->flags |= EP_Generic;
135919  }
135920  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS, 0);
135921  }else{
135922  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135923  if( yymsp[-4].minor.yy190.pExpr ){
135924  yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
135925  sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
135926  }else{
135927  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
135928  }
135929  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135930  }
135931  yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
135932  }
135933  break;
135934  case 192: /* expr ::= LP select RP */
135935 {
135936  spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
135937  yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
135938  sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
135939  }
135940  break;
135941  case 193: /* expr ::= expr in_op LP select RP */
135942 {
135943  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135944  sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
135945  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135946  yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
135947  }
135948  break;
135949  case 194: /* expr ::= expr in_op nm dbnm paren_exprlist */
135950 {
135951  SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
135952  Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
135953  if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
135954  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
135955  sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
135956  exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
135957  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];
135958  }
135959  break;
135960  case 195: /* expr ::= EXISTS LP select RP */
135961 {
135962  Expr *p;
135963  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
135964  p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
135965  sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
135966  }
135967  break;
135968  case 196: /* expr ::= CASE case_operand case_exprlist case_else END */
135969 {
135970  spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
135971  yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0, 0);
135972  if( yymsp[-4].minor.yy190.pExpr ){
135973  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;
135974  sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
135975  }else{
135976  sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
135977  sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
135978  }
135979 }
135980  break;
135981  case 197: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
135982 {
135983  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
135984  yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
135985 }
135986  break;
135987  case 198: /* case_exprlist ::= WHEN expr THEN expr */
135988 {
135989  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
135990  yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
135991 }
135992  break;
135993  case 201: /* case_operand ::= expr */
135994 {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
135995  break;
135996  case 204: /* nexprlist ::= nexprlist COMMA expr */
135997 {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
135998  break;
135999  case 205: /* nexprlist ::= expr */
136000 {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
136001  break;
136002  case 207: /* paren_exprlist ::= LP exprlist RP */
136003  case 212: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==212);
136004 {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
136005  break;
136006  case 208: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
136007 {
136008  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
136009  sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
136010  &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
136011 }
136012  break;
136013  case 209: /* uniqueflag ::= UNIQUE */
136014  case 250: /* raisetype ::= ABORT */ yytestcase(yyruleno==250);
136015 {yymsp[0].minor.yy194 = OE_Abort;}
136016  break;
136017  case 210: /* uniqueflag ::= */
136018 {yymsp[1].minor.yy194 = OE_None;}
136019  break;
136020  case 213: /* eidlist ::= eidlist COMMA nm collate sortorder */
136021 {
136022  yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
136023 }
136024  break;
136025  case 214: /* eidlist ::= nm collate sortorder */
136026 {
136027  yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
136028 }
136029  break;
136030  case 217: /* cmd ::= DROP INDEX ifexists fullname */
136031 {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
136032  break;
136033  case 218: /* cmd ::= VACUUM */
136034 {sqlite3Vacuum(pParse,0);}
136035  break;
136036  case 219: /* cmd ::= VACUUM nm */
136037 {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
136038  break;
136039  case 220: /* cmd ::= PRAGMA nm dbnm */
136040 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
136041  break;
136042  case 221: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
136043 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
136044  break;
136045  case 222: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
136046 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
136047  break;
136048  case 223: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
136049 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
136050  break;
136051  case 224: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
136052 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
136053  break;
136054  case 227: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
136055 {
136056  Token all;
136057  all.z = yymsp[-3].minor.yy0.z;
136058  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
136059  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
136060 }
136061  break;
136062  case 228: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
136063 {
136064  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);
136065  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
136066 }
136067  break;
136068  case 229: /* trigger_time ::= BEFORE */
136069 { yymsp[0].minor.yy194 = TK_BEFORE; }
136070  break;
136071  case 230: /* trigger_time ::= AFTER */
136072 { yymsp[0].minor.yy194 = TK_AFTER; }
136073  break;
136074  case 231: /* trigger_time ::= INSTEAD OF */
136075 { yymsp[-1].minor.yy194 = TK_INSTEAD;}
136076  break;
136077  case 232: /* trigger_time ::= */
136078 { yymsp[1].minor.yy194 = TK_BEFORE; }
136079  break;
136080  case 233: /* trigger_event ::= DELETE|INSERT */
136081  case 234: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==234);
136082 {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
136083  break;
136084  case 235: /* trigger_event ::= UPDATE OF idlist */
136085 {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
136086  break;
136087  case 236: /* when_clause ::= */
136088  case 255: /* key_opt ::= */ yytestcase(yyruleno==255);
136089 { yymsp[1].minor.yy72 = 0; }
136090  break;
136091  case 237: /* when_clause ::= WHEN expr */
136092  case 256: /* key_opt ::= KEY expr */ yytestcase(yyruleno==256);
136093 { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
136094  break;
136095  case 238: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
136096 {
136097  assert( yymsp[-2].minor.yy145!=0 );
136098  yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
136099  yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
136100 }
136101  break;
136102  case 239: /* trigger_cmd_list ::= trigger_cmd SEMI */
136103 {
136104  assert( yymsp[-1].minor.yy145!=0 );
136105  yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
136106 }
136107  break;
136108  case 240: /* trnm ::= nm DOT nm */
136109 {
136110  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
136111  sqlite3ErrorMsg(pParse,
136112  "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
136113  "statements within triggers");
136114 }
136115  break;
136116  case 241: /* tridxby ::= INDEXED BY nm */
136117 {
136118  sqlite3ErrorMsg(pParse,
136119  "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
136120  "within triggers");
136121 }
136122  break;
136123  case 242: /* tridxby ::= NOT INDEXED */
136124 {
136125  sqlite3ErrorMsg(pParse,
136126  "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
136127  "within triggers");
136128 }
136129  break;
136130  case 243: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
136131 {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
136132  break;
136133  case 244: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
136134 {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*/}
136135  break;
136136  case 245: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
136137 {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
136138  break;
136139  case 246: /* trigger_cmd ::= select */
136140 {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
136141  break;
136142  case 247: /* expr ::= RAISE LP IGNORE RP */
136143 {
136144  spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
136145  yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
136146  if( yymsp[-3].minor.yy190.pExpr ){
136147  yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
136148  }
136149 }
136150  break;
136151  case 248: /* expr ::= RAISE LP raisetype COMMA nm RP */
136152 {
136153  spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
136154  yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
136155  if( yymsp[-5].minor.yy190.pExpr ) {
136156  yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
136157  }
136158 }
136159  break;
136160  case 249: /* raisetype ::= ROLLBACK */
136161 {yymsp[0].minor.yy194 = OE_Rollback;}
136162  break;
136163  case 251: /* raisetype ::= FAIL */
136164 {yymsp[0].minor.yy194 = OE_Fail;}
136165  break;
136166  case 252: /* cmd ::= DROP TRIGGER ifexists fullname */
136167 {
136168  sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
136169 }
136170  break;
136171  case 253: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
136172 {
136173  sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
136174 }
136175  break;
136176  case 254: /* cmd ::= DETACH database_kw_opt expr */
136177 {
136178  sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
136179 }
136180  break;
136181  case 257: /* cmd ::= REINDEX */
136182 {sqlite3Reindex(pParse, 0, 0);}
136183  break;
136184  case 258: /* cmd ::= REINDEX nm dbnm */
136185 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
136186  break;
136187  case 259: /* cmd ::= ANALYZE */
136188 {sqlite3Analyze(pParse, 0, 0);}
136189  break;
136190  case 260: /* cmd ::= ANALYZE nm dbnm */
136191 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
136192  break;
136193  case 261: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
136194 {
136195  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
136196 }
136197  break;
136198  case 262: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
136199 {
136200  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
136201  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
136202 }
136203  break;
136204  case 263: /* add_column_fullname ::= fullname */
136205 {
136206  disableLookaside(pParse);
136207  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
136208 }
136209  break;
136210  case 264: /* cmd ::= create_vtab */
136211 {sqlite3VtabFinishParse(pParse,0);}
136212  break;
136213  case 265: /* cmd ::= create_vtab LP vtabarglist RP */
136214 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
136215  break;
136216  case 266: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
136217 {
136218  sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
136219 }
136220  break;
136221  case 267: /* vtabarg ::= */
136222 {sqlite3VtabArgInit(pParse);}
136223  break;
136224  case 268: /* vtabargtoken ::= ANY */
136225  case 269: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==269);
136226  case 270: /* lp ::= LP */ yytestcase(yyruleno==270);
136227 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
136228  break;
136229  case 271: /* with ::= */
136230 {yymsp[1].minor.yy285 = 0;}
136231  break;
136232  case 272: /* with ::= WITH wqlist */
136233 { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
136234  break;
136235  case 273: /* with ::= WITH RECURSIVE wqlist */
136236 { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
136237  break;
136238  case 274: /* wqlist ::= nm eidlist_opt AS LP select RP */
136239 {
136240  yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
136241 }
136242  break;
136243  case 275: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
136244 {
136245  yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
136246 }
136247  break;
136248  default:
136249  /* (276) input ::= cmdlist */ yytestcase(yyruleno==276);
136250  /* (277) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==277);
136251  /* (278) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=278);
136252  /* (279) ecmd ::= SEMI */ yytestcase(yyruleno==279);
136253  /* (280) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==280);
136254  /* (281) explain ::= */ yytestcase(yyruleno==281);
136255  /* (282) trans_opt ::= */ yytestcase(yyruleno==282);
136256  /* (283) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==283);
136257  /* (284) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==284);
136258  /* (285) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==285);
136259  /* (286) savepoint_opt ::= */ yytestcase(yyruleno==286);
136260  /* (287) cmd ::= create_table create_table_args */ yytestcase(yyruleno==287);
136261  /* (288) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==288);
136262  /* (289) columnlist ::= columnname carglist */ yytestcase(yyruleno==289);
136263  /* (290) nm ::= ID|INDEXED */ yytestcase(yyruleno==290);
136264  /* (291) nm ::= STRING */ yytestcase(yyruleno==291);
136265  /* (292) nm ::= JOIN_KW */ yytestcase(yyruleno==292);
136266  /* (293) typetoken ::= typename */ yytestcase(yyruleno==293);
136267  /* (294) typename ::= ID|STRING */ yytestcase(yyruleno==294);
136268  /* (295) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=295);
136269  /* (296) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=296);
136270  /* (297) carglist ::= carglist ccons */ yytestcase(yyruleno==297);
136271  /* (298) carglist ::= */ yytestcase(yyruleno==298);
136272  /* (299) ccons ::= NULL onconf */ yytestcase(yyruleno==299);
136273  /* (300) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==300);
136274  /* (301) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==301);
136275  /* (302) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=302);
136276  /* (303) tconscomma ::= */ yytestcase(yyruleno==303);
136277  /* (304) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=304);
136278  /* (305) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=305);
136279  /* (306) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=306);
136280  /* (307) oneselect ::= values */ yytestcase(yyruleno==307);
136281  /* (308) sclp ::= selcollist COMMA */ yytestcase(yyruleno==308);
136282  /* (309) as ::= ID|STRING */ yytestcase(yyruleno==309);
136283  /* (310) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=310);
136284  /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311);
136285  /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312);
136286  /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313);
136287  /* (314) nmnum ::= ON */ yytestcase(yyruleno==314);
136288  /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315);
136289  /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316);
136290  /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317);
136291  /* (318) foreach_clause ::= */ yytestcase(yyruleno==318);
136292  /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319);
136293  /* (320) trnm ::= nm */ yytestcase(yyruleno==320);
136294  /* (321) tridxby ::= */ yytestcase(yyruleno==321);
136295  /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322);
136296  /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323);
136297  /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324);
136298  /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325);
136299  /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326);
136300  /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327);
136301  /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328);
136302  /* (329) anylist ::= */ yytestcase(yyruleno==329);
136303  /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330);
136304  /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331);
136305  break;
136306 /********** End reduce actions ************************************************/
136307  };
136308  assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
136309  yygoto = yyRuleInfo[yyruleno].lhs;
136310  yysize = yyRuleInfo[yyruleno].nrhs;
136311  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
136312  if( yyact <= YY_MAX_SHIFTREDUCE ){
136313  if( yyact>YY_MAX_SHIFT ){
136314  yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
136315  }
136316  yymsp -= yysize-1;
136317  yypParser->yytos = yymsp;
136318  yymsp->stateno = (YYACTIONTYPE)yyact;
136319  yymsp->major = (YYCODETYPE)yygoto;
136320  yyTraceShift(yypParser, yyact);
136321  }else{
136322  assert( yyact == YY_ACCEPT_ACTION );
136323  yypParser->yytos -= yysize;
136324  yy_accept(yypParser);
136325  }
136326 }
136327 
136328 /*
136329 ** The following code executes when the parse fails
136330 */
136331 #ifndef YYNOERRORRECOVERY
136332 static void yy_parse_failed(
136333  yyParser *yypParser /* The parser */
136334 ){
136336 #ifndef NDEBUG
136337  if( yyTraceFILE ){
136338  fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
136339  }
136340 #endif
136341  while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
136342  /* Here code is inserted which will be executed whenever the
136343  ** parser fails */
136344 /************ Begin %parse_failure code ***************************************/
136345 /************ End %parse_failure code *****************************************/
136346  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
136347 }
136348 #endif /* YYNOERRORRECOVERY */
136349 
136350 /*
136351 ** The following code executes when a syntax error first occurs.
136352 */
136353 static void yy_syntax_error(
136354  yyParser *yypParser, /* The parser */
136355  int yymajor, /* The major type of the error token */
136356  sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
136357 ){
136359 #define TOKEN yyminor
136360 /************ Begin %syntax_error code ****************************************/
136361 
136362  UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
136363  assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
136364  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
136365 /************ End %syntax_error code ******************************************/
136366  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
136367 }
136368 
136369 /*
136370 ** The following is executed when the parser accepts
136371 */
136372 static void yy_accept(
136373  yyParser *yypParser /* The parser */
136374 ){
136376 #ifndef NDEBUG
136377  if( yyTraceFILE ){
136378  fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
136379  }
136380 #endif
136381 #ifndef YYNOERRORRECOVERY
136382  yypParser->yyerrcnt = -1;
136383 #endif
136384  assert( yypParser->yytos==yypParser->yystack );
136385  /* Here code is inserted which will be executed whenever the
136386  ** parser accepts */
136387 /*********** Begin %parse_accept code *****************************************/
136388 /*********** End %parse_accept code *******************************************/
136389  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
136390 }
136391 
136392 /* The main parser program.
136393 ** The first argument is a pointer to a structure obtained from
136394 ** "sqlite3ParserAlloc" which describes the current state of the parser.
136395 ** The second argument is the major token number. The third is
136396 ** the minor token. The fourth optional argument is whatever the
136397 ** user wants (and specified in the grammar) and is available for
136398 ** use by the action routines.
136399 **
136400 ** Inputs:
136401 ** <ul>
136402 ** <li> A pointer to the parser (an opaque structure.)
136403 ** <li> The major token number.
136404 ** <li> The minor token number.
136405 ** <li> An option argument of a grammar-specified type.
136406 ** </ul>
136407 **
136408 ** Outputs:
136409 ** None.
136410 */
136412  void *yyp, /* The parser */
136413  int yymajor, /* The major token code number */
136414  sqlite3ParserTOKENTYPE yyminor /* The value for the token */
136415  sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
136416 ){
136417  YYMINORTYPE yyminorunion;
136418  unsigned int yyact; /* The parser action. */
136419 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
136420  int yyendofinput; /* True if we are at the end of input */
136421 #endif
136422 #ifdef YYERRORSYMBOL
136423  int yyerrorhit = 0; /* True if yymajor has invoked an error */
136424 #endif
136425  yyParser *yypParser; /* The parser */
136426 
136427  yypParser = (yyParser*)yyp;
136428  assert( yypParser->yytos!=0 );
136429 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
136430  yyendofinput = (yymajor==0);
136431 #endif
136433 
136434 #ifndef NDEBUG
136435  if( yyTraceFILE ){
136436  fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
136437  }
136438 #endif
136439 
136440  do{
136441  yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
136442  if( yyact <= YY_MAX_SHIFTREDUCE ){
136443  yy_shift(yypParser,yyact,yymajor,yyminor);
136444 #ifndef YYNOERRORRECOVERY
136445  yypParser->yyerrcnt--;
136446 #endif
136447  yymajor = YYNOCODE;
136448  }else if( yyact <= YY_MAX_REDUCE ){
136449  yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
136450  }else{
136451  assert( yyact == YY_ERROR_ACTION );
136452  yyminorunion.yy0 = yyminor;
136453 #ifdef YYERRORSYMBOL
136454  int yymx;
136455 #endif
136456 #ifndef NDEBUG
136457  if( yyTraceFILE ){
136458  fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
136459  }
136460 #endif
136461 #ifdef YYERRORSYMBOL
136462  /* A syntax error has occurred.
136463  ** The response to an error depends upon whether or not the
136464  ** grammar defines an error token "ERROR".
136465  **
136466  ** This is what we do if the grammar does define ERROR:
136467  **
136468  ** * Call the %syntax_error function.
136469  **
136470  ** * Begin popping the stack until we enter a state where
136471  ** it is legal to shift the error symbol, then shift
136472  ** the error symbol.
136473  **
136474  ** * Set the error count to three.
136475  **
136476  ** * Begin accepting and shifting new tokens. No new error
136477  ** processing will occur until three tokens have been
136478  ** shifted successfully.
136479  **
136480  */
136481  if( yypParser->yyerrcnt<0 ){
136482  yy_syntax_error(yypParser,yymajor,yyminor);
136483  }
136484  yymx = yypParser->yytos->major;
136485  if( yymx==YYERRORSYMBOL || yyerrorhit ){
136486 #ifndef NDEBUG
136487  if( yyTraceFILE ){
136488  fprintf(yyTraceFILE,"%sDiscard input token %s\n",
136489  yyTracePrompt,yyTokenName[yymajor]);
136490  }
136491 #endif
136492  yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
136493  yymajor = YYNOCODE;
136494  }else{
136495  while( yypParser->yytos >= yypParser->yystack
136496  && yymx != YYERRORSYMBOL
136497  && (yyact = yy_find_reduce_action(
136498  yypParser->yytos->stateno,
136499  YYERRORSYMBOL)) >= YY_MIN_REDUCE
136500  ){
136501  yy_pop_parser_stack(yypParser);
136502  }
136503  if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
136504  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
136505  yy_parse_failed(yypParser);
136506 #ifndef YYNOERRORRECOVERY
136507  yypParser->yyerrcnt = -1;
136508 #endif
136509  yymajor = YYNOCODE;
136510  }else if( yymx!=YYERRORSYMBOL ){
136511  yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
136512  }
136513  }
136514  yypParser->yyerrcnt = 3;
136515  yyerrorhit = 1;
136516 #elif defined(YYNOERRORRECOVERY)
136517  /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
136518  ** do any kind of error recovery. Instead, simply invoke the syntax
136519  ** error routine and continue going as if nothing had happened.
136520  **
136521  ** Applications can set this macro (for example inside %include) if
136522  ** they intend to abandon the parse upon the first syntax error seen.
136523  */
136524  yy_syntax_error(yypParser,yymajor, yyminor);
136525  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
136526  yymajor = YYNOCODE;
136527 
136528 #else /* YYERRORSYMBOL is not defined */
136529  /* This is what we do if the grammar does not define ERROR:
136530  **
136531  ** * Report an error message, and throw away the input token.
136532  **
136533  ** * If the input token is $, then fail the parse.
136534  **
136535  ** As before, subsequent error messages are suppressed until
136536  ** three input tokens have been successfully shifted.
136537  */
136538  if( yypParser->yyerrcnt<=0 ){
136539  yy_syntax_error(yypParser,yymajor, yyminor);
136540  }
136541  yypParser->yyerrcnt = 3;
136542  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
136543  if( yyendofinput ){
136544  yy_parse_failed(yypParser);
136545 #ifndef YYNOERRORRECOVERY
136546  yypParser->yyerrcnt = -1;
136547 #endif
136548  }
136549  yymajor = YYNOCODE;
136550 #endif
136551  }
136552  }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
136553 #ifndef NDEBUG
136554  if( yyTraceFILE ){
136555  yyStackEntry *i;
136556  char cDiv = '[';
136557  fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
136558  for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
136559  fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
136560  cDiv = ' ';
136561  }
136562  fprintf(yyTraceFILE,"]\n");
136563  }
136564 #endif
136565  return;
136566 }
136567 
136568 /************** End of parse.c ***********************************************/
136569 /************** Begin file tokenize.c ****************************************/
136570 /*
136571 ** 2001 September 15
136572 **
136573 ** The author disclaims copyright to this source code. In place of
136574 ** a legal notice, here is a blessing:
136575 **
136576 ** May you do good and not evil.
136577 ** May you find forgiveness for yourself and forgive others.
136578 ** May you share freely, never taking more than you give.
136579 **
136580 *************************************************************************
136581 ** An tokenizer for SQL
136582 **
136583 ** This file contains C code that splits an SQL input string up into
136584 ** individual tokens and sends those tokens one-by-one over to the
136585 ** parser for analysis.
136586 */
136587 /* #include "sqliteInt.h" */
136588 /* #include <stdlib.h> */
136589 
136590 /* Character classes for tokenizing
136591 **
136592 ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
136593 ** using a lookup table, whereas a switch() directly on c uses a binary search.
136594 ** The lookup table is much faster. To maximize speed, and to ensure that
136595 ** a lookup table is used, all of the classes need to be small integers and
136596 ** all of them need to be used within the switch.
136597 */
136598 #define CC_X 0 /* The letter 'x', or start of BLOB literal */
136599 #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
136600 #define CC_ID 2 /* unicode characters usable in IDs */
136601 #define CC_DIGIT 3 /* Digits */
136602 #define CC_DOLLAR 4 /* '$' */
136603 #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
136604 #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
136605 #define CC_SPACE 7 /* Space characters */
136606 #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
136607 #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
136608 #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
136609 #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
136610 #define CC_LT 12 /* '<'. Part of < or <= or <> */
136611 #define CC_GT 13 /* '>'. Part of > or >= */
136612 #define CC_EQ 14 /* '='. Part of = or == */
136613 #define CC_BANG 15 /* '!'. Part of != */
136614 #define CC_SLASH 16 /* '/'. / or c-style comment */
136615 #define CC_LP 17 /* '(' */
136616 #define CC_RP 18 /* ')' */
136617 #define CC_SEMI 19 /* ';' */
136618 #define CC_PLUS 20 /* '+' */
136619 #define CC_STAR 21 /* '*' */
136620 #define CC_PERCENT 22 /* '%' */
136621 #define CC_COMMA 23 /* ',' */
136622 #define CC_AND 24 /* '&' */
136623 #define CC_TILDA 25 /* '~' */
136624 #define CC_DOT 26 /* '.' */
136625 #define CC_ILLEGAL 27 /* Illegal character */
136626 
136627 static const unsigned char aiClass[] = {
136628 #ifdef SQLITE_ASCII
136629 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
136630 /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
136631 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136632 /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
136633 /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
136634 /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
136635 /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
136636 /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
136637 /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
136638 /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136639 /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136640 /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136641 /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136642 /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136643 /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136644 /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
136645 /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
136646 #endif
136647 #ifdef SQLITE_EBCDIC
136648 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
136649 /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
136650 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136651 /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136652 /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
136653 /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10,
136654 /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
136655 /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 7,
136656 /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
136657 /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136658 /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136659 /* 9x */ 25, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
136660 /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
136661 /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136662 /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
136663 /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
136664 /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
136665 #endif
136666 };
136667 
136668 /*
136669 ** The charMap() macro maps alphabetic characters (only) into their
136670 ** lower-case ASCII equivalent. On ASCII machines, this is just
136671 ** an upper-to-lower case map. On EBCDIC machines we also need
136672 ** to adjust the encoding. The mapping is only valid for alphabetics
136673 ** which are the only characters for which this feature is used.
136674 **
136675 ** Used by keywordhash.h
136676 */
136677 #ifdef SQLITE_ASCII
136678 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
136679 #endif
136680 #ifdef SQLITE_EBCDIC
136681 # define charMap(X) ebcdicToAscii[(unsigned char)X]
136682 const unsigned char ebcdicToAscii[] = {
136683 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
136684  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
136685  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
136686  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
136687  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
136688  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
136689  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
136690  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
136691  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
136692  0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
136693  0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
136694  0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
136695  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
136696  0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
136697  0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
136698  0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
136699  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
136700 };
136701 #endif
136702 
136703 /*
136704 ** The sqlite3KeywordCode function looks up an identifier to determine if
136705 ** it is a keyword. If it is a keyword, the token code of that keyword is
136706 ** returned. If the input is not a keyword, TK_ID is returned.
136707 **
136708 ** The implementation of this routine was generated by a program,
136709 ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
136710 ** The output of the mkkeywordhash.c program is written into a file
136711 ** named keywordhash.h and then included into this source file by
136712 ** the #include below.
136713 */
136714 /************** Include keywordhash.h in the middle of tokenize.c ************/
136715 /************** Begin file keywordhash.h *************************************/
136716 /***** This file contains automatically generated code ******
136717 **
136718 ** The code in this file has been automatically generated by
136719 **
136720 ** sqlite/tool/mkkeywordhash.c
136721 **
136722 ** The code in this file implements a function that determines whether
136723 ** or not a given identifier is really an SQL keyword. The same thing
136724 ** might be implemented more directly using a hand-written hash table.
136725 ** But by using this automatically generated code, the size of the code
136726 ** is substantially reduced. This is important for embedded applications
136727 ** on platforms with limited memory.
136728 */
136729 /* Hash score: 182 */
136730 static int keywordCode(const char *z, int n, int *pType){
136731  /* zText[] encodes 834 bytes of keywords in 554 bytes */
136732  /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
136733  /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
136734  /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
136735  /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
136736  /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
136737  /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
136738  /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
136739  /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
136740  /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
136741  /* VACUUMVIEWINITIALLY */
136742  static const char zText[553] = {
136743  'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
136744  'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
136745  'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
136746  'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
136747  'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
136748  'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
136749  'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
136750  'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
136751  'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
136752  'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
136753  'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
136754  'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
136755  'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
136756  'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
136757  'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
136758  'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
136759  'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
136760  'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
136761  'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
136762  'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
136763  'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
136764  'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
136765  'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
136766  'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
136767  'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
136768  'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
136769  'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
136770  'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
136771  'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
136772  'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
136773  'V','I','E','W','I','N','I','T','I','A','L','L','Y',
136774  };
136775  static const unsigned char aHash[127] = {
136776  76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
136777  42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
136778  121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
136779  0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
136780  0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
136781  96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
136782  100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
136783  39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
136784  62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
136785  29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
136786  };
136787  static const unsigned char aNext[124] = {
136788  0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
136789  0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
136790  0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
136791  0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
136792  0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
136793  0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
136794  0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
136795  10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
136796  0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
136797  73, 83, 0, 35, 68, 0, 0,
136798  };
136799  static const unsigned char aLen[124] = {
136800  7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
136801  7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
136802  11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
136803  4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
136804  6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
136805  7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
136806  7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
136807  13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
136808  2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
136809  3, 5, 5, 6, 4, 9, 3,
136810  };
136811  static const unsigned short int aOffset[124] = {
136812  0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
136813  36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
136814  86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
136815  159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
136816  199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
136817  250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
136818  320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
136819  387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
136820  460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
136821  521, 524, 529, 534, 540, 544, 549,
136822  };
136823  static const unsigned char aCode[124] = {
136849  };
136850  int i, j;
136851  const char *zKW;
136852  if( n>=2 ){
136853  i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
136854  for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
136855  if( aLen[i]!=n ) continue;
136856  j = 0;
136857  zKW = &zText[aOffset[i]];
136858 #ifdef SQLITE_ASCII
136859  while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
136860 #endif
136861 #ifdef SQLITE_EBCDIC
136862  while( j<n && toupper(z[j])==zKW[j] ){ j++; }
136863 #endif
136864  if( j<n ) continue;
136865  testcase( i==0 ); /* REINDEX */
136866  testcase( i==1 ); /* INDEXED */
136867  testcase( i==2 ); /* INDEX */
136868  testcase( i==3 ); /* DESC */
136869  testcase( i==4 ); /* ESCAPE */
136870  testcase( i==5 ); /* EACH */
136871  testcase( i==6 ); /* CHECK */
136872  testcase( i==7 ); /* KEY */
136873  testcase( i==8 ); /* BEFORE */
136874  testcase( i==9 ); /* FOREIGN */
136875  testcase( i==10 ); /* FOR */
136876  testcase( i==11 ); /* IGNORE */
136877  testcase( i==12 ); /* REGEXP */
136878  testcase( i==13 ); /* EXPLAIN */
136879  testcase( i==14 ); /* INSTEAD */
136880  testcase( i==15 ); /* ADD */
136881  testcase( i==16 ); /* DATABASE */
136882  testcase( i==17 ); /* AS */
136883  testcase( i==18 ); /* SELECT */
136884  testcase( i==19 ); /* TABLE */
136885  testcase( i==20 ); /* LEFT */
136886  testcase( i==21 ); /* THEN */
136887  testcase( i==22 ); /* END */
136888  testcase( i==23 ); /* DEFERRABLE */
136889  testcase( i==24 ); /* ELSE */
136890  testcase( i==25 ); /* EXCEPT */
136891  testcase( i==26 ); /* TRANSACTION */
136892  testcase( i==27 ); /* ACTION */
136893  testcase( i==28 ); /* ON */
136894  testcase( i==29 ); /* NATURAL */
136895  testcase( i==30 ); /* ALTER */
136896  testcase( i==31 ); /* RAISE */
136897  testcase( i==32 ); /* EXCLUSIVE */
136898  testcase( i==33 ); /* EXISTS */
136899  testcase( i==34 ); /* SAVEPOINT */
136900  testcase( i==35 ); /* INTERSECT */
136901  testcase( i==36 ); /* TRIGGER */
136902  testcase( i==37 ); /* REFERENCES */
136903  testcase( i==38 ); /* CONSTRAINT */
136904  testcase( i==39 ); /* INTO */
136905  testcase( i==40 ); /* OFFSET */
136906  testcase( i==41 ); /* OF */
136907  testcase( i==42 ); /* SET */
136908  testcase( i==43 ); /* TEMPORARY */
136909  testcase( i==44 ); /* TEMP */
136910  testcase( i==45 ); /* OR */
136911  testcase( i==46 ); /* UNIQUE */
136912  testcase( i==47 ); /* QUERY */
136913  testcase( i==48 ); /* WITHOUT */
136914  testcase( i==49 ); /* WITH */
136915  testcase( i==50 ); /* OUTER */
136916  testcase( i==51 ); /* RELEASE */
136917  testcase( i==52 ); /* ATTACH */
136918  testcase( i==53 ); /* HAVING */
136919  testcase( i==54 ); /* GROUP */
136920  testcase( i==55 ); /* UPDATE */
136921  testcase( i==56 ); /* BEGIN */
136922  testcase( i==57 ); /* INNER */
136923  testcase( i==58 ); /* RECURSIVE */
136924  testcase( i==59 ); /* BETWEEN */
136925  testcase( i==60 ); /* NOTNULL */
136926  testcase( i==61 ); /* NOT */
136927  testcase( i==62 ); /* NO */
136928  testcase( i==63 ); /* NULL */
136929  testcase( i==64 ); /* LIKE */
136930  testcase( i==65 ); /* CASCADE */
136931  testcase( i==66 ); /* ASC */
136932  testcase( i==67 ); /* DELETE */
136933  testcase( i==68 ); /* CASE */
136934  testcase( i==69 ); /* COLLATE */
136935  testcase( i==70 ); /* CREATE */
136936  testcase( i==71 ); /* CURRENT_DATE */
136937  testcase( i==72 ); /* DETACH */
136938  testcase( i==73 ); /* IMMEDIATE */
136939  testcase( i==74 ); /* JOIN */
136940  testcase( i==75 ); /* INSERT */
136941  testcase( i==76 ); /* MATCH */
136942  testcase( i==77 ); /* PLAN */
136943  testcase( i==78 ); /* ANALYZE */
136944  testcase( i==79 ); /* PRAGMA */
136945  testcase( i==80 ); /* ABORT */
136946  testcase( i==81 ); /* VALUES */
136947  testcase( i==82 ); /* VIRTUAL */
136948  testcase( i==83 ); /* LIMIT */
136949  testcase( i==84 ); /* WHEN */
136950  testcase( i==85 ); /* WHERE */
136951  testcase( i==86 ); /* RENAME */
136952  testcase( i==87 ); /* AFTER */
136953  testcase( i==88 ); /* REPLACE */
136954  testcase( i==89 ); /* AND */
136955  testcase( i==90 ); /* DEFAULT */
136956  testcase( i==91 ); /* AUTOINCREMENT */
136957  testcase( i==92 ); /* TO */
136958  testcase( i==93 ); /* IN */
136959  testcase( i==94 ); /* CAST */
136960  testcase( i==95 ); /* COLUMN */
136961  testcase( i==96 ); /* COMMIT */
136962  testcase( i==97 ); /* CONFLICT */
136963  testcase( i==98 ); /* CROSS */
136964  testcase( i==99 ); /* CURRENT_TIMESTAMP */
136965  testcase( i==100 ); /* CURRENT_TIME */
136966  testcase( i==101 ); /* PRIMARY */
136967  testcase( i==102 ); /* DEFERRED */
136968  testcase( i==103 ); /* DISTINCT */
136969  testcase( i==104 ); /* IS */
136970  testcase( i==105 ); /* DROP */
136971  testcase( i==106 ); /* FAIL */
136972  testcase( i==107 ); /* FROM */
136973  testcase( i==108 ); /* FULL */
136974  testcase( i==109 ); /* GLOB */
136975  testcase( i==110 ); /* BY */
136976  testcase( i==111 ); /* IF */
136977  testcase( i==112 ); /* ISNULL */
136978  testcase( i==113 ); /* ORDER */
136979  testcase( i==114 ); /* RESTRICT */
136980  testcase( i==115 ); /* RIGHT */
136981  testcase( i==116 ); /* ROLLBACK */
136982  testcase( i==117 ); /* ROW */
136983  testcase( i==118 ); /* UNION */
136984  testcase( i==119 ); /* USING */
136985  testcase( i==120 ); /* VACUUM */
136986  testcase( i==121 ); /* VIEW */
136987  testcase( i==122 ); /* INITIALLY */
136988  testcase( i==123 ); /* ALL */
136989  *pType = aCode[i];
136990  break;
136991  }
136992  }
136993  return n;
136994 }
136995 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
136996  int id = TK_ID;
136997  keywordCode((char*)z, n, &id);
136998  return id;
136999 }
137000 #define SQLITE_N_KEYWORD 124
137001 
137002 /************** End of keywordhash.h *****************************************/
137003 /************** Continuing where we left off in tokenize.c *******************/
137004 
137005 
137006 /*
137007 ** If X is a character that can be used in an identifier then
137008 ** IdChar(X) will be true. Otherwise it is false.
137009 **
137010 ** For ASCII, any character with the high-order bit set is
137011 ** allowed in an identifier. For 7-bit characters,
137012 ** sqlite3IsIdChar[X] must be 1.
137013 **
137014 ** For EBCDIC, the rules are more complex but have the same
137015 ** end result.
137016 **
137017 ** Ticket #1066. the SQL standard does not allow '$' in the
137018 ** middle of identifiers. But many SQL implementations do.
137019 ** SQLite will allow '$' in identifiers for compatibility.
137020 ** But the feature is undocumented.
137021 */
137022 #ifdef SQLITE_ASCII
137023 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
137024 #endif
137025 #ifdef SQLITE_EBCDIC
137026 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
137027 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
137028  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
137029  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
137030  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
137031  0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
137032  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
137033  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
137034  1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
137035  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
137036  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
137037  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
137038  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
137039  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
137040 };
137041 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
137042 #endif
137043 
137044 /* Make the IdChar function accessible from ctime.c */
137045 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
137046 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
137047 #endif
137048 
137049 
137050 /*
137051 ** Return the length (in bytes) of the token that begins at z[0].
137052 ** Store the token type in *tokenType before returning.
137053 */
137054 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
137055  int i, c;
137056  switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
137057  ** of the token. See the comment on the CC_ defines
137058  ** above. */
137059  case CC_SPACE: {
137060  testcase( z[0]==' ' );
137061  testcase( z[0]=='\t' );
137062  testcase( z[0]=='\n' );
137063  testcase( z[0]=='\f' );
137064  testcase( z[0]=='\r' );
137065  for(i=1; sqlite3Isspace(z[i]); i++){}
137066  *tokenType = TK_SPACE;
137067  return i;
137068  }
137069  case CC_MINUS: {
137070  if( z[1]=='-' ){
137071  for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
137072  *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
137073  return i;
137074  }
137075  *tokenType = TK_MINUS;
137076  return 1;
137077  }
137078  case CC_LP: {
137079  *tokenType = TK_LP;
137080  return 1;
137081  }
137082  case CC_RP: {
137083  *tokenType = TK_RP;
137084  return 1;
137085  }
137086  case CC_SEMI: {
137087  *tokenType = TK_SEMI;
137088  return 1;
137089  }
137090  case CC_PLUS: {
137091  *tokenType = TK_PLUS;
137092  return 1;
137093  }
137094  case CC_STAR: {
137095  *tokenType = TK_STAR;
137096  return 1;
137097  }
137098  case CC_SLASH: {
137099  if( z[1]!='*' || z[2]==0 ){
137100  *tokenType = TK_SLASH;
137101  return 1;
137102  }
137103  for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
137104  if( c ) i++;
137105  *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
137106  return i;
137107  }
137108  case CC_PERCENT: {
137109  *tokenType = TK_REM;
137110  return 1;
137111  }
137112  case CC_EQ: {
137113  *tokenType = TK_EQ;
137114  return 1 + (z[1]=='=');
137115  }
137116  case CC_LT: {
137117  if( (c=z[1])=='=' ){
137118  *tokenType = TK_LE;
137119  return 2;
137120  }else if( c=='>' ){
137121  *tokenType = TK_NE;
137122  return 2;
137123  }else if( c=='<' ){
137124  *tokenType = TK_LSHIFT;
137125  return 2;
137126  }else{
137127  *tokenType = TK_LT;
137128  return 1;
137129  }
137130  }
137131  case CC_GT: {
137132  if( (c=z[1])=='=' ){
137133  *tokenType = TK_GE;
137134  return 2;
137135  }else if( c=='>' ){
137136  *tokenType = TK_RSHIFT;
137137  return 2;
137138  }else{
137139  *tokenType = TK_GT;
137140  return 1;
137141  }
137142  }
137143  case CC_BANG: {
137144  if( z[1]!='=' ){
137145  *tokenType = TK_ILLEGAL;
137146  return 1;
137147  }else{
137148  *tokenType = TK_NE;
137149  return 2;
137150  }
137151  }
137152  case CC_PIPE: {
137153  if( z[1]!='|' ){
137154  *tokenType = TK_BITOR;
137155  return 1;
137156  }else{
137157  *tokenType = TK_CONCAT;
137158  return 2;
137159  }
137160  }
137161  case CC_COMMA: {
137162  *tokenType = TK_COMMA;
137163  return 1;
137164  }
137165  case CC_AND: {
137166  *tokenType = TK_BITAND;
137167  return 1;
137168  }
137169  case CC_TILDA: {
137170  *tokenType = TK_BITNOT;
137171  return 1;
137172  }
137173  case CC_QUOTE: {
137174  int delim = z[0];
137175  testcase( delim=='`' );
137176  testcase( delim=='\'' );
137177  testcase( delim=='"' );
137178  for(i=1; (c=z[i])!=0; i++){
137179  if( c==delim ){
137180  if( z[i+1]==delim ){
137181  i++;
137182  }else{
137183  break;
137184  }
137185  }
137186  }
137187  if( c=='\'' ){
137188  *tokenType = TK_STRING;
137189  return i+1;
137190  }else if( c!=0 ){
137191  *tokenType = TK_ID;
137192  return i+1;
137193  }else{
137194  *tokenType = TK_ILLEGAL;
137195  return i;
137196  }
137197  }
137198  case CC_DOT: {
137199 #ifndef SQLITE_OMIT_FLOATING_POINT
137200  if( !sqlite3Isdigit(z[1]) )
137201 #endif
137202  {
137203  *tokenType = TK_DOT;
137204  return 1;
137205  }
137206  /* If the next character is a digit, this is a floating point
137207  ** number that begins with ".". Fall thru into the next case */
137208  }
137209  case CC_DIGIT: {
137210  testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
137211  testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
137212  testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
137213  testcase( z[0]=='9' );
137214  *tokenType = TK_INTEGER;
137215 #ifndef SQLITE_OMIT_HEX_INTEGER
137216  if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
137217  for(i=3; sqlite3Isxdigit(z[i]); i++){}
137218  return i;
137219  }
137220 #endif
137221  for(i=0; sqlite3Isdigit(z[i]); i++){}
137222 #ifndef SQLITE_OMIT_FLOATING_POINT
137223  if( z[i]=='.' ){
137224  i++;
137225  while( sqlite3Isdigit(z[i]) ){ i++; }
137226  *tokenType = TK_FLOAT;
137227  }
137228  if( (z[i]=='e' || z[i]=='E') &&
137229  ( sqlite3Isdigit(z[i+1])
137230  || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
137231  )
137232  ){
137233  i += 2;
137234  while( sqlite3Isdigit(z[i]) ){ i++; }
137235  *tokenType = TK_FLOAT;
137236  }
137237 #endif
137238  while( IdChar(z[i]) ){
137239  *tokenType = TK_ILLEGAL;
137240  i++;
137241  }
137242  return i;
137243  }
137244  case CC_QUOTE2: {
137245  for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
137246  *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
137247  return i;
137248  }
137249  case CC_VARNUM: {
137250  *tokenType = TK_VARIABLE;
137251  for(i=1; sqlite3Isdigit(z[i]); i++){}
137252  return i;
137253  }
137254  case CC_DOLLAR:
137255  case CC_VARALPHA: {
137256  int n = 0;
137257  testcase( z[0]=='$' ); testcase( z[0]=='@' );
137258  testcase( z[0]==':' ); testcase( z[0]=='#' );
137259  *tokenType = TK_VARIABLE;
137260  for(i=1; (c=z[i])!=0; i++){
137261  if( IdChar(c) ){
137262  n++;
137263 #ifndef SQLITE_OMIT_TCL_VARIABLE
137264  }else if( c=='(' && n>0 ){
137265  do{
137266  i++;
137267  }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
137268  if( c==')' ){
137269  i++;
137270  }else{
137271  *tokenType = TK_ILLEGAL;
137272  }
137273  break;
137274  }else if( c==':' && z[i+1]==':' ){
137275  i++;
137276 #endif
137277  }else{
137278  break;
137279  }
137280  }
137281  if( n==0 ) *tokenType = TK_ILLEGAL;
137282  return i;
137283  }
137284  case CC_KYWD: {
137285  for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
137286  if( IdChar(z[i]) ){
137287  /* This token started out using characters that can appear in keywords,
137288  ** but z[i] is a character not allowed within keywords, so this must
137289  ** be an identifier instead */
137290  i++;
137291  break;
137292  }
137293  *tokenType = TK_ID;
137294  return keywordCode((char*)z, i, tokenType);
137295  }
137296  case CC_X: {
137297 #ifndef SQLITE_OMIT_BLOB_LITERAL
137298  testcase( z[0]=='x' ); testcase( z[0]=='X' );
137299  if( z[1]=='\'' ){
137300  *tokenType = TK_BLOB;
137301  for(i=2; sqlite3Isxdigit(z[i]); i++){}
137302  if( z[i]!='\'' || i%2 ){
137303  *tokenType = TK_ILLEGAL;
137304  while( z[i] && z[i]!='\'' ){ i++; }
137305  }
137306  if( z[i] ) i++;
137307  return i;
137308  }
137309 #endif
137310  /* If it is not a BLOB literal, then it must be an ID, since no
137311  ** SQL keywords start with the letter 'x'. Fall through */
137312  }
137313  case CC_ID: {
137314  i = 1;
137315  break;
137316  }
137317  default: {
137318  *tokenType = TK_ILLEGAL;
137319  return 1;
137320  }
137321  }
137322  while( IdChar(z[i]) ){ i++; }
137323  *tokenType = TK_ID;
137324  return i;
137325 }
137326 
137327 /*
137328 ** Run the parser on the given SQL string. The parser structure is
137329 ** passed in. An SQLITE_ status code is returned. If an error occurs
137330 ** then an and attempt is made to write an error message into
137331 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
137332 ** error message.
137333 */
137334 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
137335  int nErr = 0; /* Number of errors encountered */
137336  int i; /* Loop counter */
137337  void *pEngine; /* The LEMON-generated LALR(1) parser */
137338  int tokenType; /* type of the next token */
137339  int lastTokenParsed = -1; /* type of the previous token */
137340  sqlite3 *db = pParse->db; /* The database connection */
137341  int mxSqlLen; /* Max length of an SQL string */
137342 
137343  assert( zSql!=0 );
137344  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
137345  if( db->nVdbeActive==0 ){
137346  db->u1.isInterrupted = 0;
137347  }
137348  pParse->rc = SQLITE_OK;
137349  pParse->zTail = zSql;
137350  i = 0;
137351  assert( pzErrMsg!=0 );
137352  /* sqlite3ParserTrace(stdout, "parser: "); */
137353  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
137354  if( pEngine==0 ){
137355  sqlite3OomFault(db);
137356  return SQLITE_NOMEM_BKPT;
137357  }
137358  assert( pParse->pNewTable==0 );
137359  assert( pParse->pNewTrigger==0 );
137360  assert( pParse->nVar==0 );
137361  assert( pParse->nzVar==0 );
137362  assert( pParse->azVar==0 );
137363  while( 1 ){
137364  assert( i>=0 );
137365  if( zSql[i]!=0 ){
137366  pParse->sLastToken.z = &zSql[i];
137367  pParse->sLastToken.n = sqlite3GetToken((u8*)&zSql[i],&tokenType);
137368  i += pParse->sLastToken.n;
137369  if( i>mxSqlLen ){
137370  pParse->rc = SQLITE_TOOBIG;
137371  break;
137372  }
137373  }else{
137374  /* Upon reaching the end of input, call the parser two more times
137375  ** with tokens TK_SEMI and 0, in that order. */
137376  if( lastTokenParsed==TK_SEMI ){
137377  tokenType = 0;
137378  }else if( lastTokenParsed==0 ){
137379  break;
137380  }else{
137381  tokenType = TK_SEMI;
137382  }
137383  }
137384  if( tokenType>=TK_SPACE ){
137385  assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
137386  if( db->u1.isInterrupted ){
137387  pParse->rc = SQLITE_INTERRUPT;
137388  break;
137389  }
137390  if( tokenType==TK_ILLEGAL ){
137391  sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
137392  &pParse->sLastToken);
137393  break;
137394  }
137395  }else{
137396  sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
137397  lastTokenParsed = tokenType;
137398  if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
137399  }
137400  }
137401  assert( nErr==0 );
137402  pParse->zTail = &zSql[i];
137403 #ifdef YYTRACKMAXSTACKDEPTH
137406  sqlite3ParserStackPeak(pEngine)
137407  );
137409 #endif /* YYDEBUG */
137410  sqlite3ParserFree(pEngine, sqlite3_free);
137411  if( db->mallocFailed ){
137412  pParse->rc = SQLITE_NOMEM_BKPT;
137413  }
137414  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
137415  pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
137416  }
137417  assert( pzErrMsg!=0 );
137418  if( pParse->zErrMsg ){
137419  *pzErrMsg = pParse->zErrMsg;
137420  sqlite3_log(pParse->rc, "%s", *pzErrMsg);
137421  pParse->zErrMsg = 0;
137422  nErr++;
137423  }
137424  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
137425  sqlite3VdbeDelete(pParse->pVdbe);
137426  pParse->pVdbe = 0;
137427  }
137428 #ifndef SQLITE_OMIT_SHARED_CACHE
137429  if( pParse->nested==0 ){
137430  sqlite3DbFree(db, pParse->aTableLock);
137431  pParse->aTableLock = 0;
137432  pParse->nTableLock = 0;
137433  }
137434 #endif
137435 #ifndef SQLITE_OMIT_VIRTUALTABLE
137436  sqlite3_free(pParse->apVtabLock);
137437 #endif
137438 
137439  if( !IN_DECLARE_VTAB ){
137440  /* If the pParse->declareVtab flag is set, do not delete any table
137441  ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
137442  ** will take responsibility for freeing the Table structure.
137443  */
137444  sqlite3DeleteTable(db, pParse->pNewTable);
137445  }
137446 
137447  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
137448  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
137449  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
137450  sqlite3DbFree(db, pParse->azVar);
137451  while( pParse->pAinc ){
137452  AutoincInfo *p = pParse->pAinc;
137453  pParse->pAinc = p->pNext;
137454  sqlite3DbFree(db, p);
137455  }
137456  while( pParse->pZombieTab ){
137457  Table *p = pParse->pZombieTab;
137458  pParse->pZombieTab = p->pNextZombie;
137459  sqlite3DeleteTable(db, p);
137460  }
137461  assert( nErr==0 || pParse->rc!=SQLITE_OK );
137462  return nErr;
137463 }
137464 
137465 /************** End of tokenize.c ********************************************/
137466 /************** Begin file complete.c ****************************************/
137467 /*
137468 ** 2001 September 15
137469 **
137470 ** The author disclaims copyright to this source code. In place of
137471 ** a legal notice, here is a blessing:
137472 **
137473 ** May you do good and not evil.
137474 ** May you find forgiveness for yourself and forgive others.
137475 ** May you share freely, never taking more than you give.
137476 **
137477 *************************************************************************
137478 ** An tokenizer for SQL
137479 **
137480 ** This file contains C code that implements the sqlite3_complete() API.
137481 ** This code used to be part of the tokenizer.c source file. But by
137482 ** separating it out, the code will be automatically omitted from
137483 ** static links that do not use it.
137484 */
137485 /* #include "sqliteInt.h" */
137486 #ifndef SQLITE_OMIT_COMPLETE
137487 
137488 /*
137489 ** This is defined in tokenize.c. We just have to import the definition.
137490 */
137491 #ifndef SQLITE_AMALGAMATION
137492 #ifdef SQLITE_ASCII
137493 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
137494 #endif
137495 #ifdef SQLITE_EBCDIC
137496 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
137497 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
137498 #endif
137499 #endif /* SQLITE_AMALGAMATION */
137500 
137501 
137502 /*
137503 ** Token types used by the sqlite3_complete() routine. See the header
137504 ** comments on that procedure for additional information.
137505 */
137506 #define tkSEMI 0
137507 #define tkWS 1
137508 #define tkOTHER 2
137509 #ifndef SQLITE_OMIT_TRIGGER
137510 #define tkEXPLAIN 3
137511 #define tkCREATE 4
137512 #define tkTEMP 5
137513 #define tkTRIGGER 6
137514 #define tkEND 7
137515 #endif
137516 
137517 /*
137518 ** Return TRUE if the given SQL string ends in a semicolon.
137519 **
137520 ** Special handling is require for CREATE TRIGGER statements.
137521 ** Whenever the CREATE TRIGGER keywords are seen, the statement
137522 ** must end with ";END;".
137523 **
137524 ** This implementation uses a state machine with 8 states:
137525 **
137526 ** (0) INVALID We have not yet seen a non-whitespace character.
137527 **
137528 ** (1) START At the beginning or end of an SQL statement. This routine
137529 ** returns 1 if it ends in the START state and 0 if it ends
137530 ** in any other state.
137531 **
137532 ** (2) NORMAL We are in the middle of statement which ends with a single
137533 ** semicolon.
137534 **
137535 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
137536 ** a statement.
137537 **
137538 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
137539 ** statement, possibly preceded by EXPLAIN and/or followed by
137540 ** TEMP or TEMPORARY
137541 **
137542 ** (5) TRIGGER We are in the middle of a trigger definition that must be
137543 ** ended by a semicolon, the keyword END, and another semicolon.
137544 **
137545 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
137546 ** the end of a trigger definition.
137547 **
137548 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
137549 ** of a trigger definition.
137550 **
137551 ** Transitions between states above are determined by tokens extracted
137552 ** from the input. The following tokens are significant:
137553 **
137554 ** (0) tkSEMI A semicolon.
137555 ** (1) tkWS Whitespace.
137556 ** (2) tkOTHER Any other SQL token.
137557 ** (3) tkEXPLAIN The "explain" keyword.
137558 ** (4) tkCREATE The "create" keyword.
137559 ** (5) tkTEMP The "temp" or "temporary" keyword.
137560 ** (6) tkTRIGGER The "trigger" keyword.
137561 ** (7) tkEND The "end" keyword.
137562 **
137563 ** Whitespace never causes a state transition and is always ignored.
137564 ** This means that a SQL string of all whitespace is invalid.
137565 **
137566 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
137567 ** to recognize the end of a trigger can be omitted. All we have to do
137568 ** is look for a semicolon that is not part of an string or comment.
137569 */
137570 SQLITE_API int sqlite3_complete(const char *zSql){
137571  u8 state = 0; /* Current state, using numbers defined in header comment */
137572  u8 token; /* Value of the next token */
137573 
137574 #ifndef SQLITE_OMIT_TRIGGER
137575  /* A complex statement machine used to detect the end of a CREATE TRIGGER
137576  ** statement. This is the normal case.
137577  */
137578  static const u8 trans[8][8] = {
137579  /* Token: */
137580  /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
137581  /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
137582  /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
137583  /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
137584  /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
137585  /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
137586  /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
137587  /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
137588  /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
137589  };
137590 #else
137591  /* If triggers are not supported by this compile then the statement machine
137592  ** used to detect the end of a statement is much simpler
137593  */
137594  static const u8 trans[3][3] = {
137595  /* Token: */
137596  /* State: ** SEMI WS OTHER */
137597  /* 0 INVALID: */ { 1, 0, 2, },
137598  /* 1 START: */ { 1, 1, 2, },
137599  /* 2 NORMAL: */ { 1, 2, 2, },
137600  };
137601 #endif /* SQLITE_OMIT_TRIGGER */
137602 
137603 #ifdef SQLITE_ENABLE_API_ARMOR
137604  if( zSql==0 ){
137605  (void)SQLITE_MISUSE_BKPT;
137606  return 0;
137607  }
137608 #endif
137609 
137610  while( *zSql ){
137611  switch( *zSql ){
137612  case ';': { /* A semicolon */
137613  token = tkSEMI;
137614  break;
137615  }
137616  case ' ':
137617  case '\r':
137618  case '\t':
137619  case '\n':
137620  case '\f': { /* White space is ignored */
137621  token = tkWS;
137622  break;
137623  }
137624  case '/': { /* C-style comments */
137625  if( zSql[1]!='*' ){
137626  token = tkOTHER;
137627  break;
137628  }
137629  zSql += 2;
137630  while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
137631  if( zSql[0]==0 ) return 0;
137632  zSql++;
137633  token = tkWS;
137634  break;
137635  }
137636  case '-': { /* SQL-style comments from "--" to end of line */
137637  if( zSql[1]!='-' ){
137638  token = tkOTHER;
137639  break;
137640  }
137641  while( *zSql && *zSql!='\n' ){ zSql++; }
137642  if( *zSql==0 ) return state==1;
137643  token = tkWS;
137644  break;
137645  }
137646  case '[': { /* Microsoft-style identifiers in [...] */
137647  zSql++;
137648  while( *zSql && *zSql!=']' ){ zSql++; }
137649  if( *zSql==0 ) return 0;
137650  token = tkOTHER;
137651  break;
137652  }
137653  case '`': /* Grave-accent quoted symbols used by MySQL */
137654  case '"': /* single- and double-quoted strings */
137655  case '\'': {
137656  int c = *zSql;
137657  zSql++;
137658  while( *zSql && *zSql!=c ){ zSql++; }
137659  if( *zSql==0 ) return 0;
137660  token = tkOTHER;
137661  break;
137662  }
137663  default: {
137664 #ifdef SQLITE_EBCDIC
137665  unsigned char c;
137666 #endif
137667  if( IdChar((u8)*zSql) ){
137668  /* Keywords and unquoted identifiers */
137669  int nId;
137670  for(nId=1; IdChar(zSql[nId]); nId++){}
137671 #ifdef SQLITE_OMIT_TRIGGER
137672  token = tkOTHER;
137673 #else
137674  switch( *zSql ){
137675  case 'c': case 'C': {
137676  if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
137677  token = tkCREATE;
137678  }else{
137679  token = tkOTHER;
137680  }
137681  break;
137682  }
137683  case 't': case 'T': {
137684  if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
137685  token = tkTRIGGER;
137686  }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
137687  token = tkTEMP;
137688  }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
137689  token = tkTEMP;
137690  }else{
137691  token = tkOTHER;
137692  }
137693  break;
137694  }
137695  case 'e': case 'E': {
137696  if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
137697  token = tkEND;
137698  }else
137699 #ifndef SQLITE_OMIT_EXPLAIN
137700  if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
137701  token = tkEXPLAIN;
137702  }else
137703 #endif
137704  {
137705  token = tkOTHER;
137706  }
137707  break;
137708  }
137709  default: {
137710  token = tkOTHER;
137711  break;
137712  }
137713  }
137714 #endif /* SQLITE_OMIT_TRIGGER */
137715  zSql += nId-1;
137716  }else{
137717  /* Operators and special symbols */
137718  token = tkOTHER;
137719  }
137720  break;
137721  }
137722  }
137723  state = trans[state][token];
137724  zSql++;
137725  }
137726  return state==1;
137727 }
137728 
137729 #ifndef SQLITE_OMIT_UTF16
137730 /*
137731 ** This routine is the same as the sqlite3_complete() routine described
137732 ** above, except that the parameter is required to be UTF-16 encoded, not
137733 ** UTF-8.
137734 */
137735 SQLITE_API int sqlite3_complete16(const void *zSql){
137736  sqlite3_value *pVal;
137737  char const *zSql8;
137738  int rc;
137739 
137740 #ifndef SQLITE_OMIT_AUTOINIT
137741  rc = sqlite3_initialize();
137742  if( rc ) return rc;
137743 #endif
137744  pVal = sqlite3ValueNew(0);
137746  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
137747  if( zSql8 ){
137748  rc = sqlite3_complete(zSql8);
137749  }else{
137750  rc = SQLITE_NOMEM_BKPT;
137751  }
137752  sqlite3ValueFree(pVal);
137753  return rc & 0xff;
137754 }
137755 #endif /* SQLITE_OMIT_UTF16 */
137756 #endif /* SQLITE_OMIT_COMPLETE */
137757 
137758 /************** End of complete.c ********************************************/
137759 /************** Begin file main.c ********************************************/
137760 /*
137761 ** 2001 September 15
137762 **
137763 ** The author disclaims copyright to this source code. In place of
137764 ** a legal notice, here is a blessing:
137765 **
137766 ** May you do good and not evil.
137767 ** May you find forgiveness for yourself and forgive others.
137768 ** May you share freely, never taking more than you give.
137769 **
137770 *************************************************************************
137771 ** Main file for the SQLite library. The routines in this file
137772 ** implement the programmer interface to the library. Routines in
137773 ** other files are for internal use by SQLite and should not be
137774 ** accessed by users of the library.
137775 */
137776 /* #include "sqliteInt.h" */
137777 
137778 #ifdef SQLITE_ENABLE_FTS3
137779 /************** Include fts3.h in the middle of main.c ***********************/
137780 /************** Begin file fts3.h ********************************************/
137781 /*
137782 ** 2006 Oct 10
137783 **
137784 ** The author disclaims copyright to this source code. In place of
137785 ** a legal notice, here is a blessing:
137786 **
137787 ** May you do good and not evil.
137788 ** May you find forgiveness for yourself and forgive others.
137789 ** May you share freely, never taking more than you give.
137790 **
137791 ******************************************************************************
137792 **
137793 ** This header file is used by programs that want to link against the
137794 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
137795 */
137796 /* #include "sqlite3.h" */
137797 
137798 #if 0
137799 extern "C" {
137800 #endif /* __cplusplus */
137801 
137802 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
137803 
137804 #if 0
137805 } /* extern "C" */
137806 #endif /* __cplusplus */
137807 
137808 /************** End of fts3.h ************************************************/
137809 /************** Continuing where we left off in main.c ***********************/
137810 #endif
137811 #ifdef SQLITE_ENABLE_RTREE
137812 /************** Include rtree.h in the middle of main.c **********************/
137813 /************** Begin file rtree.h *******************************************/
137814 /*
137815 ** 2008 May 26
137816 **
137817 ** The author disclaims copyright to this source code. In place of
137818 ** a legal notice, here is a blessing:
137819 **
137820 ** May you do good and not evil.
137821 ** May you find forgiveness for yourself and forgive others.
137822 ** May you share freely, never taking more than you give.
137823 **
137824 ******************************************************************************
137825 **
137826 ** This header file is used by programs that want to link against the
137827 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
137828 */
137829 /* #include "sqlite3.h" */
137830 
137831 #if 0
137832 extern "C" {
137833 #endif /* __cplusplus */
137834 
137835 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
137836 
137837 #if 0
137838 } /* extern "C" */
137839 #endif /* __cplusplus */
137840 
137841 /************** End of rtree.h ***********************************************/
137842 /************** Continuing where we left off in main.c ***********************/
137843 #endif
137844 #ifdef SQLITE_ENABLE_ICU
137845 /************** Include sqliteicu.h in the middle of main.c ******************/
137846 /************** Begin file sqliteicu.h ***************************************/
137847 /*
137848 ** 2008 May 26
137849 **
137850 ** The author disclaims copyright to this source code. In place of
137851 ** a legal notice, here is a blessing:
137852 **
137853 ** May you do good and not evil.
137854 ** May you find forgiveness for yourself and forgive others.
137855 ** May you share freely, never taking more than you give.
137856 **
137857 ******************************************************************************
137858 **
137859 ** This header file is used by programs that want to link against the
137860 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
137861 */
137862 /* #include "sqlite3.h" */
137863 
137864 #if 0
137865 extern "C" {
137866 #endif /* __cplusplus */
137867 
137868 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
137869 
137870 #if 0
137871 } /* extern "C" */
137872 #endif /* __cplusplus */
137873 
137874 
137875 /************** End of sqliteicu.h *******************************************/
137876 /************** Continuing where we left off in main.c ***********************/
137877 #endif
137878 #ifdef SQLITE_ENABLE_JSON1
137879 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
137880 #endif
137881 #ifdef SQLITE_ENABLE_FTS5
137882 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
137883 #endif
137884 
137885 #ifndef SQLITE_AMALGAMATION
137886 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
137887 ** contains the text of SQLITE_VERSION macro.
137888 */
137889 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
137890 #endif
137891 
137892 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
137893 ** a pointer to the to the sqlite3_version[] string constant.
137894 */
137895 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
137896 
137897 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
137898 ** pointer to a string constant whose value is the same as the
137899 ** SQLITE_SOURCE_ID C preprocessor macro.
137900 */
137901 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
137902 
137903 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
137904 ** returns an integer equal to SQLITE_VERSION_NUMBER.
137905 */
137907 
137908 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
137909 ** zero if and only if SQLite was compiled with mutexing code omitted due to
137910 ** the SQLITE_THREADSAFE compile-time option being set to 0.
137911 */
137913 
137914 /*
137915 ** When compiling the test fixture or with debugging enabled (on Win32),
137916 ** this variable being set to non-zero will cause OSTRACE macros to emit
137917 ** extra diagnostic information.
137918 */
137919 #ifdef SQLITE_HAVE_OS_TRACE
137920 # ifndef SQLITE_DEBUG_OS_TRACE
137921 # define SQLITE_DEBUG_OS_TRACE 0
137922 # endif
137923  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
137924 #endif
137925 
137926 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
137927 /*
137928 ** If the following function pointer is not NULL and if
137929 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
137930 ** I/O active are written using this function. These messages
137931 ** are intended for debugging activity only.
137932 */
137933 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
137934 #endif
137935 
137936 /*
137937 ** If the following global variable points to a string which is the
137938 ** name of a directory, then that directory will be used to store
137939 ** temporary files.
137940 **
137941 ** See also the "PRAGMA temp_store_directory" SQL command.
137942 */
137943 SQLITE_API char *sqlite3_temp_directory = 0;
137944 
137945 /*
137946 ** If the following global variable points to a string which is the
137947 ** name of a directory, then that directory will be used to store
137948 ** all database files specified with a relative pathname.
137949 **
137950 ** See also the "PRAGMA data_store_directory" SQL command.
137951 */
137952 SQLITE_API char *sqlite3_data_directory = 0;
137953 
137954 /*
137955 ** Initialize SQLite.
137956 **
137957 ** This routine must be called to initialize the memory allocation,
137958 ** VFS, and mutex subsystems prior to doing any serious work with
137959 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
137960 ** this routine will be called automatically by key routines such as
137961 ** sqlite3_open().
137962 **
137963 ** This routine is a no-op except on its very first call for the process,
137964 ** or for the first call after a call to sqlite3_shutdown.
137965 **
137966 ** The first thread to call this routine runs the initialization to
137967 ** completion. If subsequent threads call this routine before the first
137968 ** thread has finished the initialization process, then the subsequent
137969 ** threads must block until the first thread finishes with the initialization.
137970 **
137971 ** The first thread might call this routine recursively. Recursive
137972 ** calls to this routine should not block, of course. Otherwise the
137973 ** initialization process would never complete.
137974 **
137975 ** Let X be the first thread to enter this routine. Let Y be some other
137976 ** thread. Then while the initial invocation of this routine by X is
137977 ** incomplete, it is required that:
137978 **
137979 ** * Calls to this routine from Y must block until the outer-most
137980 ** call by X completes.
137981 **
137982 ** * Recursive calls to this routine from thread X return immediately
137983 ** without blocking.
137984 */
137986  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
137987  int rc; /* Result code */
137988 #ifdef SQLITE_EXTRA_INIT
137989  int bRunExtraInit = 0; /* Extra initialization needed */
137990 #endif
137991 
137992 #ifdef SQLITE_OMIT_WSD
137993  rc = sqlite3_wsd_init(4096, 24);
137994  if( rc!=SQLITE_OK ){
137995  return rc;
137996  }
137997 #endif
137998 
137999  /* If the following assert() fails on some obscure processor/compiler
138000  ** combination, the work-around is to set the correct pointer
138001  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
138002  assert( SQLITE_PTRSIZE==sizeof(char*) );
138003 
138004  /* If SQLite is already completely initialized, then this call
138005  ** to sqlite3_initialize() should be a no-op. But the initialization
138006  ** must be complete. So isInit must not be set until the very end
138007  ** of this routine.
138008  */
138009  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
138010 
138011  /* Make sure the mutex subsystem is initialized. If unable to
138012  ** initialize the mutex subsystem, return early with the error.
138013  ** If the system is so sick that we are unable to allocate a mutex,
138014  ** there is not much SQLite is going to be able to do.
138015  **
138016  ** The mutex subsystem must take care of serializing its own
138017  ** initialization.
138018  */
138019  rc = sqlite3MutexInit();
138020  if( rc ) return rc;
138021 
138022  /* Initialize the malloc() system and the recursive pInitMutex mutex.
138023  ** This operation is protected by the STATIC_MASTER mutex. Note that
138024  ** MutexAlloc() is called for a static mutex prior to initializing the
138025  ** malloc subsystem - this implies that the allocation of a static
138026  ** mutex must not require support from the malloc subsystem.
138027  */
138029  sqlite3_mutex_enter(pMaster);
138030  sqlite3GlobalConfig.isMutexInit = 1;
138031  if( !sqlite3GlobalConfig.isMallocInit ){
138032  rc = sqlite3MallocInit();
138033  }
138034  if( rc==SQLITE_OK ){
138035  sqlite3GlobalConfig.isMallocInit = 1;
138036  if( !sqlite3GlobalConfig.pInitMutex ){
138037  sqlite3GlobalConfig.pInitMutex =
138039  if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
138040  rc = SQLITE_NOMEM_BKPT;
138041  }
138042  }
138043  }
138044  if( rc==SQLITE_OK ){
138045  sqlite3GlobalConfig.nRefInitMutex++;
138046  }
138047  sqlite3_mutex_leave(pMaster);
138048 
138049  /* If rc is not SQLITE_OK at this point, then either the malloc
138050  ** subsystem could not be initialized or the system failed to allocate
138051  ** the pInitMutex mutex. Return an error in either case. */
138052  if( rc!=SQLITE_OK ){
138053  return rc;
138054  }
138055 
138056  /* Do the rest of the initialization under the recursive mutex so
138057  ** that we will be able to handle recursive calls into
138058  ** sqlite3_initialize(). The recursive calls normally come through
138059  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
138060  ** recursive calls might also be possible.
138061  **
138062  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
138063  ** to the xInit method, so the xInit method need not be threadsafe.
138064  **
138065  ** The following mutex is what serializes access to the appdef pcache xInit
138066  ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
138067  ** call to sqlite3PcacheInitialize().
138068  */
138070  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
138071  sqlite3GlobalConfig.inProgress = 1;
138072 #ifdef SQLITE_ENABLE_SQLLOG
138073  {
138074  extern void sqlite3_init_sqllog(void);
138075  sqlite3_init_sqllog();
138076  }
138077 #endif
138078  memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
138080  if( sqlite3GlobalConfig.isPCacheInit==0 ){
138081  rc = sqlite3PcacheInitialize();
138082  }
138083  if( rc==SQLITE_OK ){
138084  sqlite3GlobalConfig.isPCacheInit = 1;
138085  rc = sqlite3OsInit();
138086  }
138087  if( rc==SQLITE_OK ){
138089  sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
138090  sqlite3GlobalConfig.isInit = 1;
138091 #ifdef SQLITE_EXTRA_INIT
138092  bRunExtraInit = 1;
138093 #endif
138094  }
138095  sqlite3GlobalConfig.inProgress = 0;
138096  }
138098 
138099  /* Go back under the static mutex and clean up the recursive
138100  ** mutex to prevent a resource leak.
138101  */
138102  sqlite3_mutex_enter(pMaster);
138103  sqlite3GlobalConfig.nRefInitMutex--;
138104  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
138105  assert( sqlite3GlobalConfig.nRefInitMutex==0 );
138107  sqlite3GlobalConfig.pInitMutex = 0;
138108  }
138109  sqlite3_mutex_leave(pMaster);
138110 
138111  /* The following is just a sanity check to make sure SQLite has
138112  ** been compiled correctly. It is important to run this code, but
138113  ** we don't want to run it too often and soak up CPU cycles for no
138114  ** reason. So we run it once during initialization.
138115  */
138116 #ifndef NDEBUG
138117 #ifndef SQLITE_OMIT_FLOATING_POINT
138118  /* This section of code's only "output" is via assert() statements. */
138119  if ( rc==SQLITE_OK ){
138120  u64 x = (((u64)1)<<63)-1;
138121  double y;
138122  assert(sizeof(x)==8);
138123  assert(sizeof(x)==sizeof(y));
138124  memcpy(&y, &x, 8);
138125  assert( sqlite3IsNaN(y) );
138126  }
138127 #endif
138128 #endif
138129 
138130  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
138131  ** compile-time option.
138132  */
138133 #ifdef SQLITE_EXTRA_INIT
138134  if( bRunExtraInit ){
138135  int SQLITE_EXTRA_INIT(const char*);
138136  rc = SQLITE_EXTRA_INIT(0);
138137  }
138138 #endif
138139 
138140  return rc;
138141 }
138142 
138143 /*
138144 ** Undo the effects of sqlite3_initialize(). Must not be called while
138145 ** there are outstanding database connections or memory allocations or
138146 ** while any part of SQLite is otherwise in use in any thread. This
138147 ** routine is not threadsafe. But it is safe to invoke this routine
138148 ** on when SQLite is already shut down. If SQLite is already shut down
138149 ** when this routine is invoked, then this routine is a harmless no-op.
138150 */
138152 #ifdef SQLITE_OMIT_WSD
138153  int rc = sqlite3_wsd_init(4096, 24);
138154  if( rc!=SQLITE_OK ){
138155  return rc;
138156  }
138157 #endif
138158 
138159  if( sqlite3GlobalConfig.isInit ){
138160 #ifdef SQLITE_EXTRA_SHUTDOWN
138161  void SQLITE_EXTRA_SHUTDOWN(void);
138162  SQLITE_EXTRA_SHUTDOWN();
138163 #endif
138164  sqlite3_os_end();
138166  sqlite3GlobalConfig.isInit = 0;
138167  }
138168  if( sqlite3GlobalConfig.isPCacheInit ){
138170  sqlite3GlobalConfig.isPCacheInit = 0;
138171  }
138172  if( sqlite3GlobalConfig.isMallocInit ){
138173  sqlite3MallocEnd();
138174  sqlite3GlobalConfig.isMallocInit = 0;
138175 
138176 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
138177  /* The heap subsystem has now been shutdown and these values are supposed
138178  ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
138179  ** which would rely on that heap subsystem; therefore, make sure these
138180  ** values cannot refer to heap memory that was just invalidated when the
138181  ** heap subsystem was shutdown. This is only done if the current call to
138182  ** this function resulted in the heap subsystem actually being shutdown.
138183  */
138184  sqlite3_data_directory = 0;
138185  sqlite3_temp_directory = 0;
138186 #endif
138187  }
138188  if( sqlite3GlobalConfig.isMutexInit ){
138189  sqlite3MutexEnd();
138190  sqlite3GlobalConfig.isMutexInit = 0;
138191  }
138192 
138193  return SQLITE_OK;
138194 }
138195 
138196 /*
138197 ** This API allows applications to modify the global configuration of
138198 ** the SQLite library at run-time.
138199 **
138200 ** This routine should only be called when there are no outstanding
138201 ** database connections or memory allocations. This routine is not
138202 ** threadsafe. Failure to heed these warnings can lead to unpredictable
138203 ** behavior.
138204 */
138205 SQLITE_API int sqlite3_config(int op, ...){
138206  va_list ap;
138207  int rc = SQLITE_OK;
138208 
138209  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
138210  ** the SQLite library is in use. */
138211  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
138212 
138213  va_start(ap, op);
138214  switch( op ){
138215 
138216  /* Mutex configuration options are only available in a threadsafe
138217  ** compile.
138218  */
138219 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
138221  /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
138222  ** Single-thread. */
138223  sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
138224  sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
138225  break;
138226  }
138227 #endif
138228 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
138229  case SQLITE_CONFIG_MULTITHREAD: {
138230  /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
138231  ** Multi-thread. */
138232  sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
138233  sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
138234  break;
138235  }
138236 #endif
138237 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
138238  case SQLITE_CONFIG_SERIALIZED: {
138239  /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
138240  ** Serialized. */
138241  sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
138242  sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
138243  break;
138244  }
138245 #endif
138246 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
138247  case SQLITE_CONFIG_MUTEX: {
138248  /* Specify an alternative mutex implementation */
138249  sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
138250  break;
138251  }
138252 #endif
138253 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
138254  case SQLITE_CONFIG_GETMUTEX: {
138255  /* Retrieve the current mutex implementation */
138256  *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
138257  break;
138258  }
138259 #endif
138260 
138261  case SQLITE_CONFIG_MALLOC: {
138262  /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
138263  ** single argument which is a pointer to an instance of the
138264  ** sqlite3_mem_methods structure. The argument specifies alternative
138265  ** low-level memory allocation routines to be used in place of the memory
138266  ** allocation routines built into SQLite. */
138267  sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
138268  break;
138269  }
138270  case SQLITE_CONFIG_GETMALLOC: {
138271  /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
138272  ** single argument which is a pointer to an instance of the
138273  ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
138274  ** filled with the currently defined memory allocation routines. */
138275  if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
138276  *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
138277  break;
138278  }
138279  case SQLITE_CONFIG_MEMSTATUS: {
138280  /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
138281  ** single argument of type int, interpreted as a boolean, which enables
138282  ** or disables the collection of memory allocation statistics. */
138283  sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
138284  break;
138285  }
138286  case SQLITE_CONFIG_SCRATCH: {
138287  /* EVIDENCE-OF: R-08404-60887 There are three arguments to
138288  ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
138289  ** which the scratch allocations will be drawn, the size of each scratch
138290  ** allocation (sz), and the maximum number of scratch allocations (N). */
138291  sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
138292  sqlite3GlobalConfig.szScratch = va_arg(ap, int);
138293  sqlite3GlobalConfig.nScratch = va_arg(ap, int);
138294  break;
138295  }
138296  case SQLITE_CONFIG_PAGECACHE: {
138297  /* EVIDENCE-OF: R-18761-36601 There are three arguments to
138298  ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
138299  ** the size of each page cache line (sz), and the number of cache lines
138300  ** (N). */
138301  sqlite3GlobalConfig.pPage = va_arg(ap, void*);
138302  sqlite3GlobalConfig.szPage = va_arg(ap, int);
138303  sqlite3GlobalConfig.nPage = va_arg(ap, int);
138304  break;
138305  }
138307  /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
138308  ** a single parameter which is a pointer to an integer and writes into
138309  ** that integer the number of extra bytes per page required for each page
138310  ** in SQLITE_CONFIG_PAGECACHE. */
138311  *va_arg(ap, int*) =
138315  break;
138316  }
138317 
138318  case SQLITE_CONFIG_PCACHE: {
138319  /* no-op */
138320  break;
138321  }
138322  case SQLITE_CONFIG_GETPCACHE: {
138323  /* now an error */
138324  rc = SQLITE_ERROR;
138325  break;
138326  }
138327 
138328  case SQLITE_CONFIG_PCACHE2: {
138329  /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
138330  ** single argument which is a pointer to an sqlite3_pcache_methods2
138331  ** object. This object specifies the interface to a custom page cache
138332  ** implementation. */
138333  sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
138334  break;
138335  }
138336  case SQLITE_CONFIG_GETPCACHE2: {
138337  /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
138338  ** single argument which is a pointer to an sqlite3_pcache_methods2
138339  ** object. SQLite copies of the current page cache implementation into
138340  ** that object. */
138341  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
138343  }
138344  *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
138345  break;
138346  }
138347 
138348 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
138349 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
138350 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
138351 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
138352  case SQLITE_CONFIG_HEAP: {
138353  /* EVIDENCE-OF: R-19854-42126 There are three arguments to
138354  ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
138355  ** number of bytes in the memory buffer, and the minimum allocation size.
138356  */
138357  sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
138358  sqlite3GlobalConfig.nHeap = va_arg(ap, int);
138359  sqlite3GlobalConfig.mnReq = va_arg(ap, int);
138360 
138361  if( sqlite3GlobalConfig.mnReq<1 ){
138362  sqlite3GlobalConfig.mnReq = 1;
138363  }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
138364  /* cap min request size at 2^12 */
138365  sqlite3GlobalConfig.mnReq = (1<<12);
138366  }
138367 
138368  if( sqlite3GlobalConfig.pHeap==0 ){
138369  /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
138370  ** is NULL, then SQLite reverts to using its default memory allocator
138371  ** (the system malloc() implementation), undoing any prior invocation of
138372  ** SQLITE_CONFIG_MALLOC.
138373  **
138374  ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
138375  ** revert to its default implementation when sqlite3_initialize() is run
138376  */
138377  memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
138378  }else{
138379  /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
138380  ** alternative memory allocator is engaged to handle all of SQLites
138381  ** memory allocation needs. */
138382 #ifdef SQLITE_ENABLE_MEMSYS3
138383  sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
138384 #endif
138385 #ifdef SQLITE_ENABLE_MEMSYS5
138386  sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
138387 #endif
138388  }
138389  break;
138390  }
138391 #endif
138392 
138393  case SQLITE_CONFIG_LOOKASIDE: {
138394  sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
138395  sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
138396  break;
138397  }
138398 
138399  /* Record a pointer to the logger function and its first argument.
138400  ** The default is NULL. Logging is disabled if the function pointer is
138401  ** NULL.
138402  */
138403  case SQLITE_CONFIG_LOG: {
138404  /* MSVC is picky about pulling func ptrs from va lists.
138405  ** http://support.microsoft.com/kb/47961
138406  ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
138407  */
138408  typedef void(*LOGFUNC_t)(void*,int,const char*);
138409  sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
138410  sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
138411  break;
138412  }
138413 
138414  /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
138415  ** can be changed at start-time using the
138416  ** sqlite3_config(SQLITE_CONFIG_URI,1) or
138417  ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
138418  */
138419  case SQLITE_CONFIG_URI: {
138420  /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
138421  ** argument of type int. If non-zero, then URI handling is globally
138422  ** enabled. If the parameter is zero, then URI handling is globally
138423  ** disabled. */
138424  sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
138425  break;
138426  }
138427 
138429  /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
138430  ** option takes a single integer argument which is interpreted as a
138431  ** boolean in order to enable or disable the use of covering indices for
138432  ** full table scans in the query optimizer. */
138433  sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
138434  break;
138435  }
138436 
138437 #ifdef SQLITE_ENABLE_SQLLOG
138438  case SQLITE_CONFIG_SQLLOG: {
138439  typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
138440  sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
138441  sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
138442  break;
138443  }
138444 #endif
138445 
138446  case SQLITE_CONFIG_MMAP_SIZE: {
138447  /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
138448  ** integer (sqlite3_int64) values that are the default mmap size limit
138449  ** (the default setting for PRAGMA mmap_size) and the maximum allowed
138450  ** mmap size limit. */
138451  sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
138452  sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
138453  /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
138454  ** negative, then that argument is changed to its compile-time default.
138455  **
138456  ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
138457  ** silently truncated if necessary so that it does not exceed the
138458  ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
138459  ** compile-time option.
138460  */
138461  if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
138462  mxMmap = SQLITE_MAX_MMAP_SIZE;
138463  }
138464  if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
138465  if( szMmap>mxMmap) szMmap = mxMmap;
138466  sqlite3GlobalConfig.mxMmap = mxMmap;
138467  sqlite3GlobalConfig.szMmap = szMmap;
138468  break;
138469  }
138470 
138471 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
138473  /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
138474  ** unsigned integer value that specifies the maximum size of the created
138475  ** heap. */
138476  sqlite3GlobalConfig.nHeap = va_arg(ap, int);
138477  break;
138478  }
138479 #endif
138480 
138481  case SQLITE_CONFIG_PMASZ: {
138482  sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
138483  break;
138484  }
138485 
138487  sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
138488  break;
138489  }
138490 
138491  default: {
138492  rc = SQLITE_ERROR;
138493  break;
138494  }
138495  }
138496  va_end(ap);
138497  return rc;
138498 }
138499 
138500 /*
138501 ** Set up the lookaside buffers for a database connection.
138502 ** Return SQLITE_OK on success.
138503 ** If lookaside is already active, return SQLITE_BUSY.
138504 **
138505 ** The sz parameter is the number of bytes in each lookaside slot.
138506 ** The cnt parameter is the number of slots. If pStart is NULL the
138507 ** space for the lookaside memory is obtained from sqlite3_malloc().
138508 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
138509 ** the lookaside memory.
138510 */
138511 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
138512 #ifndef SQLITE_OMIT_LOOKASIDE
138513  void *pStart;
138514  if( db->lookaside.nOut ){
138515  return SQLITE_BUSY;
138516  }
138517  /* Free any existing lookaside buffer for this handle before
138518  ** allocating a new one so we don't have to have space for
138519  ** both at the same time.
138520  */
138521  if( db->lookaside.bMalloced ){
138523  }
138524  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
138525  ** than a pointer to be useful.
138526  */
138527  sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
138528  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
138529  if( cnt<0 ) cnt = 0;
138530  if( sz==0 || cnt==0 ){
138531  sz = 0;
138532  pStart = 0;
138533  }else if( pBuf==0 ){
138535  pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
138537  if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
138538  }else{
138539  pStart = pBuf;
138540  }
138541  db->lookaside.pStart = pStart;
138542  db->lookaside.pFree = 0;
138543  db->lookaside.sz = (u16)sz;
138544  if( pStart ){
138545  int i;
138546  LookasideSlot *p;
138547  assert( sz > (int)sizeof(LookasideSlot*) );
138548  p = (LookasideSlot*)pStart;
138549  for(i=cnt-1; i>=0; i--){
138550  p->pNext = db->lookaside.pFree;
138551  db->lookaside.pFree = p;
138552  p = (LookasideSlot*)&((u8*)p)[sz];
138553  }
138554  db->lookaside.pEnd = p;
138555  db->lookaside.bDisable = 0;
138556  db->lookaside.bMalloced = pBuf==0 ?1:0;
138557  }else{
138558  db->lookaside.pStart = db;
138559  db->lookaside.pEnd = db;
138560  db->lookaside.bDisable = 1;
138561  db->lookaside.bMalloced = 0;
138562  }
138563 #endif /* SQLITE_OMIT_LOOKASIDE */
138564  return SQLITE_OK;
138565 }
138566 
138567 /*
138568 ** Return the mutex associated with a database connection.
138569 */
138571 #ifdef SQLITE_ENABLE_API_ARMOR
138572  if( !sqlite3SafetyCheckOk(db) ){
138573  (void)SQLITE_MISUSE_BKPT;
138574  return 0;
138575  }
138576 #endif
138577  return db->mutex;
138578 }
138579 
138580 /*
138581 ** Free up as much memory as we can from the given database
138582 ** connection.
138583 */
138585  int i;
138586 
138587 #ifdef SQLITE_ENABLE_API_ARMOR
138588  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138589 #endif
138590  sqlite3_mutex_enter(db->mutex);
138591  sqlite3BtreeEnterAll(db);
138592  for(i=0; i<db->nDb; i++){
138593  Btree *pBt = db->aDb[i].pBt;
138594  if( pBt ){
138595  Pager *pPager = sqlite3BtreePager(pBt);
138596  sqlite3PagerShrink(pPager);
138597  }
138598  }
138599  sqlite3BtreeLeaveAll(db);
138600  sqlite3_mutex_leave(db->mutex);
138601  return SQLITE_OK;
138602 }
138603 
138604 /*
138605 ** Flush any dirty pages in the pager-cache for any attached database
138606 ** to disk.
138607 */
138609  int i;
138610  int rc = SQLITE_OK;
138611  int bSeenBusy = 0;
138612 
138613 #ifdef SQLITE_ENABLE_API_ARMOR
138614  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138615 #endif
138616  sqlite3_mutex_enter(db->mutex);
138617  sqlite3BtreeEnterAll(db);
138618  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
138619  Btree *pBt = db->aDb[i].pBt;
138620  if( pBt && sqlite3BtreeIsInTrans(pBt) ){
138621  Pager *pPager = sqlite3BtreePager(pBt);
138622  rc = sqlite3PagerFlush(pPager);
138623  if( rc==SQLITE_BUSY ){
138624  bSeenBusy = 1;
138625  rc = SQLITE_OK;
138626  }
138627  }
138628  }
138629  sqlite3BtreeLeaveAll(db);
138630  sqlite3_mutex_leave(db->mutex);
138631  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
138632 }
138633 
138634 /*
138635 ** Configuration settings for an individual database connection
138636 */
138637 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
138638  va_list ap;
138639  int rc;
138640  va_start(ap, op);
138641  switch( op ){
138643  db->aDb[0].zDbSName = va_arg(ap,char*);
138644  rc = SQLITE_OK;
138645  break;
138646  }
138647  case SQLITE_DBCONFIG_LOOKASIDE: {
138648  void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
138649  int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
138650  int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
138651  rc = setupLookaside(db, pBuf, sz, cnt);
138652  break;
138653  }
138654  default: {
138655  static const struct {
138656  int op; /* The opcode */
138657  u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
138658  } aFlagOp[] = {
138663  };
138664  unsigned int i;
138665  rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
138666  for(i=0; i<ArraySize(aFlagOp); i++){
138667  if( aFlagOp[i].op==op ){
138668  int onoff = va_arg(ap, int);
138669  int *pRes = va_arg(ap, int*);
138670  int oldFlags = db->flags;
138671  if( onoff>0 ){
138672  db->flags |= aFlagOp[i].mask;
138673  }else if( onoff==0 ){
138674  db->flags &= ~aFlagOp[i].mask;
138675  }
138676  if( oldFlags!=db->flags ){
138678  }
138679  if( pRes ){
138680  *pRes = (db->flags & aFlagOp[i].mask)!=0;
138681  }
138682  rc = SQLITE_OK;
138683  break;
138684  }
138685  }
138686  break;
138687  }
138688  }
138689  va_end(ap);
138690  return rc;
138691 }
138692 
138693 
138694 /*
138695 ** Return true if the buffer z[0..n-1] contains all spaces.
138696 */
138697 static int allSpaces(const char *z, int n){
138698  while( n>0 && z[n-1]==' ' ){ n--; }
138699  return n==0;
138700 }
138701 
138702 /*
138703 ** This is the default collating function named "BINARY" which is always
138704 ** available.
138705 **
138706 ** If the padFlag argument is not NULL then space padding at the end
138707 ** of strings is ignored. This implements the RTRIM collation.
138708 */
138709 static int binCollFunc(
138710  void *padFlag,
138711  int nKey1, const void *pKey1,
138712  int nKey2, const void *pKey2
138713 ){
138714  int rc, n;
138715  n = nKey1<nKey2 ? nKey1 : nKey2;
138716  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
138717  ** strings byte by byte using the memcmp() function from the standard C
138718  ** library. */
138719  rc = memcmp(pKey1, pKey2, n);
138720  if( rc==0 ){
138721  if( padFlag
138722  && allSpaces(((char*)pKey1)+n, nKey1-n)
138723  && allSpaces(((char*)pKey2)+n, nKey2-n)
138724  ){
138725  /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
138726  ** spaces at the end of either string do not change the result. In other
138727  ** words, strings will compare equal to one another as long as they
138728  ** differ only in the number of spaces at the end.
138729  */
138730  }else{
138731  rc = nKey1 - nKey2;
138732  }
138733  }
138734  return rc;
138735 }
138736 
138737 /*
138738 ** Another built-in collating sequence: NOCASE.
138739 **
138740 ** This collating sequence is intended to be used for "case independent
138741 ** comparison". SQLite's knowledge of upper and lower case equivalents
138742 ** extends only to the 26 characters used in the English language.
138743 **
138744 ** At the moment there is only a UTF-8 implementation.
138745 */
138747  void *NotUsed,
138748  int nKey1, const void *pKey1,
138749  int nKey2, const void *pKey2
138750 ){
138751  int r = sqlite3StrNICmp(
138752  (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
138753  UNUSED_PARAMETER(NotUsed);
138754  if( 0==r ){
138755  r = nKey1-nKey2;
138756  }
138757  return r;
138758 }
138759 
138760 /*
138761 ** Return the ROWID of the most recent insert
138762 */
138763 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
138764 #ifdef SQLITE_ENABLE_API_ARMOR
138765  if( !sqlite3SafetyCheckOk(db) ){
138766  (void)SQLITE_MISUSE_BKPT;
138767  return 0;
138768  }
138769 #endif
138770  return db->lastRowid;
138771 }
138772 
138773 /*
138774 ** Return the number of changes in the most recent call to sqlite3_exec().
138775 */
138776 SQLITE_API int sqlite3_changes(sqlite3 *db){
138777 #ifdef SQLITE_ENABLE_API_ARMOR
138778  if( !sqlite3SafetyCheckOk(db) ){
138779  (void)SQLITE_MISUSE_BKPT;
138780  return 0;
138781  }
138782 #endif
138783  return db->nChange;
138784 }
138785 
138786 /*
138787 ** Return the number of changes since the database handle was opened.
138788 */
138790 #ifdef SQLITE_ENABLE_API_ARMOR
138791  if( !sqlite3SafetyCheckOk(db) ){
138792  (void)SQLITE_MISUSE_BKPT;
138793  return 0;
138794  }
138795 #endif
138796  return db->nTotalChange;
138797 }
138798 
138799 /*
138800 ** Close all open savepoints. This function only manipulates fields of the
138801 ** database handle object, it does not close any savepoints that may be open
138802 ** at the b-tree/pager level.
138803 */
138805  while( db->pSavepoint ){
138806  Savepoint *pTmp = db->pSavepoint;
138807  db->pSavepoint = pTmp->pNext;
138808  sqlite3DbFree(db, pTmp);
138809  }
138810  db->nSavepoint = 0;
138811  db->nStatement = 0;
138812  db->isTransactionSavepoint = 0;
138813 }
138814 
138815 /*
138816 ** Invoke the destructor function associated with FuncDef p, if any. Except,
138817 ** if this is not the last copy of the function, do not invoke it. Multiple
138818 ** copies of a single function are created when create_function() is called
138819 ** with SQLITE_ANY as the encoding.
138820 */
138821 static void functionDestroy(sqlite3 *db, FuncDef *p){
138822  FuncDestructor *pDestructor = p->u.pDestructor;
138823  if( pDestructor ){
138824  pDestructor->nRef--;
138825  if( pDestructor->nRef==0 ){
138826  pDestructor->xDestroy(pDestructor->pUserData);
138827  sqlite3DbFree(db, pDestructor);
138828  }
138829  }
138830 }
138831 
138832 /*
138833 ** Disconnect all sqlite3_vtab objects that belong to database connection
138834 ** db. This is called when db is being closed.
138835 */
138836 static void disconnectAllVtab(sqlite3 *db){
138837 #ifndef SQLITE_OMIT_VIRTUALTABLE
138838  int i;
138839  HashElem *p;
138840  sqlite3BtreeEnterAll(db);
138841  for(i=0; i<db->nDb; i++){
138842  Schema *pSchema = db->aDb[i].pSchema;
138843  if( db->aDb[i].pSchema ){
138844  for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
138845  Table *pTab = (Table *)sqliteHashData(p);
138846  if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
138847  }
138848  }
138849  }
138850  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
138851  Module *pMod = (Module *)sqliteHashData(p);
138852  if( pMod->pEpoTab ){
138853  sqlite3VtabDisconnect(db, pMod->pEpoTab);
138854  }
138855  }
138856  sqlite3VtabUnlockList(db);
138857  sqlite3BtreeLeaveAll(db);
138858 #else
138859  UNUSED_PARAMETER(db);
138860 #endif
138861 }
138862 
138863 /*
138864 ** Return TRUE if database connection db has unfinalized prepared
138865 ** statements or unfinished sqlite3_backup objects.
138866 */
138867 static int connectionIsBusy(sqlite3 *db){
138868  int j;
138869  assert( sqlite3_mutex_held(db->mutex) );
138870  if( db->pVdbe ) return 1;
138871  for(j=0; j<db->nDb; j++){
138872  Btree *pBt = db->aDb[j].pBt;
138873  if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
138874  }
138875  return 0;
138876 }
138877 
138878 /*
138879 ** Close an existing SQLite database
138880 */
138881 static int sqlite3Close(sqlite3 *db, int forceZombie){
138882  if( !db ){
138883  /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
138884  ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
138885  return SQLITE_OK;
138886  }
138887  if( !sqlite3SafetyCheckSickOrOk(db) ){
138888  return SQLITE_MISUSE_BKPT;
138889  }
138890  sqlite3_mutex_enter(db->mutex);
138891  if( db->mTrace & SQLITE_TRACE_CLOSE ){
138892  db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
138893  }
138894 
138895  /* Force xDisconnect calls on all virtual tables */
138896  disconnectAllVtab(db);
138897 
138898  /* If a transaction is open, the disconnectAllVtab() call above
138899  ** will not have called the xDisconnect() method on any virtual
138900  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
138901  ** call will do so. We need to do this before the check for active
138902  ** SQL statements below, as the v-table implementation may be storing
138903  ** some prepared statements internally.
138904  */
138905  sqlite3VtabRollback(db);
138906 
138907  /* Legacy behavior (sqlite3_close() behavior) is to return
138908  ** SQLITE_BUSY if the connection can not be closed immediately.
138909  */
138910  if( !forceZombie && connectionIsBusy(db) ){
138911  sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
138912  "statements or unfinished backups");
138913  sqlite3_mutex_leave(db->mutex);
138914  return SQLITE_BUSY;
138915  }
138916 
138917 #ifdef SQLITE_ENABLE_SQLLOG
138918  if( sqlite3GlobalConfig.xSqllog ){
138919  /* Closing the handle. Fourth parameter is passed the value 2. */
138920  sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
138921  }
138922 #endif
138923 
138924  /* Convert the connection into a zombie and then close it.
138925  */
138926  db->magic = SQLITE_MAGIC_ZOMBIE;
138928  return SQLITE_OK;
138929 }
138930 
138931 /*
138932 ** Two variations on the public interface for closing a database
138933 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
138934 ** leaves the connection option if there are unfinalized prepared
138935 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
138936 ** version forces the connection to become a zombie if there are
138937 ** unclosed resources, and arranges for deallocation when the last
138938 ** prepare statement or sqlite3_backup closes.
138939 */
138940 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
138941 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
138942 
138943 
138944 /*
138945 ** Close the mutex on database connection db.
138946 **
138947 ** Furthermore, if database connection db is a zombie (meaning that there
138948 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
138949 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
138950 ** finished, then free all resources.
138951 */
138953  HashElem *i; /* Hash table iterator */
138954  int j;
138955 
138956  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
138957  ** or if the connection has not yet been closed by sqlite3_close_v2(),
138958  ** then just leave the mutex and return.
138959  */
138960  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
138961  sqlite3_mutex_leave(db->mutex);
138962  return;
138963  }
138964 
138965  /* If we reach this point, it means that the database connection has
138966  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
138967  ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
138968  ** go ahead and free all resources.
138969  */
138970 
138971  /* If a transaction is open, roll it back. This also ensures that if
138972  ** any database schemas have been modified by an uncommitted transaction
138973  ** they are reset. And that the required b-tree mutex is held to make
138974  ** the pager rollback and schema reset an atomic operation. */
138976 
138977  /* Free any outstanding Savepoint structures. */
138979 
138980  /* Close all database connections */
138981  for(j=0; j<db->nDb; j++){
138982  struct Db *pDb = &db->aDb[j];
138983  if( pDb->pBt ){
138984  sqlite3BtreeClose(pDb->pBt);
138985  pDb->pBt = 0;
138986  if( j!=1 ){
138987  pDb->pSchema = 0;
138988  }
138989  }
138990  }
138991  /* Clear the TEMP schema separately and last */
138992  if( db->aDb[1].pSchema ){
138993  sqlite3SchemaClear(db->aDb[1].pSchema);
138994  }
138995  sqlite3VtabUnlockList(db);
138996 
138997  /* Free up the array of auxiliary databases */
138999  assert( db->nDb<=2 );
139000  assert( db->aDb==db->aDbStatic );
139001 
139002  /* Tell the code in notify.c that the connection no longer holds any
139003  ** locks and does not require any further unlock-notify callbacks.
139004  */
139006 
139007  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
139008  FuncDef *pNext, *p;
139009  p = sqliteHashData(i);
139010  do{
139011  functionDestroy(db, p);
139012  pNext = p->pNext;
139013  sqlite3DbFree(db, p);
139014  p = pNext;
139015  }while( p );
139016  }
139017  sqlite3HashClear(&db->aFunc);
139018  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
139019  CollSeq *pColl = (CollSeq *)sqliteHashData(i);
139020  /* Invoke any destructors registered for collation sequence user data. */
139021  for(j=0; j<3; j++){
139022  if( pColl[j].xDel ){
139023  pColl[j].xDel(pColl[j].pUser);
139024  }
139025  }
139026  sqlite3DbFree(db, pColl);
139027  }
139028  sqlite3HashClear(&db->aCollSeq);
139029 #ifndef SQLITE_OMIT_VIRTUALTABLE
139030  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
139031  Module *pMod = (Module *)sqliteHashData(i);
139032  if( pMod->xDestroy ){
139033  pMod->xDestroy(pMod->pAux);
139034  }
139035  sqlite3VtabEponymousTableClear(db, pMod);
139036  sqlite3DbFree(db, pMod);
139037  }
139038  sqlite3HashClear(&db->aModule);
139039 #endif
139040 
139041  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
139042  sqlite3ValueFree(db->pErr);
139044 #if SQLITE_USER_AUTHENTICATION
139045  sqlite3_free(db->auth.zAuthUser);
139046  sqlite3_free(db->auth.zAuthPW);
139047 #endif
139048 
139049  db->magic = SQLITE_MAGIC_ERROR;
139050 
139051  /* The temp-database schema is allocated differently from the other schema
139052  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
139053  ** So it needs to be freed here. Todo: Why not roll the temp schema into
139054  ** the same sqliteMalloc() as the one that allocates the database
139055  ** structure?
139056  */
139057  sqlite3DbFree(db, db->aDb[1].pSchema);
139058  sqlite3_mutex_leave(db->mutex);
139059  db->magic = SQLITE_MAGIC_CLOSED;
139060  sqlite3_mutex_free(db->mutex);
139061  assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
139062  if( db->lookaside.bMalloced ){
139064  }
139065  sqlite3_free(db);
139066 }
139067 
139068 /*
139069 ** Rollback all database files. If tripCode is not SQLITE_OK, then
139070 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
139071 ** breaker") and made to return tripCode if there are any further
139072 ** attempts to use that cursor. Read cursors remain open and valid
139073 ** but are "saved" in case the table pages are moved around.
139074 */
139075 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
139076  int i;
139077  int inTrans = 0;
139078  int schemaChange;
139079  assert( sqlite3_mutex_held(db->mutex) );
139081 
139082  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
139083  ** This is important in case the transaction being rolled back has
139084  ** modified the database schema. If the b-tree mutexes are not taken
139085  ** here, then another shared-cache connection might sneak in between
139086  ** the database rollback and schema reset, which can cause false
139087  ** corruption reports in some cases. */
139088  sqlite3BtreeEnterAll(db);
139089  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
139090 
139091  for(i=0; i<db->nDb; i++){
139092  Btree *p = db->aDb[i].pBt;
139093  if( p ){
139094  if( sqlite3BtreeIsInTrans(p) ){
139095  inTrans = 1;
139096  }
139097  sqlite3BtreeRollback(p, tripCode, !schemaChange);
139098  }
139099  }
139100  sqlite3VtabRollback(db);
139102 
139103  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
139106  }
139107  sqlite3BtreeLeaveAll(db);
139108 
139109  /* Any deferred constraint violations have now been resolved. */
139110  db->nDeferredCons = 0;
139111  db->nDeferredImmCons = 0;
139112  db->flags &= ~SQLITE_DeferFKs;
139113 
139114  /* If one has been configured, invoke the rollback-hook callback */
139115  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
139116  db->xRollbackCallback(db->pRollbackArg);
139117  }
139118 }
139119 
139120 /*
139121 ** Return a static string containing the name corresponding to the error code
139122 ** specified in the argument.
139123 */
139124 #if defined(SQLITE_NEED_ERR_NAME)
139125 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
139126  const char *zName = 0;
139127  int i, origRc = rc;
139128  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
139129  switch( rc ){
139130  case SQLITE_OK: zName = "SQLITE_OK"; break;
139131  case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
139132  case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
139133  case SQLITE_PERM: zName = "SQLITE_PERM"; break;
139134  case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
139135  case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
139136  case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
139137  case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
139138  case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
139139  case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
139140  case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
139141  case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
139142  case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
139143  case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
139144  case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
139145  case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
139146  case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
139147  case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
139148  case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
139149  case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
139150  case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
139151  case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
139152  case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
139153  case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
139154  case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
139155  case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
139156  case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
139157  case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
139158  case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
139159  case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
139160  case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
139162  zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
139163  case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
139164  case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
139165  case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
139166  case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
139167  case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
139168  case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
139169  case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
139170  case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
139171  case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
139172  case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
139173  case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
139174  case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
139175  case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
139176  case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
139177  case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
139178  case SQLITE_FULL: zName = "SQLITE_FULL"; break;
139179  case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
139180  case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
139181  case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
139182  case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
139183  case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
139184  case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
139185  case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
139186  case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
139187  case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
139188  case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
139189  case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
139190  case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
139192  zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
139193  case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
139195  zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
139196  case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
139198  zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
139199  case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
139201  zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
139202  case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
139203  case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
139204  case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
139205  case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
139206  case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
139207  case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
139208  case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
139209  case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
139210  case SQLITE_ROW: zName = "SQLITE_ROW"; break;
139211  case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
139212  case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
139214  zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
139215  case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
139216  case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
139217  case SQLITE_DONE: zName = "SQLITE_DONE"; break;
139218  }
139219  }
139220  if( zName==0 ){
139221  static char zBuf[50];
139222  sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
139223  zName = zBuf;
139224  }
139225  return zName;
139226 }
139227 #endif
139228 
139229 /*
139230 ** Return a static string that describes the kind of error specified in the
139231 ** argument.
139232 */
139233 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
139234  static const char* const aMsg[] = {
139235  /* SQLITE_OK */ "not an error",
139236  /* SQLITE_ERROR */ "SQL logic error or missing database",
139237  /* SQLITE_INTERNAL */ 0,
139238  /* SQLITE_PERM */ "access permission denied",
139239  /* SQLITE_ABORT */ "callback requested query abort",
139240  /* SQLITE_BUSY */ "database is locked",
139241  /* SQLITE_LOCKED */ "database table is locked",
139242  /* SQLITE_NOMEM */ "out of memory",
139243  /* SQLITE_READONLY */ "attempt to write a readonly database",
139244  /* SQLITE_INTERRUPT */ "interrupted",
139245  /* SQLITE_IOERR */ "disk I/O error",
139246  /* SQLITE_CORRUPT */ "database disk image is malformed",
139247  /* SQLITE_NOTFOUND */ "unknown operation",
139248  /* SQLITE_FULL */ "database or disk is full",
139249  /* SQLITE_CANTOPEN */ "unable to open database file",
139250  /* SQLITE_PROTOCOL */ "locking protocol",
139251  /* SQLITE_EMPTY */ "table contains no data",
139252  /* SQLITE_SCHEMA */ "database schema has changed",
139253  /* SQLITE_TOOBIG */ "string or blob too big",
139254  /* SQLITE_CONSTRAINT */ "constraint failed",
139255  /* SQLITE_MISMATCH */ "datatype mismatch",
139256  /* SQLITE_MISUSE */ "library routine called out of sequence",
139257  /* SQLITE_NOLFS */ "large file support is disabled",
139258  /* SQLITE_AUTH */ "authorization denied",
139259  /* SQLITE_FORMAT */ "auxiliary database format error",
139260  /* SQLITE_RANGE */ "bind or column index out of range",
139261  /* SQLITE_NOTADB */ "file is encrypted or is not a database",
139262  };
139263  const char *zErr = "unknown error";
139264  switch( rc ){
139265  case SQLITE_ABORT_ROLLBACK: {
139266  zErr = "abort due to ROLLBACK";
139267  break;
139268  }
139269  default: {
139270  rc &= 0xff;
139271  if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
139272  zErr = aMsg[rc];
139273  }
139274  break;
139275  }
139276  }
139277  return zErr;
139278 }
139279 
139280 /*
139281 ** This routine implements a busy callback that sleeps and tries
139282 ** again until a timeout value is reached. The timeout value is
139283 ** an integer number of milliseconds passed in as the first
139284 ** argument.
139285 */
139287  void *ptr, /* Database connection */
139288  int count /* Number of times table has been busy */
139289 ){
139290 #if SQLITE_OS_WIN || HAVE_USLEEP
139291  static const u8 delays[] =
139292  { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
139293  static const u8 totals[] =
139294  { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
139295 # define NDELAY ArraySize(delays)
139296  sqlite3 *db = (sqlite3 *)ptr;
139297  int timeout = db->busyTimeout;
139298  int delay, prior;
139299 
139300  assert( count>=0 );
139301  if( count < NDELAY ){
139302  delay = delays[count];
139303  prior = totals[count];
139304  }else{
139305  delay = delays[NDELAY-1];
139306  prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
139307  }
139308  if( prior + delay > timeout ){
139309  delay = timeout - prior;
139310  if( delay<=0 ) return 0;
139311  }
139312  sqlite3OsSleep(db->pVfs, delay*1000);
139313  return 1;
139314 #else
139315  sqlite3 *db = (sqlite3 *)ptr;
139316  int timeout = ((sqlite3 *)ptr)->busyTimeout;
139317  if( (count+1)*1000 > timeout ){
139318  return 0;
139319  }
139320  sqlite3OsSleep(db->pVfs, 1000000);
139321  return 1;
139322 #endif
139323 }
139324 
139325 /*
139326 ** Invoke the given busy handler.
139327 **
139328 ** This routine is called when an operation failed with a lock.
139329 ** If this routine returns non-zero, the lock is retried. If it
139330 ** returns 0, the operation aborts with an SQLITE_BUSY error.
139331 */
139333  int rc;
139334  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
139335  rc = p->xFunc(p->pArg, p->nBusy);
139336  if( rc==0 ){
139337  p->nBusy = -1;
139338  }else{
139339  p->nBusy++;
139340  }
139341  return rc;
139342 }
139343 
139344 /*
139345 ** This routine sets the busy callback for an Sqlite database to the
139346 ** given callback function with the given argument.
139347 */
139349  sqlite3 *db,
139350  int (*xBusy)(void*,int),
139351  void *pArg
139352 ){
139353 #ifdef SQLITE_ENABLE_API_ARMOR
139354  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139355 #endif
139356  sqlite3_mutex_enter(db->mutex);
139357  db->busyHandler.xFunc = xBusy;
139358  db->busyHandler.pArg = pArg;
139359  db->busyHandler.nBusy = 0;
139360  db->busyTimeout = 0;
139361  sqlite3_mutex_leave(db->mutex);
139362  return SQLITE_OK;
139363 }
139364 
139365 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
139366 /*
139367 ** This routine sets the progress callback for an Sqlite database to the
139368 ** given callback function with the given argument. The progress callback will
139369 ** be invoked every nOps opcodes.
139370 */
139372  sqlite3 *db,
139373  int nOps,
139374  int (*xProgress)(void*),
139375  void *pArg
139376 ){
139377 #ifdef SQLITE_ENABLE_API_ARMOR
139378  if( !sqlite3SafetyCheckOk(db) ){
139379  (void)SQLITE_MISUSE_BKPT;
139380  return;
139381  }
139382 #endif
139383  sqlite3_mutex_enter(db->mutex);
139384  if( nOps>0 ){
139385  db->xProgress = xProgress;
139386  db->nProgressOps = (unsigned)nOps;
139387  db->pProgressArg = pArg;
139388  }else{
139389  db->xProgress = 0;
139390  db->nProgressOps = 0;
139391  db->pProgressArg = 0;
139392  }
139393  sqlite3_mutex_leave(db->mutex);
139394 }
139395 #endif
139396 
139397 
139398 /*
139399 ** This routine installs a default busy handler that waits for the
139400 ** specified number of milliseconds before returning 0.
139401 */
139402 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
139403 #ifdef SQLITE_ENABLE_API_ARMOR
139404  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139405 #endif
139406  if( ms>0 ){
139408  db->busyTimeout = ms;
139409  }else{
139410  sqlite3_busy_handler(db, 0, 0);
139411  }
139412  return SQLITE_OK;
139413 }
139414 
139415 /*
139416 ** Cause any pending operation to stop at its earliest opportunity.
139417 */
139418 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
139419 #ifdef SQLITE_ENABLE_API_ARMOR
139420  if( !sqlite3SafetyCheckOk(db) ){
139421  (void)SQLITE_MISUSE_BKPT;
139422  return;
139423  }
139424 #endif
139425  db->u1.isInterrupted = 1;
139426 }
139427 
139428 
139429 /*
139430 ** This function is exactly the same as sqlite3_create_function(), except
139431 ** that it is designed to be called by internal code. The difference is
139432 ** that if a malloc() fails in sqlite3_create_function(), an error code
139433 ** is returned and the mallocFailed flag cleared.
139434 */
139436  sqlite3 *db,
139437  const char *zFunctionName,
139438  int nArg,
139439  int enc,
139440  void *pUserData,
139441  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
139442  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
139443  void (*xFinal)(sqlite3_context*),
139444  FuncDestructor *pDestructor
139445 ){
139446  FuncDef *p;
139447  int nName;
139448  int extraFlags;
139449 
139450  assert( sqlite3_mutex_held(db->mutex) );
139451  if( zFunctionName==0 ||
139452  (xSFunc && (xFinal || xStep)) ||
139453  (!xSFunc && (xFinal && !xStep)) ||
139454  (!xSFunc && (!xFinal && xStep)) ||
139455  (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
139456  (255<(nName = sqlite3Strlen30( zFunctionName))) ){
139457  return SQLITE_MISUSE_BKPT;
139458  }
139459 
139461  extraFlags = enc & SQLITE_DETERMINISTIC;
139462  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
139463 
139464 #ifndef SQLITE_OMIT_UTF16
139465  /* If SQLITE_UTF16 is specified as the encoding type, transform this
139466  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
139467  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
139468  **
139469  ** If SQLITE_ANY is specified, add three versions of the function
139470  ** to the hash table.
139471  */
139472  if( enc==SQLITE_UTF16 ){
139473  enc = SQLITE_UTF16NATIVE;
139474  }else if( enc==SQLITE_ANY ){
139475  int rc;
139476  rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
139477  pUserData, xSFunc, xStep, xFinal, pDestructor);
139478  if( rc==SQLITE_OK ){
139479  rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
139480  pUserData, xSFunc, xStep, xFinal, pDestructor);
139481  }
139482  if( rc!=SQLITE_OK ){
139483  return rc;
139484  }
139485  enc = SQLITE_UTF16BE;
139486  }
139487 #else
139488  enc = SQLITE_UTF8;
139489 #endif
139490 
139491  /* Check if an existing function is being overridden or deleted. If so,
139492  ** and there are active VMs, then return SQLITE_BUSY. If a function
139493  ** is being overridden/deleted but there are no active VMs, allow the
139494  ** operation to continue but invalidate all precompiled statements.
139495  */
139496  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
139497  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
139498  if( db->nVdbeActive ){
139500  "unable to delete/modify user-function due to active statements");
139501  assert( !db->mallocFailed );
139502  return SQLITE_BUSY;
139503  }else{
139505  }
139506  }
139507 
139508  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
139509  assert(p || db->mallocFailed);
139510  if( !p ){
139511  return SQLITE_NOMEM_BKPT;
139512  }
139513 
139514  /* If an older version of the function with a configured destructor is
139515  ** being replaced invoke the destructor function here. */
139516  functionDestroy(db, p);
139517 
139518  if( pDestructor ){
139519  pDestructor->nRef++;
139520  }
139521  p->u.pDestructor = pDestructor;
139522  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
139523  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
139524  p->xSFunc = xSFunc ? xSFunc : xStep;
139525  p->xFinalize = xFinal;
139526  p->pUserData = pUserData;
139527  p->nArg = (u16)nArg;
139528  return SQLITE_OK;
139529 }
139530 
139531 /*
139532 ** Create new user functions.
139533 */
139535  sqlite3 *db,
139536  const char *zFunc,
139537  int nArg,
139538  int enc,
139539  void *p,
139540  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
139541  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
139542  void (*xFinal)(sqlite3_context*)
139543 ){
139544  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
139545  xFinal, 0);
139546 }
139547 
139549  sqlite3 *db,
139550  const char *zFunc,
139551  int nArg,
139552  int enc,
139553  void *p,
139554  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
139555  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
139556  void (*xFinal)(sqlite3_context*),
139557  void (*xDestroy)(void *)
139558 ){
139559  int rc = SQLITE_ERROR;
139560  FuncDestructor *pArg = 0;
139561 
139562 #ifdef SQLITE_ENABLE_API_ARMOR
139563  if( !sqlite3SafetyCheckOk(db) ){
139564  return SQLITE_MISUSE_BKPT;
139565  }
139566 #endif
139567  sqlite3_mutex_enter(db->mutex);
139568  if( xDestroy ){
139569  pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
139570  if( !pArg ){
139571  xDestroy(p);
139572  goto out;
139573  }
139574  pArg->xDestroy = xDestroy;
139575  pArg->pUserData = p;
139576  }
139577  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
139578  if( pArg && pArg->nRef==0 ){
139579  assert( rc!=SQLITE_OK );
139580  xDestroy(p);
139581  sqlite3DbFree(db, pArg);
139582  }
139583 
139584  out:
139585  rc = sqlite3ApiExit(db, rc);
139586  sqlite3_mutex_leave(db->mutex);
139587  return rc;
139588 }
139589 
139590 #ifndef SQLITE_OMIT_UTF16
139592  sqlite3 *db,
139593  const void *zFunctionName,
139594  int nArg,
139595  int eTextRep,
139596  void *p,
139597  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
139598  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
139599  void (*xFinal)(sqlite3_context*)
139600 ){
139601  int rc;
139602  char *zFunc8;
139603 
139604 #ifdef SQLITE_ENABLE_API_ARMOR
139605  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
139606 #endif
139607  sqlite3_mutex_enter(db->mutex);
139608  assert( !db->mallocFailed );
139609  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
139610  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
139611  sqlite3DbFree(db, zFunc8);
139612  rc = sqlite3ApiExit(db, rc);
139613  sqlite3_mutex_leave(db->mutex);
139614  return rc;
139615 }
139616 #endif
139617 
139618 
139619 /*
139620 ** Declare that a function has been overloaded by a virtual table.
139621 **
139622 ** If the function already exists as a regular global function, then
139623 ** this routine is a no-op. If the function does not exist, then create
139624 ** a new one that always throws a run-time error.
139625 **
139626 ** When virtual tables intend to provide an overloaded function, they
139627 ** should call this routine to make sure the global function exists.
139628 ** A global function must exist in order for name resolution to work
139629 ** properly.
139630 */
139632  sqlite3 *db,
139633  const char *zName,
139634  int nArg
139635 ){
139636  int rc = SQLITE_OK;
139637 
139638 #ifdef SQLITE_ENABLE_API_ARMOR
139639  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
139640  return SQLITE_MISUSE_BKPT;
139641  }
139642 #endif
139643  sqlite3_mutex_enter(db->mutex);
139644  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
139645  rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
139646  0, sqlite3InvalidFunction, 0, 0, 0);
139647  }
139648  rc = sqlite3ApiExit(db, rc);
139649  sqlite3_mutex_leave(db->mutex);
139650  return rc;
139651 }
139652 
139653 #ifndef SQLITE_OMIT_TRACE
139654 /*
139655 ** Register a trace function. The pArg from the previously registered trace
139656 ** is returned.
139657 **
139658 ** A NULL trace function means that no tracing is executes. A non-NULL
139659 ** trace is a pointer to a function that is invoked at the start of each
139660 ** SQL statement.
139661 */
139662 #ifndef SQLITE_OMIT_DEPRECATED
139663 SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
139664  void *pOld;
139665 
139666 #ifdef SQLITE_ENABLE_API_ARMOR
139667  if( !sqlite3SafetyCheckOk(db) ){
139668  (void)SQLITE_MISUSE_BKPT;
139669  return 0;
139670  }
139671 #endif
139672  sqlite3_mutex_enter(db->mutex);
139673  pOld = db->pTraceArg;
139674  db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
139675  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
139676  db->pTraceArg = pArg;
139677  sqlite3_mutex_leave(db->mutex);
139678  return pOld;
139679 }
139680 #endif /* SQLITE_OMIT_DEPRECATED */
139681 
139682 /* Register a trace callback using the version-2 interface.
139683 */
139685  sqlite3 *db, /* Trace this connection */
139686  unsigned mTrace, /* Mask of events to be traced */
139687  int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
139688  void *pArg /* Context */
139689 ){
139690 #ifdef SQLITE_ENABLE_API_ARMOR
139691  if( !sqlite3SafetyCheckOk(db) ){
139692  return SQLITE_MISUSE_BKPT;
139693  }
139694 #endif
139695  sqlite3_mutex_enter(db->mutex);
139696  if( mTrace==0 ) xTrace = 0;
139697  if( xTrace==0 ) mTrace = 0;
139698  db->mTrace = mTrace;
139699  db->xTrace = xTrace;
139700  db->pTraceArg = pArg;
139701  sqlite3_mutex_leave(db->mutex);
139702  return SQLITE_OK;
139703 }
139704 
139705 #ifndef SQLITE_OMIT_DEPRECATED
139706 /*
139707 ** Register a profile function. The pArg from the previously registered
139708 ** profile function is returned.
139709 **
139710 ** A NULL profile function means that no profiling is executes. A non-NULL
139711 ** profile is a pointer to a function that is invoked at the conclusion of
139712 ** each SQL statement that is run.
139713 */
139715  sqlite3 *db,
139716  void (*xProfile)(void*,const char*,sqlite_uint64),
139717  void *pArg
139718 ){
139719  void *pOld;
139720 
139721 #ifdef SQLITE_ENABLE_API_ARMOR
139722  if( !sqlite3SafetyCheckOk(db) ){
139723  (void)SQLITE_MISUSE_BKPT;
139724  return 0;
139725  }
139726 #endif
139727  sqlite3_mutex_enter(db->mutex);
139728  pOld = db->pProfileArg;
139729  db->xProfile = xProfile;
139730  db->pProfileArg = pArg;
139731  sqlite3_mutex_leave(db->mutex);
139732  return pOld;
139733 }
139734 #endif /* SQLITE_OMIT_DEPRECATED */
139735 #endif /* SQLITE_OMIT_TRACE */
139736 
139737 /*
139738 ** Register a function to be invoked when a transaction commits.
139739 ** If the invoked function returns non-zero, then the commit becomes a
139740 ** rollback.
139741 */
139743  sqlite3 *db, /* Attach the hook to this database */
139744  int (*xCallback)(void*), /* Function to invoke on each commit */
139745  void *pArg /* Argument to the function */
139746 ){
139747  void *pOld;
139748 
139749 #ifdef SQLITE_ENABLE_API_ARMOR
139750  if( !sqlite3SafetyCheckOk(db) ){
139751  (void)SQLITE_MISUSE_BKPT;
139752  return 0;
139753  }
139754 #endif
139755  sqlite3_mutex_enter(db->mutex);
139756  pOld = db->pCommitArg;
139757  db->xCommitCallback = xCallback;
139758  db->pCommitArg = pArg;
139759  sqlite3_mutex_leave(db->mutex);
139760  return pOld;
139761 }
139762 
139763 /*
139764 ** Register a callback to be invoked each time a row is updated,
139765 ** inserted or deleted using this database connection.
139766 */
139768  sqlite3 *db, /* Attach the hook to this database */
139769  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
139770  void *pArg /* Argument to the function */
139771 ){
139772  void *pRet;
139773 
139774 #ifdef SQLITE_ENABLE_API_ARMOR
139775  if( !sqlite3SafetyCheckOk(db) ){
139776  (void)SQLITE_MISUSE_BKPT;
139777  return 0;
139778  }
139779 #endif
139780  sqlite3_mutex_enter(db->mutex);
139781  pRet = db->pUpdateArg;
139782  db->xUpdateCallback = xCallback;
139783  db->pUpdateArg = pArg;
139784  sqlite3_mutex_leave(db->mutex);
139785  return pRet;
139786 }
139787 
139788 /*
139789 ** Register a callback to be invoked each time a transaction is rolled
139790 ** back by this database connection.
139791 */
139793  sqlite3 *db, /* Attach the hook to this database */
139794  void (*xCallback)(void*), /* Callback function */
139795  void *pArg /* Argument to the function */
139796 ){
139797  void *pRet;
139798 
139799 #ifdef SQLITE_ENABLE_API_ARMOR
139800  if( !sqlite3SafetyCheckOk(db) ){
139801  (void)SQLITE_MISUSE_BKPT;
139802  return 0;
139803  }
139804 #endif
139805  sqlite3_mutex_enter(db->mutex);
139806  pRet = db->pRollbackArg;
139807  db->xRollbackCallback = xCallback;
139808  db->pRollbackArg = pArg;
139809  sqlite3_mutex_leave(db->mutex);
139810  return pRet;
139811 }
139812 
139813 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
139814 /*
139815 ** Register a callback to be invoked each time a row is updated,
139816 ** inserted or deleted using this database connection.
139817 */
139819  sqlite3 *db, /* Attach the hook to this database */
139820  void(*xCallback)( /* Callback function */
139821  void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
139822  void *pArg /* First callback argument */
139823 ){
139824  void *pRet;
139825  sqlite3_mutex_enter(db->mutex);
139826  pRet = db->pPreUpdateArg;
139827  db->xPreUpdateCallback = xCallback;
139828  db->pPreUpdateArg = pArg;
139829  sqlite3_mutex_leave(db->mutex);
139830  return pRet;
139831 }
139832 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
139833 
139834 #ifndef SQLITE_OMIT_WAL
139835 /*
139836 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
139837 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
139838 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
139839 ** wal_autocheckpoint()).
139840 */
139842  void *pClientData, /* Argument */
139843  sqlite3 *db, /* Connection */
139844  const char *zDb, /* Database */
139845  int nFrame /* Size of WAL */
139846 ){
139847  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
139849  sqlite3_wal_checkpoint(db, zDb);
139851  }
139852  return SQLITE_OK;
139853 }
139854 #endif /* SQLITE_OMIT_WAL */
139855 
139856 /*
139857 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
139858 ** a database after committing a transaction if there are nFrame or
139859 ** more frames in the log file. Passing zero or a negative value as the
139860 ** nFrame parameter disables automatic checkpoints entirely.
139861 **
139862 ** The callback registered by this function replaces any existing callback
139863 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
139864 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
139865 ** configured by this function.
139866 */
139867 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
139868 #ifdef SQLITE_OMIT_WAL
139869  UNUSED_PARAMETER(db);
139870  UNUSED_PARAMETER(nFrame);
139871 #else
139872 #ifdef SQLITE_ENABLE_API_ARMOR
139873  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139874 #endif
139875  if( nFrame>0 ){
139877  }else{
139878  sqlite3_wal_hook(db, 0, 0);
139879  }
139880 #endif
139881  return SQLITE_OK;
139882 }
139883 
139884 /*
139885 ** Register a callback to be invoked each time a transaction is written
139886 ** into the write-ahead-log by this database connection.
139887 */
139889  sqlite3 *db, /* Attach the hook to this db handle */
139890  int(*xCallback)(void *, sqlite3*, const char*, int),
139891  void *pArg /* First argument passed to xCallback() */
139892 ){
139893 #ifndef SQLITE_OMIT_WAL
139894  void *pRet;
139895 #ifdef SQLITE_ENABLE_API_ARMOR
139896  if( !sqlite3SafetyCheckOk(db) ){
139897  (void)SQLITE_MISUSE_BKPT;
139898  return 0;
139899  }
139900 #endif
139901  sqlite3_mutex_enter(db->mutex);
139902  pRet = db->pWalArg;
139903  db->xWalCallback = xCallback;
139904  db->pWalArg = pArg;
139905  sqlite3_mutex_leave(db->mutex);
139906  return pRet;
139907 #else
139908  return 0;
139909 #endif
139910 }
139911 
139912 /*
139913 ** Checkpoint database zDb.
139914 */
139916  sqlite3 *db, /* Database handle */
139917  const char *zDb, /* Name of attached database (or NULL) */
139918  int eMode, /* SQLITE_CHECKPOINT_* value */
139919  int *pnLog, /* OUT: Size of WAL log in frames */
139920  int *pnCkpt /* OUT: Total number of frames checkpointed */
139921 ){
139922 #ifdef SQLITE_OMIT_WAL
139923  return SQLITE_OK;
139924 #else
139925  int rc; /* Return code */
139926  int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
139927 
139928 #ifdef SQLITE_ENABLE_API_ARMOR
139929  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139930 #endif
139931 
139932  /* Initialize the output variables to -1 in case an error occurs. */
139933  if( pnLog ) *pnLog = -1;
139934  if( pnCkpt ) *pnCkpt = -1;
139935 
139936  assert( SQLITE_CHECKPOINT_PASSIVE==0 );
139937  assert( SQLITE_CHECKPOINT_FULL==1 );
139938  assert( SQLITE_CHECKPOINT_RESTART==2 );
139939  assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
139940  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
139941  /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
139942  ** mode: */
139943  return SQLITE_MISUSE;
139944  }
139945 
139946  sqlite3_mutex_enter(db->mutex);
139947  if( zDb && zDb[0] ){
139948  iDb = sqlite3FindDbName(db, zDb);
139949  }
139950  if( iDb<0 ){
139951  rc = SQLITE_ERROR;
139952  sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
139953  }else{
139954  db->busyHandler.nBusy = 0;
139955  rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
139956  sqlite3Error(db, rc);
139957  }
139958  rc = sqlite3ApiExit(db, rc);
139959  sqlite3_mutex_leave(db->mutex);
139960  return rc;
139961 #endif
139962 }
139963 
139964 
139965 /*
139966 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
139967 ** to contains a zero-length string, all attached databases are
139968 ** checkpointed.
139969 */
139970 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
139971  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
139972  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
139974 }
139975 
139976 #ifndef SQLITE_OMIT_WAL
139977 /*
139978 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
139979 ** not currently open in WAL mode.
139980 **
139981 ** If a transaction is open on the database being checkpointed, this
139982 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
139983 ** an error occurs while running the checkpoint, an SQLite error code is
139984 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
139985 **
139986 ** The mutex on database handle db should be held by the caller. The mutex
139987 ** associated with the specific b-tree being checkpointed is taken by
139988 ** this function while the checkpoint is running.
139989 **
139990 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
139991 ** checkpointed. If an error is encountered it is returned immediately -
139992 ** no attempt is made to checkpoint any remaining databases.
139993 **
139994 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
139995 */
139996 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
139997  int rc = SQLITE_OK; /* Return code */
139998  int i; /* Used to iterate through attached dbs */
139999  int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
140000 
140001  assert( sqlite3_mutex_held(db->mutex) );
140002  assert( !pnLog || *pnLog==-1 );
140003  assert( !pnCkpt || *pnCkpt==-1 );
140004 
140005  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
140006  if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
140007  rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
140008  pnLog = 0;
140009  pnCkpt = 0;
140010  if( rc==SQLITE_BUSY ){
140011  bBusy = 1;
140012  rc = SQLITE_OK;
140013  }
140014  }
140015  }
140016 
140017  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
140018 }
140019 #endif /* SQLITE_OMIT_WAL */
140020 
140021 /*
140022 ** This function returns true if main-memory should be used instead of
140023 ** a temporary file for transient pager files and statement journals.
140024 ** The value returned depends on the value of db->temp_store (runtime
140025 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
140026 ** following table describes the relationship between these two values
140027 ** and this functions return value.
140028 **
140029 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
140030 ** ----------------- -------------- ------------------------------
140031 ** 0 any file (return 0)
140032 ** 1 1 file (return 0)
140033 ** 1 2 memory (return 1)
140034 ** 1 0 file (return 0)
140035 ** 2 1 file (return 0)
140036 ** 2 2 memory (return 1)
140037 ** 2 0 memory (return 1)
140038 ** 3 any memory (return 1)
140039 */
140040 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
140041 #if SQLITE_TEMP_STORE==1
140042  return ( db->temp_store==2 );
140043 #endif
140044 #if SQLITE_TEMP_STORE==2
140045  return ( db->temp_store!=1 );
140046 #endif
140047 #if SQLITE_TEMP_STORE==3
140048  UNUSED_PARAMETER(db);
140049  return 1;
140050 #endif
140051 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
140052  UNUSED_PARAMETER(db);
140053  return 0;
140054 #endif
140055 }
140056 
140057 /*
140058 ** Return UTF-8 encoded English language explanation of the most recent
140059 ** error.
140060 */
140061 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
140062  const char *z;
140063  if( !db ){
140065  }
140066  if( !sqlite3SafetyCheckSickOrOk(db) ){
140068  }
140069  sqlite3_mutex_enter(db->mutex);
140070  if( db->mallocFailed ){
140072  }else{
140073  testcase( db->pErr==0 );
140074  z = (char*)sqlite3_value_text(db->pErr);
140075  assert( !db->mallocFailed );
140076  if( z==0 ){
140077  z = sqlite3ErrStr(db->errCode);
140078  }
140079  }
140080  sqlite3_mutex_leave(db->mutex);
140081  return z;
140082 }
140083 
140084 #ifndef SQLITE_OMIT_UTF16
140085 /*
140086 ** Return UTF-16 encoded English language explanation of the most recent
140087 ** error.
140088 */
140089 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
140090  static const u16 outOfMem[] = {
140091  'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
140092  };
140093  static const u16 misuse[] = {
140094  'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
140095  'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
140096  'c', 'a', 'l', 'l', 'e', 'd', ' ',
140097  'o', 'u', 't', ' ',
140098  'o', 'f', ' ',
140099  's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
140100  };
140101 
140102  const void *z;
140103  if( !db ){
140104  return (void *)outOfMem;
140105  }
140106  if( !sqlite3SafetyCheckSickOrOk(db) ){
140107  return (void *)misuse;
140108  }
140109  sqlite3_mutex_enter(db->mutex);
140110  if( db->mallocFailed ){
140111  z = (void *)outOfMem;
140112  }else{
140113  z = sqlite3_value_text16(db->pErr);
140114  if( z==0 ){
140116  z = sqlite3_value_text16(db->pErr);
140117  }
140118  /* A malloc() may have failed within the call to sqlite3_value_text16()
140119  ** above. If this is the case, then the db->mallocFailed flag needs to
140120  ** be cleared before returning. Do this directly, instead of via
140121  ** sqlite3ApiExit(), to avoid setting the database handle error message.
140122  */
140123  sqlite3OomClear(db);
140124  }
140125  sqlite3_mutex_leave(db->mutex);
140126  return z;
140127 }
140128 #endif /* SQLITE_OMIT_UTF16 */
140129 
140130 /*
140131 ** Return the most recent error code generated by an SQLite routine. If NULL is
140132 ** passed to this function, we assume a malloc() failed during sqlite3_open().
140133 */
140134 SQLITE_API int sqlite3_errcode(sqlite3 *db){
140135  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
140136  return SQLITE_MISUSE_BKPT;
140137  }
140138  if( !db || db->mallocFailed ){
140139  return SQLITE_NOMEM_BKPT;
140140  }
140141  return db->errCode & db->errMask;
140142 }
140144  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
140145  return SQLITE_MISUSE_BKPT;
140146  }
140147  if( !db || db->mallocFailed ){
140148  return SQLITE_NOMEM_BKPT;
140149  }
140150  return db->errCode;
140151 }
140153  return db ? db->iSysErrno : 0;
140154 }
140155 
140156 /*
140157 ** Return a string that describes the kind of error specified in the
140158 ** argument. For now, this simply calls the internal sqlite3ErrStr()
140159 ** function.
140160 */
140161 SQLITE_API const char *sqlite3_errstr(int rc){
140162  return sqlite3ErrStr(rc);
140163 }
140164 
140165 /*
140166 ** Create a new collating function for database "db". The name is zName
140167 ** and the encoding is enc.
140168 */
140169 static int createCollation(
140170  sqlite3* db,
140171  const char *zName,
140172  u8 enc,
140173  void* pCtx,
140174  int(*xCompare)(void*,int,const void*,int,const void*),
140175  void(*xDel)(void*)
140176 ){
140177  CollSeq *pColl;
140178  int enc2;
140179 
140180  assert( sqlite3_mutex_held(db->mutex) );
140181 
140182  /* If SQLITE_UTF16 is specified as the encoding type, transform this
140183  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
140184  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
140185  */
140186  enc2 = enc;
140187  testcase( enc2==SQLITE_UTF16 );
140188  testcase( enc2==SQLITE_UTF16_ALIGNED );
140189  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
140190  enc2 = SQLITE_UTF16NATIVE;
140191  }
140192  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
140193  return SQLITE_MISUSE_BKPT;
140194  }
140195 
140196  /* Check if this call is removing or replacing an existing collation
140197  ** sequence. If so, and there are active VMs, return busy. If there
140198  ** are no active VMs, invalidate any pre-compiled statements.
140199  */
140200  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
140201  if( pColl && pColl->xCmp ){
140202  if( db->nVdbeActive ){
140204  "unable to delete/modify collation sequence due to active statements");
140205  return SQLITE_BUSY;
140206  }
140208 
140209  /* If collation sequence pColl was created directly by a call to
140210  ** sqlite3_create_collation, and not generated by synthCollSeq(),
140211  ** then any copies made by synthCollSeq() need to be invalidated.
140212  ** Also, collation destructor - CollSeq.xDel() - function may need
140213  ** to be called.
140214  */
140215  if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
140216  CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
140217  int j;
140218  for(j=0; j<3; j++){
140219  CollSeq *p = &aColl[j];
140220  if( p->enc==pColl->enc ){
140221  if( p->xDel ){
140222  p->xDel(p->pUser);
140223  }
140224  p->xCmp = 0;
140225  }
140226  }
140227  }
140228  }
140229 
140230  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
140231  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
140232  pColl->xCmp = xCompare;
140233  pColl->pUser = pCtx;
140234  pColl->xDel = xDel;
140235  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
140236  sqlite3Error(db, SQLITE_OK);
140237  return SQLITE_OK;
140238 }
140239 
140240 
140241 /*
140242 ** This array defines hard upper bounds on limit values. The
140243 ** initializer must be kept in sync with the SQLITE_LIMIT_*
140244 ** #defines in sqlite3.h.
140245 */
140246 static const int aHardLimit[] = {
140256  SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
140259 };
140260 
140261 /*
140262 ** Make sure the hard limits are set to reasonable values
140263 */
140264 #if SQLITE_MAX_LENGTH<100
140265 # error SQLITE_MAX_LENGTH must be at least 100
140266 #endif
140267 #if SQLITE_MAX_SQL_LENGTH<100
140268 # error SQLITE_MAX_SQL_LENGTH must be at least 100
140269 #endif
140270 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
140271 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
140272 #endif
140273 #if SQLITE_MAX_COMPOUND_SELECT<2
140274 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
140275 #endif
140276 #if SQLITE_MAX_VDBE_OP<40
140277 # error SQLITE_MAX_VDBE_OP must be at least 40
140278 #endif
140279 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
140280 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
140281 #endif
140282 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
140283 # error SQLITE_MAX_ATTACHED must be between 0 and 125
140284 #endif
140285 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
140286 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
140287 #endif
140288 #if SQLITE_MAX_COLUMN>32767
140289 # error SQLITE_MAX_COLUMN must not exceed 32767
140290 #endif
140291 #if SQLITE_MAX_TRIGGER_DEPTH<1
140292 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
140293 #endif
140294 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
140295 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
140296 #endif
140297 
140298 
140299 /*
140300 ** Change the value of a limit. Report the old value.
140301 ** If an invalid limit index is supplied, report -1.
140302 ** Make no changes but still report the old value if the
140303 ** new limit is negative.
140304 **
140305 ** A new lower limit does not shrink existing constructs.
140306 ** It merely prevents new constructs that exceed the limit
140307 ** from forming.
140308 */
140309 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
140310  int oldLimit;
140311 
140312 #ifdef SQLITE_ENABLE_API_ARMOR
140313  if( !sqlite3SafetyCheckOk(db) ){
140314  (void)SQLITE_MISUSE_BKPT;
140315  return -1;
140316  }
140317 #endif
140318 
140319  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
140320  ** there is a hard upper bound set at compile-time by a C preprocessor
140321  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
140322  ** "_MAX_".)
140323  */
140324  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
140325  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
140326  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
140327  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
140329  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
140330  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
140331  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
140332  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
140335  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
140338 
140339 
140340  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
140341  return -1;
140342  }
140343  oldLimit = db->aLimit[limitId];
140344  if( newLimit>=0 ){ /* IMP: R-52476-28732 */
140345  if( newLimit>aHardLimit[limitId] ){
140346  newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
140347  }
140348  db->aLimit[limitId] = newLimit;
140349  }
140350  return oldLimit; /* IMP: R-53341-35419 */
140351 }
140352 
140353 /*
140354 ** This function is used to parse both URIs and non-URI filenames passed by the
140355 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
140356 ** URIs specified as part of ATTACH statements.
140357 **
140358 ** The first argument to this function is the name of the VFS to use (or
140359 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
140360 ** query parameter. The second argument contains the URI (or non-URI filename)
140361 ** itself. When this function is called the *pFlags variable should contain
140362 ** the default flags to open the database handle with. The value stored in
140363 ** *pFlags may be updated before returning if the URI filename contains
140364 ** "cache=xxx" or "mode=xxx" query parameters.
140365 **
140366 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
140367 ** the VFS that should be used to open the database file. *pzFile is set to
140368 ** point to a buffer containing the name of the file to open. It is the
140369 ** responsibility of the caller to eventually call sqlite3_free() to release
140370 ** this buffer.
140371 **
140372 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
140373 ** may be set to point to a buffer containing an English language error
140374 ** message. It is the responsibility of the caller to eventually release
140375 ** this buffer by calling sqlite3_free().
140376 */
140378  const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
140379  const char *zUri, /* Nul-terminated URI to parse */
140380  unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
140381  sqlite3_vfs **ppVfs, /* OUT: VFS to use */
140382  char **pzFile, /* OUT: Filename component of URI */
140383  char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
140384 ){
140385  int rc = SQLITE_OK;
140386  unsigned int flags = *pFlags;
140387  const char *zVfs = zDefaultVfs;
140388  char *zFile;
140389  char c;
140390  int nUri = sqlite3Strlen30(zUri);
140391 
140392  assert( *pzErrMsg==0 );
140393 
140394  if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
140395  || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
140396  && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
140397  ){
140398  char *zOpt;
140399  int eState; /* Parser state when parsing URI */
140400  int iIn; /* Input character index */
140401  int iOut = 0; /* Output character index */
140402  u64 nByte = nUri+2; /* Bytes of space to allocate */
140403 
140404  /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
140405  ** method that there may be extra parameters following the file-name. */
140406  flags |= SQLITE_OPEN_URI;
140407 
140408  for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
140409  zFile = sqlite3_malloc64(nByte);
140410  if( !zFile ) return SQLITE_NOMEM_BKPT;
140411 
140412  iIn = 5;
140413 #ifdef SQLITE_ALLOW_URI_AUTHORITY
140414  if( strncmp(zUri+5, "///", 3)==0 ){
140415  iIn = 7;
140416  /* The following condition causes URIs with five leading / characters
140417  ** like file://///host/path to be converted into UNCs like //host/path.
140418  ** The correct URI for that UNC has only two or four leading / characters
140419  ** file://host/path or file:////host/path. But 5 leading slashes is a
140420  ** common error, we are told, so we handle it as a special case. */
140421  if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
140422  }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
140423  iIn = 16;
140424  }
140425 #else
140426  /* Discard the scheme and authority segments of the URI. */
140427  if( zUri[5]=='/' && zUri[6]=='/' ){
140428  iIn = 7;
140429  while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
140430  if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
140431  *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
140432  iIn-7, &zUri[7]);
140433  rc = SQLITE_ERROR;
140434  goto parse_uri_out;
140435  }
140436  }
140437 #endif
140438 
140439  /* Copy the filename and any query parameters into the zFile buffer.
140440  ** Decode %HH escape codes along the way.
140441  **
140442  ** Within this loop, variable eState may be set to 0, 1 or 2, depending
140443  ** on the parsing context. As follows:
140444  **
140445  ** 0: Parsing file-name.
140446  ** 1: Parsing name section of a name=value query parameter.
140447  ** 2: Parsing value section of a name=value query parameter.
140448  */
140449  eState = 0;
140450  while( (c = zUri[iIn])!=0 && c!='#' ){
140451  iIn++;
140452  if( c=='%'
140453  && sqlite3Isxdigit(zUri[iIn])
140454  && sqlite3Isxdigit(zUri[iIn+1])
140455  ){
140456  int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
140457  octet += sqlite3HexToInt(zUri[iIn++]);
140458 
140459  assert( octet>=0 && octet<256 );
140460  if( octet==0 ){
140461  /* This branch is taken when "%00" appears within the URI. In this
140462  ** case we ignore all text in the remainder of the path, name or
140463  ** value currently being parsed. So ignore the current character
140464  ** and skip to the next "?", "=" or "&", as appropriate. */
140465  while( (c = zUri[iIn])!=0 && c!='#'
140466  && (eState!=0 || c!='?')
140467  && (eState!=1 || (c!='=' && c!='&'))
140468  && (eState!=2 || c!='&')
140469  ){
140470  iIn++;
140471  }
140472  continue;
140473  }
140474  c = octet;
140475  }else if( eState==1 && (c=='&' || c=='=') ){
140476  if( zFile[iOut-1]==0 ){
140477  /* An empty option name. Ignore this option altogether. */
140478  while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
140479  continue;
140480  }
140481  if( c=='&' ){
140482  zFile[iOut++] = '\0';
140483  }else{
140484  eState = 2;
140485  }
140486  c = 0;
140487  }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
140488  c = 0;
140489  eState = 1;
140490  }
140491  zFile[iOut++] = c;
140492  }
140493  if( eState==1 ) zFile[iOut++] = '\0';
140494  zFile[iOut++] = '\0';
140495  zFile[iOut++] = '\0';
140496 
140497  /* Check if there were any options specified that should be interpreted
140498  ** here. Options that are interpreted here include "vfs" and those that
140499  ** correspond to flags that may be passed to the sqlite3_open_v2()
140500  ** method. */
140501  zOpt = &zFile[sqlite3Strlen30(zFile)+1];
140502  while( zOpt[0] ){
140503  int nOpt = sqlite3Strlen30(zOpt);
140504  char *zVal = &zOpt[nOpt+1];
140505  int nVal = sqlite3Strlen30(zVal);
140506 
140507  if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
140508  zVfs = zVal;
140509  }else{
140510  struct OpenMode {
140511  const char *z;
140512  int mode;
140513  } *aMode = 0;
140514  char *zModeType = 0;
140515  int mask = 0;
140516  int limit = 0;
140517 
140518  if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
140519  static struct OpenMode aCacheMode[] = {
140520  { "shared", SQLITE_OPEN_SHAREDCACHE },
140521  { "private", SQLITE_OPEN_PRIVATECACHE },
140522  { 0, 0 }
140523  };
140524 
140526  aMode = aCacheMode;
140527  limit = mask;
140528  zModeType = "cache";
140529  }
140530  if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
140531  static struct OpenMode aOpenMode[] = {
140532  { "ro", SQLITE_OPEN_READONLY },
140533  { "rw", SQLITE_OPEN_READWRITE },
140535  { "memory", SQLITE_OPEN_MEMORY },
140536  { 0, 0 }
140537  };
140538 
140541  aMode = aOpenMode;
140542  limit = mask & flags;
140543  zModeType = "access";
140544  }
140545 
140546  if( aMode ){
140547  int i;
140548  int mode = 0;
140549  for(i=0; aMode[i].z; i++){
140550  const char *z = aMode[i].z;
140551  if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
140552  mode = aMode[i].mode;
140553  break;
140554  }
140555  }
140556  if( mode==0 ){
140557  *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
140558  rc = SQLITE_ERROR;
140559  goto parse_uri_out;
140560  }
140561  if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
140562  *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
140563  zModeType, zVal);
140564  rc = SQLITE_PERM;
140565  goto parse_uri_out;
140566  }
140567  flags = (flags & ~mask) | mode;
140568  }
140569  }
140570 
140571  zOpt = &zVal[nVal+1];
140572  }
140573 
140574  }else{
140575  zFile = sqlite3_malloc64(nUri+2);
140576  if( !zFile ) return SQLITE_NOMEM_BKPT;
140577  memcpy(zFile, zUri, nUri);
140578  zFile[nUri] = '\0';
140579  zFile[nUri+1] = '\0';
140580  flags &= ~SQLITE_OPEN_URI;
140581  }
140582 
140583  *ppVfs = sqlite3_vfs_find(zVfs);
140584  if( *ppVfs==0 ){
140585  *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
140586  rc = SQLITE_ERROR;
140587  }
140588  parse_uri_out:
140589  if( rc!=SQLITE_OK ){
140590  sqlite3_free(zFile);
140591  zFile = 0;
140592  }
140593  *pFlags = flags;
140594  *pzFile = zFile;
140595  return rc;
140596 }
140597 
140598 
140599 /*
140600 ** This routine does the work of opening a database on behalf of
140601 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
140602 ** is UTF-8 encoded.
140603 */
140604 static int openDatabase(
140605  const char *zFilename, /* Database filename UTF-8 encoded */
140606  sqlite3 **ppDb, /* OUT: Returned database handle */
140607  unsigned int flags, /* Operational flags */
140608  const char *zVfs /* Name of the VFS to use */
140609 ){
140610  sqlite3 *db; /* Store allocated handle here */
140611  int rc; /* Return code */
140612  int isThreadsafe; /* True for threadsafe connections */
140613  char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
140614  char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
140615 
140616 #ifdef SQLITE_ENABLE_API_ARMOR
140617  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
140618 #endif
140619  *ppDb = 0;
140620 #ifndef SQLITE_OMIT_AUTOINIT
140621  rc = sqlite3_initialize();
140622  if( rc ) return rc;
140623 #endif
140624 
140625  /* Only allow sensible combinations of bits in the flags argument.
140626  ** Throw an error if any non-sense combination is used. If we
140627  ** do not block illegal combinations here, it could trigger
140628  ** assert() statements in deeper layers. Sensible combinations
140629  ** are:
140630  **
140631  ** 1: SQLITE_OPEN_READONLY
140632  ** 2: SQLITE_OPEN_READWRITE
140633  ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
140634  */
140635  assert( SQLITE_OPEN_READONLY == 0x01 );
140636  assert( SQLITE_OPEN_READWRITE == 0x02 );
140637  assert( SQLITE_OPEN_CREATE == 0x04 );
140638  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
140639  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
140640  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
140641  if( ((1<<(flags&7)) & 0x46)==0 ){
140642  return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
140643  }
140644 
140645  if( sqlite3GlobalConfig.bCoreMutex==0 ){
140646  isThreadsafe = 0;
140647  }else if( flags & SQLITE_OPEN_NOMUTEX ){
140648  isThreadsafe = 0;
140649  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
140650  isThreadsafe = 1;
140651  }else{
140652  isThreadsafe = sqlite3GlobalConfig.bFullMutex;
140653  }
140654  if( flags & SQLITE_OPEN_PRIVATECACHE ){
140655  flags &= ~SQLITE_OPEN_SHAREDCACHE;
140656  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
140657  flags |= SQLITE_OPEN_SHAREDCACHE;
140658  }
140659 
140660  /* Remove harmful bits from the flags parameter
140661  **
140662  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
140663  ** dealt with in the previous code block. Besides these, the only
140664  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
140665  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
140666  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
140667  ** off all other flags.
140668  */
140669  flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
140678  SQLITE_OPEN_NOMUTEX |
140679  SQLITE_OPEN_FULLMUTEX |
140681  );
140682 
140683  /* Allocate the sqlite data structure */
140684  db = sqlite3MallocZero( sizeof(sqlite3) );
140685  if( db==0 ) goto opendb_out;
140686  if( isThreadsafe ){
140688  if( db->mutex==0 ){
140689  sqlite3_free(db);
140690  db = 0;
140691  goto opendb_out;
140692  }
140693  }
140694  sqlite3_mutex_enter(db->mutex);
140695  db->errMask = 0xff;
140696  db->nDb = 2;
140697  db->magic = SQLITE_MAGIC_BUSY;
140698  db->aDb = db->aDbStatic;
140699 
140700  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
140701  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
140703  db->autoCommit = 1;
140704  db->nextAutovac = -1;
140705  db->szMmap = sqlite3GlobalConfig.szMmap;
140706  db->nextPagesize = 0;
140707  db->nMaxSorterMmap = 0x7FFFFFFF;
140709 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
140710  | SQLITE_AutoIndex
140711 #endif
140712 #if SQLITE_DEFAULT_CKPTFULLFSYNC
140714 #endif
140715 #if SQLITE_DEFAULT_FILE_FORMAT<4
140717 #endif
140718 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
140720 #endif
140721 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
140723 #endif
140724 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
140726 #endif
140727 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
140729 #endif
140730 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
140732 #endif
140733 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
140735 #endif
140736  ;
140737  sqlite3HashInit(&db->aCollSeq);
140738 #ifndef SQLITE_OMIT_VIRTUALTABLE
140739  sqlite3HashInit(&db->aModule);
140740 #endif
140741 
140742  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
140743  ** and UTF-16, so add a version for each to avoid any unnecessary
140744  ** conversions. The only error that can occur here is a malloc() failure.
140745  **
140746  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
140747  ** functions:
140748  */
140749  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
140750  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
140751  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
140752  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
140753  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
140754  if( db->mallocFailed ){
140755  goto opendb_out;
140756  }
140757  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
140758  ** strings is BINARY.
140759  */
140760  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
140761  assert( db->pDfltColl!=0 );
140762 
140763  /* Parse the filename/URI argument. */
140764  db->openFlags = flags;
140765  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
140766  if( rc!=SQLITE_OK ){
140767  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
140768  sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
140769  sqlite3_free(zErrMsg);
140770  goto opendb_out;
140771  }
140772 
140773  /* Open the backend database driver */
140774  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
140775  flags | SQLITE_OPEN_MAIN_DB);
140776  if( rc!=SQLITE_OK ){
140777  if( rc==SQLITE_IOERR_NOMEM ){
140778  rc = SQLITE_NOMEM_BKPT;
140779  }
140780  sqlite3Error(db, rc);
140781  goto opendb_out;
140782  }
140783  sqlite3BtreeEnter(db->aDb[0].pBt);
140784  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
140785  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
140786  sqlite3BtreeLeave(db->aDb[0].pBt);
140787  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
140788 
140789  /* The default safety_level for the main database is FULL; for the temp
140790  ** database it is OFF. This matches the pager layer defaults.
140791  */
140792  db->aDb[0].zDbSName = "main";
140794  db->aDb[1].zDbSName = "temp";
140796 
140797  db->magic = SQLITE_MAGIC_OPEN;
140798  if( db->mallocFailed ){
140799  goto opendb_out;
140800  }
140801 
140802  /* Register all built-in functions, but do not attempt to read the
140803  ** database schema yet. This is delayed until the first time the database
140804  ** is accessed.
140805  */
140806  sqlite3Error(db, SQLITE_OK);
140808  rc = sqlite3_errcode(db);
140809 
140810 #ifdef SQLITE_ENABLE_FTS5
140811  /* Register any built-in FTS5 module before loading the automatic
140812  ** extensions. This allows automatic extensions to register FTS5
140813  ** tokenizers and auxiliary functions. */
140814  if( !db->mallocFailed && rc==SQLITE_OK ){
140815  rc = sqlite3Fts5Init(db);
140816  }
140817 #endif
140818 
140819  /* Load automatic extensions - extensions that have been registered
140820  ** using the sqlite3_automatic_extension() API.
140821  */
140822  if( rc==SQLITE_OK ){
140824  rc = sqlite3_errcode(db);
140825  if( rc!=SQLITE_OK ){
140826  goto opendb_out;
140827  }
140828  }
140829 
140830 #ifdef SQLITE_ENABLE_FTS1
140831  if( !db->mallocFailed ){
140832  extern int sqlite3Fts1Init(sqlite3*);
140833  rc = sqlite3Fts1Init(db);
140834  }
140835 #endif
140836 
140837 #ifdef SQLITE_ENABLE_FTS2
140838  if( !db->mallocFailed && rc==SQLITE_OK ){
140839  extern int sqlite3Fts2Init(sqlite3*);
140840  rc = sqlite3Fts2Init(db);
140841  }
140842 #endif
140843 
140844 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
140845  if( !db->mallocFailed && rc==SQLITE_OK ){
140846  rc = sqlite3Fts3Init(db);
140847  }
140848 #endif
140849 
140850 #ifdef SQLITE_ENABLE_ICU
140851  if( !db->mallocFailed && rc==SQLITE_OK ){
140852  rc = sqlite3IcuInit(db);
140853  }
140854 #endif
140855 
140856 #ifdef SQLITE_ENABLE_RTREE
140857  if( !db->mallocFailed && rc==SQLITE_OK){
140858  rc = sqlite3RtreeInit(db);
140859  }
140860 #endif
140861 
140862 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
140863  if( !db->mallocFailed && rc==SQLITE_OK){
140864  rc = sqlite3DbstatRegister(db);
140865  }
140866 #endif
140867 
140868 #ifdef SQLITE_ENABLE_JSON1
140869  if( !db->mallocFailed && rc==SQLITE_OK){
140870  rc = sqlite3Json1Init(db);
140871  }
140872 #endif
140873 
140874  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
140875  ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
140876  ** mode. Doing nothing at all also makes NORMAL the default.
140877  */
140878 #ifdef SQLITE_DEFAULT_LOCKING_MODE
140879  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
140881  SQLITE_DEFAULT_LOCKING_MODE);
140882 #endif
140883 
140884  if( rc ) sqlite3Error(db, rc);
140885 
140886  /* Enable the lookaside-malloc subsystem */
140887  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
140888  sqlite3GlobalConfig.nLookaside);
140889 
140891 
140892 opendb_out:
140893  if( db ){
140894  assert( db->mutex!=0 || isThreadsafe==0
140895  || sqlite3GlobalConfig.bFullMutex==0 );
140896  sqlite3_mutex_leave(db->mutex);
140897  }
140898  rc = sqlite3_errcode(db);
140899  assert( db!=0 || rc==SQLITE_NOMEM );
140900  if( rc==SQLITE_NOMEM ){
140901  sqlite3_close(db);
140902  db = 0;
140903  }else if( rc!=SQLITE_OK ){
140904  db->magic = SQLITE_MAGIC_SICK;
140905  }
140906  *ppDb = db;
140907 #ifdef SQLITE_ENABLE_SQLLOG
140908  if( sqlite3GlobalConfig.xSqllog ){
140909  /* Opening a db handle. Fourth parameter is passed 0. */
140910  void *pArg = sqlite3GlobalConfig.pSqllogArg;
140911  sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
140912  }
140913 #endif
140914 #if defined(SQLITE_HAS_CODEC)
140915  if( rc==SQLITE_OK ){
140916  const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
140917  if( zHexKey && zHexKey[0] ){
140918  u8 iByte;
140919  int i;
140920  char zKey[40];
140921  for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
140922  iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
140923  if( (i&1)!=0 ) zKey[i/2] = iByte;
140924  }
140925  sqlite3_key_v2(db, 0, zKey, i/2);
140926  }
140927  }
140928 #endif
140929  sqlite3_free(zOpen);
140930  return rc & 0xff;
140931 }
140932 
140933 /*
140934 ** Open a new database handle.
140935 */
140937  const char *zFilename,
140938  sqlite3 **ppDb
140939 ){
140940  return openDatabase(zFilename, ppDb,
140942 }
140944  const char *filename, /* Database filename (UTF-8) */
140945  sqlite3 **ppDb, /* OUT: SQLite db handle */
140946  int flags, /* Flags */
140947  const char *zVfs /* Name of VFS module to use */
140948 ){
140949  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
140950 }
140951 
140952 #ifndef SQLITE_OMIT_UTF16
140953 /*
140954 ** Open a new database handle.
140955 */
140957  const void *zFilename,
140958  sqlite3 **ppDb
140959 ){
140960  char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
140961  sqlite3_value *pVal;
140962  int rc;
140963 
140964 #ifdef SQLITE_ENABLE_API_ARMOR
140965  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
140966 #endif
140967  *ppDb = 0;
140968 #ifndef SQLITE_OMIT_AUTOINIT
140969  rc = sqlite3_initialize();
140970  if( rc ) return rc;
140971 #endif
140972  if( zFilename==0 ) zFilename = "\000\000";
140973  pVal = sqlite3ValueNew(0);
140974  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
140975  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
140976  if( zFilename8 ){
140977  rc = openDatabase(zFilename8, ppDb,
140979  assert( *ppDb || rc==SQLITE_NOMEM );
140980  if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
140981  SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
140982  }
140983  }else{
140984  rc = SQLITE_NOMEM_BKPT;
140985  }
140986  sqlite3ValueFree(pVal);
140987 
140988  return rc & 0xff;
140989 }
140990 #endif /* SQLITE_OMIT_UTF16 */
140991 
140992 /*
140993 ** Register a new collation sequence with the database handle db.
140994 */
140996  sqlite3* db,
140997  const char *zName,
140998  int enc,
140999  void* pCtx,
141000  int(*xCompare)(void*,int,const void*,int,const void*)
141001 ){
141002  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
141003 }
141004 
141005 /*
141006 ** Register a new collation sequence with the database handle db.
141007 */
141009  sqlite3* db,
141010  const char *zName,
141011  int enc,
141012  void* pCtx,
141013  int(*xCompare)(void*,int,const void*,int,const void*),
141014  void(*xDel)(void*)
141015 ){
141016  int rc;
141017 
141018 #ifdef SQLITE_ENABLE_API_ARMOR
141019  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
141020 #endif
141021  sqlite3_mutex_enter(db->mutex);
141022  assert( !db->mallocFailed );
141023  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
141024  rc = sqlite3ApiExit(db, rc);
141025  sqlite3_mutex_leave(db->mutex);
141026  return rc;
141027 }
141028 
141029 #ifndef SQLITE_OMIT_UTF16
141030 /*
141031 ** Register a new collation sequence with the database handle db.
141032 */
141034  sqlite3* db,
141035  const void *zName,
141036  int enc,
141037  void* pCtx,
141038  int(*xCompare)(void*,int,const void*,int,const void*)
141039 ){
141040  int rc = SQLITE_OK;
141041  char *zName8;
141042 
141043 #ifdef SQLITE_ENABLE_API_ARMOR
141044  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
141045 #endif
141046  sqlite3_mutex_enter(db->mutex);
141047  assert( !db->mallocFailed );
141048  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
141049  if( zName8 ){
141050  rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
141051  sqlite3DbFree(db, zName8);
141052  }
141053  rc = sqlite3ApiExit(db, rc);
141054  sqlite3_mutex_leave(db->mutex);
141055  return rc;
141056 }
141057 #endif /* SQLITE_OMIT_UTF16 */
141058 
141059 /*
141060 ** Register a collation sequence factory callback with the database handle
141061 ** db. Replace any previously installed collation sequence factory.
141062 */
141064  sqlite3 *db,
141065  void *pCollNeededArg,
141066  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
141067 ){
141068 #ifdef SQLITE_ENABLE_API_ARMOR
141069  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141070 #endif
141071  sqlite3_mutex_enter(db->mutex);
141072  db->xCollNeeded = xCollNeeded;
141073  db->xCollNeeded16 = 0;
141074  db->pCollNeededArg = pCollNeededArg;
141075  sqlite3_mutex_leave(db->mutex);
141076  return SQLITE_OK;
141077 }
141078 
141079 #ifndef SQLITE_OMIT_UTF16
141080 /*
141081 ** Register a collation sequence factory callback with the database handle
141082 ** db. Replace any previously installed collation sequence factory.
141083 */
141085  sqlite3 *db,
141086  void *pCollNeededArg,
141087  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
141088 ){
141089 #ifdef SQLITE_ENABLE_API_ARMOR
141090  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141091 #endif
141092  sqlite3_mutex_enter(db->mutex);
141093  db->xCollNeeded = 0;
141094  db->xCollNeeded16 = xCollNeeded16;
141095  db->pCollNeededArg = pCollNeededArg;
141096  sqlite3_mutex_leave(db->mutex);
141097  return SQLITE_OK;
141098 }
141099 #endif /* SQLITE_OMIT_UTF16 */
141100 
141101 #ifndef SQLITE_OMIT_DEPRECATED
141102 /*
141103 ** This function is now an anachronism. It used to be used to recover from a
141104 ** malloc() failure, but SQLite now does this automatically.
141105 */
141107  return SQLITE_OK;
141108 }
141109 #endif
141110 
141111 /*
141112 ** Test to see whether or not the database connection is in autocommit
141113 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
141114 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
141115 ** by the next COMMIT or ROLLBACK.
141116 */
141118 #ifdef SQLITE_ENABLE_API_ARMOR
141119  if( !sqlite3SafetyCheckOk(db) ){
141120  (void)SQLITE_MISUSE_BKPT;
141121  return 0;
141122  }
141123 #endif
141124  return db->autoCommit;
141125 }
141126 
141127 /*
141128 ** The following routines are substitutes for constants SQLITE_CORRUPT,
141129 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
141130 ** constants. They serve two purposes:
141131 **
141132 ** 1. Serve as a convenient place to set a breakpoint in a debugger
141133 ** to detect when version error conditions occurs.
141134 **
141135 ** 2. Invoke sqlite3_log() to provide the source code location where
141136 ** a low-level error is first detected.
141137 */
141138 static int reportError(int iErr, int lineno, const char *zType){
141139  sqlite3_log(iErr, "%s at line %d of [%.10s]",
141140  zType, lineno, 20+sqlite3_sourceid());
141141  return iErr;
141142 }
141144  testcase( sqlite3GlobalConfig.xLog!=0 );
141145  return reportError(SQLITE_CORRUPT, lineno, "database corruption");
141146 }
141148  testcase( sqlite3GlobalConfig.xLog!=0 );
141149  return reportError(SQLITE_MISUSE, lineno, "misuse");
141150 }
141152  testcase( sqlite3GlobalConfig.xLog!=0 );
141153  return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
141154 }
141155 #ifdef SQLITE_DEBUG
141156 SQLITE_PRIVATE int sqlite3NomemError(int lineno){
141157  testcase( sqlite3GlobalConfig.xLog!=0 );
141158  return reportError(SQLITE_NOMEM, lineno, "OOM");
141159 }
141160 SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
141161  testcase( sqlite3GlobalConfig.xLog!=0 );
141162  return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
141163 }
141164 #endif
141165 
141166 #ifndef SQLITE_OMIT_DEPRECATED
141167 /*
141168 ** This is a convenience routine that makes sure that all thread-specific
141169 ** data for this thread has been deallocated.
141170 **
141171 ** SQLite no longer uses thread-specific data so this routine is now a
141172 ** no-op. It is retained for historical compatibility.
141173 */
141175 }
141176 #endif
141177 
141178 /*
141179 ** Return meta information about a specific column of a database table.
141180 ** See comment in sqlite3.h (sqlite.h.in) for details.
141181 */
141183  sqlite3 *db, /* Connection handle */
141184  const char *zDbName, /* Database name or NULL */
141185  const char *zTableName, /* Table name */
141186  const char *zColumnName, /* Column name */
141187  char const **pzDataType, /* OUTPUT: Declared data type */
141188  char const **pzCollSeq, /* OUTPUT: Collation sequence name */
141189  int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
141190  int *pPrimaryKey, /* OUTPUT: True if column part of PK */
141191  int *pAutoinc /* OUTPUT: True if column is auto-increment */
141192 ){
141193  int rc;
141194  char *zErrMsg = 0;
141195  Table *pTab = 0;
141196  Column *pCol = 0;
141197  int iCol = 0;
141198  char const *zDataType = 0;
141199  char const *zCollSeq = 0;
141200  int notnull = 0;
141201  int primarykey = 0;
141202  int autoinc = 0;
141203 
141204 
141205 #ifdef SQLITE_ENABLE_API_ARMOR
141206  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
141207  return SQLITE_MISUSE_BKPT;
141208  }
141209 #endif
141210 
141211  /* Ensure the database schema has been loaded */
141212  sqlite3_mutex_enter(db->mutex);
141213  sqlite3BtreeEnterAll(db);
141214  rc = sqlite3Init(db, &zErrMsg);
141215  if( SQLITE_OK!=rc ){
141216  goto error_out;
141217  }
141218 
141219  /* Locate the table in question */
141220  pTab = sqlite3FindTable(db, zTableName, zDbName);
141221  if( !pTab || pTab->pSelect ){
141222  pTab = 0;
141223  goto error_out;
141224  }
141225 
141226  /* Find the column for which info is requested */
141227  if( zColumnName==0 ){
141228  /* Query for existance of table only */
141229  }else{
141230  for(iCol=0; iCol<pTab->nCol; iCol++){
141231  pCol = &pTab->aCol[iCol];
141232  if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
141233  break;
141234  }
141235  }
141236  if( iCol==pTab->nCol ){
141237  if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
141238  iCol = pTab->iPKey;
141239  pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
141240  }else{
141241  pTab = 0;
141242  goto error_out;
141243  }
141244  }
141245  }
141246 
141247  /* The following block stores the meta information that will be returned
141248  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
141249  ** and autoinc. At this point there are two possibilities:
141250  **
141251  ** 1. The specified column name was rowid", "oid" or "_rowid_"
141252  ** and there is no explicitly declared IPK column.
141253  **
141254  ** 2. The table is not a view and the column name identified an
141255  ** explicitly declared column. Copy meta information from *pCol.
141256  */
141257  if( pCol ){
141258  zDataType = sqlite3ColumnType(pCol,0);
141259  zCollSeq = pCol->zColl;
141260  notnull = pCol->notNull!=0;
141261  primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
141262  autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
141263  }else{
141264  zDataType = "INTEGER";
141265  primarykey = 1;
141266  }
141267  if( !zCollSeq ){
141268  zCollSeq = sqlite3StrBINARY;
141269  }
141270 
141271 error_out:
141272  sqlite3BtreeLeaveAll(db);
141273 
141274  /* Whether the function call succeeded or failed, set the output parameters
141275  ** to whatever their local counterparts contain. If an error did occur,
141276  ** this has the effect of zeroing all output parameters.
141277  */
141278  if( pzDataType ) *pzDataType = zDataType;
141279  if( pzCollSeq ) *pzCollSeq = zCollSeq;
141280  if( pNotNull ) *pNotNull = notnull;
141281  if( pPrimaryKey ) *pPrimaryKey = primarykey;
141282  if( pAutoinc ) *pAutoinc = autoinc;
141283 
141284  if( SQLITE_OK==rc && !pTab ){
141285  sqlite3DbFree(db, zErrMsg);
141286  zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
141287  zColumnName);
141288  rc = SQLITE_ERROR;
141289  }
141290  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
141291  sqlite3DbFree(db, zErrMsg);
141292  rc = sqlite3ApiExit(db, rc);
141293  sqlite3_mutex_leave(db->mutex);
141294  return rc;
141295 }
141296 
141297 /*
141298 ** Sleep for a little while. Return the amount of time slept.
141299 */
141301  sqlite3_vfs *pVfs;
141302  int rc;
141303  pVfs = sqlite3_vfs_find(0);
141304  if( pVfs==0 ) return 0;
141305 
141306  /* This function works in milliseconds, but the underlying OsSleep()
141307  ** API uses microseconds. Hence the 1000's.
141308  */
141309  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
141310  return rc;
141311 }
141312 
141313 /*
141314 ** Enable or disable the extended result codes.
141315 */
141316 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
141317 #ifdef SQLITE_ENABLE_API_ARMOR
141318  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141319 #endif
141320  sqlite3_mutex_enter(db->mutex);
141321  db->errMask = onoff ? 0xffffffff : 0xff;
141322  sqlite3_mutex_leave(db->mutex);
141323  return SQLITE_OK;
141324 }
141325 
141326 /*
141327 ** Invoke the xFileControl method on a particular database.
141328 */
141329 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
141330  int rc = SQLITE_ERROR;
141331  Btree *pBtree;
141332 
141333 #ifdef SQLITE_ENABLE_API_ARMOR
141334  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
141335 #endif
141336  sqlite3_mutex_enter(db->mutex);
141337  pBtree = sqlite3DbNameToBtree(db, zDbName);
141338  if( pBtree ){
141339  Pager *pPager;
141340  sqlite3_file *fd;
141341  sqlite3BtreeEnter(pBtree);
141342  pPager = sqlite3BtreePager(pBtree);
141343  assert( pPager!=0 );
141344  fd = sqlite3PagerFile(pPager);
141345  assert( fd!=0 );
141346  if( op==SQLITE_FCNTL_FILE_POINTER ){
141347  *(sqlite3_file**)pArg = fd;
141348  rc = SQLITE_OK;
141349  }else if( op==SQLITE_FCNTL_VFS_POINTER ){
141350  *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
141351  rc = SQLITE_OK;
141352  }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
141353  *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
141354  rc = SQLITE_OK;
141355  }else if( fd->pMethods ){
141356  rc = sqlite3OsFileControl(fd, op, pArg);
141357  }else{
141358  rc = SQLITE_NOTFOUND;
141359  }
141360  sqlite3BtreeLeave(pBtree);
141361  }
141362  sqlite3_mutex_leave(db->mutex);
141363  return rc;
141364 }
141365 
141366 /*
141367 ** Interface to the testing logic.
141368 */
141370  int rc = 0;
141371 #ifdef SQLITE_OMIT_BUILTIN_TEST
141372  UNUSED_PARAMETER(op);
141373 #else
141374  va_list ap;
141375  va_start(ap, op);
141376  switch( op ){
141377 
141378  /*
141379  ** Save the current state of the PRNG.
141380  */
141381  case SQLITE_TESTCTRL_PRNG_SAVE: {
141383  break;
141384  }
141385 
141386  /*
141387  ** Restore the state of the PRNG to the last state saved using
141388  ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
141389  ** this verb acts like PRNG_RESET.
141390  */
141393  break;
141394  }
141395 
141396  /*
141397  ** Reset the PRNG back to its uninitialized state. The next call
141398  ** to sqlite3_randomness() will reseed the PRNG using a single call
141399  ** to the xRandomness method of the default VFS.
141400  */
141402  sqlite3_randomness(0,0);
141403  break;
141404  }
141405 
141406  /*
141407  ** sqlite3_test_control(BITVEC_TEST, size, program)
141408  **
141409  ** Run a test against a Bitvec object of size. The program argument
141410  ** is an array of integers that defines the test. Return -1 on a
141411  ** memory allocation error, 0 on success, or non-zero for an error.
141412  ** See the sqlite3BitvecBuiltinTest() for additional information.
141413  */
141415  int sz = va_arg(ap, int);
141416  int *aProg = va_arg(ap, int*);
141417  rc = sqlite3BitvecBuiltinTest(sz, aProg);
141418  break;
141419  }
141420 
141421  /*
141422  ** sqlite3_test_control(FAULT_INSTALL, xCallback)
141423  **
141424  ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
141425  ** if xCallback is not NULL.
141426  **
141427  ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
141428  ** is called immediately after installing the new callback and the return
141429  ** value from sqlite3FaultSim(0) becomes the return from
141430  ** sqlite3_test_control().
141431  */
141433  /* MSVC is picky about pulling func ptrs from va lists.
141434  ** http://support.microsoft.com/kb/47961
141435  ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
141436  */
141437  typedef int(*TESTCALLBACKFUNC_t)(int);
141438  sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
141439  rc = sqlite3FaultSim(0);
141440  break;
141441  }
141442 
141443  /*
141444  ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
141445  **
141446  ** Register hooks to call to indicate which malloc() failures
141447  ** are benign.
141448  */
141450  typedef void (*void_function)(void);
141451  void_function xBenignBegin;
141452  void_function xBenignEnd;
141453  xBenignBegin = va_arg(ap, void_function);
141454  xBenignEnd = va_arg(ap, void_function);
141455  sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
141456  break;
141457  }
141458 
141459  /*
141460  ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
141461  **
141462  ** Set the PENDING byte to the value in the argument, if X>0.
141463  ** Make no changes if X==0. Return the value of the pending byte
141464  ** as it existing before this routine was called.
141465  **
141466  ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
141467  ** an incompatible database file format. Changing the PENDING byte
141468  ** while any database connection is open results in undefined and
141469  ** deleterious behavior.
141470  */
141472  rc = PENDING_BYTE;
141473 #ifndef SQLITE_OMIT_WSD
141474  {
141475  unsigned int newVal = va_arg(ap, unsigned int);
141476  if( newVal ) sqlite3PendingByte = newVal;
141477  }
141478 #endif
141479  break;
141480  }
141481 
141482  /*
141483  ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
141484  **
141485  ** This action provides a run-time test to see whether or not
141486  ** assert() was enabled at compile-time. If X is true and assert()
141487  ** is enabled, then the return value is true. If X is true and
141488  ** assert() is disabled, then the return value is zero. If X is
141489  ** false and assert() is enabled, then the assertion fires and the
141490  ** process aborts. If X is false and assert() is disabled, then the
141491  ** return value is zero.
141492  */
141493  case SQLITE_TESTCTRL_ASSERT: {
141494  volatile int x = 0;
141495  assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
141496  rc = x;
141497  break;
141498  }
141499 
141500 
141501  /*
141502  ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
141503  **
141504  ** This action provides a run-time test to see how the ALWAYS and
141505  ** NEVER macros were defined at compile-time.
141506  **
141507  ** The return value is ALWAYS(X).
141508  **
141509  ** The recommended test is X==2. If the return value is 2, that means
141510  ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
141511  ** default setting. If the return value is 1, then ALWAYS() is either
141512  ** hard-coded to true or else it asserts if its argument is false.
141513  ** The first behavior (hard-coded to true) is the case if
141514  ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
141515  ** behavior (assert if the argument to ALWAYS() is false) is the case if
141516  ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
141517  **
141518  ** The run-time test procedure might look something like this:
141519  **
141520  ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
141521  ** // ALWAYS() and NEVER() are no-op pass-through macros
141522  ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
141523  ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
141524  ** }else{
141525  ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
141526  ** }
141527  */
141528  case SQLITE_TESTCTRL_ALWAYS: {
141529  int x = va_arg(ap,int);
141530  rc = ALWAYS(x);
141531  break;
141532  }
141533 
141534  /*
141535  ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
141536  **
141537  ** The integer returned reveals the byte-order of the computer on which
141538  ** SQLite is running:
141539  **
141540  ** 1 big-endian, determined at run-time
141541  ** 10 little-endian, determined at run-time
141542  ** 432101 big-endian, determined at compile-time
141543  ** 123410 little-endian, determined at compile-time
141544  */
141545  case SQLITE_TESTCTRL_BYTEORDER: {
141547  break;
141548  }
141549 
141550  /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
141551  **
141552  ** Set the nReserve size to N for the main database on the database
141553  ** connection db.
141554  */
141555  case SQLITE_TESTCTRL_RESERVE: {
141556  sqlite3 *db = va_arg(ap, sqlite3*);
141557  int x = va_arg(ap,int);
141558  sqlite3_mutex_enter(db->mutex);
141559  sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
141560  sqlite3_mutex_leave(db->mutex);
141561  break;
141562  }
141563 
141564  /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
141565  **
141566  ** Enable or disable various optimizations for testing purposes. The
141567  ** argument N is a bitmask of optimizations to be disabled. For normal
141568  ** operation N should be 0. The idea is that a test program (like the
141569  ** SQL Logic Test or SLT test module) can run the same SQL multiple times
141570  ** with various optimizations disabled to verify that the same answer
141571  ** is obtained in every case.
141572  */
141574  sqlite3 *db = va_arg(ap, sqlite3*);
141575  db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
141576  break;
141577  }
141578 
141579 #ifdef SQLITE_N_KEYWORD
141580  /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
141581  **
141582  ** If zWord is a keyword recognized by the parser, then return the
141583  ** number of keywords. Or if zWord is not a keyword, return 0.
141584  **
141585  ** This test feature is only available in the amalgamation since
141586  ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
141587  ** is built using separate source files.
141588  */
141589  case SQLITE_TESTCTRL_ISKEYWORD: {
141590  const char *zWord = va_arg(ap, const char*);
141591  int n = sqlite3Strlen30(zWord);
141592  rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
141593  break;
141594  }
141595 #endif
141596 
141597  /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
141598  **
141599  ** Pass pFree into sqlite3ScratchFree().
141600  ** If sz>0 then allocate a scratch buffer into pNew.
141601  */
141603  void *pFree, **ppNew;
141604  int sz;
141605  sz = va_arg(ap, int);
141606  ppNew = va_arg(ap, void**);
141607  pFree = va_arg(ap, void*);
141608  if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
141609  sqlite3ScratchFree(pFree);
141610  break;
141611  }
141612 
141613  /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
141614  **
141615  ** If parameter onoff is non-zero, configure the wrappers so that all
141616  ** subsequent calls to localtime() and variants fail. If onoff is zero,
141617  ** undo this setting.
141618  */
141620  sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
141621  break;
141622  }
141623 
141624  /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
141625  **
141626  ** Set or clear a flag that indicates that the database file is always well-
141627  ** formed and never corrupt. This flag is clear by default, indicating that
141628  ** database files might have arbitrary corruption. Setting the flag during
141629  ** testing causes certain assert() statements in the code to be activated
141630  ** that demonstrat invariants on well-formed database files.
141631  */
141633  sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
141634  break;
141635  }
141636 
141637  /* Set the threshold at which OP_Once counters reset back to zero.
141638  ** By default this is 0x7ffffffe (over 2 billion), but that value is
141639  ** too big to test in a reasonable amount of time, so this control is
141640  ** provided to set a small and easily reachable reset value.
141641  */
141643  sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
141644  break;
141645  }
141646 
141647  /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
141648  **
141649  ** Set the VDBE coverage callback function to xCallback with context
141650  ** pointer ptr.
141651  */
141653 #ifdef SQLITE_VDBE_COVERAGE
141654  typedef void (*branch_callback)(void*,int,u8,u8);
141655  sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
141656  sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
141657 #endif
141658  break;
141659  }
141660 
141661  /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
141663  sqlite3 *db = va_arg(ap, sqlite3*);
141664  db->nMaxSorterMmap = va_arg(ap, int);
141665  break;
141666  }
141667 
141668  /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
141669  **
141670  ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
141671  ** not.
141672  */
141673  case SQLITE_TESTCTRL_ISINIT: {
141674  if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
141675  break;
141676  }
141677 
141678  /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
141679  **
141680  ** This test control is used to create imposter tables. "db" is a pointer
141681  ** to the database connection. dbName is the database name (ex: "main" or
141682  ** "temp") which will receive the imposter. "onOff" turns imposter mode on
141683  ** or off. "tnum" is the root page of the b-tree to which the imposter
141684  ** table should connect.
141685  **
141686  ** Enable imposter mode only when the schema has already been parsed. Then
141687  ** run a single CREATE TABLE statement to construct the imposter table in
141688  ** the parsed schema. Then turn imposter mode back off again.
141689  **
141690  ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
141691  ** the schema to be reparsed the next time it is needed. This has the
141692  ** effect of erasing all imposter tables.
141693  */
141694  case SQLITE_TESTCTRL_IMPOSTER: {
141695  sqlite3 *db = va_arg(ap, sqlite3*);
141696  sqlite3_mutex_enter(db->mutex);
141697  db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
141698  db->init.busy = db->init.imposterTable = va_arg(ap,int);
141699  db->init.newTnum = va_arg(ap,int);
141700  if( db->init.busy==0 && db->init.newTnum>0 ){
141702  }
141703  sqlite3_mutex_leave(db->mutex);
141704  break;
141705  }
141706  }
141707  va_end(ap);
141708 #endif /* SQLITE_OMIT_BUILTIN_TEST */
141709  return rc;
141710 }
141711 
141712 /*
141713 ** This is a utility routine, useful to VFS implementations, that checks
141714 ** to see if a database file was a URI that contained a specific query
141715 ** parameter, and if so obtains the value of the query parameter.
141716 **
141717 ** The zFilename argument is the filename pointer passed into the xOpen()
141718 ** method of a VFS implementation. The zParam argument is the name of the
141719 ** query parameter we seek. This routine returns the value of the zParam
141720 ** parameter if it exists. If the parameter does not exist, this routine
141721 ** returns a NULL pointer.
141722 */
141723 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
141724  if( zFilename==0 || zParam==0 ) return 0;
141725  zFilename += sqlite3Strlen30(zFilename) + 1;
141726  while( zFilename[0] ){
141727  int x = strcmp(zFilename, zParam);
141728  zFilename += sqlite3Strlen30(zFilename) + 1;
141729  if( x==0 ) return zFilename;
141730  zFilename += sqlite3Strlen30(zFilename) + 1;
141731  }
141732  return 0;
141733 }
141734 
141735 /*
141736 ** Return a boolean value for a query parameter.
141737 */
141738 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
141739  const char *z = sqlite3_uri_parameter(zFilename, zParam);
141740  bDflt = bDflt!=0;
141741  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
141742 }
141743 
141744 /*
141745 ** Return a 64-bit integer value for a query parameter.
141746 */
141748  const char *zFilename, /* Filename as passed to xOpen */
141749  const char *zParam, /* URI parameter sought */
141750  sqlite3_int64 bDflt /* return if parameter is missing */
141751 ){
141752  const char *z = sqlite3_uri_parameter(zFilename, zParam);
141753  sqlite3_int64 v;
141754  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
141755  bDflt = v;
141756  }
141757  return bDflt;
141758 }
141759 
141760 /*
141761 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
141762 */
141763 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
141764  int i;
141765  for(i=0; i<db->nDb; i++){
141766  if( db->aDb[i].pBt
141767  && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zDbSName)==0)
141768  ){
141769  return db->aDb[i].pBt;
141770  }
141771  }
141772  return 0;
141773 }
141774 
141775 /*
141776 ** Return the filename of the database associated with a database
141777 ** connection.
141778 */
141779 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
141780  Btree *pBt;
141781 #ifdef SQLITE_ENABLE_API_ARMOR
141782  if( !sqlite3SafetyCheckOk(db) ){
141783  (void)SQLITE_MISUSE_BKPT;
141784  return 0;
141785  }
141786 #endif
141787  pBt = sqlite3DbNameToBtree(db, zDbName);
141788  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
141789 }
141790 
141791 /*
141792 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
141793 ** no such database exists.
141794 */
141795 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
141796  Btree *pBt;
141797 #ifdef SQLITE_ENABLE_API_ARMOR
141798  if( !sqlite3SafetyCheckOk(db) ){
141799  (void)SQLITE_MISUSE_BKPT;
141800  return -1;
141801  }
141802 #endif
141803  pBt = sqlite3DbNameToBtree(db, zDbName);
141804  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
141805 }
141806 
141807 #ifdef SQLITE_ENABLE_SNAPSHOT
141808 /*
141809 ** Obtain a snapshot handle for the snapshot of database zDb currently
141810 ** being read by handle db.
141811 */
141813  sqlite3 *db,
141814  const char *zDb,
141815  sqlite3_snapshot **ppSnapshot
141816 ){
141817  int rc = SQLITE_ERROR;
141818 #ifndef SQLITE_OMIT_WAL
141819  int iDb;
141820 
141821 #ifdef SQLITE_ENABLE_API_ARMOR
141822  if( !sqlite3SafetyCheckOk(db) ){
141823  return SQLITE_MISUSE_BKPT;
141824  }
141825 #endif
141826  sqlite3_mutex_enter(db->mutex);
141827 
141828  iDb = sqlite3FindDbName(db, zDb);
141829  if( iDb==0 || iDb>1 ){
141830  Btree *pBt = db->aDb[iDb].pBt;
141831  if( 0==sqlite3BtreeIsInTrans(pBt) ){
141832  rc = sqlite3BtreeBeginTrans(pBt, 0);
141833  if( rc==SQLITE_OK ){
141834  rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
141835  }
141836  }
141837  }
141838 
141839  sqlite3_mutex_leave(db->mutex);
141840 #endif /* SQLITE_OMIT_WAL */
141841  return rc;
141842 }
141843 
141844 /*
141845 ** Open a read-transaction on the snapshot idendified by pSnapshot.
141846 */
141848  sqlite3 *db,
141849  const char *zDb,
141850  sqlite3_snapshot *pSnapshot
141851 ){
141852  int rc = SQLITE_ERROR;
141853 #ifndef SQLITE_OMIT_WAL
141854 
141855 #ifdef SQLITE_ENABLE_API_ARMOR
141856  if( !sqlite3SafetyCheckOk(db) ){
141857  return SQLITE_MISUSE_BKPT;
141858  }
141859 #endif
141860  sqlite3_mutex_enter(db->mutex);
141861  if( db->autoCommit==0 ){
141862  int iDb;
141863  iDb = sqlite3FindDbName(db, zDb);
141864  if( iDb==0 || iDb>1 ){
141865  Btree *pBt = db->aDb[iDb].pBt;
141866  if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
141867  rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
141868  if( rc==SQLITE_OK ){
141869  rc = sqlite3BtreeBeginTrans(pBt, 0);
141870  sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
141871  }
141872  }
141873  }
141874  }
141875 
141876  sqlite3_mutex_leave(db->mutex);
141877 #endif /* SQLITE_OMIT_WAL */
141878  return rc;
141879 }
141880 
141881 /*
141882 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
141883 */
141885  sqlite3_free(pSnapshot);
141886 }
141887 #endif /* SQLITE_ENABLE_SNAPSHOT */
141888 
141889 /************** End of main.c ************************************************/
141890 /************** Begin file notify.c ******************************************/
141891 /*
141892 ** 2009 March 3
141893 **
141894 ** The author disclaims copyright to this source code. In place of
141895 ** a legal notice, here is a blessing:
141896 **
141897 ** May you do good and not evil.
141898 ** May you find forgiveness for yourself and forgive others.
141899 ** May you share freely, never taking more than you give.
141900 **
141901 *************************************************************************
141902 **
141903 ** This file contains the implementation of the sqlite3_unlock_notify()
141904 ** API method and its associated functionality.
141905 */
141906 /* #include "sqliteInt.h" */
141907 /* #include "btreeInt.h" */
141908 
141909 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
141910 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
141911 
141912 /*
141913 ** Public interfaces:
141914 **
141915 ** sqlite3ConnectionBlocked()
141916 ** sqlite3ConnectionUnlocked()
141917 ** sqlite3ConnectionClosed()
141918 ** sqlite3_unlock_notify()
141919 */
141920 
141921 #define assertMutexHeld() \
141922  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
141923 
141924 /*
141925 ** Head of a linked list of all sqlite3 objects created by this process
141926 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
141927 ** is not NULL. This variable may only accessed while the STATIC_MASTER
141928 ** mutex is held.
141929 */
141930 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
141931 
141932 #ifndef NDEBUG
141933 /*
141934 ** This function is a complex assert() that verifies the following
141935 ** properties of the blocked connections list:
141936 **
141937 ** 1) Each entry in the list has a non-NULL value for either
141938 ** pUnlockConnection or pBlockingConnection, or both.
141939 **
141940 ** 2) All entries in the list that share a common value for
141941 ** xUnlockNotify are grouped together.
141942 **
141943 ** 3) If the argument db is not NULL, then none of the entries in the
141944 ** blocked connections list have pUnlockConnection or pBlockingConnection
141945 ** set to db. This is used when closing connection db.
141946 */
141947 static void checkListProperties(sqlite3 *db){
141948  sqlite3 *p;
141949  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
141950  int seen = 0;
141951  sqlite3 *p2;
141952 
141953  /* Verify property (1) */
141954  assert( p->pUnlockConnection || p->pBlockingConnection );
141955 
141956  /* Verify property (2) */
141957  for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
141958  if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
141959  assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
141960  assert( db==0 || p->pUnlockConnection!=db );
141961  assert( db==0 || p->pBlockingConnection!=db );
141962  }
141963  }
141964 }
141965 #else
141966 # define checkListProperties(x)
141967 #endif
141968 
141969 /*
141970 ** Remove connection db from the blocked connections list. If connection
141971 ** db is not currently a part of the list, this function is a no-op.
141972 */
141973 static void removeFromBlockedList(sqlite3 *db){
141974  sqlite3 **pp;
141975  assertMutexHeld();
141976  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
141977  if( *pp==db ){
141978  *pp = (*pp)->pNextBlocked;
141979  break;
141980  }
141981  }
141982 }
141983 
141984 /*
141985 ** Add connection db to the blocked connections list. It is assumed
141986 ** that it is not already a part of the list.
141987 */
141988 static void addToBlockedList(sqlite3 *db){
141989  sqlite3 **pp;
141990  assertMutexHeld();
141991  for(
141992  pp=&sqlite3BlockedList;
141993  *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
141994  pp=&(*pp)->pNextBlocked
141995  );
141996  db->pNextBlocked = *pp;
141997  *pp = db;
141998 }
141999 
142000 /*
142001 ** Obtain the STATIC_MASTER mutex.
142002 */
142003 static void enterMutex(void){
142005  checkListProperties(0);
142006 }
142007 
142008 /*
142009 ** Release the STATIC_MASTER mutex.
142010 */
142011 static void leaveMutex(void){
142012  assertMutexHeld();
142013  checkListProperties(0);
142015 }
142016 
142017 /*
142018 ** Register an unlock-notify callback.
142019 **
142020 ** This is called after connection "db" has attempted some operation
142021 ** but has received an SQLITE_LOCKED error because another connection
142022 ** (call it pOther) in the same process was busy using the same shared
142023 ** cache. pOther is found by looking at db->pBlockingConnection.
142024 **
142025 ** If there is no blocking connection, the callback is invoked immediately,
142026 ** before this routine returns.
142027 **
142028 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
142029 ** a deadlock.
142030 **
142031 ** Otherwise, make arrangements to invoke xNotify when pOther drops
142032 ** its locks.
142033 **
142034 ** Each call to this routine overrides any prior callbacks registered
142035 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
142036 ** cancelled.
142037 */
142039  sqlite3 *db,
142040  void (*xNotify)(void **, int),
142041  void *pArg
142042 ){
142043  int rc = SQLITE_OK;
142044 
142045  sqlite3_mutex_enter(db->mutex);
142046  enterMutex();
142047 
142048  if( xNotify==0 ){
142049  removeFromBlockedList(db);
142050  db->pBlockingConnection = 0;
142051  db->pUnlockConnection = 0;
142052  db->xUnlockNotify = 0;
142053  db->pUnlockArg = 0;
142054  }else if( 0==db->pBlockingConnection ){
142055  /* The blocking transaction has been concluded. Or there never was a
142056  ** blocking transaction. In either case, invoke the notify callback
142057  ** immediately.
142058  */
142059  xNotify(&pArg, 1);
142060  }else{
142061  sqlite3 *p;
142062 
142063  for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
142064  if( p ){
142065  rc = SQLITE_LOCKED; /* Deadlock detected. */
142066  }else{
142067  db->pUnlockConnection = db->pBlockingConnection;
142068  db->xUnlockNotify = xNotify;
142069  db->pUnlockArg = pArg;
142070  removeFromBlockedList(db);
142071  addToBlockedList(db);
142072  }
142073  }
142074 
142075  leaveMutex();
142076  assert( !db->mallocFailed );
142077  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
142078  sqlite3_mutex_leave(db->mutex);
142079  return rc;
142080 }
142081 
142082 /*
142083 ** This function is called while stepping or preparing a statement
142084 ** associated with connection db. The operation will return SQLITE_LOCKED
142085 ** to the user because it requires a lock that will not be available
142086 ** until connection pBlocker concludes its current transaction.
142087 */
142088 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
142089  enterMutex();
142090  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
142091  addToBlockedList(db);
142092  }
142093  db->pBlockingConnection = pBlocker;
142094  leaveMutex();
142095 }
142096 
142097 /*
142098 ** This function is called when
142099 ** the transaction opened by database db has just finished. Locks held
142100 ** by database connection db have been released.
142101 **
142102 ** This function loops through each entry in the blocked connections
142103 ** list and does the following:
142104 **
142105 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
142106 ** set to db, then set pBlockingConnection=0.
142107 **
142108 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
142109 ** set to db, then invoke the configured unlock-notify callback and
142110 ** set pUnlockConnection=0.
142111 **
142112 ** 3) If the two steps above mean that pBlockingConnection==0 and
142113 ** pUnlockConnection==0, remove the entry from the blocked connections
142114 ** list.
142115 */
142116 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
142117  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
142118  int nArg = 0; /* Number of entries in aArg[] */
142119  sqlite3 **pp; /* Iterator variable */
142120  void **aArg; /* Arguments to the unlock callback */
142121  void **aDyn = 0; /* Dynamically allocated space for aArg[] */
142122  void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
142123 
142124  aArg = aStatic;
142125  enterMutex(); /* Enter STATIC_MASTER mutex */
142126 
142127  /* This loop runs once for each entry in the blocked-connections list. */
142128  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
142129  sqlite3 *p = *pp;
142130 
142131  /* Step 1. */
142132  if( p->pBlockingConnection==db ){
142133  p->pBlockingConnection = 0;
142134  }
142135 
142136  /* Step 2. */
142137  if( p->pUnlockConnection==db ){
142138  assert( p->xUnlockNotify );
142139  if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
142140  xUnlockNotify(aArg, nArg);
142141  nArg = 0;
142142  }
142143 
142145  assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
142146  assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
142147  if( (!aDyn && nArg==(int)ArraySize(aStatic))
142148  || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
142149  ){
142150  /* The aArg[] array needs to grow. */
142151  void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
142152  if( pNew ){
142153  memcpy(pNew, aArg, nArg*sizeof(void *));
142154  sqlite3_free(aDyn);
142155  aDyn = aArg = pNew;
142156  }else{
142157  /* This occurs when the array of context pointers that need to
142158  ** be passed to the unlock-notify callback is larger than the
142159  ** aStatic[] array allocated on the stack and the attempt to
142160  ** allocate a larger array from the heap has failed.
142161  **
142162  ** This is a difficult situation to handle. Returning an error
142163  ** code to the caller is insufficient, as even if an error code
142164  ** is returned the transaction on connection db will still be
142165  ** closed and the unlock-notify callbacks on blocked connections
142166  ** will go unissued. This might cause the application to wait
142167  ** indefinitely for an unlock-notify callback that will never
142168  ** arrive.
142169  **
142170  ** Instead, invoke the unlock-notify callback with the context
142171  ** array already accumulated. We can then clear the array and
142172  ** begin accumulating any further context pointers without
142173  ** requiring any dynamic allocation. This is sub-optimal because
142174  ** it means that instead of one callback with a large array of
142175  ** context pointers the application will receive two or more
142176  ** callbacks with smaller arrays of context pointers, which will
142177  ** reduce the applications ability to prioritize multiple
142178  ** connections. But it is the best that can be done under the
142179  ** circumstances.
142180  */
142181  xUnlockNotify(aArg, nArg);
142182  nArg = 0;
142183  }
142184  }
142186 
142187  aArg[nArg++] = p->pUnlockArg;
142188  xUnlockNotify = p->xUnlockNotify;
142189  p->pUnlockConnection = 0;
142190  p->xUnlockNotify = 0;
142191  p->pUnlockArg = 0;
142192  }
142193 
142194  /* Step 3. */
142195  if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
142196  /* Remove connection p from the blocked connections list. */
142197  *pp = p->pNextBlocked;
142198  p->pNextBlocked = 0;
142199  }else{
142200  pp = &p->pNextBlocked;
142201  }
142202  }
142203 
142204  if( nArg!=0 ){
142205  xUnlockNotify(aArg, nArg);
142206  }
142207  sqlite3_free(aDyn);
142208  leaveMutex(); /* Leave STATIC_MASTER mutex */
142209 }
142210 
142211 /*
142212 ** This is called when the database connection passed as an argument is
142213 ** being closed. The connection is removed from the blocked list.
142214 */
142215 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
142217  enterMutex();
142218  removeFromBlockedList(db);
142219  checkListProperties(db);
142220  leaveMutex();
142221 }
142222 #endif
142223 
142224 /************** End of notify.c **********************************************/
142225 /************** Begin file fts3.c ********************************************/
142226 /*
142227 ** 2006 Oct 10
142228 **
142229 ** The author disclaims copyright to this source code. In place of
142230 ** a legal notice, here is a blessing:
142231 **
142232 ** May you do good and not evil.
142233 ** May you find forgiveness for yourself and forgive others.
142234 ** May you share freely, never taking more than you give.
142235 **
142236 ******************************************************************************
142237 **
142238 ** This is an SQLite module implementing full-text search.
142239 */
142240 
142241 /*
142242 ** The code in this file is only compiled if:
142243 **
142244 ** * The FTS3 module is being built as an extension
142245 ** (in which case SQLITE_CORE is not defined), or
142246 **
142247 ** * The FTS3 module is being built into the core of
142248 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
142249 */
142250 
142251 /* The full-text index is stored in a series of b+tree (-like)
142252 ** structures called segments which map terms to doclists. The
142253 ** structures are like b+trees in layout, but are constructed from the
142254 ** bottom up in optimal fashion and are not updatable. Since trees
142255 ** are built from the bottom up, things will be described from the
142256 ** bottom up.
142257 **
142258 **
142259 **** Varints ****
142260 ** The basic unit of encoding is a variable-length integer called a
142261 ** varint. We encode variable-length integers in little-endian order
142262 ** using seven bits * per byte as follows:
142263 **
142264 ** KEY:
142265 ** A = 0xxxxxxx 7 bits of data and one flag bit
142266 ** B = 1xxxxxxx 7 bits of data and one flag bit
142267 **
142268 ** 7 bits - A
142269 ** 14 bits - BA
142270 ** 21 bits - BBA
142271 ** and so on.
142272 **
142273 ** This is similar in concept to how sqlite encodes "varints" but
142274 ** the encoding is not the same. SQLite varints are big-endian
142275 ** are are limited to 9 bytes in length whereas FTS3 varints are
142276 ** little-endian and can be up to 10 bytes in length (in theory).
142277 **
142278 ** Example encodings:
142279 **
142280 ** 1: 0x01
142281 ** 127: 0x7f
142282 ** 128: 0x81 0x00
142283 **
142284 **
142285 **** Document lists ****
142286 ** A doclist (document list) holds a docid-sorted list of hits for a
142287 ** given term. Doclists hold docids and associated token positions.
142288 ** A docid is the unique integer identifier for a single document.
142289 ** A position is the index of a word within the document. The first
142290 ** word of the document has a position of 0.
142291 **
142292 ** FTS3 used to optionally store character offsets using a compile-time
142293 ** option. But that functionality is no longer supported.
142294 **
142295 ** A doclist is stored like this:
142296 **
142297 ** array {
142298 ** varint docid; (delta from previous doclist)
142299 ** array { (position list for column 0)
142300 ** varint position; (2 more than the delta from previous position)
142301 ** }
142302 ** array {
142303 ** varint POS_COLUMN; (marks start of position list for new column)
142304 ** varint column; (index of new column)
142305 ** array {
142306 ** varint position; (2 more than the delta from previous position)
142307 ** }
142308 ** }
142309 ** varint POS_END; (marks end of positions for this document.
142310 ** }
142311 **
142312 ** Here, array { X } means zero or more occurrences of X, adjacent in
142313 ** memory. A "position" is an index of a token in the token stream
142314 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
142315 ** in the same logical place as the position element, and act as sentinals
142316 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
142317 ** The positions numbers are not stored literally but rather as two more
142318 ** than the difference from the prior position, or the just the position plus
142319 ** 2 for the first position. Example:
142320 **
142321 ** label: A B C D E F G H I J K
142322 ** value: 123 5 9 1 1 14 35 0 234 72 0
142323 **
142324 ** The 123 value is the first docid. For column zero in this document
142325 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
142326 ** at D signals the start of a new column; the 1 at E indicates that the
142327 ** new column is column number 1. There are two positions at 12 and 45
142328 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
142329 ** 234 at I is the delta to next docid (357). It has one position 70
142330 ** (72-2) and then terminates with the 0 at K.
142331 **
142332 ** A "position-list" is the list of positions for multiple columns for
142333 ** a single docid. A "column-list" is the set of positions for a single
142334 ** column. Hence, a position-list consists of one or more column-lists,
142335 ** a document record consists of a docid followed by a position-list and
142336 ** a doclist consists of one or more document records.
142337 **
142338 ** A bare doclist omits the position information, becoming an
142339 ** array of varint-encoded docids.
142340 **
142341 **** Segment leaf nodes ****
142342 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
142343 ** nodes are written using LeafWriter, and read using LeafReader (to
142344 ** iterate through a single leaf node's data) and LeavesReader (to
142345 ** iterate through a segment's entire leaf layer). Leaf nodes have
142346 ** the format:
142347 **
142348 ** varint iHeight; (height from leaf level, always 0)
142349 ** varint nTerm; (length of first term)
142350 ** char pTerm[nTerm]; (content of first term)
142351 ** varint nDoclist; (length of term's associated doclist)
142352 ** char pDoclist[nDoclist]; (content of doclist)
142353 ** array {
142354 ** (further terms are delta-encoded)
142355 ** varint nPrefix; (length of prefix shared with previous term)
142356 ** varint nSuffix; (length of unshared suffix)
142357 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
142358 ** varint nDoclist; (length of term's associated doclist)
142359 ** char pDoclist[nDoclist]; (content of doclist)
142360 ** }
142361 **
142362 ** Here, array { X } means zero or more occurrences of X, adjacent in
142363 ** memory.
142364 **
142365 ** Leaf nodes are broken into blocks which are stored contiguously in
142366 ** the %_segments table in sorted order. This means that when the end
142367 ** of a node is reached, the next term is in the node with the next
142368 ** greater node id.
142369 **
142370 ** New data is spilled to a new leaf node when the current node
142371 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
142372 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
142373 ** node (a leaf node with a single term and doclist). The goal of
142374 ** these settings is to pack together groups of small doclists while
142375 ** making it efficient to directly access large doclists. The
142376 ** assumption is that large doclists represent terms which are more
142377 ** likely to be query targets.
142378 **
142379 ** TODO(shess) It may be useful for blocking decisions to be more
142380 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
142381 ** node rather than splitting into 2k and .5k nodes. My intuition is
142382 ** that this might extend through 2x or 4x the pagesize.
142383 **
142384 **
142385 **** Segment interior nodes ****
142386 ** Segment interior nodes store blockids for subtree nodes and terms
142387 ** to describe what data is stored by the each subtree. Interior
142388 ** nodes are written using InteriorWriter, and read using
142389 ** InteriorReader. InteriorWriters are created as needed when
142390 ** SegmentWriter creates new leaf nodes, or when an interior node
142391 ** itself grows too big and must be split. The format of interior
142392 ** nodes:
142393 **
142394 ** varint iHeight; (height from leaf level, always >0)
142395 ** varint iBlockid; (block id of node's leftmost subtree)
142396 ** optional {
142397 ** varint nTerm; (length of first term)
142398 ** char pTerm[nTerm]; (content of first term)
142399 ** array {
142400 ** (further terms are delta-encoded)
142401 ** varint nPrefix; (length of shared prefix with previous term)
142402 ** varint nSuffix; (length of unshared suffix)
142403 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
142404 ** }
142405 ** }
142406 **
142407 ** Here, optional { X } means an optional element, while array { X }
142408 ** means zero or more occurrences of X, adjacent in memory.
142409 **
142410 ** An interior node encodes n terms separating n+1 subtrees. The
142411 ** subtree blocks are contiguous, so only the first subtree's blockid
142412 ** is encoded. The subtree at iBlockid will contain all terms less
142413 ** than the first term encoded (or all terms if no term is encoded).
142414 ** Otherwise, for terms greater than or equal to pTerm[i] but less
142415 ** than pTerm[i+1], the subtree for that term will be rooted at
142416 ** iBlockid+i. Interior nodes only store enough term data to
142417 ** distinguish adjacent children (if the rightmost term of the left
142418 ** child is "something", and the leftmost term of the right child is
142419 ** "wicked", only "w" is stored).
142420 **
142421 ** New data is spilled to a new interior node at the same height when
142422 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
142423 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
142424 ** interior nodes and making the tree too skinny. The interior nodes
142425 ** at a given height are naturally tracked by interior nodes at
142426 ** height+1, and so on.
142427 **
142428 **
142429 **** Segment directory ****
142430 ** The segment directory in table %_segdir stores meta-information for
142431 ** merging and deleting segments, and also the root node of the
142432 ** segment's tree.
142433 **
142434 ** The root node is the top node of the segment's tree after encoding
142435 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
142436 ** This could be either a leaf node or an interior node. If the top
142437 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
142438 ** and a new root interior node is generated (which should always fit
142439 ** within ROOT_MAX because it only needs space for 2 varints, the
142440 ** height and the blockid of the previous root).
142441 **
142442 ** The meta-information in the segment directory is:
142443 ** level - segment level (see below)
142444 ** idx - index within level
142445 ** - (level,idx uniquely identify a segment)
142446 ** start_block - first leaf node
142447 ** leaves_end_block - last leaf node
142448 ** end_block - last block (including interior nodes)
142449 ** root - contents of root node
142450 **
142451 ** If the root node is a leaf node, then start_block,
142452 ** leaves_end_block, and end_block are all 0.
142453 **
142454 **
142455 **** Segment merging ****
142456 ** To amortize update costs, segments are grouped into levels and
142457 ** merged in batches. Each increase in level represents exponentially
142458 ** more documents.
142459 **
142460 ** New documents (actually, document updates) are tokenized and
142461 ** written individually (using LeafWriter) to a level 0 segment, with
142462 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
142463 ** level 0 segments are merged into a single level 1 segment. Level 1
142464 ** is populated like level 0, and eventually MERGE_COUNT level 1
142465 ** segments are merged to a single level 2 segment (representing
142466 ** MERGE_COUNT^2 updates), and so on.
142467 **
142468 ** A segment merge traverses all segments at a given level in
142469 ** parallel, performing a straightforward sorted merge. Since segment
142470 ** leaf nodes are written in to the %_segments table in order, this
142471 ** merge traverses the underlying sqlite disk structures efficiently.
142472 ** After the merge, all segment blocks from the merged level are
142473 ** deleted.
142474 **
142475 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
142476 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
142477 ** very similar performance numbers to 16 on insertion, though they're
142478 ** a tiny bit slower (perhaps due to more overhead in merge-time
142479 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
142480 ** 16, 2 about 66% slower than 16.
142481 **
142482 ** At query time, high MERGE_COUNT increases the number of segments
142483 ** which need to be scanned and merged. For instance, with 100k docs
142484 ** inserted:
142485 **
142486 ** MERGE_COUNT segments
142487 ** 16 25
142488 ** 8 12
142489 ** 4 10
142490 ** 2 6
142491 **
142492 ** This appears to have only a moderate impact on queries for very
142493 ** frequent terms (which are somewhat dominated by segment merge
142494 ** costs), and infrequent and non-existent terms still seem to be fast
142495 ** even with many segments.
142496 **
142497 ** TODO(shess) That said, it would be nice to have a better query-side
142498 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
142499 ** optimizations to things like doclist merging will swing the sweet
142500 ** spot around.
142501 **
142502 **
142503 **
142504 **** Handling of deletions and updates ****
142505 ** Since we're using a segmented structure, with no docid-oriented
142506 ** index into the term index, we clearly cannot simply update the term
142507 ** index when a document is deleted or updated. For deletions, we
142508 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
142509 ** we simply write the new doclist. Segment merges overwrite older
142510 ** data for a particular docid with newer data, so deletes or updates
142511 ** will eventually overtake the earlier data and knock it out. The
142512 ** query logic likewise merges doclists so that newer data knocks out
142513 ** older data.
142514 */
142515 
142516 /************** Include fts3Int.h in the middle of fts3.c ********************/
142517 /************** Begin file fts3Int.h *****************************************/
142518 /*
142519 ** 2009 Nov 12
142520 **
142521 ** The author disclaims copyright to this source code. In place of
142522 ** a legal notice, here is a blessing:
142523 **
142524 ** May you do good and not evil.
142525 ** May you find forgiveness for yourself and forgive others.
142526 ** May you share freely, never taking more than you give.
142527 **
142528 ******************************************************************************
142529 **
142530 */
142531 #ifndef _FTSINT_H
142532 #define _FTSINT_H
142533 
142534 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
142535 # define NDEBUG 1
142536 #endif
142537 
142538 /* FTS3/FTS4 require virtual tables */
142539 #ifdef SQLITE_OMIT_VIRTUALTABLE
142540 # undef SQLITE_ENABLE_FTS3
142541 # undef SQLITE_ENABLE_FTS4
142542 #endif
142543 
142544 /*
142545 ** FTS4 is really an extension for FTS3. It is enabled using the
142546 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
142547 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
142548 */
142549 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
142550 # define SQLITE_ENABLE_FTS3
142551 #endif
142552 
142553 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142554 
142555 /* If not building as part of the core, include sqlite3ext.h. */
142556 #ifndef SQLITE_CORE
142557 /* # include "sqlite3ext.h" */
142559 #endif
142560 
142561 /* #include "sqlite3.h" */
142562 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
142563 /************** Begin file fts3_tokenizer.h **********************************/
142564 /*
142565 ** 2006 July 10
142566 **
142567 ** The author disclaims copyright to this source code.
142568 **
142569 *************************************************************************
142570 ** Defines the interface to tokenizers used by fulltext-search. There
142571 ** are three basic components:
142572 **
142573 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
142574 ** interface functions. This is essentially the class structure for
142575 ** tokenizers.
142576 **
142577 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
142578 ** including customization information defined at creation time.
142579 **
142580 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
142581 ** tokens from a particular input.
142582 */
142583 #ifndef _FTS3_TOKENIZER_H_
142584 #define _FTS3_TOKENIZER_H_
142585 
142586 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
142587 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
142588 ** we will need a way to register the API consistently.
142589 */
142590 /* #include "sqlite3.h" */
142591 
142592 /*
142593 ** Structures used by the tokenizer interface. When a new tokenizer
142594 ** implementation is registered, the caller provides a pointer to
142595 ** an sqlite3_tokenizer_module containing pointers to the callback
142596 ** functions that make up an implementation.
142597 **
142598 ** When an fts3 table is created, it passes any arguments passed to
142599 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
142600 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
142601 ** implementation. The xCreate() function in turn returns an
142602 ** sqlite3_tokenizer structure representing the specific tokenizer to
142603 ** be used for the fts3 table (customized by the tokenizer clause arguments).
142604 **
142605 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
142606 ** method is called. It returns an sqlite3_tokenizer_cursor object
142607 ** that may be used to tokenize a specific input buffer based on
142608 ** the tokenization rules supplied by a specific sqlite3_tokenizer
142609 ** object.
142610 */
142611 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
142612 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
142613 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
142614 
142615 struct sqlite3_tokenizer_module {
142616 
142617  /*
142618  ** Structure version. Should always be set to 0 or 1.
142619  */
142620  int iVersion;
142621 
142622  /*
142623  ** Create a new tokenizer. The values in the argv[] array are the
142624  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
142625  ** TABLE statement that created the fts3 table. For example, if
142626  ** the following SQL is executed:
142627  **
142628  ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
142629  **
142630  ** then argc is set to 2, and the argv[] array contains pointers
142631  ** to the strings "arg1" and "arg2".
142632  **
142633  ** This method should return either SQLITE_OK (0), or an SQLite error
142634  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
142635  ** to point at the newly created tokenizer structure. The generic
142636  ** sqlite3_tokenizer.pModule variable should not be initialized by
142637  ** this callback. The caller will do so.
142638  */
142639  int (*xCreate)(
142640  int argc, /* Size of argv array */
142641  const char *const*argv, /* Tokenizer argument strings */
142642  sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
142643  );
142644 
142645  /*
142646  ** Destroy an existing tokenizer. The fts3 module calls this method
142647  ** exactly once for each successful call to xCreate().
142648  */
142649  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
142650 
142651  /*
142652  ** Create a tokenizer cursor to tokenize an input buffer. The caller
142653  ** is responsible for ensuring that the input buffer remains valid
142654  ** until the cursor is closed (using the xClose() method).
142655  */
142656  int (*xOpen)(
142657  sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
142658  const char *pInput, int nBytes, /* Input buffer */
142659  sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
142660  );
142661 
142662  /*
142663  ** Destroy an existing tokenizer cursor. The fts3 module calls this
142664  ** method exactly once for each successful call to xOpen().
142665  */
142666  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
142667 
142668  /*
142669  ** Retrieve the next token from the tokenizer cursor pCursor. This
142670  ** method should either return SQLITE_OK and set the values of the
142671  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
142672  ** the end of the buffer has been reached, or an SQLite error code.
142673  **
142674  ** *ppToken should be set to point at a buffer containing the
142675  ** normalized version of the token (i.e. after any case-folding and/or
142676  ** stemming has been performed). *pnBytes should be set to the length
142677  ** of this buffer in bytes. The input text that generated the token is
142678  ** identified by the byte offsets returned in *piStartOffset and
142679  ** *piEndOffset. *piStartOffset should be set to the index of the first
142680  ** byte of the token in the input buffer. *piEndOffset should be set
142681  ** to the index of the first byte just past the end of the token in
142682  ** the input buffer.
142683  **
142684  ** The buffer *ppToken is set to point at is managed by the tokenizer
142685  ** implementation. It is only required to be valid until the next call
142686  ** to xNext() or xClose().
142687  */
142688  /* TODO(shess) current implementation requires pInput to be
142689  ** nul-terminated. This should either be fixed, or pInput/nBytes
142690  ** should be converted to zInput.
142691  */
142692  int (*xNext)(
142693  sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
142694  const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
142695  int *piStartOffset, /* OUT: Byte offset of token in input buffer */
142696  int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
142697  int *piPosition /* OUT: Number of tokens returned before this one */
142698  );
142699 
142700  /***********************************************************************
142701  ** Methods below this point are only available if iVersion>=1.
142702  */
142703 
142704  /*
142705  ** Configure the language id of a tokenizer cursor.
142706  */
142707  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
142708 };
142709 
142710 struct sqlite3_tokenizer {
142711  const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
142712  /* Tokenizer implementations will typically add additional fields */
142713 };
142714 
142715 struct sqlite3_tokenizer_cursor {
142716  sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
142717  /* Tokenizer implementations will typically add additional fields */
142718 };
142719 
142720 int fts3_global_term_cnt(int iTerm, int iCol);
142721 int fts3_term_cnt(int iTerm, int iCol);
142722 
142723 
142724 #endif /* _FTS3_TOKENIZER_H_ */
142725 
142726 /************** End of fts3_tokenizer.h **************************************/
142727 /************** Continuing where we left off in fts3Int.h ********************/
142728 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
142729 /************** Begin file fts3_hash.h ***************************************/
142730 /*
142731 ** 2001 September 22
142732 **
142733 ** The author disclaims copyright to this source code. In place of
142734 ** a legal notice, here is a blessing:
142735 **
142736 ** May you do good and not evil.
142737 ** May you find forgiveness for yourself and forgive others.
142738 ** May you share freely, never taking more than you give.
142739 **
142740 *************************************************************************
142741 ** This is the header file for the generic hash-table implementation
142742 ** used in SQLite. We've modified it slightly to serve as a standalone
142743 ** hash table implementation for the full-text indexing module.
142744 **
142745 */
142746 #ifndef _FTS3_HASH_H_
142747 #define _FTS3_HASH_H_
142748 
142749 /* Forward declarations of structures. */
142750 typedef struct Fts3Hash Fts3Hash;
142751 typedef struct Fts3HashElem Fts3HashElem;
142752 
142753 /* A complete hash table is an instance of the following structure.
142754 ** The internals of this structure are intended to be opaque -- client
142755 ** code should not attempt to access or modify the fields of this structure
142756 ** directly. Change this structure only by using the routines below.
142757 ** However, many of the "procedures" and "functions" for modifying and
142758 ** accessing this structure are really macros, so we can't really make
142759 ** this structure opaque.
142760 */
142761 struct Fts3Hash {
142762  char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
142763  char copyKey; /* True if copy of key made on insert */
142764  int count; /* Number of entries in this table */
142765  Fts3HashElem *first; /* The first element of the array */
142766  int htsize; /* Number of buckets in the hash table */
142767  struct _fts3ht { /* the hash table */
142768  int count; /* Number of entries with this hash */
142769  Fts3HashElem *chain; /* Pointer to first entry with this hash */
142770  } *ht;
142771 };
142772 
142773 /* Each element in the hash table is an instance of the following
142774 ** structure. All elements are stored on a single doubly-linked list.
142775 **
142776 ** Again, this structure is intended to be opaque, but it can't really
142777 ** be opaque because it is used by macros.
142778 */
142779 struct Fts3HashElem {
142780  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
142781  void *data; /* Data associated with this element */
142782  void *pKey; int nKey; /* Key associated with this element */
142783 };
142784 
142785 /*
142786 ** There are 2 different modes of operation for a hash table:
142787 **
142788 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
142789 ** (including the null-terminator, if any). Case
142790 ** is respected in comparisons.
142791 **
142792 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
142793 ** memcmp() is used to compare keys.
142794 **
142795 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
142796 */
142797 #define FTS3_HASH_STRING 1
142798 #define FTS3_HASH_BINARY 2
142799 
142800 /*
142801 ** Access routines. To delete, insert a NULL pointer.
142802 */
142803 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
142804 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
142805 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
142806 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
142807 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
142808 
142809 /*
142810 ** Shorthand for the functions above
142811 */
142812 #define fts3HashInit sqlite3Fts3HashInit
142813 #define fts3HashInsert sqlite3Fts3HashInsert
142814 #define fts3HashFind sqlite3Fts3HashFind
142815 #define fts3HashClear sqlite3Fts3HashClear
142816 #define fts3HashFindElem sqlite3Fts3HashFindElem
142817 
142818 /*
142819 ** Macros for looping over all elements of a hash table. The idiom is
142820 ** like this:
142821 **
142822 ** Fts3Hash h;
142823 ** Fts3HashElem *p;
142824 ** ...
142825 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
142826 ** SomeStructure *pData = fts3HashData(p);
142827 ** // do something with pData
142828 ** }
142829 */
142830 #define fts3HashFirst(H) ((H)->first)
142831 #define fts3HashNext(E) ((E)->next)
142832 #define fts3HashData(E) ((E)->data)
142833 #define fts3HashKey(E) ((E)->pKey)
142834 #define fts3HashKeysize(E) ((E)->nKey)
142835 
142836 /*
142837 ** Number of entries in a hash table
142838 */
142839 #define fts3HashCount(H) ((H)->count)
142840 
142841 #endif /* _FTS3_HASH_H_ */
142842 
142843 /************** End of fts3_hash.h *******************************************/
142844 /************** Continuing where we left off in fts3Int.h ********************/
142845 
142846 /*
142847 ** This constant determines the maximum depth of an FTS expression tree
142848 ** that the library will create and use. FTS uses recursion to perform
142849 ** various operations on the query tree, so the disadvantage of a large
142850 ** limit is that it may allow very large queries to use large amounts
142851 ** of stack space (perhaps causing a stack overflow).
142852 */
142853 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
142854 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
142855 #endif
142856 
142857 
142858 /*
142859 ** This constant controls how often segments are merged. Once there are
142860 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
142861 ** segment of level N+1.
142862 */
142863 #define FTS3_MERGE_COUNT 16
142864 
142865 /*
142866 ** This is the maximum amount of data (in bytes) to store in the
142867 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
142868 ** populated as documents are inserted/updated/deleted in a transaction
142869 ** and used to create a new segment when the transaction is committed.
142870 ** However if this limit is reached midway through a transaction, a new
142871 ** segment is created and the hash table cleared immediately.
142872 */
142873 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
142874 
142875 /*
142876 ** Macro to return the number of elements in an array. SQLite has a
142877 ** similar macro called ArraySize(). Use a different name to avoid
142878 ** a collision when building an amalgamation with built-in FTS3.
142879 */
142880 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
142881 
142882 
142883 #ifndef MIN
142884 # define MIN(x,y) ((x)<(y)?(x):(y))
142885 #endif
142886 #ifndef MAX
142887 # define MAX(x,y) ((x)>(y)?(x):(y))
142888 #endif
142889 
142890 /*
142891 ** Maximum length of a varint encoded integer. The varint format is different
142892 ** from that used by SQLite, so the maximum length is 10, not 9.
142893 */
142894 #define FTS3_VARINT_MAX 10
142895 
142896 /*
142897 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
142898 ** in the document set and zero or more prefix indexes. All indexes are stored
142899 ** as one or more b+-trees in the %_segments and %_segdir tables.
142900 **
142901 ** It is possible to determine which index a b+-tree belongs to based on the
142902 ** value stored in the "%_segdir.level" column. Given this value L, the index
142903 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
142904 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
142905 ** between 1024 and 2047 to index 1, and so on.
142906 **
142907 ** It is considered impossible for an index to use more than 1024 levels. In
142908 ** theory though this may happen, but only after at least
142909 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
142910 */
142911 #define FTS3_SEGDIR_MAXLEVEL 1024
142912 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
142913 
142914 /*
142915 ** The testcase() macro is only used by the amalgamation. If undefined,
142916 ** make it a no-op.
142917 */
142918 #ifndef testcase
142919 # define testcase(X)
142920 #endif
142921 
142922 /*
142923 ** Terminator values for position-lists and column-lists.
142924 */
142925 #define POS_COLUMN (1) /* Column-list terminator */
142926 #define POS_END (0) /* Position-list terminator */
142927 
142928 /*
142929 ** This section provides definitions to allow the
142930 ** FTS3 extension to be compiled outside of the
142931 ** amalgamation.
142932 */
142933 #ifndef SQLITE_AMALGAMATION
142934 /*
142935 ** Macros indicating that conditional expressions are always true or
142936 ** false.
142937 */
142938 #ifdef SQLITE_COVERAGE_TEST
142939 # define ALWAYS(x) (1)
142940 # define NEVER(X) (0)
142941 #elif defined(SQLITE_DEBUG)
142942 # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
142943 # define NEVER(x) sqlite3Fts3Never((x)!=0)
142944 SQLITE_PRIVATE int sqlite3Fts3Always(int b);
142945 SQLITE_PRIVATE int sqlite3Fts3Never(int b);
142946 #else
142947 # define ALWAYS(x) (x)
142948 # define NEVER(x) (x)
142949 #endif
142950 
142951 /*
142952 ** Internal types used by SQLite.
142953 */
142954 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
142955 typedef short int i16; /* 2-byte (or larger) signed integer */
142956 typedef unsigned int u32; /* 4-byte unsigned integer */
142957 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
142958 typedef sqlite3_int64 i64; /* 8-byte signed integer */
142959 
142960 /*
142961 ** Macro used to suppress compiler warnings for unused parameters.
142962 */
142963 #define UNUSED_PARAMETER(x) (void)(x)
142964 
142965 /*
142966 ** Activate assert() only if SQLITE_TEST is enabled.
142967 */
142968 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
142969 # define NDEBUG 1
142970 #endif
142971 
142972 /*
142973 ** The TESTONLY macro is used to enclose variable declarations or
142974 ** other bits of code that are needed to support the arguments
142975 ** within testcase() and assert() macros.
142976 */
142977 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
142978 # define TESTONLY(X) X
142979 #else
142980 # define TESTONLY(X)
142981 #endif
142982 
142983 #endif /* SQLITE_AMALGAMATION */
142984 
142985 #ifdef SQLITE_DEBUG
142986 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
142987 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
142988 #else
142989 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
142990 #endif
142991 
142992 typedef struct Fts3Table Fts3Table;
142993 typedef struct Fts3Cursor Fts3Cursor;
142994 typedef struct Fts3Expr Fts3Expr;
142995 typedef struct Fts3Phrase Fts3Phrase;
142996 typedef struct Fts3PhraseToken Fts3PhraseToken;
142997 
142998 typedef struct Fts3Doclist Fts3Doclist;
142999 typedef struct Fts3SegFilter Fts3SegFilter;
143000 typedef struct Fts3DeferredToken Fts3DeferredToken;
143001 typedef struct Fts3SegReader Fts3SegReader;
143002 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
143003 
143004 typedef struct MatchinfoBuffer MatchinfoBuffer;
143005 
143006 /*
143007 ** A connection to a fulltext index is an instance of the following
143008 ** structure. The xCreate and xConnect methods create an instance
143009 ** of this structure and xDestroy and xDisconnect free that instance.
143010 ** All other methods receive a pointer to the structure as one of their
143011 ** arguments.
143012 */
143013 struct Fts3Table {
143014  sqlite3_vtab base; /* Base class used by SQLite core */
143015  sqlite3 *db; /* The database connection */
143016  const char *zDb; /* logical database name */
143017  const char *zName; /* virtual table name */
143018  int nColumn; /* number of named columns in virtual table */
143019  char **azColumn; /* column names. malloced */
143020  u8 *abNotindexed; /* True for 'notindexed' columns */
143021  sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
143022  char *zContentTbl; /* content=xxx option, or NULL */
143023  char *zLanguageid; /* languageid=xxx option, or NULL */
143024  int nAutoincrmerge; /* Value configured by 'automerge' */
143025  u32 nLeafAdd; /* Number of leaf blocks added this trans */
143026 
143027  /* Precompiled statements used by the implementation. Each of these
143028  ** statements is run and reset within a single virtual table API call.
143029  */
143030  sqlite3_stmt *aStmt[40];
143031 
143032  char *zReadExprlist;
143033  char *zWriteExprlist;
143034 
143035  int nNodeSize; /* Soft limit for node size */
143036  u8 bFts4; /* True for FTS4, false for FTS3 */
143037  u8 bHasStat; /* True if %_stat table exists (2==unknown) */
143038  u8 bHasDocsize; /* True if %_docsize table exists */
143039  u8 bDescIdx; /* True if doclists are in reverse order */
143040  u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
143041  int nPgsz; /* Page size for host database */
143042  char *zSegmentsTbl; /* Name of %_segments table */
143043  sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
143044 
143045  /*
143046  ** The following array of hash tables is used to buffer pending index
143047  ** updates during transactions. All pending updates buffered at any one
143048  ** time must share a common language-id (see the FTS4 langid= feature).
143049  ** The current language id is stored in variable iPrevLangid.
143050  **
143051  ** A single FTS4 table may have multiple full-text indexes. For each index
143052  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
143053  ** terms that appear in the document set. Each subsequent index in aIndex[]
143054  ** is an index of prefixes of a specific length.
143055  **
143056  ** Variable nPendingData contains an estimate the memory consumed by the
143057  ** pending data structures, including hash table overhead, but not including
143058  ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
143059  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
143060  ** recently inserted record.
143061  */
143062  int nIndex; /* Size of aIndex[] */
143063  struct Fts3Index {
143064  int nPrefix; /* Prefix length (0 for main terms index) */
143065  Fts3Hash hPending; /* Pending terms table for this index */
143066  } *aIndex;
143067  int nMaxPendingData; /* Max pending data before flush to disk */
143068  int nPendingData; /* Current bytes of pending data */
143069  sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
143070  int iPrevLangid; /* Langid of recently inserted document */
143071  int bPrevDelete; /* True if last operation was a delete */
143072 
143073 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
143074  /* State variables used for validating that the transaction control
143075  ** methods of the virtual table are called at appropriate times. These
143076  ** values do not contribute to FTS functionality; they are used for
143077  ** verifying the operation of the SQLite core.
143078  */
143079  int inTransaction; /* True after xBegin but before xCommit/xRollback */
143080  int mxSavepoint; /* Largest valid xSavepoint integer */
143081 #endif
143082 
143083 #ifdef SQLITE_TEST
143084  /* True to disable the incremental doclist optimization. This is controled
143085  ** by special insert command 'test-no-incr-doclist'. */
143086  int bNoIncrDoclist;
143087 #endif
143088 };
143089 
143090 /*
143091 ** When the core wants to read from the virtual table, it creates a
143092 ** virtual table cursor (an instance of the following structure) using
143093 ** the xOpen method. Cursors are destroyed using the xClose method.
143094 */
143095 struct Fts3Cursor {
143096  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
143097  i16 eSearch; /* Search strategy (see below) */
143098  u8 isEof; /* True if at End Of Results */
143099  u8 isRequireSeek; /* True if must seek pStmt to %_content row */
143100  sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
143101  Fts3Expr *pExpr; /* Parsed MATCH query string */
143102  int iLangid; /* Language being queried for */
143103  int nPhrase; /* Number of matchable phrases in query */
143104  Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
143105  sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
143106  char *pNextId; /* Pointer into the body of aDoclist */
143107  char *aDoclist; /* List of docids for full-text queries */
143108  int nDoclist; /* Size of buffer at aDoclist */
143109  u8 bDesc; /* True to sort in descending order */
143110  int eEvalmode; /* An FTS3_EVAL_XX constant */
143111  int nRowAvg; /* Average size of database rows, in pages */
143112  sqlite3_int64 nDoc; /* Documents in table */
143113  i64 iMinDocid; /* Minimum docid to return */
143114  i64 iMaxDocid; /* Maximum docid to return */
143115  int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
143116  MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
143117 };
143118 
143119 #define FTS3_EVAL_FILTER 0
143120 #define FTS3_EVAL_NEXT 1
143121 #define FTS3_EVAL_MATCHINFO 2
143122 
143123 /*
143124 ** The Fts3Cursor.eSearch member is always set to one of the following.
143125 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
143126 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
143127 ** of the column to be searched. For example, in
143128 **
143129 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
143130 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
143131 **
143132 ** Because the LHS of the MATCH operator is 2nd column "b",
143133 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
143134 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
143135 ** indicating that all columns should be searched,
143136 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
143137 */
143138 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
143139 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
143140 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
143141 
143142 /*
143143 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
143144 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
143145 ** above. The upper 16-bits contain a combination of the following
143146 ** bits, used to describe extra constraints on full-text searches.
143147 */
143148 #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
143149 #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
143150 #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
143151 
143152 struct Fts3Doclist {
143153  char *aAll; /* Array containing doclist (or NULL) */
143154  int nAll; /* Size of a[] in bytes */
143155  char *pNextDocid; /* Pointer to next docid */
143156 
143157  sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
143158  int bFreeList; /* True if pList should be sqlite3_free()d */
143159  char *pList; /* Pointer to position list following iDocid */
143160  int nList; /* Length of position list */
143161 };
143162 
143163 /*
143164 ** A "phrase" is a sequence of one or more tokens that must match in
143165 ** sequence. A single token is the base case and the most common case.
143166 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
143167 ** nToken will be the number of tokens in the string.
143168 */
143169 struct Fts3PhraseToken {
143170  char *z; /* Text of the token */
143171  int n; /* Number of bytes in buffer z */
143172  int isPrefix; /* True if token ends with a "*" character */
143173  int bFirst; /* True if token must appear at position 0 */
143174 
143175  /* Variables above this point are populated when the expression is
143176  ** parsed (by code in fts3_expr.c). Below this point the variables are
143177  ** used when evaluating the expression. */
143178  Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
143179  Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
143180 };
143181 
143182 struct Fts3Phrase {
143183  /* Cache of doclist for this phrase. */
143184  Fts3Doclist doclist;
143185  int bIncr; /* True if doclist is loaded incrementally */
143186  int iDoclistToken;
143187 
143188  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
143189  ** OR condition. */
143190  char *pOrPoslist;
143191  i64 iOrDocid;
143192 
143193  /* Variables below this point are populated by fts3_expr.c when parsing
143194  ** a MATCH expression. Everything above is part of the evaluation phase.
143195  */
143196  int nToken; /* Number of tokens in the phrase */
143197  int iColumn; /* Index of column this phrase must match */
143198  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
143199 };
143200 
143201 /*
143202 ** A tree of these objects forms the RHS of a MATCH operator.
143203 **
143204 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
143205 ** points to a malloced buffer, size nDoclist bytes, containing the results
143206 ** of this phrase query in FTS3 doclist format. As usual, the initial
143207 ** "Length" field found in doclists stored on disk is omitted from this
143208 ** buffer.
143209 **
143210 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
143211 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
143212 ** where nCol is the number of columns in the queried FTS table. The array
143213 ** is populated as follows:
143214 **
143215 ** aMI[iCol*3 + 0] = Undefined
143216 ** aMI[iCol*3 + 1] = Number of occurrences
143217 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
143218 **
143219 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
143220 ** when the expression node is.
143221 */
143222 struct Fts3Expr {
143223  int eType; /* One of the FTSQUERY_XXX values defined below */
143224  int nNear; /* Valid if eType==FTSQUERY_NEAR */
143225  Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
143226  Fts3Expr *pLeft; /* Left operand */
143227  Fts3Expr *pRight; /* Right operand */
143228  Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
143229 
143230  /* The following are used by the fts3_eval.c module. */
143231  sqlite3_int64 iDocid; /* Current docid */
143232  u8 bEof; /* True this expression is at EOF already */
143233  u8 bStart; /* True if iDocid is valid */
143234  u8 bDeferred; /* True if this expression is entirely deferred */
143235 
143236  /* The following are used by the fts3_snippet.c module. */
143237  int iPhrase; /* Index of this phrase in matchinfo() results */
143238  u32 *aMI; /* See above */
143239 };
143240 
143241 /*
143242 ** Candidate values for Fts3Query.eType. Note that the order of the first
143243 ** four values is in order of precedence when parsing expressions. For
143244 ** example, the following:
143245 **
143246 ** "a OR b AND c NOT d NEAR e"
143247 **
143248 ** is equivalent to:
143249 **
143250 ** "a OR (b AND (c NOT (d NEAR e)))"
143251 */
143252 #define FTSQUERY_NEAR 1
143253 #define FTSQUERY_NOT 2
143254 #define FTSQUERY_AND 3
143255 #define FTSQUERY_OR 4
143256 #define FTSQUERY_PHRASE 5
143257 
143258 
143259 /* fts3_write.c */
143260 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
143261 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
143262 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
143263 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
143264 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
143265  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
143266 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
143267  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
143268 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
143269 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
143270 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
143271 
143272 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
143273 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
143274 
143275 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
143276 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
143277 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
143278 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
143279 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
143280 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
143281 #else
143282 # define sqlite3Fts3FreeDeferredTokens(x)
143283 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
143284 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
143285 # define sqlite3Fts3FreeDeferredDoclists(x)
143286 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
143287 #endif
143288 
143289 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
143290 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
143291 
143292 /* Special values interpreted by sqlite3SegReaderCursor() */
143293 #define FTS3_SEGCURSOR_PENDING -1
143294 #define FTS3_SEGCURSOR_ALL -2
143295 
143296 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
143297 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
143298 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
143299 
143300 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
143301  int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
143302 
143303 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
143304 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
143305 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
143306 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
143307 #define FTS3_SEGMENT_PREFIX 0x00000008
143308 #define FTS3_SEGMENT_SCAN 0x00000010
143309 #define FTS3_SEGMENT_FIRST 0x00000020
143310 
143311 /* Type passed as 4th argument to SegmentReaderIterate() */
143312 struct Fts3SegFilter {
143313  const char *zTerm;
143314  int nTerm;
143315  int iCol;
143316  int flags;
143317 };
143318 
143319 struct Fts3MultiSegReader {
143320  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
143321  Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
143322  int nSegment; /* Size of apSegment array */
143323  int nAdvance; /* How many seg-readers to advance */
143324  Fts3SegFilter *pFilter; /* Pointer to filter object */
143325  char *aBuffer; /* Buffer to merge doclists in */
143326  int nBuffer; /* Allocated size of aBuffer[] in bytes */
143327 
143328  int iColFilter; /* If >=0, filter for this column */
143329  int bRestart;
143330 
143331  /* Used by fts3.c only. */
143332  int nCost; /* Cost of running iterator */
143333  int bLookup; /* True if a lookup of a single entry. */
143334 
143335  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
143336  char *zTerm; /* Pointer to term buffer */
143337  int nTerm; /* Size of zTerm in bytes */
143338  char *aDoclist; /* Pointer to doclist buffer */
143339  int nDoclist; /* Size of aDoclist[] in bytes */
143340 };
143341 
143342 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
143343 
143344 #define fts3GetVarint32(p, piVal) ( \
143345  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
143346 )
143347 
143348 /* fts3.c */
143349 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
143350 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
143351 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
143352 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
143353 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
143354 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
143355 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
143356 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
143357 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
143358 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
143359 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
143360 
143361 /* fts3_tokenizer.c */
143362 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
143363 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
143364 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
143365  sqlite3_tokenizer **, char **
143366 );
143367 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
143368 
143369 /* fts3_snippet.c */
143370 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
143371 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
143372  const char *, const char *, int, int
143373 );
143374 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
143375 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
143376 
143377 /* fts3_expr.c */
143378 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
143379  char **, int, int, int, const char *, int, Fts3Expr **, char **
143380 );
143381 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
143382 #ifdef SQLITE_TEST
143383 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
143384 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
143385 #endif
143386 
143387 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
143388  sqlite3_tokenizer_cursor **
143389 );
143390 
143391 /* fts3_aux.c */
143392 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
143393 
143394 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
143395 
143396 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
143397  Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
143398 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
143399  Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
143400 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
143401 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
143402 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
143403 
143404 /* fts3_tokenize_vtab.c */
143405 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
143406 
143407 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
143408 #ifndef SQLITE_DISABLE_FTS3_UNICODE
143409 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
143410 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
143411 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
143412 #endif
143413 
143414 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
143415 #endif /* _FTSINT_H */
143416 
143417 /************** End of fts3Int.h *********************************************/
143418 /************** Continuing where we left off in fts3.c ***********************/
143419 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
143420 
143421 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
143422 # define SQLITE_CORE 1
143423 #endif
143424 
143425 /* #include <assert.h> */
143426 /* #include <stdlib.h> */
143427 /* #include <stddef.h> */
143428 /* #include <stdio.h> */
143429 /* #include <string.h> */
143430 /* #include <stdarg.h> */
143431 
143432 /* #include "fts3.h" */
143433 #ifndef SQLITE_CORE
143434 /* # include "sqlite3ext.h" */
143436 #endif
143437 
143438 static int fts3EvalNext(Fts3Cursor *pCsr);
143439 static int fts3EvalStart(Fts3Cursor *pCsr);
143440 static int fts3TermSegReaderCursor(
143441  Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
143442 
143443 #ifndef SQLITE_AMALGAMATION
143444 # if defined(SQLITE_DEBUG)
143445 SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
143446 SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
143447 # endif
143448 #endif
143449 
143450 /*
143451 ** Write a 64-bit variable-length integer to memory starting at p[0].
143452 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
143453 ** The number of bytes written is returned.
143454 */
143455 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
143456  unsigned char *q = (unsigned char *) p;
143457  sqlite_uint64 vu = v;
143458  do{
143459  *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
143460  vu >>= 7;
143461  }while( vu!=0 );
143462  q[-1] &= 0x7f; /* turn off high bit in final byte */
143463  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
143464  return (int) (q - (unsigned char *)p);
143465 }
143466 
143467 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
143468  v = (v & mask1) | ( (*ptr++) << shift ); \
143469  if( (v & mask2)==0 ){ var = v; return ret; }
143470 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
143471  v = (*ptr++); \
143472  if( (v & mask2)==0 ){ var = v; return ret; }
143473 
143474 /*
143475 ** Read a 64-bit variable-length integer from memory starting at p[0].
143476 ** Return the number of bytes read, or 0 on error.
143477 ** The value is stored in *v.
143478 */
143479 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
143480  const char *pStart = p;
143481  u32 a;
143482  u64 b;
143483  int shift;
143484 
143485  GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
143486  GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
143487  GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
143488  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
143489  b = (a & 0x0FFFFFFF );
143490 
143491  for(shift=28; shift<=63; shift+=7){
143492  u64 c = *p++;
143493  b += (c&0x7F) << shift;
143494  if( (c & 0x80)==0 ) break;
143495  }
143496  *v = b;
143497  return (int)(p - pStart);
143498 }
143499 
143500 /*
143501 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
143502 ** 32-bit integer before it is returned.
143503 */
143504 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
143505  u32 a;
143506 
143507 #ifndef fts3GetVarint32
143508  GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
143509 #else
143510  a = (*p++);
143511  assert( a & 0x80 );
143512 #endif
143513 
143514  GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
143515  GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
143516  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
143517  a = (a & 0x0FFFFFFF );
143518  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
143519  return 5;
143520 }
143521 
143522 /*
143523 ** Return the number of bytes required to encode v as a varint
143524 */
143525 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
143526  int i = 0;
143527  do{
143528  i++;
143529  v >>= 7;
143530  }while( v!=0 );
143531  return i;
143532 }
143533 
143534 /*
143535 ** Convert an SQL-style quoted string into a normal string by removing
143536 ** the quote characters. The conversion is done in-place. If the
143537 ** input does not begin with a quote character, then this routine
143538 ** is a no-op.
143539 **
143540 ** Examples:
143541 **
143542 ** "abc" becomes abc
143543 ** 'xyz' becomes xyz
143544 ** [pqr] becomes pqr
143545 ** `mno` becomes mno
143546 **
143547 */
143548 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
143549  char quote; /* Quote character (if any ) */
143550 
143551  quote = z[0];
143552  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
143553  int iIn = 1; /* Index of next byte to read from input */
143554  int iOut = 0; /* Index of next byte to write to output */
143555 
143556  /* If the first byte was a '[', then the close-quote character is a ']' */
143557  if( quote=='[' ) quote = ']';
143558 
143559  while( z[iIn] ){
143560  if( z[iIn]==quote ){
143561  if( z[iIn+1]!=quote ) break;
143562  z[iOut++] = quote;
143563  iIn += 2;
143564  }else{
143565  z[iOut++] = z[iIn++];
143566  }
143567  }
143568  z[iOut] = '\0';
143569  }
143570 }
143571 
143572 /*
143573 ** Read a single varint from the doclist at *pp and advance *pp to point
143574 ** to the first byte past the end of the varint. Add the value of the varint
143575 ** to *pVal.
143576 */
143577 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
143578  sqlite3_int64 iVal;
143579  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
143580  *pVal += iVal;
143581 }
143582 
143583 /*
143584 ** When this function is called, *pp points to the first byte following a
143585 ** varint that is part of a doclist (or position-list, or any other list
143586 ** of varints). This function moves *pp to point to the start of that varint,
143587 ** and sets *pVal by the varint value.
143588 **
143589 ** Argument pStart points to the first byte of the doclist that the
143590 ** varint is part of.
143591 */
143592 static void fts3GetReverseVarint(
143593  char **pp,
143594  char *pStart,
143595  sqlite3_int64 *pVal
143596 ){
143597  sqlite3_int64 iVal;
143598  char *p;
143599 
143600  /* Pointer p now points at the first byte past the varint we are
143601  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
143602  ** clear on character p[-1]. */
143603  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
143604  p++;
143605  *pp = p;
143606 
143607  sqlite3Fts3GetVarint(p, &iVal);
143608  *pVal = iVal;
143609 }
143610 
143611 /*
143612 ** The xDisconnect() virtual table method.
143613 */
143614 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
143615  Fts3Table *p = (Fts3Table *)pVtab;
143616  int i;
143617 
143618  assert( p->nPendingData==0 );
143619  assert( p->pSegments==0 );
143620 
143621  /* Free any prepared statements held */
143622  for(i=0; i<SizeofArray(p->aStmt); i++){
143623  sqlite3_finalize(p->aStmt[i]);
143624  }
143625  sqlite3_free(p->zSegmentsTbl);
143626  sqlite3_free(p->zReadExprlist);
143627  sqlite3_free(p->zWriteExprlist);
143628  sqlite3_free(p->zContentTbl);
143629  sqlite3_free(p->zLanguageid);
143630 
143631  /* Invoke the tokenizer destructor to free the tokenizer. */
143632  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
143633 
143634  sqlite3_free(p);
143635  return SQLITE_OK;
143636 }
143637 
143638 /*
143639 ** Write an error message into *pzErr
143640 */
143641 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
143642  va_list ap;
143643  sqlite3_free(*pzErr);
143644  va_start(ap, zFormat);
143645  *pzErr = sqlite3_vmprintf(zFormat, ap);
143646  va_end(ap);
143647 }
143648 
143649 /*
143650 ** Construct one or more SQL statements from the format string given
143651 ** and then evaluate those statements. The success code is written
143652 ** into *pRc.
143653 **
143654 ** If *pRc is initially non-zero then this routine is a no-op.
143655 */
143656 static void fts3DbExec(
143657  int *pRc, /* Success code */
143658  sqlite3 *db, /* Database in which to run SQL */
143659  const char *zFormat, /* Format string for SQL */
143660  ... /* Arguments to the format string */
143661 ){
143662  va_list ap;
143663  char *zSql;
143664  if( *pRc ) return;
143665  va_start(ap, zFormat);
143666  zSql = sqlite3_vmprintf(zFormat, ap);
143667  va_end(ap);
143668  if( zSql==0 ){
143669  *pRc = SQLITE_NOMEM;
143670  }else{
143671  *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
143672  sqlite3_free(zSql);
143673  }
143674 }
143675 
143676 /*
143677 ** The xDestroy() virtual table method.
143678 */
143679 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
143680  Fts3Table *p = (Fts3Table *)pVtab;
143681  int rc = SQLITE_OK; /* Return code */
143682  const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
143683  sqlite3 *db = p->db; /* Database handle */
143684 
143685  /* Drop the shadow tables */
143686  if( p->zContentTbl==0 ){
143687  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
143688  }
143689  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
143690  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
143691  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
143692  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
143693 
143694  /* If everything has worked, invoke fts3DisconnectMethod() to free the
143695  ** memory associated with the Fts3Table structure and return SQLITE_OK.
143696  ** Otherwise, return an SQLite error code.
143697  */
143698  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
143699 }
143700 
143701 
143702 /*
143703 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
143704 ** passed as the first argument. This is done as part of the xConnect()
143705 ** and xCreate() methods.
143706 **
143707 ** If *pRc is non-zero when this function is called, it is a no-op.
143708 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
143709 ** before returning.
143710 */
143711 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
143712  if( *pRc==SQLITE_OK ){
143713  int i; /* Iterator variable */
143714  int rc; /* Return code */
143715  char *zSql; /* SQL statement passed to declare_vtab() */
143716  char *zCols; /* List of user defined columns */
143717  const char *zLanguageid;
143718 
143719  zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
143721 
143722  /* Create a list of user columns for the virtual table */
143723  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
143724  for(i=1; zCols && i<p->nColumn; i++){
143725  zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
143726  }
143727 
143728  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
143729  zSql = sqlite3_mprintf(
143730  "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
143731  zCols, p->zName, zLanguageid
143732  );
143733  if( !zCols || !zSql ){
143734  rc = SQLITE_NOMEM;
143735  }else{
143736  rc = sqlite3_declare_vtab(p->db, zSql);
143737  }
143738 
143739  sqlite3_free(zSql);
143740  sqlite3_free(zCols);
143741  *pRc = rc;
143742  }
143743 }
143744 
143745 /*
143746 ** Create the %_stat table if it does not already exist.
143747 */
143748 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
143749  fts3DbExec(pRc, p->db,
143750  "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
143751  "(id INTEGER PRIMARY KEY, value BLOB);",
143752  p->zDb, p->zName
143753  );
143754  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
143755 }
143756 
143757 /*
143758 ** Create the backing store tables (%_content, %_segments and %_segdir)
143759 ** required by the FTS3 table passed as the only argument. This is done
143760 ** as part of the vtab xCreate() method.
143761 **
143762 ** If the p->bHasDocsize boolean is true (indicating that this is an
143763 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
143764 ** %_stat tables required by FTS4.
143765 */
143766 static int fts3CreateTables(Fts3Table *p){
143767  int rc = SQLITE_OK; /* Return code */
143768  int i; /* Iterator variable */
143769  sqlite3 *db = p->db; /* The database connection */
143770 
143771  if( p->zContentTbl==0 ){
143772  const char *zLanguageid = p->zLanguageid;
143773  char *zContentCols; /* Columns of %_content table */
143774 
143775  /* Create a list of user columns for the content table */
143776  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
143777  for(i=0; zContentCols && i<p->nColumn; i++){
143778  char *z = p->azColumn[i];
143779  zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
143780  }
143781  if( zLanguageid && zContentCols ){
143782  zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
143783  }
143784  if( zContentCols==0 ) rc = SQLITE_NOMEM;
143785 
143786  /* Create the content table */
143787  fts3DbExec(&rc, db,
143788  "CREATE TABLE %Q.'%q_content'(%s)",
143789  p->zDb, p->zName, zContentCols
143790  );
143791  sqlite3_free(zContentCols);
143792  }
143793 
143794  /* Create other tables */
143795  fts3DbExec(&rc, db,
143796  "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
143797  p->zDb, p->zName
143798  );
143799  fts3DbExec(&rc, db,
143800  "CREATE TABLE %Q.'%q_segdir'("
143801  "level INTEGER,"
143802  "idx INTEGER,"
143803  "start_block INTEGER,"
143804  "leaves_end_block INTEGER,"
143805  "end_block INTEGER,"
143806  "root BLOB,"
143807  "PRIMARY KEY(level, idx)"
143808  ");",
143809  p->zDb, p->zName
143810  );
143811  if( p->bHasDocsize ){
143812  fts3DbExec(&rc, db,
143813  "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
143814  p->zDb, p->zName
143815  );
143816  }
143817  assert( p->bHasStat==p->bFts4 );
143818  if( p->bHasStat ){
143819  sqlite3Fts3CreateStatTable(&rc, p);
143820  }
143821  return rc;
143822 }
143823 
143824 /*
143825 ** Store the current database page-size in bytes in p->nPgsz.
143826 **
143827 ** If *pRc is non-zero when this function is called, it is a no-op.
143828 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
143829 ** before returning.
143830 */
143831 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
143832  if( *pRc==SQLITE_OK ){
143833  int rc; /* Return code */
143834  char *zSql; /* SQL text "PRAGMA %Q.page_size" */
143835  sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
143836 
143837  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
143838  if( !zSql ){
143839  rc = SQLITE_NOMEM;
143840  }else{
143841  rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
143842  if( rc==SQLITE_OK ){
143843  sqlite3_step(pStmt);
143844  p->nPgsz = sqlite3_column_int(pStmt, 0);
143845  rc = sqlite3_finalize(pStmt);
143846  }else if( rc==SQLITE_AUTH ){
143847  p->nPgsz = 1024;
143848  rc = SQLITE_OK;
143849  }
143850  }
143851  assert( p->nPgsz>0 || rc!=SQLITE_OK );
143852  sqlite3_free(zSql);
143853  *pRc = rc;
143854  }
143855 }
143856 
143857 /*
143858 ** "Special" FTS4 arguments are column specifications of the following form:
143859 **
143860 ** <key> = <value>
143861 **
143862 ** There may not be whitespace surrounding the "=" character. The <value>
143863 ** term may be quoted, but the <key> may not.
143864 */
143865 static int fts3IsSpecialColumn(
143866  const char *z,
143867  int *pnKey,
143868  char **pzValue
143869 ){
143870  char *zValue;
143871  const char *zCsr = z;
143872 
143873  while( *zCsr!='=' ){
143874  if( *zCsr=='\0' ) return 0;
143875  zCsr++;
143876  }
143877 
143878  *pnKey = (int)(zCsr-z);
143879  zValue = sqlite3_mprintf("%s", &zCsr[1]);
143880  if( zValue ){
143881  sqlite3Fts3Dequote(zValue);
143882  }
143883  *pzValue = zValue;
143884  return 1;
143885 }
143886 
143887 /*
143888 ** Append the output of a printf() style formatting to an existing string.
143889 */
143890 static void fts3Appendf(
143891  int *pRc, /* IN/OUT: Error code */
143892  char **pz, /* IN/OUT: Pointer to string buffer */
143893  const char *zFormat, /* Printf format string to append */
143894  ... /* Arguments for printf format string */
143895 ){
143896  if( *pRc==SQLITE_OK ){
143897  va_list ap;
143898  char *z;
143899  va_start(ap, zFormat);
143900  z = sqlite3_vmprintf(zFormat, ap);
143901  va_end(ap);
143902  if( z && *pz ){
143903  char *z2 = sqlite3_mprintf("%s%s", *pz, z);
143904  sqlite3_free(z);
143905  z = z2;
143906  }
143907  if( z==0 ) *pRc = SQLITE_NOMEM;
143908  sqlite3_free(*pz);
143909  *pz = z;
143910  }
143911 }
143912 
143913 /*
143914 ** Return a copy of input string zInput enclosed in double-quotes (") and
143915 ** with all double quote characters escaped. For example:
143916 **
143917 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
143918 **
143919 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
143920 ** is the callers responsibility to call sqlite3_free() to release this
143921 ** memory.
143922 */
143923 static char *fts3QuoteId(char const *zInput){
143924  int nRet;
143925  char *zRet;
143926  nRet = 2 + (int)strlen(zInput)*2 + 1;
143927  zRet = sqlite3_malloc(nRet);
143928  if( zRet ){
143929  int i;
143930  char *z = zRet;
143931  *(z++) = '"';
143932  for(i=0; zInput[i]; i++){
143933  if( zInput[i]=='"' ) *(z++) = '"';
143934  *(z++) = zInput[i];
143935  }
143936  *(z++) = '"';
143937  *(z++) = '\0';
143938  }
143939  return zRet;
143940 }
143941 
143942 /*
143943 ** Return a list of comma separated SQL expressions and a FROM clause that
143944 ** could be used in a SELECT statement such as the following:
143945 **
143946 ** SELECT <list of expressions> FROM %_content AS x ...
143947 **
143948 ** to return the docid, followed by each column of text data in order
143949 ** from left to write. If parameter zFunc is not NULL, then instead of
143950 ** being returned directly each column of text data is passed to an SQL
143951 ** function named zFunc first. For example, if zFunc is "unzip" and the
143952 ** table has the three user-defined columns "a", "b", and "c", the following
143953 ** string is returned:
143954 **
143955 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
143956 **
143957 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
143958 ** is the responsibility of the caller to eventually free it.
143959 **
143960 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
143961 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
143962 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
143963 ** no error occurs, *pRc is left unmodified.
143964 */
143965 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
143966  char *zRet = 0;
143967  char *zFree = 0;
143968  char *zFunction;
143969  int i;
143970 
143971  if( p->zContentTbl==0 ){
143972  if( !zFunc ){
143973  zFunction = "";
143974  }else{
143975  zFree = zFunction = fts3QuoteId(zFunc);
143976  }
143977  fts3Appendf(pRc, &zRet, "docid");
143978  for(i=0; i<p->nColumn; i++){
143979  fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
143980  }
143981  if( p->zLanguageid ){
143982  fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
143983  }
143984  sqlite3_free(zFree);
143985  }else{
143986  fts3Appendf(pRc, &zRet, "rowid");
143987  for(i=0; i<p->nColumn; i++){
143988  fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
143989  }
143990  if( p->zLanguageid ){
143991  fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
143992  }
143993  }
143994  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
143995  p->zDb,
143996  (p->zContentTbl ? p->zContentTbl : p->zName),
143997  (p->zContentTbl ? "" : "_content")
143998  );
143999  return zRet;
144000 }
144001 
144002 /*
144003 ** Return a list of N comma separated question marks, where N is the number
144004 ** of columns in the %_content table (one for the docid plus one for each
144005 ** user-defined text column).
144006 **
144007 ** If argument zFunc is not NULL, then all but the first question mark
144008 ** is preceded by zFunc and an open bracket, and followed by a closed
144009 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
144010 ** user-defined text columns, the following string is returned:
144011 **
144012 ** "?, zip(?), zip(?), zip(?)"
144013 **
144014 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
144015 ** is the responsibility of the caller to eventually free it.
144016 **
144017 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
144018 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
144019 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
144020 ** no error occurs, *pRc is left unmodified.
144021 */
144022 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
144023  char *zRet = 0;
144024  char *zFree = 0;
144025  char *zFunction;
144026  int i;
144027 
144028  if( !zFunc ){
144029  zFunction = "";
144030  }else{
144031  zFree = zFunction = fts3QuoteId(zFunc);
144032  }
144033  fts3Appendf(pRc, &zRet, "?");
144034  for(i=0; i<p->nColumn; i++){
144035  fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
144036  }
144037  if( p->zLanguageid ){
144038  fts3Appendf(pRc, &zRet, ", ?");
144039  }
144040  sqlite3_free(zFree);
144041  return zRet;
144042 }
144043 
144044 /*
144045 ** This function interprets the string at (*pp) as a non-negative integer
144046 ** value. It reads the integer and sets *pnOut to the value read, then
144047 ** sets *pp to point to the byte immediately following the last byte of
144048 ** the integer value.
144049 **
144050 ** Only decimal digits ('0'..'9') may be part of an integer value.
144051 **
144052 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
144053 ** the output value undefined. Otherwise SQLITE_OK is returned.
144054 **
144055 ** This function is used when parsing the "prefix=" FTS4 parameter.
144056 */
144057 static int fts3GobbleInt(const char **pp, int *pnOut){
144058  const int MAX_NPREFIX = 10000000;
144059  const char *p; /* Iterator pointer */
144060  int nInt = 0; /* Output value */
144061 
144062  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
144063  nInt = nInt * 10 + (p[0] - '0');
144064  if( nInt>MAX_NPREFIX ){
144065  nInt = 0;
144066  break;
144067  }
144068  }
144069  if( p==*pp ) return SQLITE_ERROR;
144070  *pnOut = nInt;
144071  *pp = p;
144072  return SQLITE_OK;
144073 }
144074 
144075 /*
144076 ** This function is called to allocate an array of Fts3Index structures
144077 ** representing the indexes maintained by the current FTS table. FTS tables
144078 ** always maintain the main "terms" index, but may also maintain one or
144079 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
144080 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
144081 **
144082 ** Argument zParam is passed the value of the "prefix=" option if one was
144083 ** specified, or NULL otherwise.
144084 **
144085 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
144086 ** the allocated array. *pnIndex is set to the number of elements in the
144087 ** array. If an error does occur, an SQLite error code is returned.
144088 **
144089 ** Regardless of whether or not an error is returned, it is the responsibility
144090 ** of the caller to call sqlite3_free() on the output array to free it.
144091 */
144092 static int fts3PrefixParameter(
144093  const char *zParam, /* ABC in prefix=ABC parameter to parse */
144094  int *pnIndex, /* OUT: size of *apIndex[] array */
144095  struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
144096 ){
144097  struct Fts3Index *aIndex; /* Allocated array */
144098  int nIndex = 1; /* Number of entries in array */
144099 
144100  if( zParam && zParam[0] ){
144101  const char *p;
144102  nIndex++;
144103  for(p=zParam; *p; p++){
144104  if( *p==',' ) nIndex++;
144105  }
144106  }
144107 
144108  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
144109  *apIndex = aIndex;
144110  if( !aIndex ){
144111  return SQLITE_NOMEM;
144112  }
144113 
144114  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
144115  if( zParam ){
144116  const char *p = zParam;
144117  int i;
144118  for(i=1; i<nIndex; i++){
144119  int nPrefix = 0;
144120  if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
144121  assert( nPrefix>=0 );
144122  if( nPrefix==0 ){
144123  nIndex--;
144124  i--;
144125  }else{
144126  aIndex[i].nPrefix = nPrefix;
144127  }
144128  p++;
144129  }
144130  }
144131 
144132  *pnIndex = nIndex;
144133  return SQLITE_OK;
144134 }
144135 
144136 /*
144137 ** This function is called when initializing an FTS4 table that uses the
144138 ** content=xxx option. It determines the number of and names of the columns
144139 ** of the new FTS4 table.
144140 **
144141 ** The third argument passed to this function is the value passed to the
144142 ** config=xxx option (i.e. "xxx"). This function queries the database for
144143 ** a table of that name. If found, the output variables are populated
144144 ** as follows:
144145 **
144146 ** *pnCol: Set to the number of columns table xxx has,
144147 **
144148 ** *pnStr: Set to the total amount of space required to store a copy
144149 ** of each columns name, including the nul-terminator.
144150 **
144151 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
144152 ** the name of the corresponding column in table xxx. The array
144153 ** and its contents are allocated using a single allocation. It
144154 ** is the responsibility of the caller to free this allocation
144155 ** by eventually passing the *pazCol value to sqlite3_free().
144156 **
144157 ** If the table cannot be found, an error code is returned and the output
144158 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
144159 ** returned (and the output variables are undefined).
144160 */
144161 static int fts3ContentColumns(
144162  sqlite3 *db, /* Database handle */
144163  const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
144164  const char *zTbl, /* Name of content table */
144165  const char ***pazCol, /* OUT: Malloc'd array of column names */
144166  int *pnCol, /* OUT: Size of array *pazCol */
144167  int *pnStr, /* OUT: Bytes of string content */
144168  char **pzErr /* OUT: error message */
144169 ){
144170  int rc = SQLITE_OK; /* Return code */
144171  char *zSql; /* "SELECT *" statement on zTbl */
144172  sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
144173 
144174  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
144175  if( !zSql ){
144176  rc = SQLITE_NOMEM;
144177  }else{
144178  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
144179  if( rc!=SQLITE_OK ){
144180  sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
144181  }
144182  }
144183  sqlite3_free(zSql);
144184 
144185  if( rc==SQLITE_OK ){
144186  const char **azCol; /* Output array */
144187  int nStr = 0; /* Size of all column names (incl. 0x00) */
144188  int nCol; /* Number of table columns */
144189  int i; /* Used to iterate through columns */
144190 
144191  /* Loop through the returned columns. Set nStr to the number of bytes of
144192  ** space required to store a copy of each column name, including the
144193  ** nul-terminator byte. */
144194  nCol = sqlite3_column_count(pStmt);
144195  for(i=0; i<nCol; i++){
144196  const char *zCol = sqlite3_column_name(pStmt, i);
144197  nStr += (int)strlen(zCol) + 1;
144198  }
144199 
144200  /* Allocate and populate the array to return. */
144201  azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
144202  if( azCol==0 ){
144203  rc = SQLITE_NOMEM;
144204  }else{
144205  char *p = (char *)&azCol[nCol];
144206  for(i=0; i<nCol; i++){
144207  const char *zCol = sqlite3_column_name(pStmt, i);
144208  int n = (int)strlen(zCol)+1;
144209  memcpy(p, zCol, n);
144210  azCol[i] = p;
144211  p += n;
144212  }
144213  }
144214  sqlite3_finalize(pStmt);
144215 
144216  /* Set the output variables. */
144217  *pnCol = nCol;
144218  *pnStr = nStr;
144219  *pazCol = azCol;
144220  }
144221 
144222  return rc;
144223 }
144224 
144225 /*
144226 ** This function is the implementation of both the xConnect and xCreate
144227 ** methods of the FTS3 virtual table.
144228 **
144229 ** The argv[] array contains the following:
144230 **
144231 ** argv[0] -> module name ("fts3" or "fts4")
144232 ** argv[1] -> database name
144233 ** argv[2] -> table name
144234 ** argv[...] -> "column name" and other module argument fields.
144235 */
144236 static int fts3InitVtab(
144237  int isCreate, /* True for xCreate, false for xConnect */
144238  sqlite3 *db, /* The SQLite database connection */
144239  void *pAux, /* Hash table containing tokenizers */
144240  int argc, /* Number of elements in argv array */
144241  const char * const *argv, /* xCreate/xConnect argument array */
144242  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
144243  char **pzErr /* Write any error message here */
144244 ){
144245  Fts3Hash *pHash = (Fts3Hash *)pAux;
144246  Fts3Table *p = 0; /* Pointer to allocated vtab */
144247  int rc = SQLITE_OK; /* Return code */
144248  int i; /* Iterator variable */
144249  int nByte; /* Size of allocation used for *p */
144250  int iCol; /* Column index */
144251  int nString = 0; /* Bytes required to hold all column names */
144252  int nCol = 0; /* Number of columns in the FTS table */
144253  char *zCsr; /* Space for holding column names */
144254  int nDb; /* Bytes required to hold database name */
144255  int nName; /* Bytes required to hold table name */
144256  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
144257  const char **aCol; /* Array of column names */
144258  sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
144259 
144260  int nIndex = 0; /* Size of aIndex[] array */
144261  struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
144262 
144263  /* The results of parsing supported FTS4 key=value options: */
144264  int bNoDocsize = 0; /* True to omit %_docsize table */
144265  int bDescIdx = 0; /* True to store descending indexes */
144266  char *zPrefix = 0; /* Prefix parameter value (or NULL) */
144267  char *zCompress = 0; /* compress=? parameter (or NULL) */
144268  char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
144269  char *zContent = 0; /* content=? parameter (or NULL) */
144270  char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
144271  char **azNotindexed = 0; /* The set of notindexed= columns */
144272  int nNotindexed = 0; /* Size of azNotindexed[] array */
144273 
144274  assert( strlen(argv[0])==4 );
144275  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
144276  || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
144277  );
144278 
144279  nDb = (int)strlen(argv[1]) + 1;
144280  nName = (int)strlen(argv[2]) + 1;
144281 
144282  nByte = sizeof(const char *) * (argc-2);
144283  aCol = (const char **)sqlite3_malloc(nByte);
144284  if( aCol ){
144285  memset((void*)aCol, 0, nByte);
144286  azNotindexed = (char **)sqlite3_malloc(nByte);
144287  }
144288  if( azNotindexed ){
144289  memset(azNotindexed, 0, nByte);
144290  }
144291  if( !aCol || !azNotindexed ){
144292  rc = SQLITE_NOMEM;
144293  goto fts3_init_out;
144294  }
144295 
144296  /* Loop through all of the arguments passed by the user to the FTS3/4
144297  ** module (i.e. all the column names and special arguments). This loop
144298  ** does the following:
144299  **
144300  ** + Figures out the number of columns the FTSX table will have, and
144301  ** the number of bytes of space that must be allocated to store copies
144302  ** of the column names.
144303  **
144304  ** + If there is a tokenizer specification included in the arguments,
144305  ** initializes the tokenizer pTokenizer.
144306  */
144307  for(i=3; rc==SQLITE_OK && i<argc; i++){
144308  char const *z = argv[i];
144309  int nKey;
144310  char *zVal;
144311 
144312  /* Check if this is a tokenizer specification */
144313  if( !pTokenizer
144314  && strlen(z)>8
144315  && 0==sqlite3_strnicmp(z, "tokenize", 8)
144316  && 0==sqlite3Fts3IsIdChar(z[8])
144317  ){
144318  rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
144319  }
144320 
144321  /* Check if it is an FTS4 special argument. */
144322  else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
144323  struct Fts4Option {
144324  const char *zOpt;
144325  int nOpt;
144326  } aFts4Opt[] = {
144327  { "matchinfo", 9 }, /* 0 -> MATCHINFO */
144328  { "prefix", 6 }, /* 1 -> PREFIX */
144329  { "compress", 8 }, /* 2 -> COMPRESS */
144330  { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
144331  { "order", 5 }, /* 4 -> ORDER */
144332  { "content", 7 }, /* 5 -> CONTENT */
144333  { "languageid", 10 }, /* 6 -> LANGUAGEID */
144334  { "notindexed", 10 } /* 7 -> NOTINDEXED */
144335  };
144336 
144337  int iOpt;
144338  if( !zVal ){
144339  rc = SQLITE_NOMEM;
144340  }else{
144341  for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
144342  struct Fts4Option *pOp = &aFts4Opt[iOpt];
144343  if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
144344  break;
144345  }
144346  }
144347  if( iOpt==SizeofArray(aFts4Opt) ){
144348  sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
144349  rc = SQLITE_ERROR;
144350  }else{
144351  switch( iOpt ){
144352  case 0: /* MATCHINFO */
144353  if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
144354  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
144355  rc = SQLITE_ERROR;
144356  }
144357  bNoDocsize = 1;
144358  break;
144359 
144360  case 1: /* PREFIX */
144361  sqlite3_free(zPrefix);
144362  zPrefix = zVal;
144363  zVal = 0;
144364  break;
144365 
144366  case 2: /* COMPRESS */
144367  sqlite3_free(zCompress);
144368  zCompress = zVal;
144369  zVal = 0;
144370  break;
144371 
144372  case 3: /* UNCOMPRESS */
144373  sqlite3_free(zUncompress);
144374  zUncompress = zVal;
144375  zVal = 0;
144376  break;
144377 
144378  case 4: /* ORDER */
144379  if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
144380  && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
144381  ){
144382  sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
144383  rc = SQLITE_ERROR;
144384  }
144385  bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
144386  break;
144387 
144388  case 5: /* CONTENT */
144389  sqlite3_free(zContent);
144390  zContent = zVal;
144391  zVal = 0;
144392  break;
144393 
144394  case 6: /* LANGUAGEID */
144395  assert( iOpt==6 );
144396  sqlite3_free(zLanguageid);
144397  zLanguageid = zVal;
144398  zVal = 0;
144399  break;
144400 
144401  case 7: /* NOTINDEXED */
144402  azNotindexed[nNotindexed++] = zVal;
144403  zVal = 0;
144404  break;
144405  }
144406  }
144407  sqlite3_free(zVal);
144408  }
144409  }
144410 
144411  /* Otherwise, the argument is a column name. */
144412  else {
144413  nString += (int)(strlen(z) + 1);
144414  aCol[nCol++] = z;
144415  }
144416  }
144417 
144418  /* If a content=xxx option was specified, the following:
144419  **
144420  ** 1. Ignore any compress= and uncompress= options.
144421  **
144422  ** 2. If no column names were specified as part of the CREATE VIRTUAL
144423  ** TABLE statement, use all columns from the content table.
144424  */
144425  if( rc==SQLITE_OK && zContent ){
144426  sqlite3_free(zCompress);
144427  sqlite3_free(zUncompress);
144428  zCompress = 0;
144429  zUncompress = 0;
144430  if( nCol==0 ){
144431  sqlite3_free((void*)aCol);
144432  aCol = 0;
144433  rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
144434 
144435  /* If a languageid= option was specified, remove the language id
144436  ** column from the aCol[] array. */
144437  if( rc==SQLITE_OK && zLanguageid ){
144438  int j;
144439  for(j=0; j<nCol; j++){
144440  if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
144441  int k;
144442  for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
144443  nCol--;
144444  break;
144445  }
144446  }
144447  }
144448  }
144449  }
144450  if( rc!=SQLITE_OK ) goto fts3_init_out;
144451 
144452  if( nCol==0 ){
144453  assert( nString==0 );
144454  aCol[0] = "content";
144455  nString = 8;
144456  nCol = 1;
144457  }
144458 
144459  if( pTokenizer==0 ){
144460  rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
144461  if( rc!=SQLITE_OK ) goto fts3_init_out;
144462  }
144463  assert( pTokenizer );
144464 
144465  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
144466  if( rc==SQLITE_ERROR ){
144467  assert( zPrefix );
144468  sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
144469  }
144470  if( rc!=SQLITE_OK ) goto fts3_init_out;
144471 
144472  /* Allocate and populate the Fts3Table structure. */
144473  nByte = sizeof(Fts3Table) + /* Fts3Table */
144474  nCol * sizeof(char *) + /* azColumn */
144475  nIndex * sizeof(struct Fts3Index) + /* aIndex */
144476  nCol * sizeof(u8) + /* abNotindexed */
144477  nName + /* zName */
144478  nDb + /* zDb */
144479  nString; /* Space for azColumn strings */
144480  p = (Fts3Table*)sqlite3_malloc(nByte);
144481  if( p==0 ){
144482  rc = SQLITE_NOMEM;
144483  goto fts3_init_out;
144484  }
144485  memset(p, 0, nByte);
144486  p->db = db;
144487  p->nColumn = nCol;
144488  p->nPendingData = 0;
144489  p->azColumn = (char **)&p[1];
144490  p->pTokenizer = pTokenizer;
144491  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
144492  p->bHasDocsize = (isFts4 && bNoDocsize==0);
144493  p->bHasStat = isFts4;
144494  p->bFts4 = isFts4;
144495  p->bDescIdx = bDescIdx;
144496  p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
144497  p->zContentTbl = zContent;
144498  p->zLanguageid = zLanguageid;
144499  zContent = 0;
144500  zLanguageid = 0;
144501  TESTONLY( p->inTransaction = -1 );
144502  TESTONLY( p->mxSavepoint = -1 );
144503 
144504  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
144505  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
144506  p->nIndex = nIndex;
144507  for(i=0; i<nIndex; i++){
144508  fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
144509  }
144510  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
144511 
144512  /* Fill in the zName and zDb fields of the vtab structure. */
144513  zCsr = (char *)&p->abNotindexed[nCol];
144514  p->zName = zCsr;
144515  memcpy(zCsr, argv[2], nName);
144516  zCsr += nName;
144517  p->zDb = zCsr;
144518  memcpy(zCsr, argv[1], nDb);
144519  zCsr += nDb;
144520 
144521  /* Fill in the azColumn array */
144522  for(iCol=0; iCol<nCol; iCol++){
144523  char *z;
144524  int n = 0;
144525  z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
144526  memcpy(zCsr, z, n);
144527  zCsr[n] = '\0';
144528  sqlite3Fts3Dequote(zCsr);
144529  p->azColumn[iCol] = zCsr;
144530  zCsr += n+1;
144531  assert( zCsr <= &((char *)p)[nByte] );
144532  }
144533 
144534  /* Fill in the abNotindexed array */
144535  for(iCol=0; iCol<nCol; iCol++){
144536  int n = (int)strlen(p->azColumn[iCol]);
144537  for(i=0; i<nNotindexed; i++){
144538  char *zNot = azNotindexed[i];
144539  if( zNot && n==(int)strlen(zNot)
144540  && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
144541  ){
144542  p->abNotindexed[iCol] = 1;
144543  sqlite3_free(zNot);
144544  azNotindexed[i] = 0;
144545  }
144546  }
144547  }
144548  for(i=0; i<nNotindexed; i++){
144549  if( azNotindexed[i] ){
144550  sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
144551  rc = SQLITE_ERROR;
144552  }
144553  }
144554 
144555  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
144556  char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
144557  rc = SQLITE_ERROR;
144558  sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
144559  }
144560  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
144561  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
144562  if( rc!=SQLITE_OK ) goto fts3_init_out;
144563 
144564  /* If this is an xCreate call, create the underlying tables in the
144565  ** database. TODO: For xConnect(), it could verify that said tables exist.
144566  */
144567  if( isCreate ){
144568  rc = fts3CreateTables(p);
144569  }
144570 
144571  /* Check to see if a legacy fts3 table has been "upgraded" by the
144572  ** addition of a %_stat table so that it can use incremental merge.
144573  */
144574  if( !isFts4 && !isCreate ){
144575  p->bHasStat = 2;
144576  }
144577 
144578  /* Figure out the page-size for the database. This is required in order to
144579  ** estimate the cost of loading large doclists from the database. */
144580  fts3DatabasePageSize(&rc, p);
144581  p->nNodeSize = p->nPgsz-35;
144582 
144583  /* Declare the table schema to SQLite. */
144584  fts3DeclareVtab(&rc, p);
144585 
144586 fts3_init_out:
144587  sqlite3_free(zPrefix);
144588  sqlite3_free(aIndex);
144589  sqlite3_free(zCompress);
144590  sqlite3_free(zUncompress);
144591  sqlite3_free(zContent);
144592  sqlite3_free(zLanguageid);
144593  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
144594  sqlite3_free((void *)aCol);
144595  sqlite3_free((void *)azNotindexed);
144596  if( rc!=SQLITE_OK ){
144597  if( p ){
144598  fts3DisconnectMethod((sqlite3_vtab *)p);
144599  }else if( pTokenizer ){
144600  pTokenizer->pModule->xDestroy(pTokenizer);
144601  }
144602  }else{
144603  assert( p->pSegments==0 );
144604  *ppVTab = &p->base;
144605  }
144606  return rc;
144607 }
144608 
144609 /*
144610 ** The xConnect() and xCreate() methods for the virtual table. All the
144611 ** work is done in function fts3InitVtab().
144612 */
144613 static int fts3ConnectMethod(
144614  sqlite3 *db, /* Database connection */
144615  void *pAux, /* Pointer to tokenizer hash table */
144616  int argc, /* Number of elements in argv array */
144617  const char * const *argv, /* xCreate/xConnect argument array */
144618  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
144619  char **pzErr /* OUT: sqlite3_malloc'd error message */
144620 ){
144621  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
144622 }
144623 static int fts3CreateMethod(
144624  sqlite3 *db, /* Database connection */
144625  void *pAux, /* Pointer to tokenizer hash table */
144626  int argc, /* Number of elements in argv array */
144627  const char * const *argv, /* xCreate/xConnect argument array */
144628  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
144629  char **pzErr /* OUT: sqlite3_malloc'd error message */
144630 ){
144631  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
144632 }
144633 
144634 /*
144635 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
144636 ** extension is currently being used by a version of SQLite too old to
144637 ** support estimatedRows. In that case this function is a no-op.
144638 */
144639 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
144640 #if SQLITE_VERSION_NUMBER>=3008002
144641  if( sqlite3_libversion_number()>=3008002 ){
144642  pIdxInfo->estimatedRows = nRow;
144643  }
144644 #endif
144645 }
144646 
144647 /*
144648 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
144649 ** extension is currently being used by a version of SQLite too old to
144650 ** support index-info flags. In that case this function is a no-op.
144651 */
144652 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
144653 #if SQLITE_VERSION_NUMBER>=3008012
144654  if( sqlite3_libversion_number()>=3008012 ){
144655  pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
144656  }
144657 #endif
144658 }
144659 
144660 /*
144661 ** Implementation of the xBestIndex method for FTS3 tables. There
144662 ** are three possible strategies, in order of preference:
144663 **
144664 ** 1. Direct lookup by rowid or docid.
144665 ** 2. Full-text search using a MATCH operator on a non-docid column.
144666 ** 3. Linear scan of %_content table.
144667 */
144668 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
144669  Fts3Table *p = (Fts3Table *)pVTab;
144670  int i; /* Iterator variable */
144671  int iCons = -1; /* Index of constraint to use */
144672 
144673  int iLangidCons = -1; /* Index of langid=x constraint, if present */
144674  int iDocidGe = -1; /* Index of docid>=x constraint, if present */
144675  int iDocidLe = -1; /* Index of docid<=x constraint, if present */
144676  int iIdx;
144677 
144678  /* By default use a full table scan. This is an expensive option,
144679  ** so search through the constraints to see if a more efficient
144680  ** strategy is possible.
144681  */
144682  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
144683  pInfo->estimatedCost = 5000000;
144684  for(i=0; i<pInfo->nConstraint; i++){
144685  int bDocid; /* True if this constraint is on docid */
144686  struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
144687  if( pCons->usable==0 ){
144688  if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
144689  /* There exists an unusable MATCH constraint. This means that if
144690  ** the planner does elect to use the results of this call as part
144691  ** of the overall query plan the user will see an "unable to use
144692  ** function MATCH in the requested context" error. To discourage
144693  ** this, return a very high cost here. */
144694  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
144695  pInfo->estimatedCost = 1e50;
144696  fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
144697  return SQLITE_OK;
144698  }
144699  continue;
144700  }
144701 
144702  bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
144703 
144704  /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
144705  if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
144706  pInfo->idxNum = FTS3_DOCID_SEARCH;
144707  pInfo->estimatedCost = 1.0;
144708  iCons = i;
144709  }
144710 
144711  /* A MATCH constraint. Use a full-text search.
144712  **
144713  ** If there is more than one MATCH constraint available, use the first
144714  ** one encountered. If there is both a MATCH constraint and a direct
144715  ** rowid/docid lookup, prefer the MATCH strategy. This is done even
144716  ** though the rowid/docid lookup is faster than a MATCH query, selecting
144717  ** it would lead to an "unable to use function MATCH in the requested
144718  ** context" error.
144719  */
144720  if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
144721  && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
144722  ){
144723  pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
144724  pInfo->estimatedCost = 2.0;
144725  iCons = i;
144726  }
144727 
144728  /* Equality constraint on the langid column */
144729  if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
144730  && pCons->iColumn==p->nColumn + 2
144731  ){
144732  iLangidCons = i;
144733  }
144734 
144735  if( bDocid ){
144736  switch( pCons->op ){
144739  iDocidGe = i;
144740  break;
144741 
144744  iDocidLe = i;
144745  break;
144746  }
144747  }
144748  }
144749 
144750  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
144751  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
144752 
144753  iIdx = 1;
144754  if( iCons>=0 ){
144755  pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
144756  pInfo->aConstraintUsage[iCons].omit = 1;
144757  }
144758  if( iLangidCons>=0 ){
144759  pInfo->idxNum |= FTS3_HAVE_LANGID;
144760  pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
144761  }
144762  if( iDocidGe>=0 ){
144763  pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
144764  pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
144765  }
144766  if( iDocidLe>=0 ){
144767  pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
144768  pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
144769  }
144770 
144771  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
144772  ** docid) order. Both ascending and descending are possible.
144773  */
144774  if( pInfo->nOrderBy==1 ){
144775  struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
144776  if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
144777  if( pOrder->desc ){
144778  pInfo->idxStr = "DESC";
144779  }else{
144780  pInfo->idxStr = "ASC";
144781  }
144782  pInfo->orderByConsumed = 1;
144783  }
144784  }
144785 
144786  assert( p->pSegments==0 );
144787  return SQLITE_OK;
144788 }
144789 
144790 /*
144791 ** Implementation of xOpen method.
144792 */
144793 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
144794  sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
144795 
144796  UNUSED_PARAMETER(pVTab);
144797 
144798  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
144799  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
144800  ** if the allocation fails, return SQLITE_NOMEM.
144801  */
144802  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
144803  if( !pCsr ){
144804  return SQLITE_NOMEM;
144805  }
144806  memset(pCsr, 0, sizeof(Fts3Cursor));
144807  return SQLITE_OK;
144808 }
144809 
144810 /*
144811 ** Close the cursor. For additional information see the documentation
144812 ** on the xClose method of the virtual table interface.
144813 */
144814 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
144815  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144816  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144817  sqlite3_finalize(pCsr->pStmt);
144818  sqlite3Fts3ExprFree(pCsr->pExpr);
144819  sqlite3Fts3FreeDeferredTokens(pCsr);
144820  sqlite3_free(pCsr->aDoclist);
144821  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
144822  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144823  sqlite3_free(pCsr);
144824  return SQLITE_OK;
144825 }
144826 
144827 /*
144828 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
144829 ** compose and prepare an SQL statement of the form:
144830 **
144831 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
144832 **
144833 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
144834 ** it. If an error occurs, return an SQLite error code.
144835 **
144836 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
144837 */
144838 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
144839  int rc = SQLITE_OK;
144840  if( pCsr->pStmt==0 ){
144841  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
144842  char *zSql;
144843  zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
144844  if( !zSql ) return SQLITE_NOMEM;
144845  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
144846  sqlite3_free(zSql);
144847  }
144848  *ppStmt = pCsr->pStmt;
144849  return rc;
144850 }
144851 
144852 /*
144853 ** Position the pCsr->pStmt statement so that it is on the row
144854 ** of the %_content table that contains the last match. Return
144855 ** SQLITE_OK on success.
144856 */
144857 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
144858  int rc = SQLITE_OK;
144859  if( pCsr->isRequireSeek ){
144860  sqlite3_stmt *pStmt = 0;
144861 
144862  rc = fts3CursorSeekStmt(pCsr, &pStmt);
144863  if( rc==SQLITE_OK ){
144864  sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
144865  pCsr->isRequireSeek = 0;
144866  if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
144867  return SQLITE_OK;
144868  }else{
144869  rc = sqlite3_reset(pCsr->pStmt);
144870  if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
144871  /* If no row was found and no error has occurred, then the %_content
144872  ** table is missing a row that is present in the full-text index.
144873  ** The data structures are corrupt. */
144874  rc = FTS_CORRUPT_VTAB;
144875  pCsr->isEof = 1;
144876  }
144877  }
144878  }
144879  }
144880 
144881  if( rc!=SQLITE_OK && pContext ){
144882  sqlite3_result_error_code(pContext, rc);
144883  }
144884  return rc;
144885 }
144886 
144887 /*
144888 ** This function is used to process a single interior node when searching
144889 ** a b-tree for a term or term prefix. The node data is passed to this
144890 ** function via the zNode/nNode parameters. The term to search for is
144891 ** passed in zTerm/nTerm.
144892 **
144893 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
144894 ** of the child node that heads the sub-tree that may contain the term.
144895 **
144896 ** If piLast is not NULL, then *piLast is set to the right-most child node
144897 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
144898 ** a prefix.
144899 **
144900 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
144901 */
144902 static int fts3ScanInteriorNode(
144903  const char *zTerm, /* Term to select leaves for */
144904  int nTerm, /* Size of term zTerm in bytes */
144905  const char *zNode, /* Buffer containing segment interior node */
144906  int nNode, /* Size of buffer at zNode */
144907  sqlite3_int64 *piFirst, /* OUT: Selected child node */
144908  sqlite3_int64 *piLast /* OUT: Selected child node */
144909 ){
144910  int rc = SQLITE_OK; /* Return code */
144911  const char *zCsr = zNode; /* Cursor to iterate through node */
144912  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
144913  char *zBuffer = 0; /* Buffer to load terms into */
144914  int nAlloc = 0; /* Size of allocated buffer */
144915  int isFirstTerm = 1; /* True when processing first term on page */
144916  sqlite3_int64 iChild; /* Block id of child node to descend to */
144917 
144918  /* Skip over the 'height' varint that occurs at the start of every
144919  ** interior node. Then load the blockid of the left-child of the b-tree
144920  ** node into variable iChild.
144921  **
144922  ** Even if the data structure on disk is corrupted, this (reading two
144923  ** varints from the buffer) does not risk an overread. If zNode is a
144924  ** root node, then the buffer comes from a SELECT statement. SQLite does
144925  ** not make this guarantee explicitly, but in practice there are always
144926  ** either more than 20 bytes of allocated space following the nNode bytes of
144927  ** contents, or two zero bytes. Or, if the node is read from the %_segments
144928  ** table, then there are always 20 bytes of zeroed padding following the
144929  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
144930  */
144931  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
144932  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
144933  if( zCsr>zEnd ){
144934  return FTS_CORRUPT_VTAB;
144935  }
144936 
144937  while( zCsr<zEnd && (piFirst || piLast) ){
144938  int cmp; /* memcmp() result */
144939  int nSuffix; /* Size of term suffix */
144940  int nPrefix = 0; /* Size of term prefix */
144941  int nBuffer; /* Total term size */
144942 
144943  /* Load the next term on the node into zBuffer. Use realloc() to expand
144944  ** the size of zBuffer if required. */
144945  if( !isFirstTerm ){
144946  zCsr += fts3GetVarint32(zCsr, &nPrefix);
144947  }
144948  isFirstTerm = 0;
144949  zCsr += fts3GetVarint32(zCsr, &nSuffix);
144950 
144951  if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
144952  rc = FTS_CORRUPT_VTAB;
144953  goto finish_scan;
144954  }
144955  if( nPrefix+nSuffix>nAlloc ){
144956  char *zNew;
144957  nAlloc = (nPrefix+nSuffix) * 2;
144958  zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
144959  if( !zNew ){
144960  rc = SQLITE_NOMEM;
144961  goto finish_scan;
144962  }
144963  zBuffer = zNew;
144964  }
144965  assert( zBuffer );
144966  memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
144967  nBuffer = nPrefix + nSuffix;
144968  zCsr += nSuffix;
144969 
144970  /* Compare the term we are searching for with the term just loaded from
144971  ** the interior node. If the specified term is greater than or equal
144972  ** to the term from the interior node, then all terms on the sub-tree
144973  ** headed by node iChild are smaller than zTerm. No need to search
144974  ** iChild.
144975  **
144976  ** If the interior node term is larger than the specified term, then
144977  ** the tree headed by iChild may contain the specified term.
144978  */
144979  cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
144980  if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
144981  *piFirst = iChild;
144982  piFirst = 0;
144983  }
144984 
144985  if( piLast && cmp<0 ){
144986  *piLast = iChild;
144987  piLast = 0;
144988  }
144989 
144990  iChild++;
144991  };
144992 
144993  if( piFirst ) *piFirst = iChild;
144994  if( piLast ) *piLast = iChild;
144995 
144996  finish_scan:
144997  sqlite3_free(zBuffer);
144998  return rc;
144999 }
145000 
145001 
145002 /*
145003 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
145004 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
145005 ** contains a term. This function searches the sub-tree headed by the zNode
145006 ** node for the range of leaf nodes that may contain the specified term
145007 ** or terms for which the specified term is a prefix.
145008 **
145009 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
145010 ** left-most leaf node in the tree that may contain the specified term.
145011 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
145012 ** right-most leaf node that may contain a term for which the specified
145013 ** term is a prefix.
145014 **
145015 ** It is possible that the range of returned leaf nodes does not contain
145016 ** the specified term or any terms for which it is a prefix. However, if the
145017 ** segment does contain any such terms, they are stored within the identified
145018 ** range. Because this function only inspects interior segment nodes (and
145019 ** never loads leaf nodes into memory), it is not possible to be sure.
145020 **
145021 ** If an error occurs, an error code other than SQLITE_OK is returned.
145022 */
145023 static int fts3SelectLeaf(
145024  Fts3Table *p, /* Virtual table handle */
145025  const char *zTerm, /* Term to select leaves for */
145026  int nTerm, /* Size of term zTerm in bytes */
145027  const char *zNode, /* Buffer containing segment interior node */
145028  int nNode, /* Size of buffer at zNode */
145029  sqlite3_int64 *piLeaf, /* Selected leaf node */
145030  sqlite3_int64 *piLeaf2 /* Selected leaf node */
145031 ){
145032  int rc = SQLITE_OK; /* Return code */
145033  int iHeight; /* Height of this node in tree */
145034 
145035  assert( piLeaf || piLeaf2 );
145036 
145037  fts3GetVarint32(zNode, &iHeight);
145038  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
145039  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
145040 
145041  if( rc==SQLITE_OK && iHeight>1 ){
145042  char *zBlob = 0; /* Blob read from %_segments table */
145043  int nBlob = 0; /* Size of zBlob in bytes */
145044 
145045  if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
145046  rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
145047  if( rc==SQLITE_OK ){
145048  rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
145049  }
145050  sqlite3_free(zBlob);
145051  piLeaf = 0;
145052  zBlob = 0;
145053  }
145054 
145055  if( rc==SQLITE_OK ){
145056  rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
145057  }
145058  if( rc==SQLITE_OK ){
145059  rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
145060  }
145061  sqlite3_free(zBlob);
145062  }
145063 
145064  return rc;
145065 }
145066 
145067 /*
145068 ** This function is used to create delta-encoded serialized lists of FTS3
145069 ** varints. Each call to this function appends a single varint to a list.
145070 */
145071 static void fts3PutDeltaVarint(
145072  char **pp, /* IN/OUT: Output pointer */
145073  sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
145074  sqlite3_int64 iVal /* Write this value to the list */
145075 ){
145076  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
145077  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
145078  *piPrev = iVal;
145079 }
145080 
145081 /*
145082 ** When this function is called, *ppPoslist is assumed to point to the
145083 ** start of a position-list. After it returns, *ppPoslist points to the
145084 ** first byte after the position-list.
145085 **
145086 ** A position list is list of positions (delta encoded) and columns for
145087 ** a single document record of a doclist. So, in other words, this
145088 ** routine advances *ppPoslist so that it points to the next docid in
145089 ** the doclist, or to the first byte past the end of the doclist.
145090 **
145091 ** If pp is not NULL, then the contents of the position list are copied
145092 ** to *pp. *pp is set to point to the first byte past the last byte copied
145093 ** before this function returns.
145094 */
145095 static void fts3PoslistCopy(char **pp, char **ppPoslist){
145096  char *pEnd = *ppPoslist;
145097  char c = 0;
145098 
145099  /* The end of a position list is marked by a zero encoded as an FTS3
145100  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
145101  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
145102  ** of some other, multi-byte, value.
145103  **
145104  ** The following while-loop moves pEnd to point to the first byte that is not
145105  ** immediately preceded by a byte with the 0x80 bit set. Then increments
145106  ** pEnd once more so that it points to the byte immediately following the
145107  ** last byte in the position-list.
145108  */
145109  while( *pEnd | c ){
145110  c = *pEnd++ & 0x80;
145111  testcase( c!=0 && (*pEnd)==0 );
145112  }
145113  pEnd++; /* Advance past the POS_END terminator byte */
145114 
145115  if( pp ){
145116  int n = (int)(pEnd - *ppPoslist);
145117  char *p = *pp;
145118  memcpy(p, *ppPoslist, n);
145119  p += n;
145120  *pp = p;
145121  }
145122  *ppPoslist = pEnd;
145123 }
145124 
145125 /*
145126 ** When this function is called, *ppPoslist is assumed to point to the
145127 ** start of a column-list. After it returns, *ppPoslist points to the
145128 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
145129 **
145130 ** A column-list is list of delta-encoded positions for a single column
145131 ** within a single document within a doclist.
145132 **
145133 ** The column-list is terminated either by a POS_COLUMN varint (1) or
145134 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
145135 ** the POS_COLUMN or POS_END that terminates the column-list.
145136 **
145137 ** If pp is not NULL, then the contents of the column-list are copied
145138 ** to *pp. *pp is set to point to the first byte past the last byte copied
145139 ** before this function returns. The POS_COLUMN or POS_END terminator
145140 ** is not copied into *pp.
145141 */
145142 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
145143  char *pEnd = *ppPoslist;
145144  char c = 0;
145145 
145146  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
145147  ** not part of a multi-byte varint.
145148  */
145149  while( 0xFE & (*pEnd | c) ){
145150  c = *pEnd++ & 0x80;
145151  testcase( c!=0 && ((*pEnd)&0xfe)==0 );
145152  }
145153  if( pp ){
145154  int n = (int)(pEnd - *ppPoslist);
145155  char *p = *pp;
145156  memcpy(p, *ppPoslist, n);
145157  p += n;
145158  *pp = p;
145159  }
145160  *ppPoslist = pEnd;
145161 }
145162 
145163 /*
145164 ** Value used to signify the end of an position-list. This is safe because
145165 ** it is not possible to have a document with 2^31 terms.
145166 */
145167 #define POSITION_LIST_END 0x7fffffff
145168 
145169 /*
145170 ** This function is used to help parse position-lists. When this function is
145171 ** called, *pp may point to the start of the next varint in the position-list
145172 ** being parsed, or it may point to 1 byte past the end of the position-list
145173 ** (in which case **pp will be a terminator bytes POS_END (0) or
145174 ** (1)).
145175 **
145176 ** If *pp points past the end of the current position-list, set *pi to
145177 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
145178 ** increment the current value of *pi by the value read, and set *pp to
145179 ** point to the next value before returning.
145180 **
145181 ** Before calling this routine *pi must be initialized to the value of
145182 ** the previous position, or zero if we are reading the first position
145183 ** in the position-list. Because positions are delta-encoded, the value
145184 ** of the previous position is needed in order to compute the value of
145185 ** the next position.
145186 */
145187 static void fts3ReadNextPos(
145188  char **pp, /* IN/OUT: Pointer into position-list buffer */
145189  sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
145190 ){
145191  if( (**pp)&0xFE ){
145192  fts3GetDeltaVarint(pp, pi);
145193  *pi -= 2;
145194  }else{
145195  *pi = POSITION_LIST_END;
145196  }
145197 }
145198 
145199 /*
145200 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
145201 ** the value of iCol encoded as a varint to *pp. This will start a new
145202 ** column list.
145203 **
145204 ** Set *pp to point to the byte just after the last byte written before
145205 ** returning (do not modify it if iCol==0). Return the total number of bytes
145206 ** written (0 if iCol==0).
145207 */
145208 static int fts3PutColNumber(char **pp, int iCol){
145209  int n = 0; /* Number of bytes written */
145210  if( iCol ){
145211  char *p = *pp; /* Output pointer */
145212  n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
145213  *p = 0x01;
145214  *pp = &p[n];
145215  }
145216  return n;
145217 }
145218 
145219 /*
145220 ** Compute the union of two position lists. The output written
145221 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
145222 ** order and with any duplicates removed. All pointers are
145223 ** updated appropriately. The caller is responsible for insuring
145224 ** that there is enough space in *pp to hold the complete output.
145225 */
145226 static void fts3PoslistMerge(
145227  char **pp, /* Output buffer */
145228  char **pp1, /* Left input list */
145229  char **pp2 /* Right input list */
145230 ){
145231  char *p = *pp;
145232  char *p1 = *pp1;
145233  char *p2 = *pp2;
145234 
145235  while( *p1 || *p2 ){
145236  int iCol1; /* The current column index in pp1 */
145237  int iCol2; /* The current column index in pp2 */
145238 
145239  if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
145240  else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
145241  else iCol1 = 0;
145242 
145243  if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
145244  else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
145245  else iCol2 = 0;
145246 
145247  if( iCol1==iCol2 ){
145248  sqlite3_int64 i1 = 0; /* Last position from pp1 */
145249  sqlite3_int64 i2 = 0; /* Last position from pp2 */
145250  sqlite3_int64 iPrev = 0;
145251  int n = fts3PutColNumber(&p, iCol1);
145252  p1 += n;
145253  p2 += n;
145254 
145255  /* At this point, both p1 and p2 point to the start of column-lists
145256  ** for the same column (the column with index iCol1 and iCol2).
145257  ** A column-list is a list of non-negative delta-encoded varints, each
145258  ** incremented by 2 before being stored. Each list is terminated by a
145259  ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
145260  ** and writes the results to buffer p. p is left pointing to the byte
145261  ** after the list written. No terminator (POS_END or POS_COLUMN) is
145262  ** written to the output.
145263  */
145264  fts3GetDeltaVarint(&p1, &i1);
145265  fts3GetDeltaVarint(&p2, &i2);
145266  do {
145267  fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
145268  iPrev -= 2;
145269  if( i1==i2 ){
145270  fts3ReadNextPos(&p1, &i1);
145271  fts3ReadNextPos(&p2, &i2);
145272  }else if( i1<i2 ){
145273  fts3ReadNextPos(&p1, &i1);
145274  }else{
145275  fts3ReadNextPos(&p2, &i2);
145276  }
145277  }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
145278  }else if( iCol1<iCol2 ){
145279  p1 += fts3PutColNumber(&p, iCol1);
145280  fts3ColumnlistCopy(&p, &p1);
145281  }else{
145282  p2 += fts3PutColNumber(&p, iCol2);
145283  fts3ColumnlistCopy(&p, &p2);
145284  }
145285  }
145286 
145287  *p++ = POS_END;
145288  *pp = p;
145289  *pp1 = p1 + 1;
145290  *pp2 = p2 + 1;
145291 }
145292 
145293 /*
145294 ** This function is used to merge two position lists into one. When it is
145295 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
145296 ** the part of a doclist that follows each document id. For example, if a row
145297 ** contains:
145298 **
145299 ** 'a b c'|'x y z'|'a b b a'
145300 **
145301 ** Then the position list for this row for token 'b' would consist of:
145302 **
145303 ** 0x02 0x01 0x02 0x03 0x03 0x00
145304 **
145305 ** When this function returns, both *pp1 and *pp2 are left pointing to the
145306 ** byte following the 0x00 terminator of their respective position lists.
145307 **
145308 ** If isSaveLeft is 0, an entry is added to the output position list for
145309 ** each position in *pp2 for which there exists one or more positions in
145310 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
145311 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
145312 ** slots before it.
145313 **
145314 ** e.g. nToken==1 searches for adjacent positions.
145315 */
145316 static int fts3PoslistPhraseMerge(
145317  char **pp, /* IN/OUT: Preallocated output buffer */
145318  int nToken, /* Maximum difference in token positions */
145319  int isSaveLeft, /* Save the left position */
145320  int isExact, /* If *pp1 is exactly nTokens before *pp2 */
145321  char **pp1, /* IN/OUT: Left input list */
145322  char **pp2 /* IN/OUT: Right input list */
145323 ){
145324  char *p = *pp;
145325  char *p1 = *pp1;
145326  char *p2 = *pp2;
145327  int iCol1 = 0;
145328  int iCol2 = 0;
145329 
145330  /* Never set both isSaveLeft and isExact for the same invocation. */
145331  assert( isSaveLeft==0 || isExact==0 );
145332 
145333  assert( p!=0 && *p1!=0 && *p2!=0 );
145334  if( *p1==POS_COLUMN ){
145335  p1++;
145336  p1 += fts3GetVarint32(p1, &iCol1);
145337  }
145338  if( *p2==POS_COLUMN ){
145339  p2++;
145340  p2 += fts3GetVarint32(p2, &iCol2);
145341  }
145342 
145343  while( 1 ){
145344  if( iCol1==iCol2 ){
145345  char *pSave = p;
145346  sqlite3_int64 iPrev = 0;
145347  sqlite3_int64 iPos1 = 0;
145348  sqlite3_int64 iPos2 = 0;
145349 
145350  if( iCol1 ){
145351  *p++ = POS_COLUMN;
145352  p += sqlite3Fts3PutVarint(p, iCol1);
145353  }
145354 
145355  assert( *p1!=POS_END && *p1!=POS_COLUMN );
145356  assert( *p2!=POS_END && *p2!=POS_COLUMN );
145357  fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
145358  fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
145359 
145360  while( 1 ){
145361  if( iPos2==iPos1+nToken
145362  || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
145363  ){
145364  sqlite3_int64 iSave;
145365  iSave = isSaveLeft ? iPos1 : iPos2;
145366  fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
145367  pSave = 0;
145368  assert( p );
145369  }
145370  if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
145371  if( (*p2&0xFE)==0 ) break;
145372  fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
145373  }else{
145374  if( (*p1&0xFE)==0 ) break;
145375  fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
145376  }
145377  }
145378 
145379  if( pSave ){
145380  assert( pp && p );
145381  p = pSave;
145382  }
145383 
145384  fts3ColumnlistCopy(0, &p1);
145385  fts3ColumnlistCopy(0, &p2);
145386  assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
145387  if( 0==*p1 || 0==*p2 ) break;
145388 
145389  p1++;
145390  p1 += fts3GetVarint32(p1, &iCol1);
145391  p2++;
145392  p2 += fts3GetVarint32(p2, &iCol2);
145393  }
145394 
145395  /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
145396  ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
145397  ** end of the position list, or the 0x01 that precedes the next
145398  ** column-number in the position list.
145399  */
145400  else if( iCol1<iCol2 ){
145401  fts3ColumnlistCopy(0, &p1);
145402  if( 0==*p1 ) break;
145403  p1++;
145404  p1 += fts3GetVarint32(p1, &iCol1);
145405  }else{
145406  fts3ColumnlistCopy(0, &p2);
145407  if( 0==*p2 ) break;
145408  p2++;
145409  p2 += fts3GetVarint32(p2, &iCol2);
145410  }
145411  }
145412 
145413  fts3PoslistCopy(0, &p2);
145414  fts3PoslistCopy(0, &p1);
145415  *pp1 = p1;
145416  *pp2 = p2;
145417  if( *pp==p ){
145418  return 0;
145419  }
145420  *p++ = 0x00;
145421  *pp = p;
145422  return 1;
145423 }
145424 
145425 /*
145426 ** Merge two position-lists as required by the NEAR operator. The argument
145427 ** position lists correspond to the left and right phrases of an expression
145428 ** like:
145429 **
145430 ** "phrase 1" NEAR "phrase number 2"
145431 **
145432 ** Position list *pp1 corresponds to the left-hand side of the NEAR
145433 ** expression and *pp2 to the right. As usual, the indexes in the position
145434 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
145435 ** in the example above).
145436 **
145437 ** The output position list - written to *pp - is a copy of *pp2 with those
145438 ** entries that are not sufficiently NEAR entries in *pp1 removed.
145439 */
145440 static int fts3PoslistNearMerge(
145441  char **pp, /* Output buffer */
145442  char *aTmp, /* Temporary buffer space */
145443  int nRight, /* Maximum difference in token positions */
145444  int nLeft, /* Maximum difference in token positions */
145445  char **pp1, /* IN/OUT: Left input list */
145446  char **pp2 /* IN/OUT: Right input list */
145447 ){
145448  char *p1 = *pp1;
145449  char *p2 = *pp2;
145450 
145451  char *pTmp1 = aTmp;
145452  char *pTmp2;
145453  char *aTmp2;
145454  int res = 1;
145455 
145456  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
145457  aTmp2 = pTmp2 = pTmp1;
145458  *pp1 = p1;
145459  *pp2 = p2;
145460  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
145461  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
145462  fts3PoslistMerge(pp, &aTmp, &aTmp2);
145463  }else if( pTmp1!=aTmp ){
145464  fts3PoslistCopy(pp, &aTmp);
145465  }else if( pTmp2!=aTmp2 ){
145466  fts3PoslistCopy(pp, &aTmp2);
145467  }else{
145468  res = 0;
145469  }
145470 
145471  return res;
145472 }
145473 
145474 /*
145475 ** An instance of this function is used to merge together the (potentially
145476 ** large number of) doclists for each term that matches a prefix query.
145477 ** See function fts3TermSelectMerge() for details.
145478 */
145479 typedef struct TermSelect TermSelect;
145480 struct TermSelect {
145481  char *aaOutput[16]; /* Malloc'd output buffers */
145482  int anOutput[16]; /* Size each output buffer in bytes */
145483 };
145484 
145485 /*
145486 ** This function is used to read a single varint from a buffer. Parameter
145487 ** pEnd points 1 byte past the end of the buffer. When this function is
145488 ** called, if *pp points to pEnd or greater, then the end of the buffer
145489 ** has been reached. In this case *pp is set to 0 and the function returns.
145490 **
145491 ** If *pp does not point to or past pEnd, then a single varint is read
145492 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
145493 **
145494 ** If bDescIdx is false, the value read is added to *pVal before returning.
145495 ** If it is true, the value read is subtracted from *pVal before this
145496 ** function returns.
145497 */
145498 static void fts3GetDeltaVarint3(
145499  char **pp, /* IN/OUT: Point to read varint from */
145500  char *pEnd, /* End of buffer */
145501  int bDescIdx, /* True if docids are descending */
145502  sqlite3_int64 *pVal /* IN/OUT: Integer value */
145503 ){
145504  if( *pp>=pEnd ){
145505  *pp = 0;
145506  }else{
145507  sqlite3_int64 iVal;
145508  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
145509  if( bDescIdx ){
145510  *pVal -= iVal;
145511  }else{
145512  *pVal += iVal;
145513  }
145514  }
145515 }
145516 
145517 /*
145518 ** This function is used to write a single varint to a buffer. The varint
145519 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
145520 ** end of the value written.
145521 **
145522 ** If *pbFirst is zero when this function is called, the value written to
145523 ** the buffer is that of parameter iVal.
145524 **
145525 ** If *pbFirst is non-zero when this function is called, then the value
145526 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
145527 ** (if bDescIdx is non-zero).
145528 **
145529 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
145530 ** to the value of parameter iVal.
145531 */
145532 static void fts3PutDeltaVarint3(
145533  char **pp, /* IN/OUT: Output pointer */
145534  int bDescIdx, /* True for descending docids */
145535  sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
145536  int *pbFirst, /* IN/OUT: True after first int written */
145537  sqlite3_int64 iVal /* Write this value to the list */
145538 ){
145539  sqlite3_int64 iWrite;
145540  if( bDescIdx==0 || *pbFirst==0 ){
145541  iWrite = iVal - *piPrev;
145542  }else{
145543  iWrite = *piPrev - iVal;
145544  }
145545  assert( *pbFirst || *piPrev==0 );
145546  assert( *pbFirst==0 || iWrite>0 );
145547  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
145548  *piPrev = iVal;
145549  *pbFirst = 1;
145550 }
145551 
145552 
145553 /*
145554 ** This macro is used by various functions that merge doclists. The two
145555 ** arguments are 64-bit docid values. If the value of the stack variable
145556 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
145557 ** Otherwise, (i2-i1).
145558 **
145559 ** Using this makes it easier to write code that can merge doclists that are
145560 ** sorted in either ascending or descending order.
145561 */
145562 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
145563 
145564 /*
145565 ** This function does an "OR" merge of two doclists (output contains all
145566 ** positions contained in either argument doclist). If the docids in the
145567 ** input doclists are sorted in ascending order, parameter bDescDoclist
145568 ** should be false. If they are sorted in ascending order, it should be
145569 ** passed a non-zero value.
145570 **
145571 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
145572 ** containing the output doclist and SQLITE_OK is returned. In this case
145573 ** *pnOut is set to the number of bytes in the output doclist.
145574 **
145575 ** If an error occurs, an SQLite error code is returned. The output values
145576 ** are undefined in this case.
145577 */
145578 static int fts3DoclistOrMerge(
145579  int bDescDoclist, /* True if arguments are desc */
145580  char *a1, int n1, /* First doclist */
145581  char *a2, int n2, /* Second doclist */
145582  char **paOut, int *pnOut /* OUT: Malloc'd doclist */
145583 ){
145584  sqlite3_int64 i1 = 0;
145585  sqlite3_int64 i2 = 0;
145586  sqlite3_int64 iPrev = 0;
145587  char *pEnd1 = &a1[n1];
145588  char *pEnd2 = &a2[n2];
145589  char *p1 = a1;
145590  char *p2 = a2;
145591  char *p;
145592  char *aOut;
145593  int bFirstOut = 0;
145594 
145595  *paOut = 0;
145596  *pnOut = 0;
145597 
145598  /* Allocate space for the output. Both the input and output doclists
145599  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
145600  ** then the first docid in each list is simply encoded as a varint. For
145601  ** each subsequent docid, the varint stored is the difference between the
145602  ** current and previous docid (a positive number - since the list is in
145603  ** ascending order).
145604  **
145605  ** The first docid written to the output is therefore encoded using the
145606  ** same number of bytes as it is in whichever of the input lists it is
145607  ** read from. And each subsequent docid read from the same input list
145608  ** consumes either the same or less bytes as it did in the input (since
145609  ** the difference between it and the previous value in the output must
145610  ** be a positive value less than or equal to the delta value read from
145611  ** the input list). The same argument applies to all but the first docid
145612  ** read from the 'other' list. And to the contents of all position lists
145613  ** that will be copied and merged from the input to the output.
145614  **
145615  ** However, if the first docid copied to the output is a negative number,
145616  ** then the encoding of the first docid from the 'other' input list may
145617  ** be larger in the output than it was in the input (since the delta value
145618  ** may be a larger positive integer than the actual docid).
145619  **
145620  ** The space required to store the output is therefore the sum of the
145621  ** sizes of the two inputs, plus enough space for exactly one of the input
145622  ** docids to grow.
145623  **
145624  ** A symetric argument may be made if the doclists are in descending
145625  ** order.
145626  */
145627  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
145628  if( !aOut ) return SQLITE_NOMEM;
145629 
145630  p = aOut;
145631  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
145632  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
145633  while( p1 || p2 ){
145634  sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
145635 
145636  if( p2 && p1 && iDiff==0 ){
145637  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
145638  fts3PoslistMerge(&p, &p1, &p2);
145639  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145640  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145641  }else if( !p2 || (p1 && iDiff<0) ){
145642  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
145643  fts3PoslistCopy(&p, &p1);
145644  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145645  }else{
145646  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
145647  fts3PoslistCopy(&p, &p2);
145648  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145649  }
145650  }
145651 
145652  *paOut = aOut;
145653  *pnOut = (int)(p-aOut);
145654  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
145655  return SQLITE_OK;
145656 }
145657 
145658 /*
145659 ** This function does a "phrase" merge of two doclists. In a phrase merge,
145660 ** the output contains a copy of each position from the right-hand input
145661 ** doclist for which there is a position in the left-hand input doclist
145662 ** exactly nDist tokens before it.
145663 **
145664 ** If the docids in the input doclists are sorted in ascending order,
145665 ** parameter bDescDoclist should be false. If they are sorted in ascending
145666 ** order, it should be passed a non-zero value.
145667 **
145668 ** The right-hand input doclist is overwritten by this function.
145669 */
145670 static int fts3DoclistPhraseMerge(
145671  int bDescDoclist, /* True if arguments are desc */
145672  int nDist, /* Distance from left to right (1=adjacent) */
145673  char *aLeft, int nLeft, /* Left doclist */
145674  char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
145675 ){
145676  sqlite3_int64 i1 = 0;
145677  sqlite3_int64 i2 = 0;
145678  sqlite3_int64 iPrev = 0;
145679  char *aRight = *paRight;
145680  char *pEnd1 = &aLeft[nLeft];
145681  char *pEnd2 = &aRight[*pnRight];
145682  char *p1 = aLeft;
145683  char *p2 = aRight;
145684  char *p;
145685  int bFirstOut = 0;
145686  char *aOut;
145687 
145688  assert( nDist>0 );
145689  if( bDescDoclist ){
145690  aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
145691  if( aOut==0 ) return SQLITE_NOMEM;
145692  }else{
145693  aOut = aRight;
145694  }
145695  p = aOut;
145696 
145697  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
145698  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
145699 
145700  while( p1 && p2 ){
145701  sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
145702  if( iDiff==0 ){
145703  char *pSave = p;
145704  sqlite3_int64 iPrevSave = iPrev;
145705  int bFirstOutSave = bFirstOut;
145706 
145707  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
145708  if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
145709  p = pSave;
145710  iPrev = iPrevSave;
145711  bFirstOut = bFirstOutSave;
145712  }
145713  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145714  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145715  }else if( iDiff<0 ){
145716  fts3PoslistCopy(0, &p1);
145717  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
145718  }else{
145719  fts3PoslistCopy(0, &p2);
145720  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
145721  }
145722  }
145723 
145724  *pnRight = (int)(p - aOut);
145725  if( bDescDoclist ){
145726  sqlite3_free(aRight);
145727  *paRight = aOut;
145728  }
145729 
145730  return SQLITE_OK;
145731 }
145732 
145733 /*
145734 ** Argument pList points to a position list nList bytes in size. This
145735 ** function checks to see if the position list contains any entries for
145736 ** a token in position 0 (of any column). If so, it writes argument iDelta
145737 ** to the output buffer pOut, followed by a position list consisting only
145738 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
145739 ** The value returned is the number of bytes written to pOut (if any).
145740 */
145741 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
145742  sqlite3_int64 iDelta, /* Varint that may be written to pOut */
145743  char *pList, /* Position list (no 0x00 term) */
145744  int nList, /* Size of pList in bytes */
145745  char *pOut /* Write output here */
145746 ){
145747  int nOut = 0;
145748  int bWritten = 0; /* True once iDelta has been written */
145749  char *p = pList;
145750  char *pEnd = &pList[nList];
145751 
145752  if( *p!=0x01 ){
145753  if( *p==0x02 ){
145754  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
145755  pOut[nOut++] = 0x02;
145756  bWritten = 1;
145757  }
145758  fts3ColumnlistCopy(0, &p);
145759  }
145760 
145761  while( p<pEnd && *p==0x01 ){
145762  sqlite3_int64 iCol;
145763  p++;
145764  p += sqlite3Fts3GetVarint(p, &iCol);
145765  if( *p==0x02 ){
145766  if( bWritten==0 ){
145767  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
145768  bWritten = 1;
145769  }
145770  pOut[nOut++] = 0x01;
145771  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
145772  pOut[nOut++] = 0x02;
145773  }
145774  fts3ColumnlistCopy(0, &p);
145775  }
145776  if( bWritten ){
145777  pOut[nOut++] = 0x00;
145778  }
145779 
145780  return nOut;
145781 }
145782 
145783 
145784 /*
145785 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
145786 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
145787 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
145788 **
145789 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
145790 ** the responsibility of the caller to free any doclists left in the
145791 ** TermSelect.aaOutput[] array.
145792 */
145793 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
145794  char *aOut = 0;
145795  int nOut = 0;
145796  int i;
145797 
145798  /* Loop through the doclists in the aaOutput[] array. Merge them all
145799  ** into a single doclist.
145800  */
145801  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
145802  if( pTS->aaOutput[i] ){
145803  if( !aOut ){
145804  aOut = pTS->aaOutput[i];
145805  nOut = pTS->anOutput[i];
145806  pTS->aaOutput[i] = 0;
145807  }else{
145808  int nNew;
145809  char *aNew;
145810 
145811  int rc = fts3DoclistOrMerge(p->bDescIdx,
145812  pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
145813  );
145814  if( rc!=SQLITE_OK ){
145815  sqlite3_free(aOut);
145816  return rc;
145817  }
145818 
145819  sqlite3_free(pTS->aaOutput[i]);
145820  sqlite3_free(aOut);
145821  pTS->aaOutput[i] = 0;
145822  aOut = aNew;
145823  nOut = nNew;
145824  }
145825  }
145826  }
145827 
145828  pTS->aaOutput[0] = aOut;
145829  pTS->anOutput[0] = nOut;
145830  return SQLITE_OK;
145831 }
145832 
145833 /*
145834 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
145835 ** as the first argument. The merge is an "OR" merge (see function
145836 ** fts3DoclistOrMerge() for details).
145837 **
145838 ** This function is called with the doclist for each term that matches
145839 ** a queried prefix. It merges all these doclists into one, the doclist
145840 ** for the specified prefix. Since there can be a very large number of
145841 ** doclists to merge, the merging is done pair-wise using the TermSelect
145842 ** object.
145843 **
145844 ** This function returns SQLITE_OK if the merge is successful, or an
145845 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
145846 */
145847 static int fts3TermSelectMerge(
145848  Fts3Table *p, /* FTS table handle */
145849  TermSelect *pTS, /* TermSelect object to merge into */
145850  char *aDoclist, /* Pointer to doclist */
145851  int nDoclist /* Size of aDoclist in bytes */
145852 ){
145853  if( pTS->aaOutput[0]==0 ){
145854  /* If this is the first term selected, copy the doclist to the output
145855  ** buffer using memcpy().
145856  **
145857  ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
145858  ** allocation. This is so as to ensure that the buffer is big enough
145859  ** to hold the current doclist AND'd with any other doclist. If the
145860  ** doclists are stored in order=ASC order, this padding would not be
145861  ** required (since the size of [doclistA AND doclistB] is always less
145862  ** than or equal to the size of [doclistA] in that case). But this is
145863  ** not true for order=DESC. For example, a doclist containing (1, -1)
145864  ** may be smaller than (-1), as in the first example the -1 may be stored
145865  ** as a single-byte delta, whereas in the second it must be stored as a
145866  ** FTS3_VARINT_MAX byte varint.
145867  **
145868  ** Similar padding is added in the fts3DoclistOrMerge() function.
145869  */
145870  pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
145871  pTS->anOutput[0] = nDoclist;
145872  if( pTS->aaOutput[0] ){
145873  memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
145874  }else{
145875  return SQLITE_NOMEM;
145876  }
145877  }else{
145878  char *aMerge = aDoclist;
145879  int nMerge = nDoclist;
145880  int iOut;
145881 
145882  for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
145883  if( pTS->aaOutput[iOut]==0 ){
145884  assert( iOut>0 );
145885  pTS->aaOutput[iOut] = aMerge;
145886  pTS->anOutput[iOut] = nMerge;
145887  break;
145888  }else{
145889  char *aNew;
145890  int nNew;
145891 
145892  int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
145893  pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
145894  );
145895  if( rc!=SQLITE_OK ){
145896  if( aMerge!=aDoclist ) sqlite3_free(aMerge);
145897  return rc;
145898  }
145899 
145900  if( aMerge!=aDoclist ) sqlite3_free(aMerge);
145901  sqlite3_free(pTS->aaOutput[iOut]);
145902  pTS->aaOutput[iOut] = 0;
145903 
145904  aMerge = aNew;
145905  nMerge = nNew;
145906  if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
145907  pTS->aaOutput[iOut] = aMerge;
145908  pTS->anOutput[iOut] = nMerge;
145909  }
145910  }
145911  }
145912  }
145913  return SQLITE_OK;
145914 }
145915 
145916 /*
145917 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
145918 */
145919 static int fts3SegReaderCursorAppend(
145920  Fts3MultiSegReader *pCsr,
145921  Fts3SegReader *pNew
145922 ){
145923  if( (pCsr->nSegment%16)==0 ){
145924  Fts3SegReader **apNew;
145925  int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
145926  apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
145927  if( !apNew ){
145928  sqlite3Fts3SegReaderFree(pNew);
145929  return SQLITE_NOMEM;
145930  }
145931  pCsr->apSegment = apNew;
145932  }
145933  pCsr->apSegment[pCsr->nSegment++] = pNew;
145934  return SQLITE_OK;
145935 }
145936 
145937 /*
145938 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
145939 ** 8th argument.
145940 **
145941 ** This function returns SQLITE_OK if successful, or an SQLite error code
145942 ** otherwise.
145943 */
145944 static int fts3SegReaderCursor(
145945  Fts3Table *p, /* FTS3 table handle */
145946  int iLangid, /* Language id */
145947  int iIndex, /* Index to search (from 0 to p->nIndex-1) */
145948  int iLevel, /* Level of segments to scan */
145949  const char *zTerm, /* Term to query for */
145950  int nTerm, /* Size of zTerm in bytes */
145951  int isPrefix, /* True for a prefix search */
145952  int isScan, /* True to scan from zTerm to EOF */
145953  Fts3MultiSegReader *pCsr /* Cursor object to populate */
145954 ){
145955  int rc = SQLITE_OK; /* Error code */
145956  sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
145957  int rc2; /* Result of sqlite3_reset() */
145958 
145959  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
145960  ** for the pending-terms. If this is a scan, then this call must be being
145961  ** made by an fts4aux module, not an FTS table. In this case calling
145962  ** Fts3SegReaderPending might segfault, as the data structures used by
145963  ** fts4aux are not completely populated. So it's easiest to filter these
145964  ** calls out here. */
145965  if( iLevel<0 && p->aIndex ){
145966  Fts3SegReader *pSeg = 0;
145967  rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
145968  if( rc==SQLITE_OK && pSeg ){
145969  rc = fts3SegReaderCursorAppend(pCsr, pSeg);
145970  }
145971  }
145972 
145973  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145974  if( rc==SQLITE_OK ){
145975  rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
145976  }
145977 
145978  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
145979  Fts3SegReader *pSeg = 0;
145980 
145981  /* Read the values returned by the SELECT into local variables. */
145982  sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
145983  sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
145984  sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
145985  int nRoot = sqlite3_column_bytes(pStmt, 4);
145986  char const *zRoot = sqlite3_column_blob(pStmt, 4);
145987 
145988  /* If zTerm is not NULL, and this segment is not stored entirely on its
145989  ** root node, the range of leaves scanned can be reduced. Do this. */
145990  if( iStartBlock && zTerm ){
145991  sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
145992  rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
145993  if( rc!=SQLITE_OK ) goto finished;
145994  if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
145995  }
145996 
145997  rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
145998  (isPrefix==0 && isScan==0),
145999  iStartBlock, iLeavesEndBlock,
146000  iEndBlock, zRoot, nRoot, &pSeg
146001  );
146002  if( rc!=SQLITE_OK ) goto finished;
146003  rc = fts3SegReaderCursorAppend(pCsr, pSeg);
146004  }
146005  }
146006 
146007  finished:
146008  rc2 = sqlite3_reset(pStmt);
146009  if( rc==SQLITE_DONE ) rc = rc2;
146010 
146011  return rc;
146012 }
146013 
146014 /*
146015 ** Set up a cursor object for iterating through a full-text index or a
146016 ** single level therein.
146017 */
146018 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
146019  Fts3Table *p, /* FTS3 table handle */
146020  int iLangid, /* Language-id to search */
146021  int iIndex, /* Index to search (from 0 to p->nIndex-1) */
146022  int iLevel, /* Level of segments to scan */
146023  const char *zTerm, /* Term to query for */
146024  int nTerm, /* Size of zTerm in bytes */
146025  int isPrefix, /* True for a prefix search */
146026  int isScan, /* True to scan from zTerm to EOF */
146027  Fts3MultiSegReader *pCsr /* Cursor object to populate */
146028 ){
146029  assert( iIndex>=0 && iIndex<p->nIndex );
146030  assert( iLevel==FTS3_SEGCURSOR_ALL
146031  || iLevel==FTS3_SEGCURSOR_PENDING
146032  || iLevel>=0
146033  );
146034  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
146035  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
146036  assert( isPrefix==0 || isScan==0 );
146037 
146038  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
146039  return fts3SegReaderCursor(
146040  p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
146041  );
146042 }
146043 
146044 /*
146045 ** In addition to its current configuration, have the Fts3MultiSegReader
146046 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
146047 **
146048 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
146049 */
146050 static int fts3SegReaderCursorAddZero(
146051  Fts3Table *p, /* FTS virtual table handle */
146052  int iLangid,
146053  const char *zTerm, /* Term to scan doclist of */
146054  int nTerm, /* Number of bytes in zTerm */
146055  Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
146056 ){
146057  return fts3SegReaderCursor(p,
146058  iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
146059  );
146060 }
146061 
146062 /*
146063 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
146064 ** if isPrefix is true, to scan the doclist for all terms for which
146065 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
146066 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
146067 ** an SQLite error code.
146068 **
146069 ** It is the responsibility of the caller to free this object by eventually
146070 ** passing it to fts3SegReaderCursorFree()
146071 **
146072 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
146073 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
146074 */
146075 static int fts3TermSegReaderCursor(
146076  Fts3Cursor *pCsr, /* Virtual table cursor handle */
146077  const char *zTerm, /* Term to query for */
146078  int nTerm, /* Size of zTerm in bytes */
146079  int isPrefix, /* True for a prefix search */
146080  Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
146081 ){
146082  Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
146083  int rc = SQLITE_NOMEM; /* Return code */
146084 
146085  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
146086  if( pSegcsr ){
146087  int i;
146088  int bFound = 0; /* True once an index has been found */
146089  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
146090 
146091  if( isPrefix ){
146092  for(i=1; bFound==0 && i<p->nIndex; i++){
146093  if( p->aIndex[i].nPrefix==nTerm ){
146094  bFound = 1;
146095  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
146096  i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
146097  );
146098  pSegcsr->bLookup = 1;
146099  }
146100  }
146101 
146102  for(i=1; bFound==0 && i<p->nIndex; i++){
146103  if( p->aIndex[i].nPrefix==nTerm+1 ){
146104  bFound = 1;
146105  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
146106  i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
146107  );
146108  if( rc==SQLITE_OK ){
146109  rc = fts3SegReaderCursorAddZero(
146110  p, pCsr->iLangid, zTerm, nTerm, pSegcsr
146111  );
146112  }
146113  }
146114  }
146115  }
146116 
146117  if( bFound==0 ){
146118  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
146119  0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
146120  );
146121  pSegcsr->bLookup = !isPrefix;
146122  }
146123  }
146124 
146125  *ppSegcsr = pSegcsr;
146126  return rc;
146127 }
146128 
146129 /*
146130 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
146131 */
146132 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
146133  sqlite3Fts3SegReaderFinish(pSegcsr);
146134  sqlite3_free(pSegcsr);
146135 }
146136 
146137 /*
146138 ** This function retrieves the doclist for the specified term (or term
146139 ** prefix) from the database.
146140 */
146141 static int fts3TermSelect(
146142  Fts3Table *p, /* Virtual table handle */
146143  Fts3PhraseToken *pTok, /* Token to query for */
146144  int iColumn, /* Column to query (or -ve for all columns) */
146145  int *pnOut, /* OUT: Size of buffer at *ppOut */
146146  char **ppOut /* OUT: Malloced result buffer */
146147 ){
146148  int rc; /* Return code */
146149  Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
146150  TermSelect tsc; /* Object for pair-wise doclist merging */
146151  Fts3SegFilter filter; /* Segment term filter configuration */
146152 
146153  pSegcsr = pTok->pSegcsr;
146154  memset(&tsc, 0, sizeof(TermSelect));
146155 
146156  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
146157  | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
146158  | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
146159  | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
146160  filter.iCol = iColumn;
146161  filter.zTerm = pTok->z;
146162  filter.nTerm = pTok->n;
146163 
146164  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
146165  while( SQLITE_OK==rc
146166  && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
146167  ){
146168  rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
146169  }
146170 
146171  if( rc==SQLITE_OK ){
146172  rc = fts3TermSelectFinishMerge(p, &tsc);
146173  }
146174  if( rc==SQLITE_OK ){
146175  *ppOut = tsc.aaOutput[0];
146176  *pnOut = tsc.anOutput[0];
146177  }else{
146178  int i;
146179  for(i=0; i<SizeofArray(tsc.aaOutput); i++){
146180  sqlite3_free(tsc.aaOutput[i]);
146181  }
146182  }
146183 
146184  fts3SegReaderCursorFree(pSegcsr);
146185  pTok->pSegcsr = 0;
146186  return rc;
146187 }
146188 
146189 /*
146190 ** This function counts the total number of docids in the doclist stored
146191 ** in buffer aList[], size nList bytes.
146192 **
146193 ** If the isPoslist argument is true, then it is assumed that the doclist
146194 ** contains a position-list following each docid. Otherwise, it is assumed
146195 ** that the doclist is simply a list of docids stored as delta encoded
146196 ** varints.
146197 */
146198 static int fts3DoclistCountDocids(char *aList, int nList){
146199  int nDoc = 0; /* Return value */
146200  if( aList ){
146201  char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
146202  char *p = aList; /* Cursor */
146203  while( p<aEnd ){
146204  nDoc++;
146205  while( (*p++)&0x80 ); /* Skip docid varint */
146206  fts3PoslistCopy(0, &p); /* Skip over position list */
146207  }
146208  }
146209 
146210  return nDoc;
146211 }
146212 
146213 /*
146214 ** Advance the cursor to the next row in the %_content table that
146215 ** matches the search criteria. For a MATCH search, this will be
146216 ** the next row that matches. For a full-table scan, this will be
146217 ** simply the next row in the %_content table. For a docid lookup,
146218 ** this routine simply sets the EOF flag.
146219 **
146220 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
146221 ** even if we reach end-of-file. The fts3EofMethod() will be called
146222 ** subsequently to determine whether or not an EOF was hit.
146223 */
146224 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
146225  int rc;
146226  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
146227  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
146228  if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
146229  pCsr->isEof = 1;
146230  rc = sqlite3_reset(pCsr->pStmt);
146231  }else{
146232  pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
146233  rc = SQLITE_OK;
146234  }
146235  }else{
146236  rc = fts3EvalNext((Fts3Cursor *)pCursor);
146237  }
146238  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
146239  return rc;
146240 }
146241 
146242 /*
146243 ** The following are copied from sqliteInt.h.
146244 **
146245 ** Constants for the largest and smallest possible 64-bit signed integers.
146246 ** These macros are designed to work correctly on both 32-bit and 64-bit
146247 ** compilers.
146248 */
146249 #ifndef SQLITE_AMALGAMATION
146250 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
146251 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
146252 #endif
146253 
146254 /*
146255 ** If the numeric type of argument pVal is "integer", then return it
146256 ** converted to a 64-bit signed integer. Otherwise, return a copy of
146257 ** the second parameter, iDefault.
146258 */
146259 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
146260  if( pVal ){
146261  int eType = sqlite3_value_numeric_type(pVal);
146262  if( eType==SQLITE_INTEGER ){
146263  return sqlite3_value_int64(pVal);
146264  }
146265  }
146266  return iDefault;
146267 }
146268 
146269 /*
146270 ** This is the xFilter interface for the virtual table. See
146271 ** the virtual table xFilter method documentation for additional
146272 ** information.
146273 **
146274 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
146275 ** the %_content table.
146276 **
146277 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
146278 ** in the %_content table.
146279 **
146280 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
146281 ** column on the left-hand side of the MATCH operator is column
146282 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
146283 ** side of the MATCH operator.
146284 */
146285 static int fts3FilterMethod(
146286  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
146287  int idxNum, /* Strategy index */
146288  const char *idxStr, /* Unused */
146289  int nVal, /* Number of elements in apVal */
146290  sqlite3_value **apVal /* Arguments for the indexing scheme */
146291 ){
146292  int rc = SQLITE_OK;
146293  char *zSql; /* SQL statement used to access %_content */
146294  int eSearch;
146295  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
146296  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
146297 
146298  sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
146299  sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
146300  sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
146301  sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
146302  int iIdx;
146303 
146304  UNUSED_PARAMETER(idxStr);
146305  UNUSED_PARAMETER(nVal);
146306 
146307  eSearch = (idxNum & 0x0000FFFF);
146308  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
146309  assert( p->pSegments==0 );
146310 
146311  /* Collect arguments into local variables */
146312  iIdx = 0;
146313  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
146314  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
146315  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
146316  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
146317  assert( iIdx==nVal );
146318 
146319  /* In case the cursor has been used before, clear it now. */
146320  sqlite3_finalize(pCsr->pStmt);
146321  sqlite3_free(pCsr->aDoclist);
146322  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
146323  sqlite3Fts3ExprFree(pCsr->pExpr);
146324  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
146325 
146326  /* Set the lower and upper bounds on docids to return */
146327  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
146328  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
146329 
146330  if( idxStr ){
146331  pCsr->bDesc = (idxStr[0]=='D');
146332  }else{
146333  pCsr->bDesc = p->bDescIdx;
146334  }
146335  pCsr->eSearch = (i16)eSearch;
146336 
146337  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
146338  int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
146339  const char *zQuery = (const char *)sqlite3_value_text(pCons);
146340 
146341  if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
146342  return SQLITE_NOMEM;
146343  }
146344 
146345  pCsr->iLangid = 0;
146346  if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
146347 
146348  assert( p->base.zErrMsg==0 );
146349  rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
146350  p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
146351  &p->base.zErrMsg
146352  );
146353  if( rc!=SQLITE_OK ){
146354  return rc;
146355  }
146356 
146357  rc = fts3EvalStart(pCsr);
146358  sqlite3Fts3SegmentsClose(p);
146359  if( rc!=SQLITE_OK ) return rc;
146360  pCsr->pNextId = pCsr->aDoclist;
146361  pCsr->iPrevId = 0;
146362  }
146363 
146364  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
146365  ** statement loops through all rows of the %_content table. For a
146366  ** full-text query or docid lookup, the statement retrieves a single
146367  ** row by docid.
146368  */
146369  if( eSearch==FTS3_FULLSCAN_SEARCH ){
146370  if( pDocidGe || pDocidLe ){
146371  zSql = sqlite3_mprintf(
146372  "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
146373  p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
146374  (pCsr->bDesc ? "DESC" : "ASC")
146375  );
146376  }else{
146377  zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
146378  p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
146379  );
146380  }
146381  if( zSql ){
146382  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
146383  sqlite3_free(zSql);
146384  }else{
146385  rc = SQLITE_NOMEM;
146386  }
146387  }else if( eSearch==FTS3_DOCID_SEARCH ){
146388  rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
146389  if( rc==SQLITE_OK ){
146390  rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
146391  }
146392  }
146393  if( rc!=SQLITE_OK ) return rc;
146394 
146395  return fts3NextMethod(pCursor);
146396 }
146397 
146398 /*
146399 ** This is the xEof method of the virtual table. SQLite calls this
146400 ** routine to find out if it has reached the end of a result set.
146401 */
146402 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
146403  return ((Fts3Cursor *)pCursor)->isEof;
146404 }
146405 
146406 /*
146407 ** This is the xRowid method. The SQLite core calls this routine to
146408 ** retrieve the rowid for the current row of the result set. fts3
146409 ** exposes %_content.docid as the rowid for the virtual table. The
146410 ** rowid should be written to *pRowid.
146411 */
146412 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
146413  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
146414  *pRowid = pCsr->iPrevId;
146415  return SQLITE_OK;
146416 }
146417 
146418 /*
146419 ** This is the xColumn method, called by SQLite to request a value from
146420 ** the row that the supplied cursor currently points to.
146421 **
146422 ** If:
146423 **
146424 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
146425 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
146426 ** (iCol == p->nColumn+1) -> Docid column
146427 ** (iCol == p->nColumn+2) -> Langid column
146428 */
146429 static int fts3ColumnMethod(
146430  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
146431  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
146432  int iCol /* Index of column to read value from */
146433 ){
146434  int rc = SQLITE_OK; /* Return Code */
146435  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
146436  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
146437 
146438  /* The column value supplied by SQLite must be in range. */
146439  assert( iCol>=0 && iCol<=p->nColumn+2 );
146440 
146441  if( iCol==p->nColumn+1 ){
146442  /* This call is a request for the "docid" column. Since "docid" is an
146443  ** alias for "rowid", use the xRowid() method to obtain the value.
146444  */
146445  sqlite3_result_int64(pCtx, pCsr->iPrevId);
146446  }else if( iCol==p->nColumn ){
146447  /* The extra column whose name is the same as the table.
146448  ** Return a blob which is a pointer to the cursor. */
146449  sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
146450  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
146451  sqlite3_result_int64(pCtx, pCsr->iLangid);
146452  }else{
146453  /* The requested column is either a user column (one that contains
146454  ** indexed data), or the language-id column. */
146455  rc = fts3CursorSeek(0, pCsr);
146456 
146457  if( rc==SQLITE_OK ){
146458  if( iCol==p->nColumn+2 ){
146459  int iLangid = 0;
146460  if( p->zLanguageid ){
146461  iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
146462  }
146463  sqlite3_result_int(pCtx, iLangid);
146464  }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
146465  sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
146466  }
146467  }
146468  }
146469 
146470  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
146471  return rc;
146472 }
146473 
146474 /*
146475 ** This function is the implementation of the xUpdate callback used by
146476 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
146477 ** inserted, updated or deleted.
146478 */
146479 static int fts3UpdateMethod(
146480  sqlite3_vtab *pVtab, /* Virtual table handle */
146481  int nArg, /* Size of argument array */
146482  sqlite3_value **apVal, /* Array of arguments */
146483  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
146484 ){
146485  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
146486 }
146487 
146488 /*
146489 ** Implementation of xSync() method. Flush the contents of the pending-terms
146490 ** hash-table to the database.
146491 */
146492 static int fts3SyncMethod(sqlite3_vtab *pVtab){
146493 
146494  /* Following an incremental-merge operation, assuming that the input
146495  ** segments are not completely consumed (the usual case), they are updated
146496  ** in place to remove the entries that have already been merged. This
146497  ** involves updating the leaf block that contains the smallest unmerged
146498  ** entry and each block (if any) between the leaf and the root node. So
146499  ** if the height of the input segment b-trees is N, and input segments
146500  ** are merged eight at a time, updating the input segments at the end
146501  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
146502  ** small - often between 0 and 2. So the overhead of the incremental
146503  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
146504  ** dwarfing the actual productive work accomplished, the incremental merge
146505  ** is only attempted if it will write at least 64 leaf blocks. Hence
146506  ** nMinMerge.
146507  **
146508  ** Of course, updating the input segments also involves deleting a bunch
146509  ** of blocks from the segments table. But this is not considered overhead
146510  ** as it would also be required by a crisis-merge that used the same input
146511  ** segments.
146512  */
146513  const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
146514 
146515  Fts3Table *p = (Fts3Table*)pVtab;
146516  int rc = sqlite3Fts3PendingTermsFlush(p);
146517 
146518  if( rc==SQLITE_OK
146519  && p->nLeafAdd>(nMinMerge/16)
146520  && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
146521  ){
146522  int mxLevel = 0; /* Maximum relative level value in db */
146523  int A; /* Incr-merge parameter A */
146524 
146525  rc = sqlite3Fts3MaxLevel(p, &mxLevel);
146526  assert( rc==SQLITE_OK || mxLevel==0 );
146527  A = p->nLeafAdd * mxLevel;
146528  A += (A/2);
146529  if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
146530  }
146531  sqlite3Fts3SegmentsClose(p);
146532  return rc;
146533 }
146534 
146535 /*
146536 ** If it is currently unknown whether or not the FTS table has an %_stat
146537 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
146538 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
146539 ** if an error occurs.
146540 */
146541 static int fts3SetHasStat(Fts3Table *p){
146542  int rc = SQLITE_OK;
146543  if( p->bHasStat==2 ){
146544  const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
146545  char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
146546  if( zSql ){
146547  sqlite3_stmt *pStmt = 0;
146548  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
146549  if( rc==SQLITE_OK ){
146550  int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
146551  rc = sqlite3_finalize(pStmt);
146552  if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
146553  }
146554  sqlite3_free(zSql);
146555  }else{
146556  rc = SQLITE_NOMEM;
146557  }
146558  }
146559  return rc;
146560 }
146561 
146562 /*
146563 ** Implementation of xBegin() method.
146564 */
146565 static int fts3BeginMethod(sqlite3_vtab *pVtab){
146566  Fts3Table *p = (Fts3Table*)pVtab;
146567  UNUSED_PARAMETER(pVtab);
146568  assert( p->pSegments==0 );
146569  assert( p->nPendingData==0 );
146570  assert( p->inTransaction!=1 );
146571  TESTONLY( p->inTransaction = 1 );
146572  TESTONLY( p->mxSavepoint = -1; );
146573  p->nLeafAdd = 0;
146574  return fts3SetHasStat(p);
146575 }
146576 
146577 /*
146578 ** Implementation of xCommit() method. This is a no-op. The contents of
146579 ** the pending-terms hash-table have already been flushed into the database
146580 ** by fts3SyncMethod().
146581 */
146582 static int fts3CommitMethod(sqlite3_vtab *pVtab){
146583  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
146584  UNUSED_PARAMETER(pVtab);
146585  assert( p->nPendingData==0 );
146586  assert( p->inTransaction!=0 );
146587  assert( p->pSegments==0 );
146588  TESTONLY( p->inTransaction = 0 );
146589  TESTONLY( p->mxSavepoint = -1; );
146590  return SQLITE_OK;
146591 }
146592 
146593 /*
146594 ** Implementation of xRollback(). Discard the contents of the pending-terms
146595 ** hash-table. Any changes made to the database are reverted by SQLite.
146596 */
146597 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
146598  Fts3Table *p = (Fts3Table*)pVtab;
146599  sqlite3Fts3PendingTermsClear(p);
146600  assert( p->inTransaction!=0 );
146601  TESTONLY( p->inTransaction = 0 );
146602  TESTONLY( p->mxSavepoint = -1; );
146603  return SQLITE_OK;
146604 }
146605 
146606 /*
146607 ** When called, *ppPoslist must point to the byte immediately following the
146608 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
146609 ** moves *ppPoslist so that it instead points to the first byte of the
146610 ** same position list.
146611 */
146612 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
146613  char *p = &(*ppPoslist)[-2];
146614  char c = 0;
146615 
146616  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
146617  while( p>pStart && (c=*p--)==0 );
146618 
146619  /* Search backwards for a varint with value zero (the end of the previous
146620  ** poslist). This is an 0x00 byte preceded by some byte that does not
146621  ** have the 0x80 bit set. */
146622  while( p>pStart && (*p & 0x80) | c ){
146623  c = *p--;
146624  }
146625  assert( p==pStart || c==0 );
146626 
146627  /* At this point p points to that preceding byte without the 0x80 bit
146628  ** set. So to find the start of the poslist, skip forward 2 bytes then
146629  ** over a varint.
146630  **
146631  ** Normally. The other case is that p==pStart and the poslist to return
146632  ** is the first in the doclist. In this case do not skip forward 2 bytes.
146633  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
146634  ** is required for cases where the first byte of a doclist and the
146635  ** doclist is empty. For example, if the first docid is 10, a doclist
146636  ** that begins with:
146637  **
146638  ** 0x0A 0x00 <next docid delta varint>
146639  */
146640  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
146641  while( *p++&0x80 );
146642  *ppPoslist = p;
146643 }
146644 
146645 /*
146646 ** Helper function used by the implementation of the overloaded snippet(),
146647 ** offsets() and optimize() SQL functions.
146648 **
146649 ** If the value passed as the third argument is a blob of size
146650 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
146651 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
146652 ** message is written to context pContext and SQLITE_ERROR returned. The
146653 ** string passed via zFunc is used as part of the error message.
146654 */
146655 static int fts3FunctionArg(
146656  sqlite3_context *pContext, /* SQL function call context */
146657  const char *zFunc, /* Function name */
146658  sqlite3_value *pVal, /* argv[0] passed to function */
146659  Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
146660 ){
146661  Fts3Cursor *pRet;
146662  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
146663  || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
146664  ){
146665  char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
146666  sqlite3_result_error(pContext, zErr, -1);
146667  sqlite3_free(zErr);
146668  return SQLITE_ERROR;
146669  }
146670  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
146671  *ppCsr = pRet;
146672  return SQLITE_OK;
146673 }
146674 
146675 /*
146676 ** Implementation of the snippet() function for FTS3
146677 */
146678 static void fts3SnippetFunc(
146679  sqlite3_context *pContext, /* SQLite function call context */
146680  int nVal, /* Size of apVal[] array */
146681  sqlite3_value **apVal /* Array of arguments */
146682 ){
146683  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
146684  const char *zStart = "<b>";
146685  const char *zEnd = "</b>";
146686  const char *zEllipsis = "<b>...</b>";
146687  int iCol = -1;
146688  int nToken = 15; /* Default number of tokens in snippet */
146689 
146690  /* There must be at least one argument passed to this function (otherwise
146691  ** the non-overloaded version would have been called instead of this one).
146692  */
146693  assert( nVal>=1 );
146694 
146695  if( nVal>6 ){
146696  sqlite3_result_error(pContext,
146697  "wrong number of arguments to function snippet()", -1);
146698  return;
146699  }
146700  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
146701 
146702  switch( nVal ){
146703  case 6: nToken = sqlite3_value_int(apVal[5]);
146704  case 5: iCol = sqlite3_value_int(apVal[4]);
146705  case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
146706  case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
146707  case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
146708  }
146709  if( !zEllipsis || !zEnd || !zStart ){
146710  sqlite3_result_error_nomem(pContext);
146711  }else if( nToken==0 ){
146712  sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
146713  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
146714  sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
146715  }
146716 }
146717 
146718 /*
146719 ** Implementation of the offsets() function for FTS3
146720 */
146721 static void fts3OffsetsFunc(
146722  sqlite3_context *pContext, /* SQLite function call context */
146723  int nVal, /* Size of argument array */
146724  sqlite3_value **apVal /* Array of arguments */
146725 ){
146726  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
146727 
146728  UNUSED_PARAMETER(nVal);
146729 
146730  assert( nVal==1 );
146731  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
146732  assert( pCsr );
146733  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
146734  sqlite3Fts3Offsets(pContext, pCsr);
146735  }
146736 }
146737 
146738 /*
146739 ** Implementation of the special optimize() function for FTS3. This
146740 ** function merges all segments in the database to a single segment.
146741 ** Example usage is:
146742 **
146743 ** SELECT optimize(t) FROM t LIMIT 1;
146744 **
146745 ** where 't' is the name of an FTS3 table.
146746 */
146747 static void fts3OptimizeFunc(
146748  sqlite3_context *pContext, /* SQLite function call context */
146749  int nVal, /* Size of argument array */
146750  sqlite3_value **apVal /* Array of arguments */
146751 ){
146752  int rc; /* Return code */
146753  Fts3Table *p; /* Virtual table handle */
146754  Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
146755 
146756  UNUSED_PARAMETER(nVal);
146757 
146758  assert( nVal==1 );
146759  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
146760  p = (Fts3Table *)pCursor->base.pVtab;
146761  assert( p );
146762 
146763  rc = sqlite3Fts3Optimize(p);
146764 
146765  switch( rc ){
146766  case SQLITE_OK:
146767  sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
146768  break;
146769  case SQLITE_DONE:
146770  sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
146771  break;
146772  default:
146773  sqlite3_result_error_code(pContext, rc);
146774  break;
146775  }
146776 }
146777 
146778 /*
146779 ** Implementation of the matchinfo() function for FTS3
146780 */
146781 static void fts3MatchinfoFunc(
146782  sqlite3_context *pContext, /* SQLite function call context */
146783  int nVal, /* Size of argument array */
146784  sqlite3_value **apVal /* Array of arguments */
146785 ){
146786  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
146787  assert( nVal==1 || nVal==2 );
146788  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
146789  const char *zArg = 0;
146790  if( nVal>1 ){
146791  zArg = (const char *)sqlite3_value_text(apVal[1]);
146792  }
146793  sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
146794  }
146795 }
146796 
146797 /*
146798 ** This routine implements the xFindFunction method for the FTS3
146799 ** virtual table.
146800 */
146801 static int fts3FindFunctionMethod(
146802  sqlite3_vtab *pVtab, /* Virtual table handle */
146803  int nArg, /* Number of SQL function arguments */
146804  const char *zName, /* Name of SQL function */
146805  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
146806  void **ppArg /* Unused */
146807 ){
146808  struct Overloaded {
146809  const char *zName;
146810  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
146811  } aOverload[] = {
146812  { "snippet", fts3SnippetFunc },
146813  { "offsets", fts3OffsetsFunc },
146814  { "optimize", fts3OptimizeFunc },
146815  { "matchinfo", fts3MatchinfoFunc },
146816  };
146817  int i; /* Iterator variable */
146818 
146819  UNUSED_PARAMETER(pVtab);
146820  UNUSED_PARAMETER(nArg);
146821  UNUSED_PARAMETER(ppArg);
146822 
146823  for(i=0; i<SizeofArray(aOverload); i++){
146824  if( strcmp(zName, aOverload[i].zName)==0 ){
146825  *pxFunc = aOverload[i].xFunc;
146826  return 1;
146827  }
146828  }
146829 
146830  /* No function of the specified name was found. Return 0. */
146831  return 0;
146832 }
146833 
146834 /*
146835 ** Implementation of FTS3 xRename method. Rename an fts3 table.
146836 */
146837 static int fts3RenameMethod(
146838  sqlite3_vtab *pVtab, /* Virtual table handle */
146839  const char *zName /* New name of table */
146840 ){
146841  Fts3Table *p = (Fts3Table *)pVtab;
146842  sqlite3 *db = p->db; /* Database connection */
146843  int rc; /* Return Code */
146844 
146845  /* At this point it must be known if the %_stat table exists or not.
146846  ** So bHasStat may not be 2. */
146847  rc = fts3SetHasStat(p);
146848 
146849  /* As it happens, the pending terms table is always empty here. This is
146850  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
146851  ** always opens a savepoint transaction. And the xSavepoint() method
146852  ** flushes the pending terms table. But leave the (no-op) call to
146853  ** PendingTermsFlush() in in case that changes.
146854  */
146855  assert( p->nPendingData==0 );
146856  if( rc==SQLITE_OK ){
146857  rc = sqlite3Fts3PendingTermsFlush(p);
146858  }
146859 
146860  if( p->zContentTbl==0 ){
146861  fts3DbExec(&rc, db,
146862  "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
146863  p->zDb, p->zName, zName
146864  );
146865  }
146866 
146867  if( p->bHasDocsize ){
146868  fts3DbExec(&rc, db,
146869  "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
146870  p->zDb, p->zName, zName
146871  );
146872  }
146873  if( p->bHasStat ){
146874  fts3DbExec(&rc, db,
146875  "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
146876  p->zDb, p->zName, zName
146877  );
146878  }
146879  fts3DbExec(&rc, db,
146880  "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
146881  p->zDb, p->zName, zName
146882  );
146883  fts3DbExec(&rc, db,
146884  "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
146885  p->zDb, p->zName, zName
146886  );
146887  return rc;
146888 }
146889 
146890 /*
146891 ** The xSavepoint() method.
146892 **
146893 ** Flush the contents of the pending-terms table to disk.
146894 */
146895 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
146896  int rc = SQLITE_OK;
146897  UNUSED_PARAMETER(iSavepoint);
146898  assert( ((Fts3Table *)pVtab)->inTransaction );
146899  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
146900  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
146901  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
146902  rc = fts3SyncMethod(pVtab);
146903  }
146904  return rc;
146905 }
146906 
146907 /*
146908 ** The xRelease() method.
146909 **
146910 ** This is a no-op.
146911 */
146912 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
146913  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
146914  UNUSED_PARAMETER(iSavepoint);
146915  UNUSED_PARAMETER(pVtab);
146916  assert( p->inTransaction );
146917  assert( p->mxSavepoint >= iSavepoint );
146918  TESTONLY( p->mxSavepoint = iSavepoint-1 );
146919  return SQLITE_OK;
146920 }
146921 
146922 /*
146923 ** The xRollbackTo() method.
146924 **
146925 ** Discard the contents of the pending terms table.
146926 */
146927 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
146928  Fts3Table *p = (Fts3Table*)pVtab;
146929  UNUSED_PARAMETER(iSavepoint);
146930  assert( p->inTransaction );
146931  assert( p->mxSavepoint >= iSavepoint );
146932  TESTONLY( p->mxSavepoint = iSavepoint );
146933  sqlite3Fts3PendingTermsClear(p);
146934  return SQLITE_OK;
146935 }
146936 
146937 static const sqlite3_module fts3Module = {
146938  /* iVersion */ 2,
146939  /* xCreate */ fts3CreateMethod,
146940  /* xConnect */ fts3ConnectMethod,
146941  /* xBestIndex */ fts3BestIndexMethod,
146942  /* xDisconnect */ fts3DisconnectMethod,
146943  /* xDestroy */ fts3DestroyMethod,
146944  /* xOpen */ fts3OpenMethod,
146945  /* xClose */ fts3CloseMethod,
146946  /* xFilter */ fts3FilterMethod,
146947  /* xNext */ fts3NextMethod,
146948  /* xEof */ fts3EofMethod,
146949  /* xColumn */ fts3ColumnMethod,
146950  /* xRowid */ fts3RowidMethod,
146951  /* xUpdate */ fts3UpdateMethod,
146952  /* xBegin */ fts3BeginMethod,
146953  /* xSync */ fts3SyncMethod,
146954  /* xCommit */ fts3CommitMethod,
146955  /* xRollback */ fts3RollbackMethod,
146956  /* xFindFunction */ fts3FindFunctionMethod,
146957  /* xRename */ fts3RenameMethod,
146958  /* xSavepoint */ fts3SavepointMethod,
146959  /* xRelease */ fts3ReleaseMethod,
146960  /* xRollbackTo */ fts3RollbackToMethod,
146961 };
146962 
146963 /*
146964 ** This function is registered as the module destructor (called when an
146965 ** FTS3 enabled database connection is closed). It frees the memory
146966 ** allocated for the tokenizer hash table.
146967 */
146968 static void hashDestroy(void *p){
146969  Fts3Hash *pHash = (Fts3Hash *)p;
146970  sqlite3Fts3HashClear(pHash);
146971  sqlite3_free(pHash);
146972 }
146973 
146974 /*
146975 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
146976 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
146977 ** respectively. The following three forward declarations are for functions
146978 ** declared in these files used to retrieve the respective implementations.
146979 **
146980 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
146981 ** to by the argument to point to the "simple" tokenizer implementation.
146982 ** And so on.
146983 */
146984 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
146985 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
146986 #ifndef SQLITE_DISABLE_FTS3_UNICODE
146987 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
146988 #endif
146989 #ifdef SQLITE_ENABLE_ICU
146990 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
146991 #endif
146992 
146993 /*
146994 ** Initialize the fts3 extension. If this extension is built as part
146995 ** of the sqlite library, then this function is called directly by
146996 ** SQLite. If fts3 is built as a dynamically loadable extension, this
146997 ** function is called by the sqlite3_extension_init() entry point.
146998 */
146999 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
147000  int rc = SQLITE_OK;
147001  Fts3Hash *pHash = 0;
147002  const sqlite3_tokenizer_module *pSimple = 0;
147003  const sqlite3_tokenizer_module *pPorter = 0;
147004 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147005  const sqlite3_tokenizer_module *pUnicode = 0;
147006 #endif
147007 
147008 #ifdef SQLITE_ENABLE_ICU
147009  const sqlite3_tokenizer_module *pIcu = 0;
147010  sqlite3Fts3IcuTokenizerModule(&pIcu);
147011 #endif
147012 
147013 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147014  sqlite3Fts3UnicodeTokenizer(&pUnicode);
147015 #endif
147016 
147017 #ifdef SQLITE_TEST
147018  rc = sqlite3Fts3InitTerm(db);
147019  if( rc!=SQLITE_OK ) return rc;
147020 #endif
147021 
147022  rc = sqlite3Fts3InitAux(db);
147023  if( rc!=SQLITE_OK ) return rc;
147024 
147025  sqlite3Fts3SimpleTokenizerModule(&pSimple);
147026  sqlite3Fts3PorterTokenizerModule(&pPorter);
147027 
147028  /* Allocate and initialize the hash-table used to store tokenizers. */
147029  pHash = sqlite3_malloc(sizeof(Fts3Hash));
147030  if( !pHash ){
147031  rc = SQLITE_NOMEM;
147032  }else{
147033  sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
147034  }
147035 
147036  /* Load the built-in tokenizers into the hash table */
147037  if( rc==SQLITE_OK ){
147038  if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
147039  || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
147040 
147041 #ifndef SQLITE_DISABLE_FTS3_UNICODE
147042  || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
147043 #endif
147044 #ifdef SQLITE_ENABLE_ICU
147045  || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
147046 #endif
147047  ){
147048  rc = SQLITE_NOMEM;
147049  }
147050  }
147051 
147052 #ifdef SQLITE_TEST
147053  if( rc==SQLITE_OK ){
147054  rc = sqlite3Fts3ExprInitTestInterface(db);
147055  }
147056 #endif
147057 
147058  /* Create the virtual table wrapper around the hash-table and overload
147059  ** the two scalar functions. If this is successful, register the
147060  ** module with sqlite.
147061  */
147062  if( SQLITE_OK==rc
147063  && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
147064  && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
147065  && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
147066  && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
147067  && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
147068  && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
147069  ){
147071  db, "fts3", &fts3Module, (void *)pHash, hashDestroy
147072  );
147073  if( rc==SQLITE_OK ){
147075  db, "fts4", &fts3Module, (void *)pHash, 0
147076  );
147077  }
147078  if( rc==SQLITE_OK ){
147079  rc = sqlite3Fts3InitTok(db, (void *)pHash);
147080  }
147081  return rc;
147082  }
147083 
147084 
147085  /* An error has occurred. Delete the hash table and return the error code. */
147086  assert( rc!=SQLITE_OK );
147087  if( pHash ){
147088  sqlite3Fts3HashClear(pHash);
147089  sqlite3_free(pHash);
147090  }
147091  return rc;
147092 }
147093 
147094 /*
147095 ** Allocate an Fts3MultiSegReader for each token in the expression headed
147096 ** by pExpr.
147097 **
147098 ** An Fts3SegReader object is a cursor that can seek or scan a range of
147099 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
147100 ** Fts3SegReader objects internally to provide an interface to seek or scan
147101 ** within the union of all segments of a b-tree. Hence the name.
147102 **
147103 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
147104 ** segment b-tree (if the term is not a prefix or it is a prefix for which
147105 ** there exists prefix b-tree of the right length) then it may be traversed
147106 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
147107 ** doclist and then traversed.
147108 */
147109 static void fts3EvalAllocateReaders(
147110  Fts3Cursor *pCsr, /* FTS cursor handle */
147111  Fts3Expr *pExpr, /* Allocate readers for this expression */
147112  int *pnToken, /* OUT: Total number of tokens in phrase. */
147113  int *pnOr, /* OUT: Total number of OR nodes in expr. */
147114  int *pRc /* IN/OUT: Error code */
147115 ){
147116  if( pExpr && SQLITE_OK==*pRc ){
147117  if( pExpr->eType==FTSQUERY_PHRASE ){
147118  int i;
147119  int nToken = pExpr->pPhrase->nToken;
147120  *pnToken += nToken;
147121  for(i=0; i<nToken; i++){
147122  Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
147123  int rc = fts3TermSegReaderCursor(pCsr,
147124  pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
147125  );
147126  if( rc!=SQLITE_OK ){
147127  *pRc = rc;
147128  return;
147129  }
147130  }
147131  assert( pExpr->pPhrase->iDoclistToken==0 );
147132  pExpr->pPhrase->iDoclistToken = -1;
147133  }else{
147134  *pnOr += (pExpr->eType==FTSQUERY_OR);
147135  fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
147136  fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
147137  }
147138  }
147139 }
147140 
147141 /*
147142 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
147143 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
147144 **
147145 ** This function assumes that pList points to a buffer allocated using
147146 ** sqlite3_malloc(). This function takes responsibility for eventually
147147 ** freeing the buffer.
147148 **
147149 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
147150 */
147151 static int fts3EvalPhraseMergeToken(
147152  Fts3Table *pTab, /* FTS Table pointer */
147153  Fts3Phrase *p, /* Phrase to merge pList/nList into */
147154  int iToken, /* Token pList/nList corresponds to */
147155  char *pList, /* Pointer to doclist */
147156  int nList /* Number of bytes in pList */
147157 ){
147158  int rc = SQLITE_OK;
147159  assert( iToken!=p->iDoclistToken );
147160 
147161  if( pList==0 ){
147162  sqlite3_free(p->doclist.aAll);
147163  p->doclist.aAll = 0;
147164  p->doclist.nAll = 0;
147165  }
147166 
147167  else if( p->iDoclistToken<0 ){
147168  p->doclist.aAll = pList;
147169  p->doclist.nAll = nList;
147170  }
147171 
147172  else if( p->doclist.aAll==0 ){
147173  sqlite3_free(pList);
147174  }
147175 
147176  else {
147177  char *pLeft;
147178  char *pRight;
147179  int nLeft;
147180  int nRight;
147181  int nDiff;
147182 
147183  if( p->iDoclistToken<iToken ){
147184  pLeft = p->doclist.aAll;
147185  nLeft = p->doclist.nAll;
147186  pRight = pList;
147187  nRight = nList;
147188  nDiff = iToken - p->iDoclistToken;
147189  }else{
147190  pRight = p->doclist.aAll;
147191  nRight = p->doclist.nAll;
147192  pLeft = pList;
147193  nLeft = nList;
147194  nDiff = p->iDoclistToken - iToken;
147195  }
147196 
147197  rc = fts3DoclistPhraseMerge(
147198  pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
147199  );
147200  sqlite3_free(pLeft);
147201  p->doclist.aAll = pRight;
147202  p->doclist.nAll = nRight;
147203  }
147204 
147205  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
147206  return rc;
147207 }
147208 
147209 /*
147210 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
147211 ** does not take deferred tokens into account.
147212 **
147213 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
147214 */
147215 static int fts3EvalPhraseLoad(
147216  Fts3Cursor *pCsr, /* FTS Cursor handle */
147217  Fts3Phrase *p /* Phrase object */
147218 ){
147219  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147220  int iToken;
147221  int rc = SQLITE_OK;
147222 
147223  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
147224  Fts3PhraseToken *pToken = &p->aToken[iToken];
147225  assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
147226 
147227  if( pToken->pSegcsr ){
147228  int nThis = 0;
147229  char *pThis = 0;
147230  rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
147231  if( rc==SQLITE_OK ){
147232  rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
147233  }
147234  }
147235  assert( pToken->pSegcsr==0 );
147236  }
147237 
147238  return rc;
147239 }
147240 
147241 /*
147242 ** This function is called on each phrase after the position lists for
147243 ** any deferred tokens have been loaded into memory. It updates the phrases
147244 ** current position list to include only those positions that are really
147245 ** instances of the phrase (after considering deferred tokens). If this
147246 ** means that the phrase does not appear in the current row, doclist.pList
147247 ** and doclist.nList are both zeroed.
147248 **
147249 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
147250 */
147251 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
147252  int iToken; /* Used to iterate through phrase tokens */
147253  char *aPoslist = 0; /* Position list for deferred tokens */
147254  int nPoslist = 0; /* Number of bytes in aPoslist */
147255  int iPrev = -1; /* Token number of previous deferred token */
147256 
147257  assert( pPhrase->doclist.bFreeList==0 );
147258 
147259  for(iToken=0; iToken<pPhrase->nToken; iToken++){
147260  Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
147261  Fts3DeferredToken *pDeferred = pToken->pDeferred;
147262 
147263  if( pDeferred ){
147264  char *pList;
147265  int nList;
147266  int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
147267  if( rc!=SQLITE_OK ) return rc;
147268 
147269  if( pList==0 ){
147270  sqlite3_free(aPoslist);
147271  pPhrase->doclist.pList = 0;
147272  pPhrase->doclist.nList = 0;
147273  return SQLITE_OK;
147274 
147275  }else if( aPoslist==0 ){
147276  aPoslist = pList;
147277  nPoslist = nList;
147278 
147279  }else{
147280  char *aOut = pList;
147281  char *p1 = aPoslist;
147282  char *p2 = aOut;
147283 
147284  assert( iPrev>=0 );
147285  fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
147286  sqlite3_free(aPoslist);
147287  aPoslist = pList;
147288  nPoslist = (int)(aOut - aPoslist);
147289  if( nPoslist==0 ){
147290  sqlite3_free(aPoslist);
147291  pPhrase->doclist.pList = 0;
147292  pPhrase->doclist.nList = 0;
147293  return SQLITE_OK;
147294  }
147295  }
147296  iPrev = iToken;
147297  }
147298  }
147299 
147300  if( iPrev>=0 ){
147301  int nMaxUndeferred = pPhrase->iDoclistToken;
147302  if( nMaxUndeferred<0 ){
147303  pPhrase->doclist.pList = aPoslist;
147304  pPhrase->doclist.nList = nPoslist;
147305  pPhrase->doclist.iDocid = pCsr->iPrevId;
147306  pPhrase->doclist.bFreeList = 1;
147307  }else{
147308  int nDistance;
147309  char *p1;
147310  char *p2;
147311  char *aOut;
147312 
147313  if( nMaxUndeferred>iPrev ){
147314  p1 = aPoslist;
147315  p2 = pPhrase->doclist.pList;
147316  nDistance = nMaxUndeferred - iPrev;
147317  }else{
147318  p1 = pPhrase->doclist.pList;
147319  p2 = aPoslist;
147320  nDistance = iPrev - nMaxUndeferred;
147321  }
147322 
147323  aOut = (char *)sqlite3_malloc(nPoslist+8);
147324  if( !aOut ){
147325  sqlite3_free(aPoslist);
147326  return SQLITE_NOMEM;
147327  }
147328 
147329  pPhrase->doclist.pList = aOut;
147330  if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
147331  pPhrase->doclist.bFreeList = 1;
147332  pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
147333  }else{
147334  sqlite3_free(aOut);
147335  pPhrase->doclist.pList = 0;
147336  pPhrase->doclist.nList = 0;
147337  }
147338  sqlite3_free(aPoslist);
147339  }
147340  }
147341 
147342  return SQLITE_OK;
147343 }
147344 
147345 /*
147346 ** Maximum number of tokens a phrase may have to be considered for the
147347 ** incremental doclists strategy.
147348 */
147349 #define MAX_INCR_PHRASE_TOKENS 4
147350 
147351 /*
147352 ** This function is called for each Fts3Phrase in a full-text query
147353 ** expression to initialize the mechanism for returning rows. Once this
147354 ** function has been called successfully on an Fts3Phrase, it may be
147355 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
147356 **
147357 ** If parameter bOptOk is true, then the phrase may (or may not) use the
147358 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
147359 ** memory within this call.
147360 **
147361 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
147362 */
147363 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
147364  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147365  int rc = SQLITE_OK; /* Error code */
147366  int i;
147367 
147368  /* Determine if doclists may be loaded from disk incrementally. This is
147369  ** possible if the bOptOk argument is true, the FTS doclists will be
147370  ** scanned in forward order, and the phrase consists of
147371  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
147372  ** tokens or prefix tokens that cannot use a prefix-index. */
147373  int bHaveIncr = 0;
147374  int bIncrOk = (bOptOk
147375  && pCsr->bDesc==pTab->bDescIdx
147376  && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
147377 #ifdef SQLITE_TEST
147378  && pTab->bNoIncrDoclist==0
147379 #endif
147380  );
147381  for(i=0; bIncrOk==1 && i<p->nToken; i++){
147382  Fts3PhraseToken *pToken = &p->aToken[i];
147383  if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
147384  bIncrOk = 0;
147385  }
147386  if( pToken->pSegcsr ) bHaveIncr = 1;
147387  }
147388 
147389  if( bIncrOk && bHaveIncr ){
147390  /* Use the incremental approach. */
147391  int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
147392  for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
147393  Fts3PhraseToken *pToken = &p->aToken[i];
147394  Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
147395  if( pSegcsr ){
147396  rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
147397  }
147398  }
147399  p->bIncr = 1;
147400  }else{
147401  /* Load the full doclist for the phrase into memory. */
147402  rc = fts3EvalPhraseLoad(pCsr, p);
147403  p->bIncr = 0;
147404  }
147405 
147406  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
147407  return rc;
147408 }
147409 
147410 /*
147411 ** This function is used to iterate backwards (from the end to start)
147412 ** through doclists. It is used by this module to iterate through phrase
147413 ** doclists in reverse and by the fts3_write.c module to iterate through
147414 ** pending-terms lists when writing to databases with "order=desc".
147415 **
147416 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
147417 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
147418 ** function iterates from the end of the doclist to the beginning.
147419 */
147420 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
147421  int bDescIdx, /* True if the doclist is desc */
147422  char *aDoclist, /* Pointer to entire doclist */
147423  int nDoclist, /* Length of aDoclist in bytes */
147424  char **ppIter, /* IN/OUT: Iterator pointer */
147425  sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
147426  int *pnList, /* OUT: List length pointer */
147427  u8 *pbEof /* OUT: End-of-file flag */
147428 ){
147429  char *p = *ppIter;
147430 
147431  assert( nDoclist>0 );
147432  assert( *pbEof==0 );
147433  assert( p || *piDocid==0 );
147434  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
147435 
147436  if( p==0 ){
147437  sqlite3_int64 iDocid = 0;
147438  char *pNext = 0;
147439  char *pDocid = aDoclist;
147440  char *pEnd = &aDoclist[nDoclist];
147441  int iMul = 1;
147442 
147443  while( pDocid<pEnd ){
147444  sqlite3_int64 iDelta;
147445  pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
147446  iDocid += (iMul * iDelta);
147447  pNext = pDocid;
147448  fts3PoslistCopy(0, &pDocid);
147449  while( pDocid<pEnd && *pDocid==0 ) pDocid++;
147450  iMul = (bDescIdx ? -1 : 1);
147451  }
147452 
147453  *pnList = (int)(pEnd - pNext);
147454  *ppIter = pNext;
147455  *piDocid = iDocid;
147456  }else{
147457  int iMul = (bDescIdx ? -1 : 1);
147458  sqlite3_int64 iDelta;
147459  fts3GetReverseVarint(&p, aDoclist, &iDelta);
147460  *piDocid -= (iMul * iDelta);
147461 
147462  if( p==aDoclist ){
147463  *pbEof = 1;
147464  }else{
147465  char *pSave = p;
147466  fts3ReversePoslist(aDoclist, &p);
147467  *pnList = (int)(pSave - p);
147468  }
147469  *ppIter = p;
147470  }
147471 }
147472 
147473 /*
147474 ** Iterate forwards through a doclist.
147475 */
147476 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
147477  int bDescIdx, /* True if the doclist is desc */
147478  char *aDoclist, /* Pointer to entire doclist */
147479  int nDoclist, /* Length of aDoclist in bytes */
147480  char **ppIter, /* IN/OUT: Iterator pointer */
147481  sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
147482  u8 *pbEof /* OUT: End-of-file flag */
147483 ){
147484  char *p = *ppIter;
147485 
147486  assert( nDoclist>0 );
147487  assert( *pbEof==0 );
147488  assert( p || *piDocid==0 );
147489  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
147490 
147491  if( p==0 ){
147492  p = aDoclist;
147493  p += sqlite3Fts3GetVarint(p, piDocid);
147494  }else{
147495  fts3PoslistCopy(0, &p);
147496  while( p<&aDoclist[nDoclist] && *p==0 ) p++;
147497  if( p>=&aDoclist[nDoclist] ){
147498  *pbEof = 1;
147499  }else{
147500  sqlite3_int64 iVar;
147501  p += sqlite3Fts3GetVarint(p, &iVar);
147502  *piDocid += ((bDescIdx ? -1 : 1) * iVar);
147503  }
147504  }
147505 
147506  *ppIter = p;
147507 }
147508 
147509 /*
147510 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
147511 ** to true if EOF is reached.
147512 */
147513 static void fts3EvalDlPhraseNext(
147514  Fts3Table *pTab,
147515  Fts3Doclist *pDL,
147516  u8 *pbEof
147517 ){
147518  char *pIter; /* Used to iterate through aAll */
147519  char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
147520 
147521  if( pDL->pNextDocid ){
147522  pIter = pDL->pNextDocid;
147523  }else{
147524  pIter = pDL->aAll;
147525  }
147526 
147527  if( pIter>=pEnd ){
147528  /* We have already reached the end of this doclist. EOF. */
147529  *pbEof = 1;
147530  }else{
147531  sqlite3_int64 iDelta;
147532  pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
147533  if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
147534  pDL->iDocid += iDelta;
147535  }else{
147536  pDL->iDocid -= iDelta;
147537  }
147538  pDL->pList = pIter;
147539  fts3PoslistCopy(0, &pIter);
147540  pDL->nList = (int)(pIter - pDL->pList);
147541 
147542  /* pIter now points just past the 0x00 that terminates the position-
147543  ** list for document pDL->iDocid. However, if this position-list was
147544  ** edited in place by fts3EvalNearTrim(), then pIter may not actually
147545  ** point to the start of the next docid value. The following line deals
147546  ** with this case by advancing pIter past the zero-padding added by
147547  ** fts3EvalNearTrim(). */
147548  while( pIter<pEnd && *pIter==0 ) pIter++;
147549 
147550  pDL->pNextDocid = pIter;
147551  assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
147552  *pbEof = 0;
147553  }
147554 }
147555 
147556 /*
147557 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
147558 */
147559 typedef struct TokenDoclist TokenDoclist;
147560 struct TokenDoclist {
147561  int bIgnore;
147562  sqlite3_int64 iDocid;
147563  char *pList;
147564  int nList;
147565 };
147566 
147567 /*
147568 ** Token pToken is an incrementally loaded token that is part of a
147569 ** multi-token phrase. Advance it to the next matching document in the
147570 ** database and populate output variable *p with the details of the new
147571 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
147572 **
147573 ** If an error occurs, return an SQLite error code. Otherwise, return
147574 ** SQLITE_OK.
147575 */
147576 static int incrPhraseTokenNext(
147577  Fts3Table *pTab, /* Virtual table handle */
147578  Fts3Phrase *pPhrase, /* Phrase to advance token of */
147579  int iToken, /* Specific token to advance */
147580  TokenDoclist *p, /* OUT: Docid and doclist for new entry */
147581  u8 *pbEof /* OUT: True if iterator is at EOF */
147582 ){
147583  int rc = SQLITE_OK;
147584 
147585  if( pPhrase->iDoclistToken==iToken ){
147586  assert( p->bIgnore==0 );
147587  assert( pPhrase->aToken[iToken].pSegcsr==0 );
147588  fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
147589  p->pList = pPhrase->doclist.pList;
147590  p->nList = pPhrase->doclist.nList;
147591  p->iDocid = pPhrase->doclist.iDocid;
147592  }else{
147593  Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
147594  assert( pToken->pDeferred==0 );
147595  assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
147596  if( pToken->pSegcsr ){
147597  assert( p->bIgnore==0 );
147598  rc = sqlite3Fts3MsrIncrNext(
147599  pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
147600  );
147601  if( p->pList==0 ) *pbEof = 1;
147602  }else{
147603  p->bIgnore = 1;
147604  }
147605  }
147606 
147607  return rc;
147608 }
147609 
147610 
147611 /*
147612 ** The phrase iterator passed as the second argument:
147613 **
147614 ** * features at least one token that uses an incremental doclist, and
147615 **
147616 ** * does not contain any deferred tokens.
147617 **
147618 ** Advance it to the next matching documnent in the database and populate
147619 ** the Fts3Doclist.pList and nList fields.
147620 **
147621 ** If there is no "next" entry and no error occurs, then *pbEof is set to
147622 ** 1 before returning. Otherwise, if no error occurs and the iterator is
147623 ** successfully advanced, *pbEof is set to 0.
147624 **
147625 ** If an error occurs, return an SQLite error code. Otherwise, return
147626 ** SQLITE_OK.
147627 */
147628 static int fts3EvalIncrPhraseNext(
147629  Fts3Cursor *pCsr, /* FTS Cursor handle */
147630  Fts3Phrase *p, /* Phrase object to advance to next docid */
147631  u8 *pbEof /* OUT: Set to 1 if EOF */
147632 ){
147633  int rc = SQLITE_OK;
147634  Fts3Doclist *pDL = &p->doclist;
147635  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147636  u8 bEof = 0;
147637 
147638  /* This is only called if it is guaranteed that the phrase has at least
147639  ** one incremental token. In which case the bIncr flag is set. */
147640  assert( p->bIncr==1 );
147641 
147642  if( p->nToken==1 && p->bIncr ){
147643  rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
147644  &pDL->iDocid, &pDL->pList, &pDL->nList
147645  );
147646  if( pDL->pList==0 ) bEof = 1;
147647  }else{
147648  int bDescDoclist = pCsr->bDesc;
147649  struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
147650 
147651  memset(a, 0, sizeof(a));
147652  assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
147653  assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
147654 
147655  while( bEof==0 ){
147656  int bMaxSet = 0;
147657  sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
147658  int i; /* Used to iterate through tokens */
147659 
147660  /* Advance the iterator for each token in the phrase once. */
147661  for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
147662  rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
147663  if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
147664  iMax = a[i].iDocid;
147665  bMaxSet = 1;
147666  }
147667  }
147668  assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
147669  assert( rc!=SQLITE_OK || bMaxSet );
147670 
147671  /* Keep advancing iterators until they all point to the same document */
147672  for(i=0; i<p->nToken; i++){
147673  while( rc==SQLITE_OK && bEof==0
147674  && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
147675  ){
147676  rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
147677  if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
147678  iMax = a[i].iDocid;
147679  i = 0;
147680  }
147681  }
147682  }
147683 
147684  /* Check if the current entries really are a phrase match */
147685  if( bEof==0 ){
147686  int nList = 0;
147687  int nByte = a[p->nToken-1].nList;
147688  char *aDoclist = sqlite3_malloc(nByte+1);
147689  if( !aDoclist ) return SQLITE_NOMEM;
147690  memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
147691 
147692  for(i=0; i<(p->nToken-1); i++){
147693  if( a[i].bIgnore==0 ){
147694  char *pL = a[i].pList;
147695  char *pR = aDoclist;
147696  char *pOut = aDoclist;
147697  int nDist = p->nToken-1-i;
147698  int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
147699  if( res==0 ) break;
147700  nList = (int)(pOut - aDoclist);
147701  }
147702  }
147703  if( i==(p->nToken-1) ){
147704  pDL->iDocid = iMax;
147705  pDL->pList = aDoclist;
147706  pDL->nList = nList;
147707  pDL->bFreeList = 1;
147708  break;
147709  }
147710  sqlite3_free(aDoclist);
147711  }
147712  }
147713  }
147714 
147715  *pbEof = bEof;
147716  return rc;
147717 }
147718 
147719 /*
147720 ** Attempt to move the phrase iterator to point to the next matching docid.
147721 ** If an error occurs, return an SQLite error code. Otherwise, return
147722 ** SQLITE_OK.
147723 **
147724 ** If there is no "next" entry and no error occurs, then *pbEof is set to
147725 ** 1 before returning. Otherwise, if no error occurs and the iterator is
147726 ** successfully advanced, *pbEof is set to 0.
147727 */
147728 static int fts3EvalPhraseNext(
147729  Fts3Cursor *pCsr, /* FTS Cursor handle */
147730  Fts3Phrase *p, /* Phrase object to advance to next docid */
147731  u8 *pbEof /* OUT: Set to 1 if EOF */
147732 ){
147733  int rc = SQLITE_OK;
147734  Fts3Doclist *pDL = &p->doclist;
147735  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147736 
147737  if( p->bIncr ){
147738  rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
147739  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
147740  sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
147741  &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
147742  );
147743  pDL->pList = pDL->pNextDocid;
147744  }else{
147745  fts3EvalDlPhraseNext(pTab, pDL, pbEof);
147746  }
147747 
147748  return rc;
147749 }
147750 
147751 /*
147752 **
147753 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147754 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
147755 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
147756 ** expressions for which all descendent tokens are deferred.
147757 **
147758 ** If parameter bOptOk is zero, then it is guaranteed that the
147759 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
147760 ** each phrase in the expression (subject to deferred token processing).
147761 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
147762 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
147763 **
147764 ** If an error occurs within this function, *pRc is set to an SQLite error
147765 ** code before returning.
147766 */
147767 static void fts3EvalStartReaders(
147768  Fts3Cursor *pCsr, /* FTS Cursor handle */
147769  Fts3Expr *pExpr, /* Expression to initialize phrases in */
147770  int *pRc /* IN/OUT: Error code */
147771 ){
147772  if( pExpr && SQLITE_OK==*pRc ){
147773  if( pExpr->eType==FTSQUERY_PHRASE ){
147774  int nToken = pExpr->pPhrase->nToken;
147775  if( nToken ){
147776  int i;
147777  for(i=0; i<nToken; i++){
147778  if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
147779  }
147780  pExpr->bDeferred = (i==nToken);
147781  }
147782  *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
147783  }else{
147784  fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
147785  fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
147786  pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
147787  }
147788  }
147789 }
147790 
147791 /*
147792 ** An array of the following structures is assembled as part of the process
147793 ** of selecting tokens to defer before the query starts executing (as part
147794 ** of the xFilter() method). There is one element in the array for each
147795 ** token in the FTS expression.
147796 **
147797 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
147798 ** to phrases that are connected only by AND and NEAR operators (not OR or
147799 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
147800 ** separately. The root of a tokens AND/NEAR cluster is stored in
147801 ** Fts3TokenAndCost.pRoot.
147802 */
147803 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
147804 struct Fts3TokenAndCost {
147805  Fts3Phrase *pPhrase; /* The phrase the token belongs to */
147806  int iToken; /* Position of token in phrase */
147807  Fts3PhraseToken *pToken; /* The token itself */
147808  Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
147809  int nOvfl; /* Number of overflow pages to load doclist */
147810  int iCol; /* The column the token must match */
147811 };
147812 
147813 /*
147814 ** This function is used to populate an allocated Fts3TokenAndCost array.
147815 **
147816 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147817 ** Otherwise, if an error occurs during execution, *pRc is set to an
147818 ** SQLite error code.
147819 */
147820 static void fts3EvalTokenCosts(
147821  Fts3Cursor *pCsr, /* FTS Cursor handle */
147822  Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
147823  Fts3Expr *pExpr, /* Expression to consider */
147824  Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
147825  Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
147826  int *pRc /* IN/OUT: Error code */
147827 ){
147828  if( *pRc==SQLITE_OK ){
147829  if( pExpr->eType==FTSQUERY_PHRASE ){
147830  Fts3Phrase *pPhrase = pExpr->pPhrase;
147831  int i;
147832  for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
147833  Fts3TokenAndCost *pTC = (*ppTC)++;
147834  pTC->pPhrase = pPhrase;
147835  pTC->iToken = i;
147836  pTC->pRoot = pRoot;
147837  pTC->pToken = &pPhrase->aToken[i];
147838  pTC->iCol = pPhrase->iColumn;
147839  *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
147840  }
147841  }else if( pExpr->eType!=FTSQUERY_NOT ){
147842  assert( pExpr->eType==FTSQUERY_OR
147843  || pExpr->eType==FTSQUERY_AND
147844  || pExpr->eType==FTSQUERY_NEAR
147845  );
147846  assert( pExpr->pLeft && pExpr->pRight );
147847  if( pExpr->eType==FTSQUERY_OR ){
147848  pRoot = pExpr->pLeft;
147849  **ppOr = pRoot;
147850  (*ppOr)++;
147851  }
147852  fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
147853  if( pExpr->eType==FTSQUERY_OR ){
147854  pRoot = pExpr->pRight;
147855  **ppOr = pRoot;
147856  (*ppOr)++;
147857  }
147858  fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
147859  }
147860  }
147861 }
147862 
147863 /*
147864 ** Determine the average document (row) size in pages. If successful,
147865 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
147866 ** an SQLite error code.
147867 **
147868 ** The average document size in pages is calculated by first calculating
147869 ** determining the average size in bytes, B. If B is less than the amount
147870 ** of data that will fit on a single leaf page of an intkey table in
147871 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
147872 ** the number of overflow pages consumed by a record B bytes in size.
147873 */
147874 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
147875  if( pCsr->nRowAvg==0 ){
147876  /* The average document size, which is required to calculate the cost
147877  ** of each doclist, has not yet been determined. Read the required
147878  ** data from the %_stat table to calculate it.
147879  **
147880  ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
147881  ** varints, where nCol is the number of columns in the FTS3 table.
147882  ** The first varint is the number of documents currently stored in
147883  ** the table. The following nCol varints contain the total amount of
147884  ** data stored in all rows of each column of the table, from left
147885  ** to right.
147886  */
147887  int rc;
147888  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
147889  sqlite3_stmt *pStmt;
147890  sqlite3_int64 nDoc = 0;
147891  sqlite3_int64 nByte = 0;
147892  const char *pEnd;
147893  const char *a;
147894 
147895  rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
147896  if( rc!=SQLITE_OK ) return rc;
147897  a = sqlite3_column_blob(pStmt, 0);
147898  assert( a );
147899 
147900  pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
147901  a += sqlite3Fts3GetVarint(a, &nDoc);
147902  while( a<pEnd ){
147903  a += sqlite3Fts3GetVarint(a, &nByte);
147904  }
147905  if( nDoc==0 || nByte==0 ){
147906  sqlite3_reset(pStmt);
147907  return FTS_CORRUPT_VTAB;
147908  }
147909 
147910  pCsr->nDoc = nDoc;
147911  pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
147912  assert( pCsr->nRowAvg>0 );
147913  rc = sqlite3_reset(pStmt);
147914  if( rc!=SQLITE_OK ) return rc;
147915  }
147916 
147917  *pnPage = pCsr->nRowAvg;
147918  return SQLITE_OK;
147919 }
147920 
147921 /*
147922 ** This function is called to select the tokens (if any) that will be
147923 ** deferred. The array aTC[] has already been populated when this is
147924 ** called.
147925 **
147926 ** This function is called once for each AND/NEAR cluster in the
147927 ** expression. Each invocation determines which tokens to defer within
147928 ** the cluster with root node pRoot. See comments above the definition
147929 ** of struct Fts3TokenAndCost for more details.
147930 **
147931 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
147932 ** called on each token to defer. Otherwise, an SQLite error code is
147933 ** returned.
147934 */
147935 static int fts3EvalSelectDeferred(
147936  Fts3Cursor *pCsr, /* FTS Cursor handle */
147937  Fts3Expr *pRoot, /* Consider tokens with this root node */
147938  Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
147939  int nTC /* Number of entries in aTC[] */
147940 ){
147941  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147942  int nDocSize = 0; /* Number of pages per doc loaded */
147943  int rc = SQLITE_OK; /* Return code */
147944  int ii; /* Iterator variable for various purposes */
147945  int nOvfl = 0; /* Total overflow pages used by doclists */
147946  int nToken = 0; /* Total number of tokens in cluster */
147947 
147948  int nMinEst = 0; /* The minimum count for any phrase so far. */
147949  int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
147950 
147951  /* Tokens are never deferred for FTS tables created using the content=xxx
147952  ** option. The reason being that it is not guaranteed that the content
147953  ** table actually contains the same data as the index. To prevent this from
147954  ** causing any problems, the deferred token optimization is completely
147955  ** disabled for content=xxx tables. */
147956  if( pTab->zContentTbl ){
147957  return SQLITE_OK;
147958  }
147959 
147960  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
147961  ** associated with the tokens spill onto overflow pages, or if there is
147962  ** only 1 token, exit early. No tokens to defer in this case. */
147963  for(ii=0; ii<nTC; ii++){
147964  if( aTC[ii].pRoot==pRoot ){
147965  nOvfl += aTC[ii].nOvfl;
147966  nToken++;
147967  }
147968  }
147969  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
147970 
147971  /* Obtain the average docsize (in pages). */
147972  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
147973  assert( rc!=SQLITE_OK || nDocSize>0 );
147974 
147975 
147976  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
147977  ** of the number of overflow pages that will be loaded by the pager layer
147978  ** to retrieve the entire doclist for the token from the full-text index.
147979  ** Load the doclists for tokens that are either:
147980  **
147981  ** a. The cheapest token in the entire query (i.e. the one visited by the
147982  ** first iteration of this loop), or
147983  **
147984  ** b. Part of a multi-token phrase.
147985  **
147986  ** After each token doclist is loaded, merge it with the others from the
147987  ** same phrase and count the number of documents that the merged doclist
147988  ** contains. Set variable "nMinEst" to the smallest number of documents in
147989  ** any phrase doclist for which 1 or more token doclists have been loaded.
147990  ** Let nOther be the number of other phrases for which it is certain that
147991  ** one or more tokens will not be deferred.
147992  **
147993  ** Then, for each token, defer it if loading the doclist would result in
147994  ** loading N or more overflow pages into memory, where N is computed as:
147995  **
147996  ** (nMinEst + 4^nOther - 1) / (4^nOther)
147997  */
147998  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
147999  int iTC; /* Used to iterate through aTC[] array. */
148000  Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
148001 
148002  /* Set pTC to point to the cheapest remaining token. */
148003  for(iTC=0; iTC<nTC; iTC++){
148004  if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
148005  && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
148006  ){
148007  pTC = &aTC[iTC];
148008  }
148009  }
148010  assert( pTC );
148011 
148012  if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
148013  /* The number of overflow pages to load for this (and therefore all
148014  ** subsequent) tokens is greater than the estimated number of pages
148015  ** that will be loaded if all subsequent tokens are deferred.
148016  */
148017  Fts3PhraseToken *pToken = pTC->pToken;
148018  rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
148019  fts3SegReaderCursorFree(pToken->pSegcsr);
148020  pToken->pSegcsr = 0;
148021  }else{
148022  /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
148023  ** for-loop. Except, limit the value to 2^24 to prevent it from
148024  ** overflowing the 32-bit integer it is stored in. */
148025  if( ii<12 ) nLoad4 = nLoad4*4;
148026 
148027  if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
148028  /* Either this is the cheapest token in the entire query, or it is
148029  ** part of a multi-token phrase. Either way, the entire doclist will
148030  ** (eventually) be loaded into memory. It may as well be now. */
148031  Fts3PhraseToken *pToken = pTC->pToken;
148032  int nList = 0;
148033  char *pList = 0;
148034  rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
148035  assert( rc==SQLITE_OK || pList==0 );
148036  if( rc==SQLITE_OK ){
148037  rc = fts3EvalPhraseMergeToken(
148038  pTab, pTC->pPhrase, pTC->iToken,pList,nList
148039  );
148040  }
148041  if( rc==SQLITE_OK ){
148042  int nCount;
148043  nCount = fts3DoclistCountDocids(
148044  pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
148045  );
148046  if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
148047  }
148048  }
148049  }
148050  pTC->pToken = 0;
148051  }
148052 
148053  return rc;
148054 }
148055 
148056 /*
148057 ** This function is called from within the xFilter method. It initializes
148058 ** the full-text query currently stored in pCsr->pExpr. To iterate through
148059 ** the results of a query, the caller does:
148060 **
148061 ** fts3EvalStart(pCsr);
148062 ** while( 1 ){
148063 ** fts3EvalNext(pCsr);
148064 ** if( pCsr->bEof ) break;
148065 ** ... return row pCsr->iPrevId to the caller ...
148066 ** }
148067 */
148068 static int fts3EvalStart(Fts3Cursor *pCsr){
148069  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148070  int rc = SQLITE_OK;
148071  int nToken = 0;
148072  int nOr = 0;
148073 
148074  /* Allocate a MultiSegReader for each token in the expression. */
148075  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
148076 
148077  /* Determine which, if any, tokens in the expression should be deferred. */
148078 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
148079  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
148080  Fts3TokenAndCost *aTC;
148081  Fts3Expr **apOr;
148082  aTC = (Fts3TokenAndCost *)sqlite3_malloc(
148083  sizeof(Fts3TokenAndCost) * nToken
148084  + sizeof(Fts3Expr *) * nOr * 2
148085  );
148086  apOr = (Fts3Expr **)&aTC[nToken];
148087 
148088  if( !aTC ){
148089  rc = SQLITE_NOMEM;
148090  }else{
148091  int ii;
148092  Fts3TokenAndCost *pTC = aTC;
148093  Fts3Expr **ppOr = apOr;
148094 
148095  fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
148096  nToken = (int)(pTC-aTC);
148097  nOr = (int)(ppOr-apOr);
148098 
148099  if( rc==SQLITE_OK ){
148100  rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
148101  for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
148102  rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
148103  }
148104  }
148105 
148106  sqlite3_free(aTC);
148107  }
148108  }
148109 #endif
148110 
148111  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
148112  return rc;
148113 }
148114 
148115 /*
148116 ** Invalidate the current position list for phrase pPhrase.
148117 */
148118 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
148119  if( pPhrase->doclist.bFreeList ){
148120  sqlite3_free(pPhrase->doclist.pList);
148121  }
148122  pPhrase->doclist.pList = 0;
148123  pPhrase->doclist.nList = 0;
148124  pPhrase->doclist.bFreeList = 0;
148125 }
148126 
148127 /*
148128 ** This function is called to edit the position list associated with
148129 ** the phrase object passed as the fifth argument according to a NEAR
148130 ** condition. For example:
148131 **
148132 ** abc NEAR/5 "def ghi"
148133 **
148134 ** Parameter nNear is passed the NEAR distance of the expression (5 in
148135 ** the example above). When this function is called, *paPoslist points to
148136 ** the position list, and *pnToken is the number of phrase tokens in, the
148137 ** phrase on the other side of the NEAR operator to pPhrase. For example,
148138 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
148139 ** the position list associated with phrase "abc".
148140 **
148141 ** All positions in the pPhrase position list that are not sufficiently
148142 ** close to a position in the *paPoslist position list are removed. If this
148143 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
148144 **
148145 ** Before returning, *paPoslist is set to point to the position lsit
148146 ** associated with pPhrase. And *pnToken is set to the number of tokens in
148147 ** pPhrase.
148148 */
148149 static int fts3EvalNearTrim(
148150  int nNear, /* NEAR distance. As in "NEAR/nNear". */
148151  char *aTmp, /* Temporary space to use */
148152  char **paPoslist, /* IN/OUT: Position list */
148153  int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
148154  Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
148155 ){
148156  int nParam1 = nNear + pPhrase->nToken;
148157  int nParam2 = nNear + *pnToken;
148158  int nNew;
148159  char *p2;
148160  char *pOut;
148161  int res;
148162 
148163  assert( pPhrase->doclist.pList );
148164 
148165  p2 = pOut = pPhrase->doclist.pList;
148166  res = fts3PoslistNearMerge(
148167  &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
148168  );
148169  if( res ){
148170  nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
148171  assert( pPhrase->doclist.pList[nNew]=='\0' );
148172  assert( nNew<=pPhrase->doclist.nList && nNew>0 );
148173  memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
148174  pPhrase->doclist.nList = nNew;
148175  *paPoslist = pPhrase->doclist.pList;
148176  *pnToken = pPhrase->nToken;
148177  }
148178 
148179  return res;
148180 }
148181 
148182 /*
148183 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
148184 ** Otherwise, it advances the expression passed as the second argument to
148185 ** point to the next matching row in the database. Expressions iterate through
148186 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
148187 ** or descending if it is non-zero.
148188 **
148189 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
148190 ** successful, the following variables in pExpr are set:
148191 **
148192 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
148193 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
148194 **
148195 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
148196 ** at EOF, then the following variables are populated with the position list
148197 ** for the phrase for the visited row:
148198 **
148199 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
148200 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
148201 **
148202 ** It says above that this function advances the expression to the next
148203 ** matching row. This is usually true, but there are the following exceptions:
148204 **
148205 ** 1. Deferred tokens are not taken into account. If a phrase consists
148206 ** entirely of deferred tokens, it is assumed to match every row in
148207 ** the db. In this case the position-list is not populated at all.
148208 **
148209 ** Or, if a phrase contains one or more deferred tokens and one or
148210 ** more non-deferred tokens, then the expression is advanced to the
148211 ** next possible match, considering only non-deferred tokens. In other
148212 ** words, if the phrase is "A B C", and "B" is deferred, the expression
148213 ** is advanced to the next row that contains an instance of "A * C",
148214 ** where "*" may match any single token. The position list in this case
148215 ** is populated as for "A * C" before returning.
148216 **
148217 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
148218 ** advanced to point to the next row that matches "x AND y".
148219 **
148220 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
148221 ** really a match, taking into account deferred tokens and NEAR operators.
148222 */
148223 static void fts3EvalNextRow(
148224  Fts3Cursor *pCsr, /* FTS Cursor handle */
148225  Fts3Expr *pExpr, /* Expr. to advance to next matching row */
148226  int *pRc /* IN/OUT: Error code */
148227 ){
148228  if( *pRc==SQLITE_OK ){
148229  int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
148230  assert( pExpr->bEof==0 );
148231  pExpr->bStart = 1;
148232 
148233  switch( pExpr->eType ){
148234  case FTSQUERY_NEAR:
148235  case FTSQUERY_AND: {
148236  Fts3Expr *pLeft = pExpr->pLeft;
148237  Fts3Expr *pRight = pExpr->pRight;
148238  assert( !pLeft->bDeferred || !pRight->bDeferred );
148239 
148240  if( pLeft->bDeferred ){
148241  /* LHS is entirely deferred. So we assume it matches every row.
148242  ** Advance the RHS iterator to find the next row visited. */
148243  fts3EvalNextRow(pCsr, pRight, pRc);
148244  pExpr->iDocid = pRight->iDocid;
148245  pExpr->bEof = pRight->bEof;
148246  }else if( pRight->bDeferred ){
148247  /* RHS is entirely deferred. So we assume it matches every row.
148248  ** Advance the LHS iterator to find the next row visited. */
148249  fts3EvalNextRow(pCsr, pLeft, pRc);
148250  pExpr->iDocid = pLeft->iDocid;
148251  pExpr->bEof = pLeft->bEof;
148252  }else{
148253  /* Neither the RHS or LHS are deferred. */
148254  fts3EvalNextRow(pCsr, pLeft, pRc);
148255  fts3EvalNextRow(pCsr, pRight, pRc);
148256  while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
148257  sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
148258  if( iDiff==0 ) break;
148259  if( iDiff<0 ){
148260  fts3EvalNextRow(pCsr, pLeft, pRc);
148261  }else{
148262  fts3EvalNextRow(pCsr, pRight, pRc);
148263  }
148264  }
148265  pExpr->iDocid = pLeft->iDocid;
148266  pExpr->bEof = (pLeft->bEof || pRight->bEof);
148267  if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
148268  if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
148269  Fts3Doclist *pDl = &pRight->pPhrase->doclist;
148270  while( *pRc==SQLITE_OK && pRight->bEof==0 ){
148271  memset(pDl->pList, 0, pDl->nList);
148272  fts3EvalNextRow(pCsr, pRight, pRc);
148273  }
148274  }
148275  if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
148276  Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
148277  while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
148278  memset(pDl->pList, 0, pDl->nList);
148279  fts3EvalNextRow(pCsr, pLeft, pRc);
148280  }
148281  }
148282  }
148283  }
148284  break;
148285  }
148286 
148287  case FTSQUERY_OR: {
148288  Fts3Expr *pLeft = pExpr->pLeft;
148289  Fts3Expr *pRight = pExpr->pRight;
148290  sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
148291 
148292  assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
148293  assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
148294 
148295  if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
148296  fts3EvalNextRow(pCsr, pLeft, pRc);
148297  }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
148298  fts3EvalNextRow(pCsr, pRight, pRc);
148299  }else{
148300  fts3EvalNextRow(pCsr, pLeft, pRc);
148301  fts3EvalNextRow(pCsr, pRight, pRc);
148302  }
148303 
148304  pExpr->bEof = (pLeft->bEof && pRight->bEof);
148305  iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
148306  if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
148307  pExpr->iDocid = pLeft->iDocid;
148308  }else{
148309  pExpr->iDocid = pRight->iDocid;
148310  }
148311 
148312  break;
148313  }
148314 
148315  case FTSQUERY_NOT: {
148316  Fts3Expr *pLeft = pExpr->pLeft;
148317  Fts3Expr *pRight = pExpr->pRight;
148318 
148319  if( pRight->bStart==0 ){
148320  fts3EvalNextRow(pCsr, pRight, pRc);
148321  assert( *pRc!=SQLITE_OK || pRight->bStart );
148322  }
148323 
148324  fts3EvalNextRow(pCsr, pLeft, pRc);
148325  if( pLeft->bEof==0 ){
148326  while( !*pRc
148327  && !pRight->bEof
148328  && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
148329  ){
148330  fts3EvalNextRow(pCsr, pRight, pRc);
148331  }
148332  }
148333  pExpr->iDocid = pLeft->iDocid;
148334  pExpr->bEof = pLeft->bEof;
148335  break;
148336  }
148337 
148338  default: {
148339  Fts3Phrase *pPhrase = pExpr->pPhrase;
148340  fts3EvalInvalidatePoslist(pPhrase);
148341  *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
148342  pExpr->iDocid = pPhrase->doclist.iDocid;
148343  break;
148344  }
148345  }
148346  }
148347 }
148348 
148349 /*
148350 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
148351 ** cluster, then this function returns 1 immediately.
148352 **
148353 ** Otherwise, it checks if the current row really does match the NEAR
148354 ** expression, using the data currently stored in the position lists
148355 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
148356 **
148357 ** If the current row is a match, the position list associated with each
148358 ** phrase in the NEAR expression is edited in place to contain only those
148359 ** phrase instances sufficiently close to their peers to satisfy all NEAR
148360 ** constraints. In this case it returns 1. If the NEAR expression does not
148361 ** match the current row, 0 is returned. The position lists may or may not
148362 ** be edited if 0 is returned.
148363 */
148364 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
148365  int res = 1;
148366 
148367  /* The following block runs if pExpr is the root of a NEAR query.
148368  ** For example, the query:
148369  **
148370  ** "w" NEAR "x" NEAR "y" NEAR "z"
148371  **
148372  ** which is represented in tree form as:
148373  **
148374  ** |
148375  ** +--NEAR--+ <-- root of NEAR query
148376  ** | |
148377  ** +--NEAR--+ "z"
148378  ** | |
148379  ** +--NEAR--+ "y"
148380  ** | |
148381  ** "w" "x"
148382  **
148383  ** The right-hand child of a NEAR node is always a phrase. The
148384  ** left-hand child may be either a phrase or a NEAR node. There are
148385  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
148386  */
148387  if( *pRc==SQLITE_OK
148388  && pExpr->eType==FTSQUERY_NEAR
148389  && pExpr->bEof==0
148390  && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
148391  ){
148392  Fts3Expr *p;
148393  int nTmp = 0; /* Bytes of temp space */
148394  char *aTmp; /* Temp space for PoslistNearMerge() */
148395 
148396  /* Allocate temporary working space. */
148397  for(p=pExpr; p->pLeft; p=p->pLeft){
148398  nTmp += p->pRight->pPhrase->doclist.nList;
148399  }
148400  nTmp += p->pPhrase->doclist.nList;
148401  if( nTmp==0 ){
148402  res = 0;
148403  }else{
148404  aTmp = sqlite3_malloc(nTmp*2);
148405  if( !aTmp ){
148406  *pRc = SQLITE_NOMEM;
148407  res = 0;
148408  }else{
148409  char *aPoslist = p->pPhrase->doclist.pList;
148410  int nToken = p->pPhrase->nToken;
148411 
148412  for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
148413  Fts3Phrase *pPhrase = p->pRight->pPhrase;
148414  int nNear = p->nNear;
148415  res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
148416  }
148417 
148418  aPoslist = pExpr->pRight->pPhrase->doclist.pList;
148419  nToken = pExpr->pRight->pPhrase->nToken;
148420  for(p=pExpr->pLeft; p && res; p=p->pLeft){
148421  int nNear;
148422  Fts3Phrase *pPhrase;
148423  assert( p->pParent && p->pParent->pLeft==p );
148424  nNear = p->pParent->nNear;
148425  pPhrase = (
148426  p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
148427  );
148428  res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
148429  }
148430  }
148431 
148432  sqlite3_free(aTmp);
148433  }
148434  }
148435 
148436  return res;
148437 }
148438 
148439 /*
148440 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
148441 ** Assuming no error occurs or has occurred, It returns non-zero if the
148442 ** expression passed as the second argument matches the row that pCsr
148443 ** currently points to, or zero if it does not.
148444 **
148445 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
148446 ** If an error occurs during execution of this function, *pRc is set to
148447 ** the appropriate SQLite error code. In this case the returned value is
148448 ** undefined.
148449 */
148450 static int fts3EvalTestExpr(
148451  Fts3Cursor *pCsr, /* FTS cursor handle */
148452  Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
148453  int *pRc /* IN/OUT: Error code */
148454 ){
148455  int bHit = 1; /* Return value */
148456  if( *pRc==SQLITE_OK ){
148457  switch( pExpr->eType ){
148458  case FTSQUERY_NEAR:
148459  case FTSQUERY_AND:
148460  bHit = (
148461  fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
148462  && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
148463  && fts3EvalNearTest(pExpr, pRc)
148464  );
148465 
148466  /* If the NEAR expression does not match any rows, zero the doclist for
148467  ** all phrases involved in the NEAR. This is because the snippet(),
148468  ** offsets() and matchinfo() functions are not supposed to recognize
148469  ** any instances of phrases that are part of unmatched NEAR queries.
148470  ** For example if this expression:
148471  **
148472  ** ... MATCH 'a OR (b NEAR c)'
148473  **
148474  ** is matched against a row containing:
148475  **
148476  ** 'a b d e'
148477  **
148478  ** then any snippet() should ony highlight the "a" term, not the "b"
148479  ** (as "b" is part of a non-matching NEAR clause).
148480  */
148481  if( bHit==0
148482  && pExpr->eType==FTSQUERY_NEAR
148483  && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
148484  ){
148485  Fts3Expr *p;
148486  for(p=pExpr; p->pPhrase==0; p=p->pLeft){
148487  if( p->pRight->iDocid==pCsr->iPrevId ){
148488  fts3EvalInvalidatePoslist(p->pRight->pPhrase);
148489  }
148490  }
148491  if( p->iDocid==pCsr->iPrevId ){
148492  fts3EvalInvalidatePoslist(p->pPhrase);
148493  }
148494  }
148495 
148496  break;
148497 
148498  case FTSQUERY_OR: {
148499  int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
148500  int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
148501  bHit = bHit1 || bHit2;
148502  break;
148503  }
148504 
148505  case FTSQUERY_NOT:
148506  bHit = (
148507  fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
148508  && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
148509  );
148510  break;
148511 
148512  default: {
148513 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
148514  if( pCsr->pDeferred
148515  && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
148516  ){
148517  Fts3Phrase *pPhrase = pExpr->pPhrase;
148518  assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
148519  if( pExpr->bDeferred ){
148520  fts3EvalInvalidatePoslist(pPhrase);
148521  }
148522  *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
148523  bHit = (pPhrase->doclist.pList!=0);
148524  pExpr->iDocid = pCsr->iPrevId;
148525  }else
148526 #endif
148527  {
148528  bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
148529  }
148530  break;
148531  }
148532  }
148533  }
148534  return bHit;
148535 }
148536 
148537 /*
148538 ** This function is called as the second part of each xNext operation when
148539 ** iterating through the results of a full-text query. At this point the
148540 ** cursor points to a row that matches the query expression, with the
148541 ** following caveats:
148542 **
148543 ** * Up until this point, "NEAR" operators in the expression have been
148544 ** treated as "AND".
148545 **
148546 ** * Deferred tokens have not yet been considered.
148547 **
148548 ** If *pRc is not SQLITE_OK when this function is called, it immediately
148549 ** returns 0. Otherwise, it tests whether or not after considering NEAR
148550 ** operators and deferred tokens the current row is still a match for the
148551 ** expression. It returns 1 if both of the following are true:
148552 **
148553 ** 1. *pRc is SQLITE_OK when this function returns, and
148554 **
148555 ** 2. After scanning the current FTS table row for the deferred tokens,
148556 ** it is determined that the row does *not* match the query.
148557 **
148558 ** Or, if no error occurs and it seems the current row does match the FTS
148559 ** query, return 0.
148560 */
148561 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
148562  int rc = *pRc;
148563  int bMiss = 0;
148564  if( rc==SQLITE_OK ){
148565 
148566  /* If there are one or more deferred tokens, load the current row into
148567  ** memory and scan it to determine the position list for each deferred
148568  ** token. Then, see if this row is really a match, considering deferred
148569  ** tokens and NEAR operators (neither of which were taken into account
148570  ** earlier, by fts3EvalNextRow()).
148571  */
148572  if( pCsr->pDeferred ){
148573  rc = fts3CursorSeek(0, pCsr);
148574  if( rc==SQLITE_OK ){
148575  rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
148576  }
148577  }
148578  bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
148579 
148580  /* Free the position-lists accumulated for each deferred token above. */
148581  sqlite3Fts3FreeDeferredDoclists(pCsr);
148582  *pRc = rc;
148583  }
148584  return (rc==SQLITE_OK && bMiss);
148585 }
148586 
148587 /*
148588 ** Advance to the next document that matches the FTS expression in
148589 ** Fts3Cursor.pExpr.
148590 */
148591 static int fts3EvalNext(Fts3Cursor *pCsr){
148592  int rc = SQLITE_OK; /* Return Code */
148593  Fts3Expr *pExpr = pCsr->pExpr;
148594  assert( pCsr->isEof==0 );
148595  if( pExpr==0 ){
148596  pCsr->isEof = 1;
148597  }else{
148598  do {
148599  if( pCsr->isRequireSeek==0 ){
148600  sqlite3_reset(pCsr->pStmt);
148601  }
148602  assert( sqlite3_data_count(pCsr->pStmt)==0 );
148603  fts3EvalNextRow(pCsr, pExpr, &rc);
148604  pCsr->isEof = pExpr->bEof;
148605  pCsr->isRequireSeek = 1;
148606  pCsr->isMatchinfoNeeded = 1;
148607  pCsr->iPrevId = pExpr->iDocid;
148608  }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
148609  }
148610 
148611  /* Check if the cursor is past the end of the docid range specified
148612  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
148613  if( rc==SQLITE_OK && (
148614  (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
148615  || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
148616  )){
148617  pCsr->isEof = 1;
148618  }
148619 
148620  return rc;
148621 }
148622 
148623 /*
148624 ** Restart interation for expression pExpr so that the next call to
148625 ** fts3EvalNext() visits the first row. Do not allow incremental
148626 ** loading or merging of phrase doclists for this iteration.
148627 **
148628 ** If *pRc is other than SQLITE_OK when this function is called, it is
148629 ** a no-op. If an error occurs within this function, *pRc is set to an
148630 ** SQLite error code before returning.
148631 */
148632 static void fts3EvalRestart(
148633  Fts3Cursor *pCsr,
148634  Fts3Expr *pExpr,
148635  int *pRc
148636 ){
148637  if( pExpr && *pRc==SQLITE_OK ){
148638  Fts3Phrase *pPhrase = pExpr->pPhrase;
148639 
148640  if( pPhrase ){
148641  fts3EvalInvalidatePoslist(pPhrase);
148642  if( pPhrase->bIncr ){
148643  int i;
148644  for(i=0; i<pPhrase->nToken; i++){
148645  Fts3PhraseToken *pToken = &pPhrase->aToken[i];
148646  assert( pToken->pDeferred==0 );
148647  if( pToken->pSegcsr ){
148648  sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
148649  }
148650  }
148651  *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
148652  }
148653  pPhrase->doclist.pNextDocid = 0;
148654  pPhrase->doclist.iDocid = 0;
148655  pPhrase->pOrPoslist = 0;
148656  }
148657 
148658  pExpr->iDocid = 0;
148659  pExpr->bEof = 0;
148660  pExpr->bStart = 0;
148661 
148662  fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
148663  fts3EvalRestart(pCsr, pExpr->pRight, pRc);
148664  }
148665 }
148666 
148667 /*
148668 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
148669 ** expression rooted at pExpr, the cursor iterates through all rows matched
148670 ** by pExpr, calling this function for each row. This function increments
148671 ** the values in Fts3Expr.aMI[] according to the position-list currently
148672 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
148673 ** expression nodes.
148674 */
148675 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
148676  if( pExpr ){
148677  Fts3Phrase *pPhrase = pExpr->pPhrase;
148678  if( pPhrase && pPhrase->doclist.pList ){
148679  int iCol = 0;
148680  char *p = pPhrase->doclist.pList;
148681 
148682  assert( *p );
148683  while( 1 ){
148684  u8 c = 0;
148685  int iCnt = 0;
148686  while( 0xFE & (*p | c) ){
148687  if( (c&0x80)==0 ) iCnt++;
148688  c = *p++ & 0x80;
148689  }
148690 
148691  /* aMI[iCol*3 + 1] = Number of occurrences
148692  ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
148693  */
148694  pExpr->aMI[iCol*3 + 1] += iCnt;
148695  pExpr->aMI[iCol*3 + 2] += (iCnt>0);
148696  if( *p==0x00 ) break;
148697  p++;
148698  p += fts3GetVarint32(p, &iCol);
148699  }
148700  }
148701 
148702  fts3EvalUpdateCounts(pExpr->pLeft);
148703  fts3EvalUpdateCounts(pExpr->pRight);
148704  }
148705 }
148706 
148707 /*
148708 ** Expression pExpr must be of type FTSQUERY_PHRASE.
148709 **
148710 ** If it is not already allocated and populated, this function allocates and
148711 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
148712 ** of a NEAR expression, then it also allocates and populates the same array
148713 ** for all other phrases that are part of the NEAR expression.
148714 **
148715 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
148716 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
148717 */
148718 static int fts3EvalGatherStats(
148719  Fts3Cursor *pCsr, /* Cursor object */
148720  Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
148721 ){
148722  int rc = SQLITE_OK; /* Return code */
148723 
148724  assert( pExpr->eType==FTSQUERY_PHRASE );
148725  if( pExpr->aMI==0 ){
148726  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148727  Fts3Expr *pRoot; /* Root of NEAR expression */
148728  Fts3Expr *p; /* Iterator used for several purposes */
148729 
148730  sqlite3_int64 iPrevId = pCsr->iPrevId;
148731  sqlite3_int64 iDocid;
148732  u8 bEof;
148733 
148734  /* Find the root of the NEAR expression */
148735  pRoot = pExpr;
148736  while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
148737  pRoot = pRoot->pParent;
148738  }
148739  iDocid = pRoot->iDocid;
148740  bEof = pRoot->bEof;
148741  assert( pRoot->bStart );
148742 
148743  /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
148744  for(p=pRoot; p; p=p->pLeft){
148745  Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
148746  assert( pE->aMI==0 );
148747  pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
148748  if( !pE->aMI ) return SQLITE_NOMEM;
148749  memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
148750  }
148751 
148752  fts3EvalRestart(pCsr, pRoot, &rc);
148753 
148754  while( pCsr->isEof==0 && rc==SQLITE_OK ){
148755 
148756  do {
148757  /* Ensure the %_content statement is reset. */
148758  if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
148759  assert( sqlite3_data_count(pCsr->pStmt)==0 );
148760 
148761  /* Advance to the next document */
148762  fts3EvalNextRow(pCsr, pRoot, &rc);
148763  pCsr->isEof = pRoot->bEof;
148764  pCsr->isRequireSeek = 1;
148765  pCsr->isMatchinfoNeeded = 1;
148766  pCsr->iPrevId = pRoot->iDocid;
148767  }while( pCsr->isEof==0
148768  && pRoot->eType==FTSQUERY_NEAR
148769  && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
148770  );
148771 
148772  if( rc==SQLITE_OK && pCsr->isEof==0 ){
148773  fts3EvalUpdateCounts(pRoot);
148774  }
148775  }
148776 
148777  pCsr->isEof = 0;
148778  pCsr->iPrevId = iPrevId;
148779 
148780  if( bEof ){
148781  pRoot->bEof = bEof;
148782  }else{
148783  /* Caution: pRoot may iterate through docids in ascending or descending
148784  ** order. For this reason, even though it seems more defensive, the
148785  ** do loop can not be written:
148786  **
148787  ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
148788  */
148789  fts3EvalRestart(pCsr, pRoot, &rc);
148790  do {
148791  fts3EvalNextRow(pCsr, pRoot, &rc);
148792  assert( pRoot->bEof==0 );
148793  }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
148794  }
148795  }
148796  return rc;
148797 }
148798 
148799 /*
148800 ** This function is used by the matchinfo() module to query a phrase
148801 ** expression node for the following information:
148802 **
148803 ** 1. The total number of occurrences of the phrase in each column of
148804 ** the FTS table (considering all rows), and
148805 **
148806 ** 2. For each column, the number of rows in the table for which the
148807 ** column contains at least one instance of the phrase.
148808 **
148809 ** If no error occurs, SQLITE_OK is returned and the values for each column
148810 ** written into the array aiOut as follows:
148811 **
148812 ** aiOut[iCol*3 + 1] = Number of occurrences
148813 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
148814 **
148815 ** Caveats:
148816 **
148817 ** * If a phrase consists entirely of deferred tokens, then all output
148818 ** values are set to the number of documents in the table. In other
148819 ** words we assume that very common tokens occur exactly once in each
148820 ** column of each row of the table.
148821 **
148822 ** * If a phrase contains some deferred tokens (and some non-deferred
148823 ** tokens), count the potential occurrence identified by considering
148824 ** the non-deferred tokens instead of actual phrase occurrences.
148825 **
148826 ** * If the phrase is part of a NEAR expression, then only phrase instances
148827 ** that meet the NEAR constraint are included in the counts.
148828 */
148829 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
148830  Fts3Cursor *pCsr, /* FTS cursor handle */
148831  Fts3Expr *pExpr, /* Phrase expression */
148832  u32 *aiOut /* Array to write results into (see above) */
148833 ){
148834  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148835  int rc = SQLITE_OK;
148836  int iCol;
148837 
148838  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
148839  assert( pCsr->nDoc>0 );
148840  for(iCol=0; iCol<pTab->nColumn; iCol++){
148841  aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
148842  aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
148843  }
148844  }else{
148845  rc = fts3EvalGatherStats(pCsr, pExpr);
148846  if( rc==SQLITE_OK ){
148847  assert( pExpr->aMI );
148848  for(iCol=0; iCol<pTab->nColumn; iCol++){
148849  aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
148850  aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
148851  }
148852  }
148853  }
148854 
148855  return rc;
148856 }
148857 
148858 /*
148859 ** The expression pExpr passed as the second argument to this function
148860 ** must be of type FTSQUERY_PHRASE.
148861 **
148862 ** The returned value is either NULL or a pointer to a buffer containing
148863 ** a position-list indicating the occurrences of the phrase in column iCol
148864 ** of the current row.
148865 **
148866 ** More specifically, the returned buffer contains 1 varint for each
148867 ** occurrence of the phrase in the column, stored using the normal (delta+2)
148868 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
148869 ** if the requested column contains "a b X c d X X" and the position-list
148870 ** for 'X' is requested, the buffer returned may contain:
148871 **
148872 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
148873 **
148874 ** This function works regardless of whether or not the phrase is deferred,
148875 ** incremental, or neither.
148876 */
148877 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
148878  Fts3Cursor *pCsr, /* FTS3 cursor object */
148879  Fts3Expr *pExpr, /* Phrase to return doclist for */
148880  int iCol, /* Column to return position list for */
148881  char **ppOut /* OUT: Pointer to position list */
148882 ){
148883  Fts3Phrase *pPhrase = pExpr->pPhrase;
148884  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148885  char *pIter;
148886  int iThis;
148887  sqlite3_int64 iDocid;
148888 
148889  /* If this phrase is applies specifically to some column other than
148890  ** column iCol, return a NULL pointer. */
148891  *ppOut = 0;
148892  assert( iCol>=0 && iCol<pTab->nColumn );
148893  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
148894  return SQLITE_OK;
148895  }
148896 
148897  iDocid = pExpr->iDocid;
148898  pIter = pPhrase->doclist.pList;
148899  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
148900  int rc = SQLITE_OK;
148901  int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
148902  int bOr = 0;
148903  u8 bTreeEof = 0;
148904  Fts3Expr *p; /* Used to iterate from pExpr to root */
148905  Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
148906  int bMatch;
148907 
148908  /* Check if this phrase descends from an OR expression node. If not,
148909  ** return NULL. Otherwise, the entry that corresponds to docid
148910  ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
148911  ** tree that the node is part of has been marked as EOF, but the node
148912  ** itself is not EOF, then it may point to an earlier entry. */
148913  pNear = pExpr;
148914  for(p=pExpr->pParent; p; p=p->pParent){
148915  if( p->eType==FTSQUERY_OR ) bOr = 1;
148916  if( p->eType==FTSQUERY_NEAR ) pNear = p;
148917  if( p->bEof ) bTreeEof = 1;
148918  }
148919  if( bOr==0 ) return SQLITE_OK;
148920 
148921  /* This is the descendent of an OR node. In this case we cannot use
148922  ** an incremental phrase. Load the entire doclist for the phrase
148923  ** into memory in this case. */
148924  if( pPhrase->bIncr ){
148925  int bEofSave = pNear->bEof;
148926  fts3EvalRestart(pCsr, pNear, &rc);
148927  while( rc==SQLITE_OK && !pNear->bEof ){
148928  fts3EvalNextRow(pCsr, pNear, &rc);
148929  if( bEofSave==0 && pNear->iDocid==iDocid ) break;
148930  }
148931  assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
148932  }
148933  if( bTreeEof ){
148934  while( rc==SQLITE_OK && !pNear->bEof ){
148935  fts3EvalNextRow(pCsr, pNear, &rc);
148936  }
148937  }
148938  if( rc!=SQLITE_OK ) return rc;
148939 
148940  bMatch = 1;
148941  for(p=pNear; p; p=p->pLeft){
148942  u8 bEof = 0;
148943  Fts3Expr *pTest = p;
148944  Fts3Phrase *pPh;
148945  assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
148946  if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
148947  assert( pTest->eType==FTSQUERY_PHRASE );
148948  pPh = pTest->pPhrase;
148949 
148950  pIter = pPh->pOrPoslist;
148951  iDocid = pPh->iOrDocid;
148952  if( pCsr->bDesc==bDescDoclist ){
148953  bEof = !pPh->doclist.nAll ||
148954  (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
148955  while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
148956  sqlite3Fts3DoclistNext(
148957  bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
148958  &pIter, &iDocid, &bEof
148959  );
148960  }
148961  }else{
148962  bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
148963  while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
148964  int dummy;
148965  sqlite3Fts3DoclistPrev(
148966  bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
148967  &pIter, &iDocid, &dummy, &bEof
148968  );
148969  }
148970  }
148971  pPh->pOrPoslist = pIter;
148972  pPh->iOrDocid = iDocid;
148973  if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
148974  }
148975 
148976  if( bMatch ){
148977  pIter = pPhrase->pOrPoslist;
148978  }else{
148979  pIter = 0;
148980  }
148981  }
148982  if( pIter==0 ) return SQLITE_OK;
148983 
148984  if( *pIter==0x01 ){
148985  pIter++;
148986  pIter += fts3GetVarint32(pIter, &iThis);
148987  }else{
148988  iThis = 0;
148989  }
148990  while( iThis<iCol ){
148991  fts3ColumnlistCopy(0, &pIter);
148992  if( *pIter==0x00 ) return SQLITE_OK;
148993  pIter++;
148994  pIter += fts3GetVarint32(pIter, &iThis);
148995  }
148996  if( *pIter==0x00 ){
148997  pIter = 0;
148998  }
148999 
149000  *ppOut = ((iCol==iThis)?pIter:0);
149001  return SQLITE_OK;
149002 }
149003 
149004 /*
149005 ** Free all components of the Fts3Phrase structure that were allocated by
149006 ** the eval module. Specifically, this means to free:
149007 **
149008 ** * the contents of pPhrase->doclist, and
149009 ** * any Fts3MultiSegReader objects held by phrase tokens.
149010 */
149011 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
149012  if( pPhrase ){
149013  int i;
149014  sqlite3_free(pPhrase->doclist.aAll);
149015  fts3EvalInvalidatePoslist(pPhrase);
149016  memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
149017  for(i=0; i<pPhrase->nToken; i++){
149018  fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
149019  pPhrase->aToken[i].pSegcsr = 0;
149020  }
149021  }
149022 }
149023 
149024 
149025 /*
149026 ** Return SQLITE_CORRUPT_VTAB.
149027 */
149028 #ifdef SQLITE_DEBUG
149029 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
149030  return SQLITE_CORRUPT_VTAB;
149031 }
149032 #endif
149033 
149034 #if !SQLITE_CORE
149035 /*
149036 ** Initialize API pointer table, if required.
149037 */
149038 #ifdef _WIN32
149039 __declspec(dllexport)
149040 #endif
149041 SQLITE_API int sqlite3_fts3_init(
149042  sqlite3 *db,
149043  char **pzErrMsg,
149044  const sqlite3_api_routines *pApi
149045 ){
149046  SQLITE_EXTENSION_INIT2(pApi)
149047  return sqlite3Fts3Init(db);
149048 }
149049 #endif
149050 
149051 #endif
149052 
149053 /************** End of fts3.c ************************************************/
149054 /************** Begin file fts3_aux.c ****************************************/
149055 /*
149056 ** 2011 Jan 27
149057 **
149058 ** The author disclaims copyright to this source code. In place of
149059 ** a legal notice, here is a blessing:
149060 **
149061 ** May you do good and not evil.
149062 ** May you find forgiveness for yourself and forgive others.
149063 ** May you share freely, never taking more than you give.
149064 **
149065 ******************************************************************************
149066 **
149067 */
149068 /* #include "fts3Int.h" */
149069 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149070 
149071 /* #include <string.h> */
149072 /* #include <assert.h> */
149073 
149074 typedef struct Fts3auxTable Fts3auxTable;
149075 typedef struct Fts3auxCursor Fts3auxCursor;
149076 
149077 struct Fts3auxTable {
149078  sqlite3_vtab base; /* Base class used by SQLite core */
149079  Fts3Table *pFts3Tab;
149080 };
149081 
149082 struct Fts3auxCursor {
149083  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
149084  Fts3MultiSegReader csr; /* Must be right after "base" */
149085  Fts3SegFilter filter;
149086  char *zStop;
149087  int nStop; /* Byte-length of string zStop */
149088  int iLangid; /* Language id to query */
149089  int isEof; /* True if cursor is at EOF */
149090  sqlite3_int64 iRowid; /* Current rowid */
149091 
149092  int iCol; /* Current value of 'col' column */
149093  int nStat; /* Size of aStat[] array */
149094  struct Fts3auxColstats {
149095  sqlite3_int64 nDoc; /* 'documents' values for current csr row */
149096  sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
149097  } *aStat;
149098 };
149099 
149100 /*
149101 ** Schema of the terms table.
149102 */
149103 #define FTS3_AUX_SCHEMA \
149104  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
149105 
149106 /*
149107 ** This function does all the work for both the xConnect and xCreate methods.
149108 ** These tables have no persistent representation of their own, so xConnect
149109 ** and xCreate are identical operations.
149110 */
149111 static int fts3auxConnectMethod(
149112  sqlite3 *db, /* Database connection */
149113  void *pUnused, /* Unused */
149114  int argc, /* Number of elements in argv array */
149115  const char * const *argv, /* xCreate/xConnect argument array */
149116  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
149117  char **pzErr /* OUT: sqlite3_malloc'd error message */
149118 ){
149119  char const *zDb; /* Name of database (e.g. "main") */
149120  char const *zFts3; /* Name of fts3 table */
149121  int nDb; /* Result of strlen(zDb) */
149122  int nFts3; /* Result of strlen(zFts3) */
149123  int nByte; /* Bytes of space to allocate here */
149124  int rc; /* value returned by declare_vtab() */
149125  Fts3auxTable *p; /* Virtual table object to return */
149126 
149127  UNUSED_PARAMETER(pUnused);
149128 
149129  /* The user should invoke this in one of two forms:
149130  **
149131  ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
149132  ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
149133  */
149134  if( argc!=4 && argc!=5 ) goto bad_args;
149135 
149136  zDb = argv[1];
149137  nDb = (int)strlen(zDb);
149138  if( argc==5 ){
149139  if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
149140  zDb = argv[3];
149141  nDb = (int)strlen(zDb);
149142  zFts3 = argv[4];
149143  }else{
149144  goto bad_args;
149145  }
149146  }else{
149147  zFts3 = argv[3];
149148  }
149149  nFts3 = (int)strlen(zFts3);
149150 
149151  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
149152  if( rc!=SQLITE_OK ) return rc;
149153 
149154  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
149155  p = (Fts3auxTable *)sqlite3_malloc(nByte);
149156  if( !p ) return SQLITE_NOMEM;
149157  memset(p, 0, nByte);
149158 
149159  p->pFts3Tab = (Fts3Table *)&p[1];
149160  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
149161  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
149162  p->pFts3Tab->db = db;
149163  p->pFts3Tab->nIndex = 1;
149164 
149165  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
149166  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
149167  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
149168 
149169  *ppVtab = (sqlite3_vtab *)p;
149170  return SQLITE_OK;
149171 
149172  bad_args:
149173  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
149174  return SQLITE_ERROR;
149175 }
149176 
149177 /*
149178 ** This function does the work for both the xDisconnect and xDestroy methods.
149179 ** These tables have no persistent representation of their own, so xDisconnect
149180 ** and xDestroy are identical operations.
149181 */
149182 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
149183  Fts3auxTable *p = (Fts3auxTable *)pVtab;
149184  Fts3Table *pFts3 = p->pFts3Tab;
149185  int i;
149186 
149187  /* Free any prepared statements held */
149188  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
149189  sqlite3_finalize(pFts3->aStmt[i]);
149190  }
149191  sqlite3_free(pFts3->zSegmentsTbl);
149192  sqlite3_free(p);
149193  return SQLITE_OK;
149194 }
149195 
149196 #define FTS4AUX_EQ_CONSTRAINT 1
149197 #define FTS4AUX_GE_CONSTRAINT 2
149198 #define FTS4AUX_LE_CONSTRAINT 4
149199 
149200 /*
149201 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
149202 */
149203 static int fts3auxBestIndexMethod(
149204  sqlite3_vtab *pVTab,
149205  sqlite3_index_info *pInfo
149206 ){
149207  int i;
149208  int iEq = -1;
149209  int iGe = -1;
149210  int iLe = -1;
149211  int iLangid = -1;
149212  int iNext = 1; /* Next free argvIndex value */
149213 
149214  UNUSED_PARAMETER(pVTab);
149215 
149216  /* This vtab delivers always results in "ORDER BY term ASC" order. */
149217  if( pInfo->nOrderBy==1
149218  && pInfo->aOrderBy[0].iColumn==0
149219  && pInfo->aOrderBy[0].desc==0
149220  ){
149221  pInfo->orderByConsumed = 1;
149222  }
149223 
149224  /* Search for equality and range constraints on the "term" column.
149225  ** And equality constraints on the hidden "languageid" column. */
149226  for(i=0; i<pInfo->nConstraint; i++){
149227  if( pInfo->aConstraint[i].usable ){
149228  int op = pInfo->aConstraint[i].op;
149229  int iCol = pInfo->aConstraint[i].iColumn;
149230 
149231  if( iCol==0 ){
149232  if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
149233  if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
149234  if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
149235  if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
149236  if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
149237  }
149238  if( iCol==4 ){
149239  if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
149240  }
149241  }
149242  }
149243 
149244  if( iEq>=0 ){
149245  pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
149246  pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
149247  pInfo->estimatedCost = 5;
149248  }else{
149249  pInfo->idxNum = 0;
149250  pInfo->estimatedCost = 20000;
149251  if( iGe>=0 ){
149252  pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
149253  pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
149254  pInfo->estimatedCost /= 2;
149255  }
149256  if( iLe>=0 ){
149257  pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
149258  pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
149259  pInfo->estimatedCost /= 2;
149260  }
149261  }
149262  if( iLangid>=0 ){
149263  pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
149264  pInfo->estimatedCost--;
149265  }
149266 
149267  return SQLITE_OK;
149268 }
149269 
149270 /*
149271 ** xOpen - Open a cursor.
149272 */
149273 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
149274  Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
149275 
149276  UNUSED_PARAMETER(pVTab);
149277 
149278  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
149279  if( !pCsr ) return SQLITE_NOMEM;
149280  memset(pCsr, 0, sizeof(Fts3auxCursor));
149281 
149282  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
149283  return SQLITE_OK;
149284 }
149285 
149286 /*
149287 ** xClose - Close a cursor.
149288 */
149289 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
149290  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
149291  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149292 
149293  sqlite3Fts3SegmentsClose(pFts3);
149294  sqlite3Fts3SegReaderFinish(&pCsr->csr);
149295  sqlite3_free((void *)pCsr->filter.zTerm);
149296  sqlite3_free(pCsr->zStop);
149297  sqlite3_free(pCsr->aStat);
149298  sqlite3_free(pCsr);
149299  return SQLITE_OK;
149300 }
149301 
149302 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
149303  if( nSize>pCsr->nStat ){
149304  struct Fts3auxColstats *aNew;
149305  aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
149306  sizeof(struct Fts3auxColstats) * nSize
149307  );
149308  if( aNew==0 ) return SQLITE_NOMEM;
149309  memset(&aNew[pCsr->nStat], 0,
149310  sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
149311  );
149312  pCsr->aStat = aNew;
149313  pCsr->nStat = nSize;
149314  }
149315  return SQLITE_OK;
149316 }
149317 
149318 /*
149319 ** xNext - Advance the cursor to the next row, if any.
149320 */
149321 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
149322  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149323  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
149324  int rc;
149325 
149326  /* Increment our pretend rowid value. */
149327  pCsr->iRowid++;
149328 
149329  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
149330  if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
149331  }
149332 
149333  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
149334  if( rc==SQLITE_ROW ){
149335  int i = 0;
149336  int nDoclist = pCsr->csr.nDoclist;
149337  char *aDoclist = pCsr->csr.aDoclist;
149338  int iCol;
149339 
149340  int eState = 0;
149341 
149342  if( pCsr->zStop ){
149343  int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
149344  int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
149345  if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
149346  pCsr->isEof = 1;
149347  return SQLITE_OK;
149348  }
149349  }
149350 
149351  if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
149352  memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
149353  iCol = 0;
149354 
149355  while( i<nDoclist ){
149356  sqlite3_int64 v = 0;
149357 
149358  i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
149359  switch( eState ){
149360  /* State 0. In this state the integer just read was a docid. */
149361  case 0:
149362  pCsr->aStat[0].nDoc++;
149363  eState = 1;
149364  iCol = 0;
149365  break;
149366 
149367  /* State 1. In this state we are expecting either a 1, indicating
149368  ** that the following integer will be a column number, or the
149369  ** start of a position list for column 0.
149370  **
149371  ** The only difference between state 1 and state 2 is that if the
149372  ** integer encountered in state 1 is not 0 or 1, then we need to
149373  ** increment the column 0 "nDoc" count for this term.
149374  */
149375  case 1:
149376  assert( iCol==0 );
149377  if( v>1 ){
149378  pCsr->aStat[1].nDoc++;
149379  }
149380  eState = 2;
149381  /* fall through */
149382 
149383  case 2:
149384  if( v==0 ){ /* 0x00. Next integer will be a docid. */
149385  eState = 0;
149386  }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
149387  eState = 3;
149388  }else{ /* 2 or greater. A position. */
149389  pCsr->aStat[iCol+1].nOcc++;
149390  pCsr->aStat[0].nOcc++;
149391  }
149392  break;
149393 
149394  /* State 3. The integer just read is a column number. */
149395  default: assert( eState==3 );
149396  iCol = (int)v;
149397  if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
149398  pCsr->aStat[iCol+1].nDoc++;
149399  eState = 2;
149400  break;
149401  }
149402  }
149403 
149404  pCsr->iCol = 0;
149405  rc = SQLITE_OK;
149406  }else{
149407  pCsr->isEof = 1;
149408  }
149409  return rc;
149410 }
149411 
149412 /*
149413 ** xFilter - Initialize a cursor to point at the start of its data.
149414 */
149415 static int fts3auxFilterMethod(
149416  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
149417  int idxNum, /* Strategy index */
149418  const char *idxStr, /* Unused */
149419  int nVal, /* Number of elements in apVal */
149420  sqlite3_value **apVal /* Arguments for the indexing scheme */
149421 ){
149422  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149423  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
149424  int rc;
149425  int isScan = 0;
149426  int iLangVal = 0; /* Language id to query */
149427 
149428  int iEq = -1; /* Index of term=? value in apVal */
149429  int iGe = -1; /* Index of term>=? value in apVal */
149430  int iLe = -1; /* Index of term<=? value in apVal */
149431  int iLangid = -1; /* Index of languageid=? value in apVal */
149432  int iNext = 0;
149433 
149434  UNUSED_PARAMETER(nVal);
149435  UNUSED_PARAMETER(idxStr);
149436 
149437  assert( idxStr==0 );
149438  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
149439  || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
149440  || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
149441  );
149442 
149443  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
149444  iEq = iNext++;
149445  }else{
149446  isScan = 1;
149447  if( idxNum & FTS4AUX_GE_CONSTRAINT ){
149448  iGe = iNext++;
149449  }
149450  if( idxNum & FTS4AUX_LE_CONSTRAINT ){
149451  iLe = iNext++;
149452  }
149453  }
149454  if( iNext<nVal ){
149455  iLangid = iNext++;
149456  }
149457 
149458  /* In case this cursor is being reused, close and zero it. */
149459  testcase(pCsr->filter.zTerm);
149460  sqlite3Fts3SegReaderFinish(&pCsr->csr);
149461  sqlite3_free((void *)pCsr->filter.zTerm);
149462  sqlite3_free(pCsr->aStat);
149463  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
149464 
149465  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
149466  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
149467 
149468  if( iEq>=0 || iGe>=0 ){
149469  const unsigned char *zStr = sqlite3_value_text(apVal[0]);
149470  assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
149471  if( zStr ){
149472  pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
149473  pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
149474  if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
149475  }
149476  }
149477 
149478  if( iLe>=0 ){
149479  pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
149480  pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
149481  if( pCsr->zStop==0 ) return SQLITE_NOMEM;
149482  }
149483 
149484  if( iLangid>=0 ){
149485  iLangVal = sqlite3_value_int(apVal[iLangid]);
149486 
149487  /* If the user specified a negative value for the languageid, use zero
149488  ** instead. This works, as the "languageid=?" constraint will also
149489  ** be tested by the VDBE layer. The test will always be false (since
149490  ** this module will not return a row with a negative languageid), and
149491  ** so the overall query will return zero rows. */
149492  if( iLangVal<0 ) iLangVal = 0;
149493  }
149494  pCsr->iLangid = iLangVal;
149495 
149496  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
149497  pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
149498  );
149499  if( rc==SQLITE_OK ){
149500  rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
149501  }
149502 
149503  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
149504  return rc;
149505 }
149506 
149507 /*
149508 ** xEof - Return true if the cursor is at EOF, or false otherwise.
149509 */
149510 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
149511  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149512  return pCsr->isEof;
149513 }
149514 
149515 /*
149516 ** xColumn - Return a column value.
149517 */
149518 static int fts3auxColumnMethod(
149519  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
149520  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
149521  int iCol /* Index of column to read value from */
149522 ){
149523  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
149524 
149525  assert( p->isEof==0 );
149526  switch( iCol ){
149527  case 0: /* term */
149528  sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
149529  break;
149530 
149531  case 1: /* col */
149532  if( p->iCol ){
149533  sqlite3_result_int(pCtx, p->iCol-1);
149534  }else{
149535  sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
149536  }
149537  break;
149538 
149539  case 2: /* documents */
149540  sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
149541  break;
149542 
149543  case 3: /* occurrences */
149544  sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
149545  break;
149546 
149547  default: /* languageid */
149548  assert( iCol==4 );
149549  sqlite3_result_int(pCtx, p->iLangid);
149550  break;
149551  }
149552 
149553  return SQLITE_OK;
149554 }
149555 
149556 /*
149557 ** xRowid - Return the current rowid for the cursor.
149558 */
149559 static int fts3auxRowidMethod(
149560  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
149561  sqlite_int64 *pRowid /* OUT: Rowid value */
149562 ){
149563  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
149564  *pRowid = pCsr->iRowid;
149565  return SQLITE_OK;
149566 }
149567 
149568 /*
149569 ** Register the fts3aux module with database connection db. Return SQLITE_OK
149570 ** if successful or an error code if sqlite3_create_module() fails.
149571 */
149572 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
149573  static const sqlite3_module fts3aux_module = {
149574  0, /* iVersion */
149575  fts3auxConnectMethod, /* xCreate */
149576  fts3auxConnectMethod, /* xConnect */
149577  fts3auxBestIndexMethod, /* xBestIndex */
149578  fts3auxDisconnectMethod, /* xDisconnect */
149579  fts3auxDisconnectMethod, /* xDestroy */
149580  fts3auxOpenMethod, /* xOpen */
149581  fts3auxCloseMethod, /* xClose */
149582  fts3auxFilterMethod, /* xFilter */
149583  fts3auxNextMethod, /* xNext */
149584  fts3auxEofMethod, /* xEof */
149585  fts3auxColumnMethod, /* xColumn */
149586  fts3auxRowidMethod, /* xRowid */
149587  0, /* xUpdate */
149588  0, /* xBegin */
149589  0, /* xSync */
149590  0, /* xCommit */
149591  0, /* xRollback */
149592  0, /* xFindFunction */
149593  0, /* xRename */
149594  0, /* xSavepoint */
149595  0, /* xRelease */
149596  0 /* xRollbackTo */
149597  };
149598  int rc; /* Return code */
149599 
149600  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
149601  return rc;
149602 }
149603 
149604 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149605 
149606 /************** End of fts3_aux.c ********************************************/
149607 /************** Begin file fts3_expr.c ***************************************/
149608 /*
149609 ** 2008 Nov 28
149610 **
149611 ** The author disclaims copyright to this source code. In place of
149612 ** a legal notice, here is a blessing:
149613 **
149614 ** May you do good and not evil.
149615 ** May you find forgiveness for yourself and forgive others.
149616 ** May you share freely, never taking more than you give.
149617 **
149618 ******************************************************************************
149619 **
149620 ** This module contains code that implements a parser for fts3 query strings
149621 ** (the right-hand argument to the MATCH operator). Because the supported
149622 ** syntax is relatively simple, the whole tokenizer/parser system is
149623 ** hand-coded.
149624 */
149625 /* #include "fts3Int.h" */
149626 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149627 
149628 /*
149629 ** By default, this module parses the legacy syntax that has been
149630 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
149631 ** is defined, then it uses the new syntax. The differences between
149632 ** the new and the old syntaxes are:
149633 **
149634 ** a) The new syntax supports parenthesis. The old does not.
149635 **
149636 ** b) The new syntax supports the AND and NOT operators. The old does not.
149637 **
149638 ** c) The old syntax supports the "-" token qualifier. This is not
149639 ** supported by the new syntax (it is replaced by the NOT operator).
149640 **
149641 ** d) When using the old syntax, the OR operator has a greater precedence
149642 ** than an implicit AND. When using the new, both implicity and explicit
149643 ** AND operators have a higher precedence than OR.
149644 **
149645 ** If compiled with SQLITE_TEST defined, then this module exports the
149646 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
149647 ** to zero causes the module to use the old syntax. If it is set to
149648 ** non-zero the new syntax is activated. This is so both syntaxes can
149649 ** be tested using a single build of testfixture.
149650 **
149651 ** The following describes the syntax supported by the fts3 MATCH
149652 ** operator in a similar format to that used by the lemon parser
149653 ** generator. This module does not use actually lemon, it uses a
149654 ** custom parser.
149655 **
149656 ** query ::= andexpr (OR andexpr)*.
149657 **
149658 ** andexpr ::= notexpr (AND? notexpr)*.
149659 **
149660 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
149661 ** notexpr ::= LP query RP.
149662 **
149663 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
149664 **
149665 ** distance_opt ::= .
149666 ** distance_opt ::= / INTEGER.
149667 **
149668 ** phrase ::= TOKEN.
149669 ** phrase ::= COLUMN:TOKEN.
149670 ** phrase ::= "TOKEN TOKEN TOKEN...".
149671 */
149672 
149673 #ifdef SQLITE_TEST
149674 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
149675 #else
149676 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
149677 # define sqlite3_fts3_enable_parentheses 1
149678 # else
149679 # define sqlite3_fts3_enable_parentheses 0
149680 # endif
149681 #endif
149682 
149683 /*
149684 ** Default span for NEAR operators.
149685 */
149686 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
149687 
149688 /* #include <string.h> */
149689 /* #include <assert.h> */
149690 
149691 /*
149692 ** isNot:
149693 ** This variable is used by function getNextNode(). When getNextNode() is
149694 ** called, it sets ParseContext.isNot to true if the 'next node' is a
149695 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
149696 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
149697 ** zero.
149698 */
149699 typedef struct ParseContext ParseContext;
149700 struct ParseContext {
149701  sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
149702  int iLangid; /* Language id used with tokenizer */
149703  const char **azCol; /* Array of column names for fts3 table */
149704  int bFts4; /* True to allow FTS4-only syntax */
149705  int nCol; /* Number of entries in azCol[] */
149706  int iDefaultCol; /* Default column to query */
149707  int isNot; /* True if getNextNode() sees a unary - */
149708  sqlite3_context *pCtx; /* Write error message here */
149709  int nNest; /* Number of nested brackets */
149710 };
149711 
149712 /*
149713 ** This function is equivalent to the standard isspace() function.
149714 **
149715 ** The standard isspace() can be awkward to use safely, because although it
149716 ** is defined to accept an argument of type int, its behavior when passed
149717 ** an integer that falls outside of the range of the unsigned char type
149718 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
149719 ** is defined to accept an argument of type char, and always returns 0 for
149720 ** any values that fall outside of the range of the unsigned char type (i.e.
149721 ** negative values).
149722 */
149723 static int fts3isspace(char c){
149724  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
149725 }
149726 
149727 /*
149728 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
149729 ** zero the memory before returning a pointer to it. If unsuccessful,
149730 ** return NULL.
149731 */
149732 static void *fts3MallocZero(int nByte){
149733  void *pRet = sqlite3_malloc(nByte);
149734  if( pRet ) memset(pRet, 0, nByte);
149735  return pRet;
149736 }
149737 
149738 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
149739  sqlite3_tokenizer *pTokenizer,
149740  int iLangid,
149741  const char *z,
149742  int n,
149743  sqlite3_tokenizer_cursor **ppCsr
149744 ){
149745  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
149746  sqlite3_tokenizer_cursor *pCsr = 0;
149747  int rc;
149748 
149749  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
149750  assert( rc==SQLITE_OK || pCsr==0 );
149751  if( rc==SQLITE_OK ){
149752  pCsr->pTokenizer = pTokenizer;
149753  if( pModule->iVersion>=1 ){
149754  rc = pModule->xLanguageid(pCsr, iLangid);
149755  if( rc!=SQLITE_OK ){
149756  pModule->xClose(pCsr);
149757  pCsr = 0;
149758  }
149759  }
149760  }
149761  *ppCsr = pCsr;
149762  return rc;
149763 }
149764 
149765 /*
149766 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
149767 ** call fts3ExprParse(). So this forward declaration is required.
149768 */
149769 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
149770 
149771 /*
149772 ** Extract the next token from buffer z (length n) using the tokenizer
149773 ** and other information (column names etc.) in pParse. Create an Fts3Expr
149774 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
149775 ** single token and set *ppExpr to point to it. If the end of the buffer is
149776 ** reached before a token is found, set *ppExpr to zero. It is the
149777 ** responsibility of the caller to eventually deallocate the allocated
149778 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
149779 **
149780 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
149781 ** fails.
149782 */
149783 static int getNextToken(
149784  ParseContext *pParse, /* fts3 query parse context */
149785  int iCol, /* Value for Fts3Phrase.iColumn */
149786  const char *z, int n, /* Input string */
149787  Fts3Expr **ppExpr, /* OUT: expression */
149788  int *pnConsumed /* OUT: Number of bytes consumed */
149789 ){
149790  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
149791  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
149792  int rc;
149793  sqlite3_tokenizer_cursor *pCursor;
149794  Fts3Expr *pRet = 0;
149795  int i = 0;
149796 
149797  /* Set variable i to the maximum number of bytes of input to tokenize. */
149798  for(i=0; i<n; i++){
149799  if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
149800  if( z[i]=='"' ) break;
149801  }
149802 
149803  *pnConsumed = i;
149804  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
149805  if( rc==SQLITE_OK ){
149806  const char *zToken;
149807  int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
149808  int nByte; /* total space to allocate */
149809 
149810  rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
149811  if( rc==SQLITE_OK ){
149812  nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
149813  pRet = (Fts3Expr *)fts3MallocZero(nByte);
149814  if( !pRet ){
149815  rc = SQLITE_NOMEM;
149816  }else{
149817  pRet->eType = FTSQUERY_PHRASE;
149818  pRet->pPhrase = (Fts3Phrase *)&pRet[1];
149819  pRet->pPhrase->nToken = 1;
149820  pRet->pPhrase->iColumn = iCol;
149821  pRet->pPhrase->aToken[0].n = nToken;
149822  pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
149823  memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
149824 
149825  if( iEnd<n && z[iEnd]=='*' ){
149826  pRet->pPhrase->aToken[0].isPrefix = 1;
149827  iEnd++;
149828  }
149829 
149830  while( 1 ){
149831  if( !sqlite3_fts3_enable_parentheses
149832  && iStart>0 && z[iStart-1]=='-'
149833  ){
149834  pParse->isNot = 1;
149835  iStart--;
149836  }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
149837  pRet->pPhrase->aToken[0].bFirst = 1;
149838  iStart--;
149839  }else{
149840  break;
149841  }
149842  }
149843 
149844  }
149845  *pnConsumed = iEnd;
149846  }else if( i && rc==SQLITE_DONE ){
149847  rc = SQLITE_OK;
149848  }
149849 
149850  pModule->xClose(pCursor);
149851  }
149852 
149853  *ppExpr = pRet;
149854  return rc;
149855 }
149856 
149857 
149858 /*
149859 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
149860 ** then free the old allocation.
149861 */
149862 static void *fts3ReallocOrFree(void *pOrig, int nNew){
149863  void *pRet = sqlite3_realloc(pOrig, nNew);
149864  if( !pRet ){
149865  sqlite3_free(pOrig);
149866  }
149867  return pRet;
149868 }
149869 
149870 /*
149871 ** Buffer zInput, length nInput, contains the contents of a quoted string
149872 ** that appeared as part of an fts3 query expression. Neither quote character
149873 ** is included in the buffer. This function attempts to tokenize the entire
149874 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
149875 ** containing the results.
149876 **
149877 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
149878 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
149879 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
149880 ** to 0.
149881 */
149882 static int getNextString(
149883  ParseContext *pParse, /* fts3 query parse context */
149884  const char *zInput, int nInput, /* Input string */
149885  Fts3Expr **ppExpr /* OUT: expression */
149886 ){
149887  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
149888  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
149889  int rc;
149890  Fts3Expr *p = 0;
149891  sqlite3_tokenizer_cursor *pCursor = 0;
149892  char *zTemp = 0;
149893  int nTemp = 0;
149894 
149895  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
149896  int nToken = 0;
149897 
149898  /* The final Fts3Expr data structure, including the Fts3Phrase,
149899  ** Fts3PhraseToken structures token buffers are all stored as a single
149900  ** allocation so that the expression can be freed with a single call to
149901  ** sqlite3_free(). Setting this up requires a two pass approach.
149902  **
149903  ** The first pass, in the block below, uses a tokenizer cursor to iterate
149904  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
149905  ** to assemble data in two dynamic buffers:
149906  **
149907  ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
149908  ** structure, followed by the array of Fts3PhraseToken
149909  ** structures. This pass only populates the Fts3PhraseToken array.
149910  **
149911  ** Buffer zTemp: Contains copies of all tokens.
149912  **
149913  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
149914  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
149915  ** structures.
149916  */
149917  rc = sqlite3Fts3OpenTokenizer(
149918  pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
149919  if( rc==SQLITE_OK ){
149920  int ii;
149921  for(ii=0; rc==SQLITE_OK; ii++){
149922  const char *zByte;
149923  int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
149924  rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
149925  if( rc==SQLITE_OK ){
149926  Fts3PhraseToken *pToken;
149927 
149928  p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
149929  if( !p ) goto no_mem;
149930 
149931  zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
149932  if( !zTemp ) goto no_mem;
149933 
149934  assert( nToken==ii );
149935  pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
149936  memset(pToken, 0, sizeof(Fts3PhraseToken));
149937 
149938  memcpy(&zTemp[nTemp], zByte, nByte);
149939  nTemp += nByte;
149940 
149941  pToken->n = nByte;
149942  pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
149943  pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
149944  nToken = ii+1;
149945  }
149946  }
149947 
149948  pModule->xClose(pCursor);
149949  pCursor = 0;
149950  }
149951 
149952  if( rc==SQLITE_DONE ){
149953  int jj;
149954  char *zBuf = 0;
149955 
149956  p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
149957  if( !p ) goto no_mem;
149958  memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
149959  p->eType = FTSQUERY_PHRASE;
149960  p->pPhrase = (Fts3Phrase *)&p[1];
149961  p->pPhrase->iColumn = pParse->iDefaultCol;
149962  p->pPhrase->nToken = nToken;
149963 
149964  zBuf = (char *)&p->pPhrase->aToken[nToken];
149965  if( zTemp ){
149966  memcpy(zBuf, zTemp, nTemp);
149967  sqlite3_free(zTemp);
149968  }else{
149969  assert( nTemp==0 );
149970  }
149971 
149972  for(jj=0; jj<p->pPhrase->nToken; jj++){
149973  p->pPhrase->aToken[jj].z = zBuf;
149974  zBuf += p->pPhrase->aToken[jj].n;
149975  }
149976  rc = SQLITE_OK;
149977  }
149978 
149979  *ppExpr = p;
149980  return rc;
149981 no_mem:
149982 
149983  if( pCursor ){
149984  pModule->xClose(pCursor);
149985  }
149986  sqlite3_free(zTemp);
149987  sqlite3_free(p);
149988  *ppExpr = 0;
149989  return SQLITE_NOMEM;
149990 }
149991 
149992 /*
149993 ** The output variable *ppExpr is populated with an allocated Fts3Expr
149994 ** structure, or set to 0 if the end of the input buffer is reached.
149995 **
149996 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
149997 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
149998 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
149999 */
150000 static int getNextNode(
150001  ParseContext *pParse, /* fts3 query parse context */
150002  const char *z, int n, /* Input string */
150003  Fts3Expr **ppExpr, /* OUT: expression */
150004  int *pnConsumed /* OUT: Number of bytes consumed */
150005 ){
150006  static const struct Fts3Keyword {
150007  char *z; /* Keyword text */
150008  unsigned char n; /* Length of the keyword */
150009  unsigned char parenOnly; /* Only valid in paren mode */
150010  unsigned char eType; /* Keyword code */
150011  } aKeyword[] = {
150012  { "OR" , 2, 0, FTSQUERY_OR },
150013  { "AND", 3, 1, FTSQUERY_AND },
150014  { "NOT", 3, 1, FTSQUERY_NOT },
150015  { "NEAR", 4, 0, FTSQUERY_NEAR }
150016  };
150017  int ii;
150018  int iCol;
150019  int iColLen;
150020  int rc;
150021  Fts3Expr *pRet = 0;
150022 
150023  const char *zInput = z;
150024  int nInput = n;
150025 
150026  pParse->isNot = 0;
150027 
150028  /* Skip over any whitespace before checking for a keyword, an open or
150029  ** close bracket, or a quoted string.
150030  */
150031  while( nInput>0 && fts3isspace(*zInput) ){
150032  nInput--;
150033  zInput++;
150034  }
150035  if( nInput==0 ){
150036  return SQLITE_DONE;
150037  }
150038 
150039  /* See if we are dealing with a keyword. */
150040  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
150041  const struct Fts3Keyword *pKey = &aKeyword[ii];
150042 
150043  if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
150044  continue;
150045  }
150046 
150047  if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
150048  int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
150049  int nKey = pKey->n;
150050  char cNext;
150051 
150052  /* If this is a "NEAR" keyword, check for an explicit nearness. */
150053  if( pKey->eType==FTSQUERY_NEAR ){
150054  assert( nKey==4 );
150055  if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
150056  nNear = 0;
150057  for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
150058  nNear = nNear * 10 + (zInput[nKey] - '0');
150059  }
150060  }
150061  }
150062 
150063  /* At this point this is probably a keyword. But for that to be true,
150064  ** the next byte must contain either whitespace, an open or close
150065  ** parenthesis, a quote character, or EOF.
150066  */
150067  cNext = zInput[nKey];
150068  if( fts3isspace(cNext)
150069  || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
150070  ){
150071  pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
150072  if( !pRet ){
150073  return SQLITE_NOMEM;
150074  }
150075  pRet->eType = pKey->eType;
150076  pRet->nNear = nNear;
150077  *ppExpr = pRet;
150078  *pnConsumed = (int)((zInput - z) + nKey);
150079  return SQLITE_OK;
150080  }
150081 
150082  /* Turns out that wasn't a keyword after all. This happens if the
150083  ** user has supplied a token such as "ORacle". Continue.
150084  */
150085  }
150086  }
150087 
150088  /* See if we are dealing with a quoted phrase. If this is the case, then
150089  ** search for the closing quote and pass the whole string to getNextString()
150090  ** for processing. This is easy to do, as fts3 has no syntax for escaping
150091  ** a quote character embedded in a string.
150092  */
150093  if( *zInput=='"' ){
150094  for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
150095  *pnConsumed = (int)((zInput - z) + ii + 1);
150096  if( ii==nInput ){
150097  return SQLITE_ERROR;
150098  }
150099  return getNextString(pParse, &zInput[1], ii-1, ppExpr);
150100  }
150101 
150102  if( sqlite3_fts3_enable_parentheses ){
150103  if( *zInput=='(' ){
150104  int nConsumed = 0;
150105  pParse->nNest++;
150106  rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
150107  if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
150108  *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
150109  return rc;
150110  }else if( *zInput==')' ){
150111  pParse->nNest--;
150112  *pnConsumed = (int)((zInput - z) + 1);
150113  *ppExpr = 0;
150114  return SQLITE_DONE;
150115  }
150116  }
150117 
150118  /* If control flows to this point, this must be a regular token, or
150119  ** the end of the input. Read a regular token using the sqlite3_tokenizer
150120  ** interface. Before doing so, figure out if there is an explicit
150121  ** column specifier for the token.
150122  **
150123  ** TODO: Strangely, it is not possible to associate a column specifier
150124  ** with a quoted phrase, only with a single token. Not sure if this was
150125  ** an implementation artifact or an intentional decision when fts3 was
150126  ** first implemented. Whichever it was, this module duplicates the
150127  ** limitation.
150128  */
150129  iCol = pParse->iDefaultCol;
150130  iColLen = 0;
150131  for(ii=0; ii<pParse->nCol; ii++){
150132  const char *zStr = pParse->azCol[ii];
150133  int nStr = (int)strlen(zStr);
150134  if( nInput>nStr && zInput[nStr]==':'
150135  && sqlite3_strnicmp(zStr, zInput, nStr)==0
150136  ){
150137  iCol = ii;
150138  iColLen = (int)((zInput - z) + nStr + 1);
150139  break;
150140  }
150141  }
150142  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
150143  *pnConsumed += iColLen;
150144  return rc;
150145 }
150146 
150147 /*
150148 ** The argument is an Fts3Expr structure for a binary operator (any type
150149 ** except an FTSQUERY_PHRASE). Return an integer value representing the
150150 ** precedence of the operator. Lower values have a higher precedence (i.e.
150151 ** group more tightly). For example, in the C language, the == operator
150152 ** groups more tightly than ||, and would therefore have a higher precedence.
150153 **
150154 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
150155 ** is defined), the order of the operators in precedence from highest to
150156 ** lowest is:
150157 **
150158 ** NEAR
150159 ** NOT
150160 ** AND (including implicit ANDs)
150161 ** OR
150162 **
150163 ** Note that when using the old query syntax, the OR operator has a higher
150164 ** precedence than the AND operator.
150165 */
150166 static int opPrecedence(Fts3Expr *p){
150167  assert( p->eType!=FTSQUERY_PHRASE );
150168  if( sqlite3_fts3_enable_parentheses ){
150169  return p->eType;
150170  }else if( p->eType==FTSQUERY_NEAR ){
150171  return 1;
150172  }else if( p->eType==FTSQUERY_OR ){
150173  return 2;
150174  }
150175  assert( p->eType==FTSQUERY_AND );
150176  return 3;
150177 }
150178 
150179 /*
150180 ** Argument ppHead contains a pointer to the current head of a query
150181 ** expression tree being parsed. pPrev is the expression node most recently
150182 ** inserted into the tree. This function adds pNew, which is always a binary
150183 ** operator node, into the expression tree based on the relative precedence
150184 ** of pNew and the existing nodes of the tree. This may result in the head
150185 ** of the tree changing, in which case *ppHead is set to the new root node.
150186 */
150187 static void insertBinaryOperator(
150188  Fts3Expr **ppHead, /* Pointer to the root node of a tree */
150189  Fts3Expr *pPrev, /* Node most recently inserted into the tree */
150190  Fts3Expr *pNew /* New binary node to insert into expression tree */
150191 ){
150192  Fts3Expr *pSplit = pPrev;
150193  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
150194  pSplit = pSplit->pParent;
150195  }
150196 
150197  if( pSplit->pParent ){
150198  assert( pSplit->pParent->pRight==pSplit );
150199  pSplit->pParent->pRight = pNew;
150200  pNew->pParent = pSplit->pParent;
150201  }else{
150202  *ppHead = pNew;
150203  }
150204  pNew->pLeft = pSplit;
150205  pSplit->pParent = pNew;
150206 }
150207 
150208 /*
150209 ** Parse the fts3 query expression found in buffer z, length n. This function
150210 ** returns either when the end of the buffer is reached or an unmatched
150211 ** closing bracket - ')' - is encountered.
150212 **
150213 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
150214 ** parsed form of the expression and *pnConsumed is set to the number of
150215 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
150216 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
150217 */
150218 static int fts3ExprParse(
150219  ParseContext *pParse, /* fts3 query parse context */
150220  const char *z, int n, /* Text of MATCH query */
150221  Fts3Expr **ppExpr, /* OUT: Parsed query structure */
150222  int *pnConsumed /* OUT: Number of bytes consumed */
150223 ){
150224  Fts3Expr *pRet = 0;
150225  Fts3Expr *pPrev = 0;
150226  Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
150227  int nIn = n;
150228  const char *zIn = z;
150229  int rc = SQLITE_OK;
150230  int isRequirePhrase = 1;
150231 
150232  while( rc==SQLITE_OK ){
150233  Fts3Expr *p = 0;
150234  int nByte = 0;
150235 
150236  rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
150237  assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
150238  if( rc==SQLITE_OK ){
150239  if( p ){
150240  int isPhrase;
150241 
150242  if( !sqlite3_fts3_enable_parentheses
150243  && p->eType==FTSQUERY_PHRASE && pParse->isNot
150244  ){
150245  /* Create an implicit NOT operator. */
150246  Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
150247  if( !pNot ){
150248  sqlite3Fts3ExprFree(p);
150249  rc = SQLITE_NOMEM;
150250  goto exprparse_out;
150251  }
150252  pNot->eType = FTSQUERY_NOT;
150253  pNot->pRight = p;
150254  p->pParent = pNot;
150255  if( pNotBranch ){
150256  pNot->pLeft = pNotBranch;
150257  pNotBranch->pParent = pNot;
150258  }
150259  pNotBranch = pNot;
150260  p = pPrev;
150261  }else{
150262  int eType = p->eType;
150263  isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
150264 
150265  /* The isRequirePhrase variable is set to true if a phrase or
150266  ** an expression contained in parenthesis is required. If a
150267  ** binary operator (AND, OR, NOT or NEAR) is encounted when
150268  ** isRequirePhrase is set, this is a syntax error.
150269  */
150270  if( !isPhrase && isRequirePhrase ){
150271  sqlite3Fts3ExprFree(p);
150272  rc = SQLITE_ERROR;
150273  goto exprparse_out;
150274  }
150275 
150276  if( isPhrase && !isRequirePhrase ){
150277  /* Insert an implicit AND operator. */
150278  Fts3Expr *pAnd;
150279  assert( pRet && pPrev );
150280  pAnd = fts3MallocZero(sizeof(Fts3Expr));
150281  if( !pAnd ){
150282  sqlite3Fts3ExprFree(p);
150283  rc = SQLITE_NOMEM;
150284  goto exprparse_out;
150285  }
150286  pAnd->eType = FTSQUERY_AND;
150287  insertBinaryOperator(&pRet, pPrev, pAnd);
150288  pPrev = pAnd;
150289  }
150290 
150291  /* This test catches attempts to make either operand of a NEAR
150292  ** operator something other than a phrase. For example, either of
150293  ** the following:
150294  **
150295  ** (bracketed expression) NEAR phrase
150296  ** phrase NEAR (bracketed expression)
150297  **
150298  ** Return an error in either case.
150299  */
150300  if( pPrev && (
150301  (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
150302  || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
150303  )){
150304  sqlite3Fts3ExprFree(p);
150305  rc = SQLITE_ERROR;
150306  goto exprparse_out;
150307  }
150308 
150309  if( isPhrase ){
150310  if( pRet ){
150311  assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
150312  pPrev->pRight = p;
150313  p->pParent = pPrev;
150314  }else{
150315  pRet = p;
150316  }
150317  }else{
150318  insertBinaryOperator(&pRet, pPrev, p);
150319  }
150320  isRequirePhrase = !isPhrase;
150321  }
150322  pPrev = p;
150323  }
150324  assert( nByte>0 );
150325  }
150326  assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
150327  nIn -= nByte;
150328  zIn += nByte;
150329  }
150330 
150331  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
150332  rc = SQLITE_ERROR;
150333  }
150334 
150335  if( rc==SQLITE_DONE ){
150336  rc = SQLITE_OK;
150337  if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
150338  if( !pRet ){
150339  rc = SQLITE_ERROR;
150340  }else{
150341  Fts3Expr *pIter = pNotBranch;
150342  while( pIter->pLeft ){
150343  pIter = pIter->pLeft;
150344  }
150345  pIter->pLeft = pRet;
150346  pRet->pParent = pIter;
150347  pRet = pNotBranch;
150348  }
150349  }
150350  }
150351  *pnConsumed = n - nIn;
150352 
150353 exprparse_out:
150354  if( rc!=SQLITE_OK ){
150355  sqlite3Fts3ExprFree(pRet);
150356  sqlite3Fts3ExprFree(pNotBranch);
150357  pRet = 0;
150358  }
150359  *ppExpr = pRet;
150360  return rc;
150361 }
150362 
150363 /*
150364 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
150365 ** as the only argument is more than nMaxDepth.
150366 */
150367 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
150368  int rc = SQLITE_OK;
150369  if( p ){
150370  if( nMaxDepth<0 ){
150371  rc = SQLITE_TOOBIG;
150372  }else{
150373  rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
150374  if( rc==SQLITE_OK ){
150375  rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
150376  }
150377  }
150378  }
150379  return rc;
150380 }
150381 
150382 /*
150383 ** This function attempts to transform the expression tree at (*pp) to
150384 ** an equivalent but more balanced form. The tree is modified in place.
150385 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
150386 ** new root expression node.
150387 **
150388 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
150389 **
150390 ** Otherwise, if an error occurs, an SQLite error code is returned and
150391 ** expression (*pp) freed.
150392 */
150393 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
150394  int rc = SQLITE_OK; /* Return code */
150395  Fts3Expr *pRoot = *pp; /* Initial root node */
150396  Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
150397  int eType = pRoot->eType; /* Type of node in this tree */
150398 
150399  if( nMaxDepth==0 ){
150400  rc = SQLITE_ERROR;
150401  }
150402 
150403  if( rc==SQLITE_OK ){
150404  if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
150405  Fts3Expr **apLeaf;
150406  apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
150407  if( 0==apLeaf ){
150408  rc = SQLITE_NOMEM;
150409  }else{
150410  memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
150411  }
150412 
150413  if( rc==SQLITE_OK ){
150414  int i;
150415  Fts3Expr *p;
150416 
150417  /* Set $p to point to the left-most leaf in the tree of eType nodes. */
150418  for(p=pRoot; p->eType==eType; p=p->pLeft){
150419  assert( p->pParent==0 || p->pParent->pLeft==p );
150420  assert( p->pLeft && p->pRight );
150421  }
150422 
150423  /* This loop runs once for each leaf in the tree of eType nodes. */
150424  while( 1 ){
150425  int iLvl;
150426  Fts3Expr *pParent = p->pParent; /* Current parent of p */
150427 
150428  assert( pParent==0 || pParent->pLeft==p );
150429  p->pParent = 0;
150430  if( pParent ){
150431  pParent->pLeft = 0;
150432  }else{
150433  pRoot = 0;
150434  }
150435  rc = fts3ExprBalance(&p, nMaxDepth-1);
150436  if( rc!=SQLITE_OK ) break;
150437 
150438  for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
150439  if( apLeaf[iLvl]==0 ){
150440  apLeaf[iLvl] = p;
150441  p = 0;
150442  }else{
150443  assert( pFree );
150444  pFree->pLeft = apLeaf[iLvl];
150445  pFree->pRight = p;
150446  pFree->pLeft->pParent = pFree;
150447  pFree->pRight->pParent = pFree;
150448 
150449  p = pFree;
150450  pFree = pFree->pParent;
150451  p->pParent = 0;
150452  apLeaf[iLvl] = 0;
150453  }
150454  }
150455  if( p ){
150456  sqlite3Fts3ExprFree(p);
150457  rc = SQLITE_TOOBIG;
150458  break;
150459  }
150460 
150461  /* If that was the last leaf node, break out of the loop */
150462  if( pParent==0 ) break;
150463 
150464  /* Set $p to point to the next leaf in the tree of eType nodes */
150465  for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
150466 
150467  /* Remove pParent from the original tree. */
150468  assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
150469  pParent->pRight->pParent = pParent->pParent;
150470  if( pParent->pParent ){
150471  pParent->pParent->pLeft = pParent->pRight;
150472  }else{
150473  assert( pParent==pRoot );
150474  pRoot = pParent->pRight;
150475  }
150476 
150477  /* Link pParent into the free node list. It will be used as an
150478  ** internal node of the new tree. */
150479  pParent->pParent = pFree;
150480  pFree = pParent;
150481  }
150482 
150483  if( rc==SQLITE_OK ){
150484  p = 0;
150485  for(i=0; i<nMaxDepth; i++){
150486  if( apLeaf[i] ){
150487  if( p==0 ){
150488  p = apLeaf[i];
150489  p->pParent = 0;
150490  }else{
150491  assert( pFree!=0 );
150492  pFree->pRight = p;
150493  pFree->pLeft = apLeaf[i];
150494  pFree->pLeft->pParent = pFree;
150495  pFree->pRight->pParent = pFree;
150496 
150497  p = pFree;
150498  pFree = pFree->pParent;
150499  p->pParent = 0;
150500  }
150501  }
150502  }
150503  pRoot = p;
150504  }else{
150505  /* An error occurred. Delete the contents of the apLeaf[] array
150506  ** and pFree list. Everything else is cleaned up by the call to
150507  ** sqlite3Fts3ExprFree(pRoot) below. */
150508  Fts3Expr *pDel;
150509  for(i=0; i<nMaxDepth; i++){
150510  sqlite3Fts3ExprFree(apLeaf[i]);
150511  }
150512  while( (pDel=pFree)!=0 ){
150513  pFree = pDel->pParent;
150514  sqlite3_free(pDel);
150515  }
150516  }
150517 
150518  assert( pFree==0 );
150519  sqlite3_free( apLeaf );
150520  }
150521  }else if( eType==FTSQUERY_NOT ){
150522  Fts3Expr *pLeft = pRoot->pLeft;
150523  Fts3Expr *pRight = pRoot->pRight;
150524 
150525  pRoot->pLeft = 0;
150526  pRoot->pRight = 0;
150527  pLeft->pParent = 0;
150528  pRight->pParent = 0;
150529 
150530  rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
150531  if( rc==SQLITE_OK ){
150532  rc = fts3ExprBalance(&pRight, nMaxDepth-1);
150533  }
150534 
150535  if( rc!=SQLITE_OK ){
150536  sqlite3Fts3ExprFree(pRight);
150537  sqlite3Fts3ExprFree(pLeft);
150538  }else{
150539  assert( pLeft && pRight );
150540  pRoot->pLeft = pLeft;
150541  pLeft->pParent = pRoot;
150542  pRoot->pRight = pRight;
150543  pRight->pParent = pRoot;
150544  }
150545  }
150546  }
150547 
150548  if( rc!=SQLITE_OK ){
150549  sqlite3Fts3ExprFree(pRoot);
150550  pRoot = 0;
150551  }
150552  *pp = pRoot;
150553  return rc;
150554 }
150555 
150556 /*
150557 ** This function is similar to sqlite3Fts3ExprParse(), with the following
150558 ** differences:
150559 **
150560 ** 1. It does not do expression rebalancing.
150561 ** 2. It does not check that the expression does not exceed the
150562 ** maximum allowable depth.
150563 ** 3. Even if it fails, *ppExpr may still be set to point to an
150564 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
150565 ** in this case.
150566 */
150567 static int fts3ExprParseUnbalanced(
150568  sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
150569  int iLangid, /* Language id for tokenizer */
150570  char **azCol, /* Array of column names for fts3 table */
150571  int bFts4, /* True to allow FTS4-only syntax */
150572  int nCol, /* Number of entries in azCol[] */
150573  int iDefaultCol, /* Default column to query */
150574  const char *z, int n, /* Text of MATCH query */
150575  Fts3Expr **ppExpr /* OUT: Parsed query structure */
150576 ){
150577  int nParsed;
150578  int rc;
150579  ParseContext sParse;
150580 
150581  memset(&sParse, 0, sizeof(ParseContext));
150582  sParse.pTokenizer = pTokenizer;
150583  sParse.iLangid = iLangid;
150584  sParse.azCol = (const char **)azCol;
150585  sParse.nCol = nCol;
150586  sParse.iDefaultCol = iDefaultCol;
150587  sParse.bFts4 = bFts4;
150588  if( z==0 ){
150589  *ppExpr = 0;
150590  return SQLITE_OK;
150591  }
150592  if( n<0 ){
150593  n = (int)strlen(z);
150594  }
150595  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
150596  assert( rc==SQLITE_OK || *ppExpr==0 );
150597 
150598  /* Check for mismatched parenthesis */
150599  if( rc==SQLITE_OK && sParse.nNest ){
150600  rc = SQLITE_ERROR;
150601  }
150602 
150603  return rc;
150604 }
150605 
150606 /*
150607 ** Parameters z and n contain a pointer to and length of a buffer containing
150608 ** an fts3 query expression, respectively. This function attempts to parse the
150609 ** query expression and create a tree of Fts3Expr structures representing the
150610 ** parsed expression. If successful, *ppExpr is set to point to the head
150611 ** of the parsed expression tree and SQLITE_OK is returned. If an error
150612 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
150613 ** error) is returned and *ppExpr is set to 0.
150614 **
150615 ** If parameter n is a negative number, then z is assumed to point to a
150616 ** nul-terminated string and the length is determined using strlen().
150617 **
150618 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
150619 ** use to normalize query tokens while parsing the expression. The azCol[]
150620 ** array, which is assumed to contain nCol entries, should contain the names
150621 ** of each column in the target fts3 table, in order from left to right.
150622 ** Column names must be nul-terminated strings.
150623 **
150624 ** The iDefaultCol parameter should be passed the index of the table column
150625 ** that appears on the left-hand-side of the MATCH operator (the default
150626 ** column to match against for tokens for which a column name is not explicitly
150627 ** specified as part of the query string), or -1 if tokens may by default
150628 ** match any table column.
150629 */
150630 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
150631  sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
150632  int iLangid, /* Language id for tokenizer */
150633  char **azCol, /* Array of column names for fts3 table */
150634  int bFts4, /* True to allow FTS4-only syntax */
150635  int nCol, /* Number of entries in azCol[] */
150636  int iDefaultCol, /* Default column to query */
150637  const char *z, int n, /* Text of MATCH query */
150638  Fts3Expr **ppExpr, /* OUT: Parsed query structure */
150639  char **pzErr /* OUT: Error message (sqlite3_malloc) */
150640 ){
150641  int rc = fts3ExprParseUnbalanced(
150642  pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
150643  );
150644 
150645  /* Rebalance the expression. And check that its depth does not exceed
150646  ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
150647  if( rc==SQLITE_OK && *ppExpr ){
150648  rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
150649  if( rc==SQLITE_OK ){
150650  rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
150651  }
150652  }
150653 
150654  if( rc!=SQLITE_OK ){
150655  sqlite3Fts3ExprFree(*ppExpr);
150656  *ppExpr = 0;
150657  if( rc==SQLITE_TOOBIG ){
150658  sqlite3Fts3ErrMsg(pzErr,
150659  "FTS expression tree is too large (maximum depth %d)",
150660  SQLITE_FTS3_MAX_EXPR_DEPTH
150661  );
150662  rc = SQLITE_ERROR;
150663  }else if( rc==SQLITE_ERROR ){
150664  sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
150665  }
150666  }
150667 
150668  return rc;
150669 }
150670 
150671 /*
150672 ** Free a single node of an expression tree.
150673 */
150674 static void fts3FreeExprNode(Fts3Expr *p){
150675  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
150676  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
150677  sqlite3_free(p->aMI);
150678  sqlite3_free(p);
150679 }
150680 
150681 /*
150682 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
150683 **
150684 ** This function would be simpler if it recursively called itself. But
150685 ** that would mean passing a sufficiently large expression to ExprParse()
150686 ** could cause a stack overflow.
150687 */
150688 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
150689  Fts3Expr *p;
150690  assert( pDel==0 || pDel->pParent==0 );
150691  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
150692  assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
150693  }
150694  while( p ){
150695  Fts3Expr *pParent = p->pParent;
150696  fts3FreeExprNode(p);
150697  if( pParent && p==pParent->pLeft && pParent->pRight ){
150698  p = pParent->pRight;
150699  while( p && (p->pLeft || p->pRight) ){
150700  assert( p==p->pParent->pRight || p==p->pParent->pLeft );
150701  p = (p->pLeft ? p->pLeft : p->pRight);
150702  }
150703  }else{
150704  p = pParent;
150705  }
150706  }
150707 }
150708 
150709 /****************************************************************************
150710 *****************************************************************************
150711 ** Everything after this point is just test code.
150712 */
150713 
150714 #ifdef SQLITE_TEST
150715 
150716 /* #include <stdio.h> */
150717 
150718 /*
150719 ** Function to query the hash-table of tokenizers (see README.tokenizers).
150720 */
150721 static int queryTestTokenizer(
150722  sqlite3 *db,
150723  const char *zName,
150724  const sqlite3_tokenizer_module **pp
150725 ){
150726  int rc;
150727  sqlite3_stmt *pStmt;
150728  const char zSql[] = "SELECT fts3_tokenizer(?)";
150729 
150730  *pp = 0;
150731  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150732  if( rc!=SQLITE_OK ){
150733  return rc;
150734  }
150735 
150736  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150737  if( SQLITE_ROW==sqlite3_step(pStmt) ){
150738  if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
150739  memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
150740  }
150741  }
150742 
150743  return sqlite3_finalize(pStmt);
150744 }
150745 
150746 /*
150747 ** Return a pointer to a buffer containing a text representation of the
150748 ** expression passed as the first argument. The buffer is obtained from
150749 ** sqlite3_malloc(). It is the responsibility of the caller to use
150750 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
150751 ** NULL is returned.
150752 **
150753 ** If the second argument is not NULL, then its contents are prepended to
150754 ** the returned expression text and then freed using sqlite3_free().
150755 */
150756 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
150757  if( pExpr==0 ){
150758  return sqlite3_mprintf("");
150759  }
150760  switch( pExpr->eType ){
150761  case FTSQUERY_PHRASE: {
150762  Fts3Phrase *pPhrase = pExpr->pPhrase;
150763  int i;
150764  zBuf = sqlite3_mprintf(
150765  "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
150766  for(i=0; zBuf && i<pPhrase->nToken; i++){
150767  zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
150768  pPhrase->aToken[i].n, pPhrase->aToken[i].z,
150769  (pPhrase->aToken[i].isPrefix?"+":"")
150770  );
150771  }
150772  return zBuf;
150773  }
150774 
150775  case FTSQUERY_NEAR:
150776  zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
150777  break;
150778  case FTSQUERY_NOT:
150779  zBuf = sqlite3_mprintf("%zNOT ", zBuf);
150780  break;
150781  case FTSQUERY_AND:
150782  zBuf = sqlite3_mprintf("%zAND ", zBuf);
150783  break;
150784  case FTSQUERY_OR:
150785  zBuf = sqlite3_mprintf("%zOR ", zBuf);
150786  break;
150787  }
150788 
150789  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
150790  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
150791  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
150792 
150793  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
150794  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
150795 
150796  return zBuf;
150797 }
150798 
150799 /*
150800 ** This is the implementation of a scalar SQL function used to test the
150801 ** expression parser. It should be called as follows:
150802 **
150803 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
150804 **
150805 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
150806 ** to parse the query expression (see README.tokenizers). The second argument
150807 ** is the query expression to parse. Each subsequent argument is the name
150808 ** of a column of the fts3 table that the query expression may refer to.
150809 ** For example:
150810 **
150811 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
150812 */
150813 static void fts3ExprTest(
150814  sqlite3_context *context,
150815  int argc,
150816  sqlite3_value **argv
150817 ){
150818  sqlite3_tokenizer_module const *pModule = 0;
150819  sqlite3_tokenizer *pTokenizer = 0;
150820  int rc;
150821  char **azCol = 0;
150822  const char *zExpr;
150823  int nExpr;
150824  int nCol;
150825  int ii;
150826  Fts3Expr *pExpr;
150827  char *zBuf = 0;
150828  sqlite3 *db = sqlite3_context_db_handle(context);
150829 
150830  if( argc<3 ){
150831  sqlite3_result_error(context,
150832  "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
150833  );
150834  return;
150835  }
150836 
150837  rc = queryTestTokenizer(db,
150838  (const char *)sqlite3_value_text(argv[0]), &pModule);
150839  if( rc==SQLITE_NOMEM ){
150840  sqlite3_result_error_nomem(context);
150841  goto exprtest_out;
150842  }else if( !pModule ){
150843  sqlite3_result_error(context, "No such tokenizer module", -1);
150844  goto exprtest_out;
150845  }
150846 
150847  rc = pModule->xCreate(0, 0, &pTokenizer);
150848  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
150849  if( rc==SQLITE_NOMEM ){
150850  sqlite3_result_error_nomem(context);
150851  goto exprtest_out;
150852  }
150853  pTokenizer->pModule = pModule;
150854 
150855  zExpr = (const char *)sqlite3_value_text(argv[1]);
150856  nExpr = sqlite3_value_bytes(argv[1]);
150857  nCol = argc-2;
150858  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
150859  if( !azCol ){
150860  sqlite3_result_error_nomem(context);
150861  goto exprtest_out;
150862  }
150863  for(ii=0; ii<nCol; ii++){
150864  azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
150865  }
150866 
150867  if( sqlite3_user_data(context) ){
150868  char *zDummy = 0;
150869  rc = sqlite3Fts3ExprParse(
150870  pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
150871  );
150872  assert( rc==SQLITE_OK || pExpr==0 );
150873  sqlite3_free(zDummy);
150874  }else{
150875  rc = fts3ExprParseUnbalanced(
150876  pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
150877  );
150878  }
150879 
150880  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
150881  sqlite3Fts3ExprFree(pExpr);
150882  sqlite3_result_error(context, "Error parsing expression", -1);
150883  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
150884  sqlite3_result_error_nomem(context);
150885  }else{
150886  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
150887  sqlite3_free(zBuf);
150888  }
150889 
150890  sqlite3Fts3ExprFree(pExpr);
150891 
150892 exprtest_out:
150893  if( pModule && pTokenizer ){
150894  rc = pModule->xDestroy(pTokenizer);
150895  }
150896  sqlite3_free(azCol);
150897 }
150898 
150899 /*
150900 ** Register the query expression parser test function fts3_exprtest()
150901 ** with database connection db.
150902 */
150903 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
150904  int rc = sqlite3_create_function(
150905  db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
150906  );
150907  if( rc==SQLITE_OK ){
150908  rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
150909  -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
150910  );
150911  }
150912  return rc;
150913 }
150914 
150915 #endif
150916 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150917 
150918 /************** End of fts3_expr.c *******************************************/
150919 /************** Begin file fts3_hash.c ***************************************/
150920 /*
150921 ** 2001 September 22
150922 **
150923 ** The author disclaims copyright to this source code. In place of
150924 ** a legal notice, here is a blessing:
150925 **
150926 ** May you do good and not evil.
150927 ** May you find forgiveness for yourself and forgive others.
150928 ** May you share freely, never taking more than you give.
150929 **
150930 *************************************************************************
150931 ** This is the implementation of generic hash-tables used in SQLite.
150932 ** We've modified it slightly to serve as a standalone hash table
150933 ** implementation for the full-text indexing module.
150934 */
150935 
150936 /*
150937 ** The code in this file is only compiled if:
150938 **
150939 ** * The FTS3 module is being built as an extension
150940 ** (in which case SQLITE_CORE is not defined), or
150941 **
150942 ** * The FTS3 module is being built into the core of
150943 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
150944 */
150945 /* #include "fts3Int.h" */
150946 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150947 
150948 /* #include <assert.h> */
150949 /* #include <stdlib.h> */
150950 /* #include <string.h> */
150951 
150952 /* #include "fts3_hash.h" */
150953 
150954 /*
150955 ** Malloc and Free functions
150956 */
150957 static void *fts3HashMalloc(int n){
150958  void *p = sqlite3_malloc(n);
150959  if( p ){
150960  memset(p, 0, n);
150961  }
150962  return p;
150963 }
150964 static void fts3HashFree(void *p){
150965  sqlite3_free(p);
150966 }
150967 
150968 /* Turn bulk memory into a hash table object by initializing the
150969 ** fields of the Hash structure.
150970 **
150971 ** "pNew" is a pointer to the hash table that is to be initialized.
150972 ** keyClass is one of the constants
150973 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
150974 ** determines what kind of key the hash table will use. "copyKey" is
150975 ** true if the hash table should make its own private copy of keys and
150976 ** false if it should just use the supplied pointer.
150977 */
150978 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
150979  assert( pNew!=0 );
150980  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
150981  pNew->keyClass = keyClass;
150982  pNew->copyKey = copyKey;
150983  pNew->first = 0;
150984  pNew->count = 0;
150985  pNew->htsize = 0;
150986  pNew->ht = 0;
150987 }
150988 
150989 /* Remove all entries from a hash table. Reclaim all memory.
150990 ** Call this routine to delete a hash table or to reset a hash table
150991 ** to the empty state.
150992 */
150993 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
150994  Fts3HashElem *elem; /* For looping over all elements of the table */
150995 
150996  assert( pH!=0 );
150997  elem = pH->first;
150998  pH->first = 0;
150999  fts3HashFree(pH->ht);
151000  pH->ht = 0;
151001  pH->htsize = 0;
151002  while( elem ){
151003  Fts3HashElem *next_elem = elem->next;
151004  if( pH->copyKey && elem->pKey ){
151005  fts3HashFree(elem->pKey);
151006  }
151007  fts3HashFree(elem);
151008  elem = next_elem;
151009  }
151010  pH->count = 0;
151011 }
151012 
151013 /*
151014 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
151015 */
151016 static int fts3StrHash(const void *pKey, int nKey){
151017  const char *z = (const char *)pKey;
151018  unsigned h = 0;
151019  if( nKey<=0 ) nKey = (int) strlen(z);
151020  while( nKey > 0 ){
151021  h = (h<<3) ^ h ^ *z++;
151022  nKey--;
151023  }
151024  return (int)(h & 0x7fffffff);
151025 }
151026 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
151027  if( n1!=n2 ) return 1;
151028  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
151029 }
151030 
151031 /*
151032 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
151033 */
151034 static int fts3BinHash(const void *pKey, int nKey){
151035  int h = 0;
151036  const char *z = (const char *)pKey;
151037  while( nKey-- > 0 ){
151038  h = (h<<3) ^ h ^ *(z++);
151039  }
151040  return h & 0x7fffffff;
151041 }
151042 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
151043  if( n1!=n2 ) return 1;
151044  return memcmp(pKey1,pKey2,n1);
151045 }
151046 
151047 /*
151048 ** Return a pointer to the appropriate hash function given the key class.
151049 **
151050 ** The C syntax in this function definition may be unfamilar to some
151051 ** programmers, so we provide the following additional explanation:
151052 **
151053 ** The name of the function is "ftsHashFunction". The function takes a
151054 ** single parameter "keyClass". The return value of ftsHashFunction()
151055 ** is a pointer to another function. Specifically, the return value
151056 ** of ftsHashFunction() is a pointer to a function that takes two parameters
151057 ** with types "const void*" and "int" and returns an "int".
151058 */
151059 static int (*ftsHashFunction(int keyClass))(const void*,int){
151060  if( keyClass==FTS3_HASH_STRING ){
151061  return &fts3StrHash;
151062  }else{
151063  assert( keyClass==FTS3_HASH_BINARY );
151064  return &fts3BinHash;
151065  }
151066 }
151067 
151068 /*
151069 ** Return a pointer to the appropriate hash function given the key class.
151070 **
151071 ** For help in interpreted the obscure C code in the function definition,
151072 ** see the header comment on the previous function.
151073 */
151074 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
151075  if( keyClass==FTS3_HASH_STRING ){
151076  return &fts3StrCompare;
151077  }else{
151078  assert( keyClass==FTS3_HASH_BINARY );
151079  return &fts3BinCompare;
151080  }
151081 }
151082 
151083 /* Link an element into the hash table
151084 */
151085 static void fts3HashInsertElement(
151086  Fts3Hash *pH, /* The complete hash table */
151087  struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
151088  Fts3HashElem *pNew /* The element to be inserted */
151089 ){
151090  Fts3HashElem *pHead; /* First element already in pEntry */
151091  pHead = pEntry->chain;
151092  if( pHead ){
151093  pNew->next = pHead;
151094  pNew->prev = pHead->prev;
151095  if( pHead->prev ){ pHead->prev->next = pNew; }
151096  else { pH->first = pNew; }
151097  pHead->prev = pNew;
151098  }else{
151099  pNew->next = pH->first;
151100  if( pH->first ){ pH->first->prev = pNew; }
151101  pNew->prev = 0;
151102  pH->first = pNew;
151103  }
151104  pEntry->count++;
151105  pEntry->chain = pNew;
151106 }
151107 
151108 
151109 /* Resize the hash table so that it cantains "new_size" buckets.
151110 ** "new_size" must be a power of 2. The hash table might fail
151111 ** to resize if sqliteMalloc() fails.
151112 **
151113 ** Return non-zero if a memory allocation error occurs.
151114 */
151115 static int fts3Rehash(Fts3Hash *pH, int new_size){
151116  struct _fts3ht *new_ht; /* The new hash table */
151117  Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
151118  int (*xHash)(const void*,int); /* The hash function */
151119 
151120  assert( (new_size & (new_size-1))==0 );
151121  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
151122  if( new_ht==0 ) return 1;
151123  fts3HashFree(pH->ht);
151124  pH->ht = new_ht;
151125  pH->htsize = new_size;
151126  xHash = ftsHashFunction(pH->keyClass);
151127  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
151128  int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
151129  next_elem = elem->next;
151130  fts3HashInsertElement(pH, &new_ht[h], elem);
151131  }
151132  return 0;
151133 }
151134 
151135 /* This function (for internal use only) locates an element in an
151136 ** hash table that matches the given key. The hash for this key has
151137 ** already been computed and is passed as the 4th parameter.
151138 */
151139 static Fts3HashElem *fts3FindElementByHash(
151140  const Fts3Hash *pH, /* The pH to be searched */
151141  const void *pKey, /* The key we are searching for */
151142  int nKey,
151143  int h /* The hash for this key. */
151144 ){
151145  Fts3HashElem *elem; /* Used to loop thru the element list */
151146  int count; /* Number of elements left to test */
151147  int (*xCompare)(const void*,int,const void*,int); /* comparison function */
151148 
151149  if( pH->ht ){
151150  struct _fts3ht *pEntry = &pH->ht[h];
151151  elem = pEntry->chain;
151152  count = pEntry->count;
151153  xCompare = ftsCompareFunction(pH->keyClass);
151154  while( count-- && elem ){
151155  if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
151156  return elem;
151157  }
151158  elem = elem->next;
151159  }
151160  }
151161  return 0;
151162 }
151163 
151164 /* Remove a single entry from the hash table given a pointer to that
151165 ** element and a hash on the element's key.
151166 */
151167 static void fts3RemoveElementByHash(
151168  Fts3Hash *pH, /* The pH containing "elem" */
151169  Fts3HashElem* elem, /* The element to be removed from the pH */
151170  int h /* Hash value for the element */
151171 ){
151172  struct _fts3ht *pEntry;
151173  if( elem->prev ){
151174  elem->prev->next = elem->next;
151175  }else{
151176  pH->first = elem->next;
151177  }
151178  if( elem->next ){
151179  elem->next->prev = elem->prev;
151180  }
151181  pEntry = &pH->ht[h];
151182  if( pEntry->chain==elem ){
151183  pEntry->chain = elem->next;
151184  }
151185  pEntry->count--;
151186  if( pEntry->count<=0 ){
151187  pEntry->chain = 0;
151188  }
151189  if( pH->copyKey && elem->pKey ){
151190  fts3HashFree(elem->pKey);
151191  }
151192  fts3HashFree( elem );
151193  pH->count--;
151194  if( pH->count<=0 ){
151195  assert( pH->first==0 );
151196  assert( pH->count==0 );
151197  fts3HashClear(pH);
151198  }
151199 }
151200 
151201 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
151202  const Fts3Hash *pH,
151203  const void *pKey,
151204  int nKey
151205 ){
151206  int h; /* A hash on key */
151207  int (*xHash)(const void*,int); /* The hash function */
151208 
151209  if( pH==0 || pH->ht==0 ) return 0;
151210  xHash = ftsHashFunction(pH->keyClass);
151211  assert( xHash!=0 );
151212  h = (*xHash)(pKey,nKey);
151213  assert( (pH->htsize & (pH->htsize-1))==0 );
151214  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
151215 }
151216 
151217 /*
151218 ** Attempt to locate an element of the hash table pH with a key
151219 ** that matches pKey,nKey. Return the data for this element if it is
151220 ** found, or NULL if there is no match.
151221 */
151222 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
151223  Fts3HashElem *pElem; /* The element that matches key (if any) */
151224 
151225  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
151226  return pElem ? pElem->data : 0;
151227 }
151228 
151229 /* Insert an element into the hash table pH. The key is pKey,nKey
151230 ** and the data is "data".
151231 **
151232 ** If no element exists with a matching key, then a new
151233 ** element is created. A copy of the key is made if the copyKey
151234 ** flag is set. NULL is returned.
151235 **
151236 ** If another element already exists with the same key, then the
151237 ** new data replaces the old data and the old data is returned.
151238 ** The key is not copied in this instance. If a malloc fails, then
151239 ** the new data is returned and the hash table is unchanged.
151240 **
151241 ** If the "data" parameter to this function is NULL, then the
151242 ** element corresponding to "key" is removed from the hash table.
151243 */
151244 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
151245  Fts3Hash *pH, /* The hash table to insert into */
151246  const void *pKey, /* The key */
151247  int nKey, /* Number of bytes in the key */
151248  void *data /* The data */
151249 ){
151250  int hraw; /* Raw hash value of the key */
151251  int h; /* the hash of the key modulo hash table size */
151252  Fts3HashElem *elem; /* Used to loop thru the element list */
151253  Fts3HashElem *new_elem; /* New element added to the pH */
151254  int (*xHash)(const void*,int); /* The hash function */
151255 
151256  assert( pH!=0 );
151257  xHash = ftsHashFunction(pH->keyClass);
151258  assert( xHash!=0 );
151259  hraw = (*xHash)(pKey, nKey);
151260  assert( (pH->htsize & (pH->htsize-1))==0 );
151261  h = hraw & (pH->htsize-1);
151262  elem = fts3FindElementByHash(pH,pKey,nKey,h);
151263  if( elem ){
151264  void *old_data = elem->data;
151265  if( data==0 ){
151266  fts3RemoveElementByHash(pH,elem,h);
151267  }else{
151268  elem->data = data;
151269  }
151270  return old_data;
151271  }
151272  if( data==0 ) return 0;
151273  if( (pH->htsize==0 && fts3Rehash(pH,8))
151274  || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
151275  ){
151276  pH->count = 0;
151277  return data;
151278  }
151279  assert( pH->htsize>0 );
151280  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
151281  if( new_elem==0 ) return data;
151282  if( pH->copyKey && pKey!=0 ){
151283  new_elem->pKey = fts3HashMalloc( nKey );
151284  if( new_elem->pKey==0 ){
151285  fts3HashFree(new_elem);
151286  return data;
151287  }
151288  memcpy((void*)new_elem->pKey, pKey, nKey);
151289  }else{
151290  new_elem->pKey = (void*)pKey;
151291  }
151292  new_elem->nKey = nKey;
151293  pH->count++;
151294  assert( pH->htsize>0 );
151295  assert( (pH->htsize & (pH->htsize-1))==0 );
151296  h = hraw & (pH->htsize-1);
151297  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
151298  new_elem->data = data;
151299  return 0;
151300 }
151301 
151302 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151303 
151304 /************** End of fts3_hash.c *******************************************/
151305 /************** Begin file fts3_porter.c *************************************/
151306 /*
151307 ** 2006 September 30
151308 **
151309 ** The author disclaims copyright to this source code. In place of
151310 ** a legal notice, here is a blessing:
151311 **
151312 ** May you do good and not evil.
151313 ** May you find forgiveness for yourself and forgive others.
151314 ** May you share freely, never taking more than you give.
151315 **
151316 *************************************************************************
151317 ** Implementation of the full-text-search tokenizer that implements
151318 ** a Porter stemmer.
151319 */
151320 
151321 /*
151322 ** The code in this file is only compiled if:
151323 **
151324 ** * The FTS3 module is being built as an extension
151325 ** (in which case SQLITE_CORE is not defined), or
151326 **
151327 ** * The FTS3 module is being built into the core of
151328 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
151329 */
151330 /* #include "fts3Int.h" */
151331 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151332 
151333 /* #include <assert.h> */
151334 /* #include <stdlib.h> */
151335 /* #include <stdio.h> */
151336 /* #include <string.h> */
151337 
151338 /* #include "fts3_tokenizer.h" */
151339 
151340 /*
151341 ** Class derived from sqlite3_tokenizer
151342 */
151343 typedef struct porter_tokenizer {
151344  sqlite3_tokenizer base; /* Base class */
151345 } porter_tokenizer;
151346 
151347 /*
151348 ** Class derived from sqlite3_tokenizer_cursor
151349 */
151350 typedef struct porter_tokenizer_cursor {
151351  sqlite3_tokenizer_cursor base;
151352  const char *zInput; /* input we are tokenizing */
151353  int nInput; /* size of the input */
151354  int iOffset; /* current position in zInput */
151355  int iToken; /* index of next token to be returned */
151356  char *zToken; /* storage for current token */
151357  int nAllocated; /* space allocated to zToken buffer */
151358 } porter_tokenizer_cursor;
151359 
151360 
151361 /*
151362 ** Create a new tokenizer instance.
151363 */
151364 static int porterCreate(
151365  int argc, const char * const *argv,
151366  sqlite3_tokenizer **ppTokenizer
151367 ){
151368  porter_tokenizer *t;
151369 
151370  UNUSED_PARAMETER(argc);
151371  UNUSED_PARAMETER(argv);
151372 
151373  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
151374  if( t==NULL ) return SQLITE_NOMEM;
151375  memset(t, 0, sizeof(*t));
151376  *ppTokenizer = &t->base;
151377  return SQLITE_OK;
151378 }
151379 
151380 /*
151381 ** Destroy a tokenizer
151382 */
151383 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
151384  sqlite3_free(pTokenizer);
151385  return SQLITE_OK;
151386 }
151387 
151388 /*
151389 ** Prepare to begin tokenizing a particular string. The input
151390 ** string to be tokenized is zInput[0..nInput-1]. A cursor
151391 ** used to incrementally tokenize this string is returned in
151392 ** *ppCursor.
151393 */
151394 static int porterOpen(
151395  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
151396  const char *zInput, int nInput, /* String to be tokenized */
151397  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
151398 ){
151399  porter_tokenizer_cursor *c;
151400 
151401  UNUSED_PARAMETER(pTokenizer);
151402 
151403  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
151404  if( c==NULL ) return SQLITE_NOMEM;
151405 
151406  c->zInput = zInput;
151407  if( zInput==0 ){
151408  c->nInput = 0;
151409  }else if( nInput<0 ){
151410  c->nInput = (int)strlen(zInput);
151411  }else{
151412  c->nInput = nInput;
151413  }
151414  c->iOffset = 0; /* start tokenizing at the beginning */
151415  c->iToken = 0;
151416  c->zToken = NULL; /* no space allocated, yet. */
151417  c->nAllocated = 0;
151418 
151419  *ppCursor = &c->base;
151420  return SQLITE_OK;
151421 }
151422 
151423 /*
151424 ** Close a tokenization cursor previously opened by a call to
151425 ** porterOpen() above.
151426 */
151427 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
151428  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
151429  sqlite3_free(c->zToken);
151430  sqlite3_free(c);
151431  return SQLITE_OK;
151432 }
151433 /*
151434 ** Vowel or consonant
151435 */
151436 static const char cType[] = {
151437  0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
151438  1, 1, 1, 2, 1
151439 };
151440 
151441 /*
151442 ** isConsonant() and isVowel() determine if their first character in
151443 ** the string they point to is a consonant or a vowel, according
151444 ** to Porter ruls.
151445 **
151446 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
151447 ** 'Y' is a consonant unless it follows another consonant,
151448 ** in which case it is a vowel.
151449 **
151450 ** In these routine, the letters are in reverse order. So the 'y' rule
151451 ** is that 'y' is a consonant unless it is followed by another
151452 ** consonent.
151453 */
151454 static int isVowel(const char*);
151455 static int isConsonant(const char *z){
151456  int j;
151457  char x = *z;
151458  if( x==0 ) return 0;
151459  assert( x>='a' && x<='z' );
151460  j = cType[x-'a'];
151461  if( j<2 ) return j;
151462  return z[1]==0 || isVowel(z + 1);
151463 }
151464 static int isVowel(const char *z){
151465  int j;
151466  char x = *z;
151467  if( x==0 ) return 0;
151468  assert( x>='a' && x<='z' );
151469  j = cType[x-'a'];
151470  if( j<2 ) return 1-j;
151471  return isConsonant(z + 1);
151472 }
151473 
151474 /*
151475 ** Let any sequence of one or more vowels be represented by V and let
151476 ** C be sequence of one or more consonants. Then every word can be
151477 ** represented as:
151478 **
151479 ** [C] (VC){m} [V]
151480 **
151481 ** In prose: A word is an optional consonant followed by zero or
151482 ** vowel-consonant pairs followed by an optional vowel. "m" is the
151483 ** number of vowel consonant pairs. This routine computes the value
151484 ** of m for the first i bytes of a word.
151485 **
151486 ** Return true if the m-value for z is 1 or more. In other words,
151487 ** return true if z contains at least one vowel that is followed
151488 ** by a consonant.
151489 **
151490 ** In this routine z[] is in reverse order. So we are really looking
151491 ** for an instance of a consonant followed by a vowel.
151492 */
151493 static int m_gt_0(const char *z){
151494  while( isVowel(z) ){ z++; }
151495  if( *z==0 ) return 0;
151496  while( isConsonant(z) ){ z++; }
151497  return *z!=0;
151498 }
151499 
151500 /* Like mgt0 above except we are looking for a value of m which is
151501 ** exactly 1
151502 */
151503 static int m_eq_1(const char *z){
151504  while( isVowel(z) ){ z++; }
151505  if( *z==0 ) return 0;
151506  while( isConsonant(z) ){ z++; }
151507  if( *z==0 ) return 0;
151508  while( isVowel(z) ){ z++; }
151509  if( *z==0 ) return 1;
151510  while( isConsonant(z) ){ z++; }
151511  return *z==0;
151512 }
151513 
151514 /* Like mgt0 above except we are looking for a value of m>1 instead
151515 ** or m>0
151516 */
151517 static int m_gt_1(const char *z){
151518  while( isVowel(z) ){ z++; }
151519  if( *z==0 ) return 0;
151520  while( isConsonant(z) ){ z++; }
151521  if( *z==0 ) return 0;
151522  while( isVowel(z) ){ z++; }
151523  if( *z==0 ) return 0;
151524  while( isConsonant(z) ){ z++; }
151525  return *z!=0;
151526 }
151527 
151528 /*
151529 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
151530 */
151531 static int hasVowel(const char *z){
151532  while( isConsonant(z) ){ z++; }
151533  return *z!=0;
151534 }
151535 
151536 /*
151537 ** Return TRUE if the word ends in a double consonant.
151538 **
151539 ** The text is reversed here. So we are really looking at
151540 ** the first two characters of z[].
151541 */
151542 static int doubleConsonant(const char *z){
151543  return isConsonant(z) && z[0]==z[1];
151544 }
151545 
151546 /*
151547 ** Return TRUE if the word ends with three letters which
151548 ** are consonant-vowel-consonent and where the final consonant
151549 ** is not 'w', 'x', or 'y'.
151550 **
151551 ** The word is reversed here. So we are really checking the
151552 ** first three letters and the first one cannot be in [wxy].
151553 */
151554 static int star_oh(const char *z){
151555  return
151556  isConsonant(z) &&
151557  z[0]!='w' && z[0]!='x' && z[0]!='y' &&
151558  isVowel(z+1) &&
151559  isConsonant(z+2);
151560 }
151561 
151562 /*
151563 ** If the word ends with zFrom and xCond() is true for the stem
151564 ** of the word that preceeds the zFrom ending, then change the
151565 ** ending to zTo.
151566 **
151567 ** The input word *pz and zFrom are both in reverse order. zTo
151568 ** is in normal order.
151569 **
151570 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
151571 ** match. Not that TRUE is returned even if xCond() fails and
151572 ** no substitution occurs.
151573 */
151574 static int stem(
151575  char **pz, /* The word being stemmed (Reversed) */
151576  const char *zFrom, /* If the ending matches this... (Reversed) */
151577  const char *zTo, /* ... change the ending to this (not reversed) */
151578  int (*xCond)(const char*) /* Condition that must be true */
151579 ){
151580  char *z = *pz;
151581  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
151582  if( *zFrom!=0 ) return 0;
151583  if( xCond && !xCond(z) ) return 1;
151584  while( *zTo ){
151585  *(--z) = *(zTo++);
151586  }
151587  *pz = z;
151588  return 1;
151589 }
151590 
151591 /*
151592 ** This is the fallback stemmer used when the porter stemmer is
151593 ** inappropriate. The input word is copied into the output with
151594 ** US-ASCII case folding. If the input word is too long (more
151595 ** than 20 bytes if it contains no digits or more than 6 bytes if
151596 ** it contains digits) then word is truncated to 20 or 6 bytes
151597 ** by taking 10 or 3 bytes from the beginning and end.
151598 */
151599 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
151600  int i, mx, j;
151601  int hasDigit = 0;
151602  for(i=0; i<nIn; i++){
151603  char c = zIn[i];
151604  if( c>='A' && c<='Z' ){
151605  zOut[i] = c - 'A' + 'a';
151606  }else{
151607  if( c>='0' && c<='9' ) hasDigit = 1;
151608  zOut[i] = c;
151609  }
151610  }
151611  mx = hasDigit ? 3 : 10;
151612  if( nIn>mx*2 ){
151613  for(j=mx, i=nIn-mx; i<nIn; i++, j++){
151614  zOut[j] = zOut[i];
151615  }
151616  i = j;
151617  }
151618  zOut[i] = 0;
151619  *pnOut = i;
151620 }
151621 
151622 
151623 /*
151624 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
151625 ** zOut is at least big enough to hold nIn bytes. Write the actual
151626 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
151627 **
151628 ** Any upper-case characters in the US-ASCII character set ([A-Z])
151629 ** are converted to lower case. Upper-case UTF characters are
151630 ** unchanged.
151631 **
151632 ** Words that are longer than about 20 bytes are stemmed by retaining
151633 ** a few bytes from the beginning and the end of the word. If the
151634 ** word contains digits, 3 bytes are taken from the beginning and
151635 ** 3 bytes from the end. For long words without digits, 10 bytes
151636 ** are taken from each end. US-ASCII case folding still applies.
151637 **
151638 ** If the input word contains not digits but does characters not
151639 ** in [a-zA-Z] then no stemming is attempted and this routine just
151640 ** copies the input into the input into the output with US-ASCII
151641 ** case folding.
151642 **
151643 ** Stemming never increases the length of the word. So there is
151644 ** no chance of overflowing the zOut buffer.
151645 */
151646 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
151647  int i, j;
151648  char zReverse[28];
151649  char *z, *z2;
151650  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
151651  /* The word is too big or too small for the porter stemmer.
151652  ** Fallback to the copy stemmer */
151653  copy_stemmer(zIn, nIn, zOut, pnOut);
151654  return;
151655  }
151656  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
151657  char c = zIn[i];
151658  if( c>='A' && c<='Z' ){
151659  zReverse[j] = c + 'a' - 'A';
151660  }else if( c>='a' && c<='z' ){
151661  zReverse[j] = c;
151662  }else{
151663  /* The use of a character not in [a-zA-Z] means that we fallback
151664  ** to the copy stemmer */
151665  copy_stemmer(zIn, nIn, zOut, pnOut);
151666  return;
151667  }
151668  }
151669  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
151670  z = &zReverse[j+1];
151671 
151672 
151673  /* Step 1a */
151674  if( z[0]=='s' ){
151675  if(
151676  !stem(&z, "sess", "ss", 0) &&
151677  !stem(&z, "sei", "i", 0) &&
151678  !stem(&z, "ss", "ss", 0)
151679  ){
151680  z++;
151681  }
151682  }
151683 
151684  /* Step 1b */
151685  z2 = z;
151686  if( stem(&z, "dee", "ee", m_gt_0) ){
151687  /* Do nothing. The work was all in the test */
151688  }else if(
151689  (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
151690  && z!=z2
151691  ){
151692  if( stem(&z, "ta", "ate", 0) ||
151693  stem(&z, "lb", "ble", 0) ||
151694  stem(&z, "zi", "ize", 0) ){
151695  /* Do nothing. The work was all in the test */
151696  }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
151697  z++;
151698  }else if( m_eq_1(z) && star_oh(z) ){
151699  *(--z) = 'e';
151700  }
151701  }
151702 
151703  /* Step 1c */
151704  if( z[0]=='y' && hasVowel(z+1) ){
151705  z[0] = 'i';
151706  }
151707 
151708  /* Step 2 */
151709  switch( z[1] ){
151710  case 'a':
151711  if( !stem(&z, "lanoita", "ate", m_gt_0) ){
151712  stem(&z, "lanoit", "tion", m_gt_0);
151713  }
151714  break;
151715  case 'c':
151716  if( !stem(&z, "icne", "ence", m_gt_0) ){
151717  stem(&z, "icna", "ance", m_gt_0);
151718  }
151719  break;
151720  case 'e':
151721  stem(&z, "rezi", "ize", m_gt_0);
151722  break;
151723  case 'g':
151724  stem(&z, "igol", "log", m_gt_0);
151725  break;
151726  case 'l':
151727  if( !stem(&z, "ilb", "ble", m_gt_0)
151728  && !stem(&z, "illa", "al", m_gt_0)
151729  && !stem(&z, "iltne", "ent", m_gt_0)
151730  && !stem(&z, "ile", "e", m_gt_0)
151731  ){
151732  stem(&z, "ilsuo", "ous", m_gt_0);
151733  }
151734  break;
151735  case 'o':
151736  if( !stem(&z, "noitazi", "ize", m_gt_0)
151737  && !stem(&z, "noita", "ate", m_gt_0)
151738  ){
151739  stem(&z, "rota", "ate", m_gt_0);
151740  }
151741  break;
151742  case 's':
151743  if( !stem(&z, "msila", "al", m_gt_0)
151744  && !stem(&z, "ssenevi", "ive", m_gt_0)
151745  && !stem(&z, "ssenluf", "ful", m_gt_0)
151746  ){
151747  stem(&z, "ssensuo", "ous", m_gt_0);
151748  }
151749  break;
151750  case 't':
151751  if( !stem(&z, "itila", "al", m_gt_0)
151752  && !stem(&z, "itivi", "ive", m_gt_0)
151753  ){
151754  stem(&z, "itilib", "ble", m_gt_0);
151755  }
151756  break;
151757  }
151758 
151759  /* Step 3 */
151760  switch( z[0] ){
151761  case 'e':
151762  if( !stem(&z, "etaci", "ic", m_gt_0)
151763  && !stem(&z, "evita", "", m_gt_0)
151764  ){
151765  stem(&z, "ezila", "al", m_gt_0);
151766  }
151767  break;
151768  case 'i':
151769  stem(&z, "itici", "ic", m_gt_0);
151770  break;
151771  case 'l':
151772  if( !stem(&z, "laci", "ic", m_gt_0) ){
151773  stem(&z, "luf", "", m_gt_0);
151774  }
151775  break;
151776  case 's':
151777  stem(&z, "ssen", "", m_gt_0);
151778  break;
151779  }
151780 
151781  /* Step 4 */
151782  switch( z[1] ){
151783  case 'a':
151784  if( z[0]=='l' && m_gt_1(z+2) ){
151785  z += 2;
151786  }
151787  break;
151788  case 'c':
151789  if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
151790  z += 4;
151791  }
151792  break;
151793  case 'e':
151794  if( z[0]=='r' && m_gt_1(z+2) ){
151795  z += 2;
151796  }
151797  break;
151798  case 'i':
151799  if( z[0]=='c' && m_gt_1(z+2) ){
151800  z += 2;
151801  }
151802  break;
151803  case 'l':
151804  if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
151805  z += 4;
151806  }
151807  break;
151808  case 'n':
151809  if( z[0]=='t' ){
151810  if( z[2]=='a' ){
151811  if( m_gt_1(z+3) ){
151812  z += 3;
151813  }
151814  }else if( z[2]=='e' ){
151815  if( !stem(&z, "tneme", "", m_gt_1)
151816  && !stem(&z, "tnem", "", m_gt_1)
151817  ){
151818  stem(&z, "tne", "", m_gt_1);
151819  }
151820  }
151821  }
151822  break;
151823  case 'o':
151824  if( z[0]=='u' ){
151825  if( m_gt_1(z+2) ){
151826  z += 2;
151827  }
151828  }else if( z[3]=='s' || z[3]=='t' ){
151829  stem(&z, "noi", "", m_gt_1);
151830  }
151831  break;
151832  case 's':
151833  if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
151834  z += 3;
151835  }
151836  break;
151837  case 't':
151838  if( !stem(&z, "eta", "", m_gt_1) ){
151839  stem(&z, "iti", "", m_gt_1);
151840  }
151841  break;
151842  case 'u':
151843  if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
151844  z += 3;
151845  }
151846  break;
151847  case 'v':
151848  case 'z':
151849  if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
151850  z += 3;
151851  }
151852  break;
151853  }
151854 
151855  /* Step 5a */
151856  if( z[0]=='e' ){
151857  if( m_gt_1(z+1) ){
151858  z++;
151859  }else if( m_eq_1(z+1) && !star_oh(z+1) ){
151860  z++;
151861  }
151862  }
151863 
151864  /* Step 5b */
151865  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
151866  z++;
151867  }
151868 
151869  /* z[] is now the stemmed word in reverse order. Flip it back
151870  ** around into forward order and return.
151871  */
151872  *pnOut = i = (int)strlen(z);
151873  zOut[i] = 0;
151874  while( *z ){
151875  zOut[--i] = *(z++);
151876  }
151877 }
151878 
151879 /*
151880 ** Characters that can be part of a token. We assume any character
151881 ** whose value is greater than 0x80 (any UTF character) can be
151882 ** part of a token. In other words, delimiters all must have
151883 ** values of 0x7f or lower.
151884 */
151885 static const char porterIdChar[] = {
151886 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
151887  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
151888  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
151889  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
151890  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
151891  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
151892 };
151893 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
151894 
151895 /*
151896 ** Extract the next token from a tokenization cursor. The cursor must
151897 ** have been opened by a prior call to porterOpen().
151898 */
151899 static int porterNext(
151900  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
151901  const char **pzToken, /* OUT: *pzToken is the token text */
151902  int *pnBytes, /* OUT: Number of bytes in token */
151903  int *piStartOffset, /* OUT: Starting offset of token */
151904  int *piEndOffset, /* OUT: Ending offset of token */
151905  int *piPosition /* OUT: Position integer of token */
151906 ){
151907  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
151908  const char *z = c->zInput;
151909 
151910  while( c->iOffset<c->nInput ){
151911  int iStartOffset, ch;
151912 
151913  /* Scan past delimiter characters */
151914  while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
151915  c->iOffset++;
151916  }
151917 
151918  /* Count non-delimiter characters. */
151919  iStartOffset = c->iOffset;
151920  while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
151921  c->iOffset++;
151922  }
151923 
151924  if( c->iOffset>iStartOffset ){
151925  int n = c->iOffset-iStartOffset;
151926  if( n>c->nAllocated ){
151927  char *pNew;
151928  c->nAllocated = n+20;
151929  pNew = sqlite3_realloc(c->zToken, c->nAllocated);
151930  if( !pNew ) return SQLITE_NOMEM;
151931  c->zToken = pNew;
151932  }
151933  porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
151934  *pzToken = c->zToken;
151935  *piStartOffset = iStartOffset;
151936  *piEndOffset = c->iOffset;
151937  *piPosition = c->iToken++;
151938  return SQLITE_OK;
151939  }
151940  }
151941  return SQLITE_DONE;
151942 }
151943 
151944 /*
151945 ** The set of routines that implement the porter-stemmer tokenizer
151946 */
151947 static const sqlite3_tokenizer_module porterTokenizerModule = {
151948  0,
151949  porterCreate,
151950  porterDestroy,
151951  porterOpen,
151952  porterClose,
151953  porterNext,
151954  0
151955 };
151956 
151957 /*
151958 ** Allocate a new porter tokenizer. Return a pointer to the new
151959 ** tokenizer in *ppModule
151960 */
151961 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
151962  sqlite3_tokenizer_module const**ppModule
151963 ){
151964  *ppModule = &porterTokenizerModule;
151965 }
151966 
151967 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151968 
151969 /************** End of fts3_porter.c *****************************************/
151970 /************** Begin file fts3_tokenizer.c **********************************/
151971 /*
151972 ** 2007 June 22
151973 **
151974 ** The author disclaims copyright to this source code. In place of
151975 ** a legal notice, here is a blessing:
151976 **
151977 ** May you do good and not evil.
151978 ** May you find forgiveness for yourself and forgive others.
151979 ** May you share freely, never taking more than you give.
151980 **
151981 ******************************************************************************
151982 **
151983 ** This is part of an SQLite module implementing full-text search.
151984 ** This particular file implements the generic tokenizer interface.
151985 */
151986 
151987 /*
151988 ** The code in this file is only compiled if:
151989 **
151990 ** * The FTS3 module is being built as an extension
151991 ** (in which case SQLITE_CORE is not defined), or
151992 **
151993 ** * The FTS3 module is being built into the core of
151994 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
151995 */
151996 /* #include "fts3Int.h" */
151997 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151998 
151999 /* #include <assert.h> */
152000 /* #include <string.h> */
152001 
152002 /*
152003 ** Return true if the two-argument version of fts3_tokenizer()
152004 ** has been activated via a prior call to sqlite3_db_config(db,
152005 ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
152006 */
152007 static int fts3TokenizerEnabled(sqlite3_context *context){
152008  sqlite3 *db = sqlite3_context_db_handle(context);
152009  int isEnabled = 0;
152011  return isEnabled;
152012 }
152013 
152014 /*
152015 ** Implementation of the SQL scalar function for accessing the underlying
152016 ** hash table. This function may be called as follows:
152017 **
152018 ** SELECT <function-name>(<key-name>);
152019 ** SELECT <function-name>(<key-name>, <pointer>);
152020 **
152021 ** where <function-name> is the name passed as the second argument
152022 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
152023 **
152024 ** If the <pointer> argument is specified, it must be a blob value
152025 ** containing a pointer to be stored as the hash data corresponding
152026 ** to the string <key-name>. If <pointer> is not specified, then
152027 ** the string <key-name> must already exist in the has table. Otherwise,
152028 ** an error is returned.
152029 **
152030 ** Whether or not the <pointer> argument is specified, the value returned
152031 ** is a blob containing the pointer stored as the hash data corresponding
152032 ** to string <key-name> (after the hash-table is updated, if applicable).
152033 */
152034 static void fts3TokenizerFunc(
152035  sqlite3_context *context,
152036  int argc,
152037  sqlite3_value **argv
152038 ){
152039  Fts3Hash *pHash;
152040  void *pPtr = 0;
152041  const unsigned char *zName;
152042  int nName;
152043 
152044  assert( argc==1 || argc==2 );
152045 
152046  pHash = (Fts3Hash *)sqlite3_user_data(context);
152047 
152048  zName = sqlite3_value_text(argv[0]);
152049  nName = sqlite3_value_bytes(argv[0])+1;
152050 
152051  if( argc==2 ){
152052  if( fts3TokenizerEnabled(context) ){
152053  void *pOld;
152054  int n = sqlite3_value_bytes(argv[1]);
152055  if( zName==0 || n!=sizeof(pPtr) ){
152056  sqlite3_result_error(context, "argument type mismatch", -1);
152057  return;
152058  }
152059  pPtr = *(void **)sqlite3_value_blob(argv[1]);
152060  pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
152061  if( pOld==pPtr ){
152062  sqlite3_result_error(context, "out of memory", -1);
152063  }
152064  }else{
152065  sqlite3_result_error(context, "fts3tokenize disabled", -1);
152066  return;
152067  }
152068  }else{
152069  if( zName ){
152070  pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
152071  }
152072  if( !pPtr ){
152073  char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
152074  sqlite3_result_error(context, zErr, -1);
152075  sqlite3_free(zErr);
152076  return;
152077  }
152078  }
152079  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
152080 }
152081 
152082 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
152083  static const char isFtsIdChar[] = {
152084  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
152085  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
152086  0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
152087  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
152088  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
152089  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
152090  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
152091  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
152092  };
152093  return (c&0x80 || isFtsIdChar[(int)(c)]);
152094 }
152095 
152096 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
152097  const char *z1;
152098  const char *z2 = 0;
152099 
152100  /* Find the start of the next token. */
152101  z1 = zStr;
152102  while( z2==0 ){
152103  char c = *z1;
152104  switch( c ){
152105  case '\0': return 0; /* No more tokens here */
152106  case '\'':
152107  case '"':
152108  case '`': {
152109  z2 = z1;
152110  while( *++z2 && (*z2!=c || *++z2==c) );
152111  break;
152112  }
152113  case '[':
152114  z2 = &z1[1];
152115  while( *z2 && z2[0]!=']' ) z2++;
152116  if( *z2 ) z2++;
152117  break;
152118 
152119  default:
152120  if( sqlite3Fts3IsIdChar(*z1) ){
152121  z2 = &z1[1];
152122  while( sqlite3Fts3IsIdChar(*z2) ) z2++;
152123  }else{
152124  z1++;
152125  }
152126  }
152127  }
152128 
152129  *pn = (int)(z2-z1);
152130  return z1;
152131 }
152132 
152133 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
152134  Fts3Hash *pHash, /* Tokenizer hash table */
152135  const char *zArg, /* Tokenizer name */
152136  sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
152137  char **pzErr /* OUT: Set to malloced error message */
152138 ){
152139  int rc;
152140  char *z = (char *)zArg;
152141  int n = 0;
152142  char *zCopy;
152143  char *zEnd; /* Pointer to nul-term of zCopy */
152144  sqlite3_tokenizer_module *m;
152145 
152146  zCopy = sqlite3_mprintf("%s", zArg);
152147  if( !zCopy ) return SQLITE_NOMEM;
152148  zEnd = &zCopy[strlen(zCopy)];
152149 
152150  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
152151  if( z==0 ){
152152  assert( n==0 );
152153  z = zCopy;
152154  }
152155  z[n] = '\0';
152156  sqlite3Fts3Dequote(z);
152157 
152158  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
152159  if( !m ){
152160  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
152161  rc = SQLITE_ERROR;
152162  }else{
152163  char const **aArg = 0;
152164  int iArg = 0;
152165  z = &z[n+1];
152166  while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
152167  int nNew = sizeof(char *)*(iArg+1);
152168  char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
152169  if( !aNew ){
152170  sqlite3_free(zCopy);
152171  sqlite3_free((void *)aArg);
152172  return SQLITE_NOMEM;
152173  }
152174  aArg = aNew;
152175  aArg[iArg++] = z;
152176  z[n] = '\0';
152177  sqlite3Fts3Dequote(z);
152178  z = &z[n+1];
152179  }
152180  rc = m->xCreate(iArg, aArg, ppTok);
152181  assert( rc!=SQLITE_OK || *ppTok );
152182  if( rc!=SQLITE_OK ){
152183  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
152184  }else{
152185  (*ppTok)->pModule = m;
152186  }
152187  sqlite3_free((void *)aArg);
152188  }
152189 
152190  sqlite3_free(zCopy);
152191  return rc;
152192 }
152193 
152194 
152195 #ifdef SQLITE_TEST
152196 
152197 #if defined(INCLUDE_SQLITE_TCL_H)
152198 # include "sqlite_tcl.h"
152199 #else
152200 # include "tcl.h"
152201 #endif
152202 /* #include <string.h> */
152203 
152204 /*
152205 ** Implementation of a special SQL scalar function for testing tokenizers
152206 ** designed to be used in concert with the Tcl testing framework. This
152207 ** function must be called with two or more arguments:
152208 **
152209 ** SELECT <function-name>(<key-name>, ..., <input-string>);
152210 **
152211 ** where <function-name> is the name passed as the second argument
152212 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
152213 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
152214 **
152215 ** The return value is a string that may be interpreted as a Tcl
152216 ** list. For each token in the <input-string>, three elements are
152217 ** added to the returned list. The first is the token position, the
152218 ** second is the token text (folded, stemmed, etc.) and the third is the
152219 ** substring of <input-string> associated with the token. For example,
152220 ** using the built-in "simple" tokenizer:
152221 **
152222 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
152223 **
152224 ** will return the string:
152225 **
152226 ** "{0 i I 1 dont don't 2 see see 3 how how}"
152227 **
152228 */
152229 static void testFunc(
152230  sqlite3_context *context,
152231  int argc,
152232  sqlite3_value **argv
152233 ){
152234  Fts3Hash *pHash;
152235  sqlite3_tokenizer_module *p;
152236  sqlite3_tokenizer *pTokenizer = 0;
152237  sqlite3_tokenizer_cursor *pCsr = 0;
152238 
152239  const char *zErr = 0;
152240 
152241  const char *zName;
152242  int nName;
152243  const char *zInput;
152244  int nInput;
152245 
152246  const char *azArg[64];
152247 
152248  const char *zToken;
152249  int nToken = 0;
152250  int iStart = 0;
152251  int iEnd = 0;
152252  int iPos = 0;
152253  int i;
152254 
152255  Tcl_Obj *pRet;
152256 
152257  if( argc<2 ){
152258  sqlite3_result_error(context, "insufficient arguments", -1);
152259  return;
152260  }
152261 
152262  nName = sqlite3_value_bytes(argv[0]);
152263  zName = (const char *)sqlite3_value_text(argv[0]);
152264  nInput = sqlite3_value_bytes(argv[argc-1]);
152265  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
152266 
152267  pHash = (Fts3Hash *)sqlite3_user_data(context);
152268  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
152269 
152270  if( !p ){
152271  char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
152272  sqlite3_result_error(context, zErr2, -1);
152273  sqlite3_free(zErr2);
152274  return;
152275  }
152276 
152277  pRet = Tcl_NewObj();
152278  Tcl_IncrRefCount(pRet);
152279 
152280  for(i=1; i<argc-1; i++){
152281  azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
152282  }
152283 
152284  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
152285  zErr = "error in xCreate()";
152286  goto finish;
152287  }
152288  pTokenizer->pModule = p;
152289  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
152290  zErr = "error in xOpen()";
152291  goto finish;
152292  }
152293 
152294  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
152295  Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
152296  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
152297  zToken = &zInput[iStart];
152298  nToken = iEnd-iStart;
152299  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
152300  }
152301 
152302  if( SQLITE_OK!=p->xClose(pCsr) ){
152303  zErr = "error in xClose()";
152304  goto finish;
152305  }
152306  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
152307  zErr = "error in xDestroy()";
152308  goto finish;
152309  }
152310 
152311 finish:
152312  if( zErr ){
152313  sqlite3_result_error(context, zErr, -1);
152314  }else{
152315  sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
152316  }
152317  Tcl_DecrRefCount(pRet);
152318 }
152319 
152320 static
152321 int registerTokenizer(
152322  sqlite3 *db,
152323  char *zName,
152324  const sqlite3_tokenizer_module *p
152325 ){
152326  int rc;
152327  sqlite3_stmt *pStmt;
152328  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
152329 
152330  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
152331  if( rc!=SQLITE_OK ){
152332  return rc;
152333  }
152334 
152335  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
152336  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
152337  sqlite3_step(pStmt);
152338 
152339  return sqlite3_finalize(pStmt);
152340 }
152341 
152342 
152343 static
152344 int queryTokenizer(
152345  sqlite3 *db,
152346  char *zName,
152347  const sqlite3_tokenizer_module **pp
152348 ){
152349  int rc;
152350  sqlite3_stmt *pStmt;
152351  const char zSql[] = "SELECT fts3_tokenizer(?)";
152352 
152353  *pp = 0;
152354  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
152355  if( rc!=SQLITE_OK ){
152356  return rc;
152357  }
152358 
152359  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
152360  if( SQLITE_ROW==sqlite3_step(pStmt) ){
152361  if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
152362  memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
152363  }
152364  }
152365 
152366  return sqlite3_finalize(pStmt);
152367 }
152368 
152369 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
152370 
152371 /*
152372 ** Implementation of the scalar function fts3_tokenizer_internal_test().
152373 ** This function is used for testing only, it is not included in the
152374 ** build unless SQLITE_TEST is defined.
152375 **
152376 ** The purpose of this is to test that the fts3_tokenizer() function
152377 ** can be used as designed by the C-code in the queryTokenizer and
152378 ** registerTokenizer() functions above. These two functions are repeated
152379 ** in the README.tokenizer file as an example, so it is important to
152380 ** test them.
152381 **
152382 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
152383 ** function with no arguments. An assert() will fail if a problem is
152384 ** detected. i.e.:
152385 **
152386 ** SELECT fts3_tokenizer_internal_test();
152387 **
152388 */
152389 static void intTestFunc(
152390  sqlite3_context *context,
152391  int argc,
152392  sqlite3_value **argv
152393 ){
152394  int rc;
152395  const sqlite3_tokenizer_module *p1;
152396  const sqlite3_tokenizer_module *p2;
152397  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
152398 
152399  UNUSED_PARAMETER(argc);
152400  UNUSED_PARAMETER(argv);
152401 
152402  /* Test the query function */
152403  sqlite3Fts3SimpleTokenizerModule(&p1);
152404  rc = queryTokenizer(db, "simple", &p2);
152405  assert( rc==SQLITE_OK );
152406  assert( p1==p2 );
152407  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
152408  assert( rc==SQLITE_ERROR );
152409  assert( p2==0 );
152410  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
152411 
152412  /* Test the storage function */
152413  if( fts3TokenizerEnabled(context) ){
152414  rc = registerTokenizer(db, "nosuchtokenizer", p1);
152415  assert( rc==SQLITE_OK );
152416  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
152417  assert( rc==SQLITE_OK );
152418  assert( p2==p1 );
152419  }
152420 
152421  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
152422 }
152423 
152424 #endif
152425 
152426 /*
152427 ** Set up SQL objects in database db used to access the contents of
152428 ** the hash table pointed to by argument pHash. The hash table must
152429 ** been initialized to use string keys, and to take a private copy
152430 ** of the key when a value is inserted. i.e. by a call similar to:
152431 **
152432 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
152433 **
152434 ** This function adds a scalar function (see header comment above
152435 ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
152436 ** defined at compilation time, a temporary virtual table (see header
152437 ** comment above struct HashTableVtab) to the database schema. Both
152438 ** provide read/write access to the contents of *pHash.
152439 **
152440 ** The third argument to this function, zName, is used as the name
152441 ** of both the scalar and, if created, the virtual table.
152442 */
152443 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
152444  sqlite3 *db,
152445  Fts3Hash *pHash,
152446  const char *zName
152447 ){
152448  int rc = SQLITE_OK;
152449  void *p = (void *)pHash;
152450  const int any = SQLITE_ANY;
152451 
152452 #ifdef SQLITE_TEST
152453  char *zTest = 0;
152454  char *zTest2 = 0;
152455  void *pdb = (void *)db;
152456  zTest = sqlite3_mprintf("%s_test", zName);
152457  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
152458  if( !zTest || !zTest2 ){
152459  rc = SQLITE_NOMEM;
152460  }
152461 #endif
152462 
152463  if( SQLITE_OK==rc ){
152464  rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
152465  }
152466  if( SQLITE_OK==rc ){
152467  rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
152468  }
152469 #ifdef SQLITE_TEST
152470  if( SQLITE_OK==rc ){
152471  rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
152472  }
152473  if( SQLITE_OK==rc ){
152474  rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
152475  }
152476 #endif
152477 
152478 #ifdef SQLITE_TEST
152479  sqlite3_free(zTest);
152480  sqlite3_free(zTest2);
152481 #endif
152482 
152483  return rc;
152484 }
152485 
152486 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
152487 
152488 /************** End of fts3_tokenizer.c **************************************/
152489 /************** Begin file fts3_tokenizer1.c *********************************/
152490 /*
152491 ** 2006 Oct 10
152492 **
152493 ** The author disclaims copyright to this source code. In place of
152494 ** a legal notice, here is a blessing:
152495 **
152496 ** May you do good and not evil.
152497 ** May you find forgiveness for yourself and forgive others.
152498 ** May you share freely, never taking more than you give.
152499 **
152500 ******************************************************************************
152501 **
152502 ** Implementation of the "simple" full-text-search tokenizer.
152503 */
152504 
152505 /*
152506 ** The code in this file is only compiled if:
152507 **
152508 ** * The FTS3 module is being built as an extension
152509 ** (in which case SQLITE_CORE is not defined), or
152510 **
152511 ** * The FTS3 module is being built into the core of
152512 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
152513 */
152514 /* #include "fts3Int.h" */
152515 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
152516 
152517 /* #include <assert.h> */
152518 /* #include <stdlib.h> */
152519 /* #include <stdio.h> */
152520 /* #include <string.h> */
152521 
152522 /* #include "fts3_tokenizer.h" */
152523 
152524 typedef struct simple_tokenizer {
152525  sqlite3_tokenizer base;
152526  char delim[128]; /* flag ASCII delimiters */
152527 } simple_tokenizer;
152528 
152529 typedef struct simple_tokenizer_cursor {
152530  sqlite3_tokenizer_cursor base;
152531  const char *pInput; /* input we are tokenizing */
152532  int nBytes; /* size of the input */
152533  int iOffset; /* current position in pInput */
152534  int iToken; /* index of next token to be returned */
152535  char *pToken; /* storage for current token */
152536  int nTokenAllocated; /* space allocated to zToken buffer */
152537 } simple_tokenizer_cursor;
152538 
152539 
152540 static int simpleDelim(simple_tokenizer *t, unsigned char c){
152541  return c<0x80 && t->delim[c];
152542 }
152543 static int fts3_isalnum(int x){
152544  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
152545 }
152546 
152547 /*
152548 ** Create a new tokenizer instance.
152549 */
152550 static int simpleCreate(
152551  int argc, const char * const *argv,
152552  sqlite3_tokenizer **ppTokenizer
152553 ){
152554  simple_tokenizer *t;
152555 
152556  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
152557  if( t==NULL ) return SQLITE_NOMEM;
152558  memset(t, 0, sizeof(*t));
152559 
152560  /* TODO(shess) Delimiters need to remain the same from run to run,
152561  ** else we need to reindex. One solution would be a meta-table to
152562  ** track such information in the database, then we'd only want this
152563  ** information on the initial create.
152564  */
152565  if( argc>1 ){
152566  int i, n = (int)strlen(argv[1]);
152567  for(i=0; i<n; i++){
152568  unsigned char ch = argv[1][i];
152569  /* We explicitly don't support UTF-8 delimiters for now. */
152570  if( ch>=0x80 ){
152571  sqlite3_free(t);
152572  return SQLITE_ERROR;
152573  }
152574  t->delim[ch] = 1;
152575  }
152576  } else {
152577  /* Mark non-alphanumeric ASCII characters as delimiters */
152578  int i;
152579  for(i=1; i<0x80; i++){
152580  t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
152581  }
152582  }
152583 
152584  *ppTokenizer = &t->base;
152585  return SQLITE_OK;
152586 }
152587 
152588 /*
152589 ** Destroy a tokenizer
152590 */
152591 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
152592  sqlite3_free(pTokenizer);
152593  return SQLITE_OK;
152594 }
152595 
152596 /*
152597 ** Prepare to begin tokenizing a particular string. The input
152598 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
152599 ** used to incrementally tokenize this string is returned in
152600 ** *ppCursor.
152601 */
152602 static int simpleOpen(
152603  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
152604  const char *pInput, int nBytes, /* String to be tokenized */
152605  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
152606 ){
152607  simple_tokenizer_cursor *c;
152608 
152609  UNUSED_PARAMETER(pTokenizer);
152610 
152611  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
152612  if( c==NULL ) return SQLITE_NOMEM;
152613 
152614  c->pInput = pInput;
152615  if( pInput==0 ){
152616  c->nBytes = 0;
152617  }else if( nBytes<0 ){
152618  c->nBytes = (int)strlen(pInput);
152619  }else{
152620  c->nBytes = nBytes;
152621  }
152622  c->iOffset = 0; /* start tokenizing at the beginning */
152623  c->iToken = 0;
152624  c->pToken = NULL; /* no space allocated, yet. */
152625  c->nTokenAllocated = 0;
152626 
152627  *ppCursor = &c->base;
152628  return SQLITE_OK;
152629 }
152630 
152631 /*
152632 ** Close a tokenization cursor previously opened by a call to
152633 ** simpleOpen() above.
152634 */
152635 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
152636  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
152637  sqlite3_free(c->pToken);
152638  sqlite3_free(c);
152639  return SQLITE_OK;
152640 }
152641 
152642 /*
152643 ** Extract the next token from a tokenization cursor. The cursor must
152644 ** have been opened by a prior call to simpleOpen().
152645 */
152646 static int simpleNext(
152647  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
152648  const char **ppToken, /* OUT: *ppToken is the token text */
152649  int *pnBytes, /* OUT: Number of bytes in token */
152650  int *piStartOffset, /* OUT: Starting offset of token */
152651  int *piEndOffset, /* OUT: Ending offset of token */
152652  int *piPosition /* OUT: Position integer of token */
152653 ){
152654  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
152655  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
152656  unsigned char *p = (unsigned char *)c->pInput;
152657 
152658  while( c->iOffset<c->nBytes ){
152659  int iStartOffset;
152660 
152661  /* Scan past delimiter characters */
152662  while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
152663  c->iOffset++;
152664  }
152665 
152666  /* Count non-delimiter characters. */
152667  iStartOffset = c->iOffset;
152668  while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
152669  c->iOffset++;
152670  }
152671 
152672  if( c->iOffset>iStartOffset ){
152673  int i, n = c->iOffset-iStartOffset;
152674  if( n>c->nTokenAllocated ){
152675  char *pNew;
152676  c->nTokenAllocated = n+20;
152677  pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
152678  if( !pNew ) return SQLITE_NOMEM;
152679  c->pToken = pNew;
152680  }
152681  for(i=0; i<n; i++){
152682  /* TODO(shess) This needs expansion to handle UTF-8
152683  ** case-insensitivity.
152684  */
152685  unsigned char ch = p[iStartOffset+i];
152686  c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
152687  }
152688  *ppToken = c->pToken;
152689  *pnBytes = n;
152690  *piStartOffset = iStartOffset;
152691  *piEndOffset = c->iOffset;
152692  *piPosition = c->iToken++;
152693 
152694  return SQLITE_OK;
152695  }
152696  }
152697  return SQLITE_DONE;
152698 }
152699 
152700 /*
152701 ** The set of routines that implement the simple tokenizer
152702 */
152703 static const sqlite3_tokenizer_module simpleTokenizerModule = {
152704  0,
152705  simpleCreate,
152706  simpleDestroy,
152707  simpleOpen,
152708  simpleClose,
152709  simpleNext,
152710  0,
152711 };
152712 
152713 /*
152714 ** Allocate a new simple tokenizer. Return a pointer to the new
152715 ** tokenizer in *ppModule
152716 */
152717 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
152718  sqlite3_tokenizer_module const**ppModule
152719 ){
152720  *ppModule = &simpleTokenizerModule;
152721 }
152722 
152723 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
152724 
152725 /************** End of fts3_tokenizer1.c *************************************/
152726 /************** Begin file fts3_tokenize_vtab.c ******************************/
152727 /*
152728 ** 2013 Apr 22
152729 **
152730 ** The author disclaims copyright to this source code. In place of
152731 ** a legal notice, here is a blessing:
152732 **
152733 ** May you do good and not evil.
152734 ** May you find forgiveness for yourself and forgive others.
152735 ** May you share freely, never taking more than you give.
152736 **
152737 ******************************************************************************
152738 **
152739 ** This file contains code for the "fts3tokenize" virtual table module.
152740 ** An fts3tokenize virtual table is created as follows:
152741 **
152742 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
152743 ** <tokenizer-name>, <arg-1>, ...
152744 ** );
152745 **
152746 ** The table created has the following schema:
152747 **
152748 ** CREATE TABLE <tbl>(input, token, start, end, position)
152749 **
152750 ** When queried, the query must include a WHERE clause of type:
152751 **
152752 ** input = <string>
152753 **
152754 ** The virtual table module tokenizes this <string>, using the FTS3
152755 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
152756 ** statement and returns one row for each token in the result. With
152757 ** fields set as follows:
152758 **
152759 ** input: Always set to a copy of <string>
152760 ** token: A token from the input.
152761 ** start: Byte offset of the token within the input <string>.
152762 ** end: Byte offset of the byte immediately following the end of the
152763 ** token within the input string.
152764 ** pos: Token offset of token within input.
152765 **
152766 */
152767 /* #include "fts3Int.h" */
152768 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
152769 
152770 /* #include <string.h> */
152771 /* #include <assert.h> */
152772 
152773 typedef struct Fts3tokTable Fts3tokTable;
152774 typedef struct Fts3tokCursor Fts3tokCursor;
152775 
152776 /*
152777 ** Virtual table structure.
152778 */
152779 struct Fts3tokTable {
152780  sqlite3_vtab base; /* Base class used by SQLite core */
152781  const sqlite3_tokenizer_module *pMod;
152782  sqlite3_tokenizer *pTok;
152783 };
152784 
152785 /*
152786 ** Virtual table cursor structure.
152787 */
152788 struct Fts3tokCursor {
152789  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
152790  char *zInput; /* Input string */
152791  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
152792  int iRowid; /* Current 'rowid' value */
152793  const char *zToken; /* Current 'token' value */
152794  int nToken; /* Size of zToken in bytes */
152795  int iStart; /* Current 'start' value */
152796  int iEnd; /* Current 'end' value */
152797  int iPos; /* Current 'pos' value */
152798 };
152799 
152800 /*
152801 ** Query FTS for the tokenizer implementation named zName.
152802 */
152803 static int fts3tokQueryTokenizer(
152804  Fts3Hash *pHash,
152805  const char *zName,
152806  const sqlite3_tokenizer_module **pp,
152807  char **pzErr
152808 ){
152809  sqlite3_tokenizer_module *p;
152810  int nName = (int)strlen(zName);
152811 
152812  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
152813  if( !p ){
152814  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
152815  return SQLITE_ERROR;
152816  }
152817 
152818  *pp = p;
152819  return SQLITE_OK;
152820 }
152821 
152822 /*
152823 ** The second argument, argv[], is an array of pointers to nul-terminated
152824 ** strings. This function makes a copy of the array and strings into a
152825 ** single block of memory. It then dequotes any of the strings that appear
152826 ** to be quoted.
152827 **
152828 ** If successful, output parameter *pazDequote is set to point at the
152829 ** array of dequoted strings and SQLITE_OK is returned. The caller is
152830 ** responsible for eventually calling sqlite3_free() to free the array
152831 ** in this case. Or, if an error occurs, an SQLite error code is returned.
152832 ** The final value of *pazDequote is undefined in this case.
152833 */
152834 static int fts3tokDequoteArray(
152835  int argc, /* Number of elements in argv[] */
152836  const char * const *argv, /* Input array */
152837  char ***pazDequote /* Output array */
152838 ){
152839  int rc = SQLITE_OK; /* Return code */
152840  if( argc==0 ){
152841  *pazDequote = 0;
152842  }else{
152843  int i;
152844  int nByte = 0;
152845  char **azDequote;
152846 
152847  for(i=0; i<argc; i++){
152848  nByte += (int)(strlen(argv[i]) + 1);
152849  }
152850 
152851  *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
152852  if( azDequote==0 ){
152853  rc = SQLITE_NOMEM;
152854  }else{
152855  char *pSpace = (char *)&azDequote[argc];
152856  for(i=0; i<argc; i++){
152857  int n = (int)strlen(argv[i]);
152858  azDequote[i] = pSpace;
152859  memcpy(pSpace, argv[i], n+1);
152860  sqlite3Fts3Dequote(pSpace);
152861  pSpace += (n+1);
152862  }
152863  }
152864  }
152865 
152866  return rc;
152867 }
152868 
152869 /*
152870 ** Schema of the tokenizer table.
152871 */
152872 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
152873 
152874 /*
152875 ** This function does all the work for both the xConnect and xCreate methods.
152876 ** These tables have no persistent representation of their own, so xConnect
152877 ** and xCreate are identical operations.
152878 **
152879 ** argv[0]: module name
152880 ** argv[1]: database name
152881 ** argv[2]: table name
152882 ** argv[3]: first argument (tokenizer name)
152883 */
152884 static int fts3tokConnectMethod(
152885  sqlite3 *db, /* Database connection */
152886  void *pHash, /* Hash table of tokenizers */
152887  int argc, /* Number of elements in argv array */
152888  const char * const *argv, /* xCreate/xConnect argument array */
152889  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
152890  char **pzErr /* OUT: sqlite3_malloc'd error message */
152891 ){
152892  Fts3tokTable *pTab = 0;
152893  const sqlite3_tokenizer_module *pMod = 0;
152894  sqlite3_tokenizer *pTok = 0;
152895  int rc;
152896  char **azDequote = 0;
152897  int nDequote;
152898 
152899  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
152900  if( rc!=SQLITE_OK ) return rc;
152901 
152902  nDequote = argc-3;
152903  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
152904 
152905  if( rc==SQLITE_OK ){
152906  const char *zModule;
152907  if( nDequote<1 ){
152908  zModule = "simple";
152909  }else{
152910  zModule = azDequote[0];
152911  }
152912  rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
152913  }
152914 
152915  assert( (rc==SQLITE_OK)==(pMod!=0) );
152916  if( rc==SQLITE_OK ){
152917  const char * const *azArg = (const char * const *)&azDequote[1];
152918  rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
152919  }
152920 
152921  if( rc==SQLITE_OK ){
152922  pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
152923  if( pTab==0 ){
152924  rc = SQLITE_NOMEM;
152925  }
152926  }
152927 
152928  if( rc==SQLITE_OK ){
152929  memset(pTab, 0, sizeof(Fts3tokTable));
152930  pTab->pMod = pMod;
152931  pTab->pTok = pTok;
152932  *ppVtab = &pTab->base;
152933  }else{
152934  if( pTok ){
152935  pMod->xDestroy(pTok);
152936  }
152937  }
152938 
152939  sqlite3_free(azDequote);
152940  return rc;
152941 }
152942 
152943 /*
152944 ** This function does the work for both the xDisconnect and xDestroy methods.
152945 ** These tables have no persistent representation of their own, so xDisconnect
152946 ** and xDestroy are identical operations.
152947 */
152948 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
152949  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
152950 
152951  pTab->pMod->xDestroy(pTab->pTok);
152952  sqlite3_free(pTab);
152953  return SQLITE_OK;
152954 }
152955 
152956 /*
152957 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
152958 */
152959 static int fts3tokBestIndexMethod(
152960  sqlite3_vtab *pVTab,
152961  sqlite3_index_info *pInfo
152962 ){
152963  int i;
152964  UNUSED_PARAMETER(pVTab);
152965 
152966  for(i=0; i<pInfo->nConstraint; i++){
152967  if( pInfo->aConstraint[i].usable
152968  && pInfo->aConstraint[i].iColumn==0
152969  && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
152970  ){
152971  pInfo->idxNum = 1;
152972  pInfo->aConstraintUsage[i].argvIndex = 1;
152973  pInfo->aConstraintUsage[i].omit = 1;
152974  pInfo->estimatedCost = 1;
152975  return SQLITE_OK;
152976  }
152977  }
152978 
152979  pInfo->idxNum = 0;
152980  assert( pInfo->estimatedCost>1000000.0 );
152981 
152982  return SQLITE_OK;
152983 }
152984 
152985 /*
152986 ** xOpen - Open a cursor.
152987 */
152988 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
152989  Fts3tokCursor *pCsr;
152990  UNUSED_PARAMETER(pVTab);
152991 
152992  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
152993  if( pCsr==0 ){
152994  return SQLITE_NOMEM;
152995  }
152996  memset(pCsr, 0, sizeof(Fts3tokCursor));
152997 
152998  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
152999  return SQLITE_OK;
153000 }
153001 
153002 /*
153003 ** Reset the tokenizer cursor passed as the only argument. As if it had
153004 ** just been returned by fts3tokOpenMethod().
153005 */
153006 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
153007  if( pCsr->pCsr ){
153008  Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
153009  pTab->pMod->xClose(pCsr->pCsr);
153010  pCsr->pCsr = 0;
153011  }
153012  sqlite3_free(pCsr->zInput);
153013  pCsr->zInput = 0;
153014  pCsr->zToken = 0;
153015  pCsr->nToken = 0;
153016  pCsr->iStart = 0;
153017  pCsr->iEnd = 0;
153018  pCsr->iPos = 0;
153019  pCsr->iRowid = 0;
153020 }
153021 
153022 /*
153023 ** xClose - Close a cursor.
153024 */
153025 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
153026  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153027 
153028  fts3tokResetCursor(pCsr);
153029  sqlite3_free(pCsr);
153030  return SQLITE_OK;
153031 }
153032 
153033 /*
153034 ** xNext - Advance the cursor to the next row, if any.
153035 */
153036 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
153037  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153038  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
153039  int rc; /* Return code */
153040 
153041  pCsr->iRowid++;
153042  rc = pTab->pMod->xNext(pCsr->pCsr,
153043  &pCsr->zToken, &pCsr->nToken,
153044  &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
153045  );
153046 
153047  if( rc!=SQLITE_OK ){
153048  fts3tokResetCursor(pCsr);
153049  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
153050  }
153051 
153052  return rc;
153053 }
153054 
153055 /*
153056 ** xFilter - Initialize a cursor to point at the start of its data.
153057 */
153058 static int fts3tokFilterMethod(
153059  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
153060  int idxNum, /* Strategy index */
153061  const char *idxStr, /* Unused */
153062  int nVal, /* Number of elements in apVal */
153063  sqlite3_value **apVal /* Arguments for the indexing scheme */
153064 ){
153065  int rc = SQLITE_ERROR;
153066  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153067  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
153068  UNUSED_PARAMETER(idxStr);
153069  UNUSED_PARAMETER(nVal);
153070 
153071  fts3tokResetCursor(pCsr);
153072  if( idxNum==1 ){
153073  const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
153074  int nByte = sqlite3_value_bytes(apVal[0]);
153075  pCsr->zInput = sqlite3_malloc(nByte+1);
153076  if( pCsr->zInput==0 ){
153077  rc = SQLITE_NOMEM;
153078  }else{
153079  memcpy(pCsr->zInput, zByte, nByte);
153080  pCsr->zInput[nByte] = 0;
153081  rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
153082  if( rc==SQLITE_OK ){
153083  pCsr->pCsr->pTokenizer = pTab->pTok;
153084  }
153085  }
153086  }
153087 
153088  if( rc!=SQLITE_OK ) return rc;
153089  return fts3tokNextMethod(pCursor);
153090 }
153091 
153092 /*
153093 ** xEof - Return true if the cursor is at EOF, or false otherwise.
153094 */
153095 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
153096  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153097  return (pCsr->zToken==0);
153098 }
153099 
153100 /*
153101 ** xColumn - Return a column value.
153102 */
153103 static int fts3tokColumnMethod(
153104  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
153105  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
153106  int iCol /* Index of column to read value from */
153107 ){
153108  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153109 
153110  /* CREATE TABLE x(input, token, start, end, position) */
153111  switch( iCol ){
153112  case 0:
153113  sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
153114  break;
153115  case 1:
153116  sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
153117  break;
153118  case 2:
153119  sqlite3_result_int(pCtx, pCsr->iStart);
153120  break;
153121  case 3:
153122  sqlite3_result_int(pCtx, pCsr->iEnd);
153123  break;
153124  default:
153125  assert( iCol==4 );
153126  sqlite3_result_int(pCtx, pCsr->iPos);
153127  break;
153128  }
153129  return SQLITE_OK;
153130 }
153131 
153132 /*
153133 ** xRowid - Return the current rowid for the cursor.
153134 */
153135 static int fts3tokRowidMethod(
153136  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
153137  sqlite_int64 *pRowid /* OUT: Rowid value */
153138 ){
153139  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
153140  *pRowid = (sqlite3_int64)pCsr->iRowid;
153141  return SQLITE_OK;
153142 }
153143 
153144 /*
153145 ** Register the fts3tok module with database connection db. Return SQLITE_OK
153146 ** if successful or an error code if sqlite3_create_module() fails.
153147 */
153148 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
153149  static const sqlite3_module fts3tok_module = {
153150  0, /* iVersion */
153151  fts3tokConnectMethod, /* xCreate */
153152  fts3tokConnectMethod, /* xConnect */
153153  fts3tokBestIndexMethod, /* xBestIndex */
153154  fts3tokDisconnectMethod, /* xDisconnect */
153155  fts3tokDisconnectMethod, /* xDestroy */
153156  fts3tokOpenMethod, /* xOpen */
153157  fts3tokCloseMethod, /* xClose */
153158  fts3tokFilterMethod, /* xFilter */
153159  fts3tokNextMethod, /* xNext */
153160  fts3tokEofMethod, /* xEof */
153161  fts3tokColumnMethod, /* xColumn */
153162  fts3tokRowidMethod, /* xRowid */
153163  0, /* xUpdate */
153164  0, /* xBegin */
153165  0, /* xSync */
153166  0, /* xCommit */
153167  0, /* xRollback */
153168  0, /* xFindFunction */
153169  0, /* xRename */
153170  0, /* xSavepoint */
153171  0, /* xRelease */
153172  0 /* xRollbackTo */
153173  };
153174  int rc; /* Return code */
153175 
153176  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
153177  return rc;
153178 }
153179 
153180 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
153181 
153182 /************** End of fts3_tokenize_vtab.c **********************************/
153183 /************** Begin file fts3_write.c **************************************/
153184 /*
153185 ** 2009 Oct 23
153186 **
153187 ** The author disclaims copyright to this source code. In place of
153188 ** a legal notice, here is a blessing:
153189 **
153190 ** May you do good and not evil.
153191 ** May you find forgiveness for yourself and forgive others.
153192 ** May you share freely, never taking more than you give.
153193 **
153194 ******************************************************************************
153195 **
153196 ** This file is part of the SQLite FTS3 extension module. Specifically,
153197 ** this file contains code to insert, update and delete rows from FTS3
153198 ** tables. It also contains code to merge FTS3 b-tree segments. Some
153199 ** of the sub-routines used to merge segments are also used by the query
153200 ** code in fts3.c.
153201 */
153202 
153203 /* #include "fts3Int.h" */
153204 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
153205 
153206 /* #include <string.h> */
153207 /* #include <assert.h> */
153208 /* #include <stdlib.h> */
153209 
153210 
153211 #define FTS_MAX_APPENDABLE_HEIGHT 16
153212 
153213 /*
153214 ** When full-text index nodes are loaded from disk, the buffer that they
153215 ** are loaded into has the following number of bytes of padding at the end
153216 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
153217 ** of 920 bytes is allocated for it.
153218 **
153219 ** This means that if we have a pointer into a buffer containing node data,
153220 ** it is always safe to read up to two varints from it without risking an
153221 ** overread, even if the node data is corrupted.
153222 */
153223 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
153224 
153225 /*
153226 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
153227 ** memory incrementally instead of all at once. This can be a big performance
153228 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
153229 ** method before retrieving all query results (as may happen, for example,
153230 ** if a query has a LIMIT clause).
153231 **
153232 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
153233 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
153234 ** The code is written so that the hard lower-limit for each of these values
153235 ** is 1. Clearly such small values would be inefficient, but can be useful
153236 ** for testing purposes.
153237 **
153238 ** If this module is built with SQLITE_TEST defined, these constants may
153239 ** be overridden at runtime for testing purposes. File fts3_test.c contains
153240 ** a Tcl interface to read and write the values.
153241 */
153242 #ifdef SQLITE_TEST
153243 int test_fts3_node_chunksize = (4*1024);
153244 int test_fts3_node_chunk_threshold = (4*1024)*4;
153245 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
153246 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
153247 #else
153248 # define FTS3_NODE_CHUNKSIZE (4*1024)
153249 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
153250 #endif
153251 
153252 /*
153253 ** The two values that may be meaningfully bound to the :1 parameter in
153254 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
153255 */
153256 #define FTS_STAT_DOCTOTAL 0
153257 #define FTS_STAT_INCRMERGEHINT 1
153258 #define FTS_STAT_AUTOINCRMERGE 2
153259 
153260 /*
153261 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
153262 ** and incremental merge operation that takes place. This is used for
153263 ** debugging FTS only, it should not usually be turned on in production
153264 ** systems.
153265 */
153266 #ifdef FTS3_LOG_MERGES
153267 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
153268  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
153269 }
153270 #else
153271 #define fts3LogMerge(x, y)
153272 #endif
153273 
153274 
153275 typedef struct PendingList PendingList;
153276 typedef struct SegmentNode SegmentNode;
153277 typedef struct SegmentWriter SegmentWriter;
153278 
153279 /*
153280 ** An instance of the following data structure is used to build doclists
153281 ** incrementally. See function fts3PendingListAppend() for details.
153282 */
153283 struct PendingList {
153284  int nData;
153285  char *aData;
153286  int nSpace;
153287  sqlite3_int64 iLastDocid;
153288  sqlite3_int64 iLastCol;
153289  sqlite3_int64 iLastPos;
153290 };
153291 
153292 
153293 /*
153294 ** Each cursor has a (possibly empty) linked list of the following objects.
153295 */
153296 struct Fts3DeferredToken {
153297  Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
153298  int iCol; /* Column token must occur in */
153299  Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
153300  PendingList *pList; /* Doclist is assembled here */
153301 };
153302 
153303 /*
153304 ** An instance of this structure is used to iterate through the terms on
153305 ** a contiguous set of segment b-tree leaf nodes. Although the details of
153306 ** this structure are only manipulated by code in this file, opaque handles
153307 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
153308 ** terms when querying the full-text index. See functions:
153309 **
153310 ** sqlite3Fts3SegReaderNew()
153311 ** sqlite3Fts3SegReaderFree()
153312 ** sqlite3Fts3SegReaderIterate()
153313 **
153314 ** Methods used to manipulate Fts3SegReader structures:
153315 **
153316 ** fts3SegReaderNext()
153317 ** fts3SegReaderFirstDocid()
153318 ** fts3SegReaderNextDocid()
153319 */
153320 struct Fts3SegReader {
153321  int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
153322  u8 bLookup; /* True for a lookup only */
153323  u8 rootOnly; /* True for a root-only reader */
153324 
153325  sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
153326  sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
153327  sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
153328  sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
153329 
153330  char *aNode; /* Pointer to node data (or NULL) */
153331  int nNode; /* Size of buffer at aNode (or 0) */
153332  int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
153333  sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
153334 
153335  Fts3HashElem **ppNextElem;
153336 
153337  /* Variables set by fts3SegReaderNext(). These may be read directly
153338  ** by the caller. They are valid from the time SegmentReaderNew() returns
153339  ** until SegmentReaderNext() returns something other than SQLITE_OK
153340  ** (i.e. SQLITE_DONE).
153341  */
153342  int nTerm; /* Number of bytes in current term */
153343  char *zTerm; /* Pointer to current term */
153344  int nTermAlloc; /* Allocated size of zTerm buffer */
153345  char *aDoclist; /* Pointer to doclist of current entry */
153346  int nDoclist; /* Size of doclist in current entry */
153347 
153348  /* The following variables are used by fts3SegReaderNextDocid() to iterate
153349  ** through the current doclist (aDoclist/nDoclist).
153350  */
153351  char *pOffsetList;
153352  int nOffsetList; /* For descending pending seg-readers only */
153353  sqlite3_int64 iDocid;
153354 };
153355 
153356 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
153357 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
153358 
153359 /*
153360 ** An instance of this structure is used to create a segment b-tree in the
153361 ** database. The internal details of this type are only accessed by the
153362 ** following functions:
153363 **
153364 ** fts3SegWriterAdd()
153365 ** fts3SegWriterFlush()
153366 ** fts3SegWriterFree()
153367 */
153368 struct SegmentWriter {
153369  SegmentNode *pTree; /* Pointer to interior tree structure */
153370  sqlite3_int64 iFirst; /* First slot in %_segments written */
153371  sqlite3_int64 iFree; /* Next free slot in %_segments */
153372  char *zTerm; /* Pointer to previous term buffer */
153373  int nTerm; /* Number of bytes in zTerm */
153374  int nMalloc; /* Size of malloc'd buffer at zMalloc */
153375  char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
153376  int nSize; /* Size of allocation at aData */
153377  int nData; /* Bytes of data in aData */
153378  char *aData; /* Pointer to block from malloc() */
153379  i64 nLeafData; /* Number of bytes of leaf data written */
153380 };
153381 
153382 /*
153383 ** Type SegmentNode is used by the following three functions to create
153384 ** the interior part of the segment b+-tree structures (everything except
153385 ** the leaf nodes). These functions and type are only ever used by code
153386 ** within the fts3SegWriterXXX() family of functions described above.
153387 **
153388 ** fts3NodeAddTerm()
153389 ** fts3NodeWrite()
153390 ** fts3NodeFree()
153391 **
153392 ** When a b+tree is written to the database (either as a result of a merge
153393 ** or the pending-terms table being flushed), leaves are written into the
153394 ** database file as soon as they are completely populated. The interior of
153395 ** the tree is assembled in memory and written out only once all leaves have
153396 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
153397 ** very large, meaning that the interior of the tree consumes relatively
153398 ** little memory.
153399 */
153400 struct SegmentNode {
153401  SegmentNode *pParent; /* Parent node (or NULL for root node) */
153402  SegmentNode *pRight; /* Pointer to right-sibling */
153403  SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
153404  int nEntry; /* Number of terms written to node so far */
153405  char *zTerm; /* Pointer to previous term buffer */
153406  int nTerm; /* Number of bytes in zTerm */
153407  int nMalloc; /* Size of malloc'd buffer at zMalloc */
153408  char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
153409  int nData; /* Bytes of valid data so far */
153410  char *aData; /* Node data */
153411 };
153412 
153413 /*
153414 ** Valid values for the second argument to fts3SqlStmt().
153415 */
153416 #define SQL_DELETE_CONTENT 0
153417 #define SQL_IS_EMPTY 1
153418 #define SQL_DELETE_ALL_CONTENT 2
153419 #define SQL_DELETE_ALL_SEGMENTS 3
153420 #define SQL_DELETE_ALL_SEGDIR 4
153421 #define SQL_DELETE_ALL_DOCSIZE 5
153422 #define SQL_DELETE_ALL_STAT 6
153423 #define SQL_SELECT_CONTENT_BY_ROWID 7
153424 #define SQL_NEXT_SEGMENT_INDEX 8
153425 #define SQL_INSERT_SEGMENTS 9
153426 #define SQL_NEXT_SEGMENTS_ID 10
153427 #define SQL_INSERT_SEGDIR 11
153428 #define SQL_SELECT_LEVEL 12
153429 #define SQL_SELECT_LEVEL_RANGE 13
153430 #define SQL_SELECT_LEVEL_COUNT 14
153431 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
153432 #define SQL_DELETE_SEGDIR_LEVEL 16
153433 #define SQL_DELETE_SEGMENTS_RANGE 17
153434 #define SQL_CONTENT_INSERT 18
153435 #define SQL_DELETE_DOCSIZE 19
153436 #define SQL_REPLACE_DOCSIZE 20
153437 #define SQL_SELECT_DOCSIZE 21
153438 #define SQL_SELECT_STAT 22
153439 #define SQL_REPLACE_STAT 23
153440 
153441 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
153442 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
153443 #define SQL_DELETE_SEGDIR_RANGE 26
153444 #define SQL_SELECT_ALL_LANGID 27
153445 #define SQL_FIND_MERGE_LEVEL 28
153446 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
153447 #define SQL_DELETE_SEGDIR_ENTRY 30
153448 #define SQL_SHIFT_SEGDIR_ENTRY 31
153449 #define SQL_SELECT_SEGDIR 32
153450 #define SQL_CHOMP_SEGDIR 33
153451 #define SQL_SEGMENT_IS_APPENDABLE 34
153452 #define SQL_SELECT_INDEXES 35
153453 #define SQL_SELECT_MXLEVEL 36
153454 
153455 #define SQL_SELECT_LEVEL_RANGE2 37
153456 #define SQL_UPDATE_LEVEL_IDX 38
153457 #define SQL_UPDATE_LEVEL 39
153458 
153459 /*
153460 ** This function is used to obtain an SQLite prepared statement handle
153461 ** for the statement identified by the second argument. If successful,
153462 ** *pp is set to the requested statement handle and SQLITE_OK returned.
153463 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
153464 **
153465 ** If argument apVal is not NULL, then it must point to an array with
153466 ** at least as many entries as the requested statement has bound
153467 ** parameters. The values are bound to the statements parameters before
153468 ** returning.
153469 */
153470 static int fts3SqlStmt(
153471  Fts3Table *p, /* Virtual table handle */
153472  int eStmt, /* One of the SQL_XXX constants above */
153473  sqlite3_stmt **pp, /* OUT: Statement handle */
153474  sqlite3_value **apVal /* Values to bind to statement */
153475 ){
153476  const char *azSql[] = {
153477 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
153478 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
153479 /* 2 */ "DELETE FROM %Q.'%q_content'",
153480 /* 3 */ "DELETE FROM %Q.'%q_segments'",
153481 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
153482 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
153483 /* 6 */ "DELETE FROM %Q.'%q_stat'",
153484 /* 7 */ "SELECT %s WHERE rowid=?",
153485 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
153486 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
153487 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
153488 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
153489 
153490  /* Return segments in order from oldest to newest.*/
153491 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
153492  "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
153493 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
153494  "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
153495  "ORDER BY level DESC, idx ASC",
153496 
153497 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
153498 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
153499 
153500 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
153501 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
153502 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
153503 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
153504 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
153505 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
153506 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
153507 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
153508 /* 24 */ "",
153509 /* 25 */ "",
153510 
153511 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
153512 /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
153513 
153514 /* This statement is used to determine which level to read the input from
153515 ** when performing an incremental merge. It returns the absolute level number
153516 ** of the oldest level in the db that contains at least ? segments. Or,
153517 ** if no level in the FTS index contains more than ? segments, the statement
153518 ** returns zero rows. */
153519 /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
153520  " GROUP BY level HAVING cnt>=?"
153521  " ORDER BY (level %% 1024) ASC LIMIT 1",
153522 
153523 /* Estimate the upper limit on the number of leaf nodes in a new segment
153524 ** created by merging the oldest :2 segments from absolute level :1. See
153525 ** function sqlite3Fts3Incrmerge() for details. */
153526 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
153527  " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
153528 
153529 /* SQL_DELETE_SEGDIR_ENTRY
153530 ** Delete the %_segdir entry on absolute level :1 with index :2. */
153531 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
153532 
153533 /* SQL_SHIFT_SEGDIR_ENTRY
153534 ** Modify the idx value for the segment with idx=:3 on absolute level :2
153535 ** to :1. */
153536 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
153537 
153538 /* SQL_SELECT_SEGDIR
153539 ** Read a single entry from the %_segdir table. The entry from absolute
153540 ** level :1 with index value :2. */
153541 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
153542  "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
153543 
153544 /* SQL_CHOMP_SEGDIR
153545 ** Update the start_block (:1) and root (:2) fields of the %_segdir
153546 ** entry located on absolute level :3 with index :4. */
153547 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
153548  "WHERE level = ? AND idx = ?",
153549 
153550 /* SQL_SEGMENT_IS_APPENDABLE
153551 ** Return a single row if the segment with end_block=? is appendable. Or
153552 ** no rows otherwise. */
153553 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
153554 
153555 /* SQL_SELECT_INDEXES
153556 ** Return the list of valid segment indexes for absolute level ? */
153557 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
153558 
153559 /* SQL_SELECT_MXLEVEL
153560 ** Return the largest relative level in the FTS index or indexes. */
153561 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
153562 
153563  /* Return segments in order from oldest to newest.*/
153564 /* 37 */ "SELECT level, idx, end_block "
153565  "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
153566  "ORDER BY level DESC, idx ASC",
153567 
153568  /* Update statements used while promoting segments */
153569 /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
153570  "WHERE level=? AND idx=?",
153571 /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
153572 
153573  };
153574  int rc = SQLITE_OK;
153575  sqlite3_stmt *pStmt;
153576 
153577  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
153578  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
153579 
153580  pStmt = p->aStmt[eStmt];
153581  if( !pStmt ){
153582  char *zSql;
153583  if( eStmt==SQL_CONTENT_INSERT ){
153584  zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
153585  }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
153586  zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
153587  }else{
153588  zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
153589  }
153590  if( !zSql ){
153591  rc = SQLITE_NOMEM;
153592  }else{
153593  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
153594  sqlite3_free(zSql);
153595  assert( rc==SQLITE_OK || pStmt==0 );
153596  p->aStmt[eStmt] = pStmt;
153597  }
153598  }
153599  if( apVal ){
153600  int i;
153601  int nParam = sqlite3_bind_parameter_count(pStmt);
153602  for(i=0; rc==SQLITE_OK && i<nParam; i++){
153603  rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
153604  }
153605  }
153606  *pp = pStmt;
153607  return rc;
153608 }
153609 
153610 
153611 static int fts3SelectDocsize(
153612  Fts3Table *pTab, /* FTS3 table handle */
153613  sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
153614  sqlite3_stmt **ppStmt /* OUT: Statement handle */
153615 ){
153616  sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
153617  int rc; /* Return code */
153618 
153619  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
153620  if( rc==SQLITE_OK ){
153621  sqlite3_bind_int64(pStmt, 1, iDocid);
153622  rc = sqlite3_step(pStmt);
153623  if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
153624  rc = sqlite3_reset(pStmt);
153625  if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
153626  pStmt = 0;
153627  }else{
153628  rc = SQLITE_OK;
153629  }
153630  }
153631 
153632  *ppStmt = pStmt;
153633  return rc;
153634 }
153635 
153636 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
153637  Fts3Table *pTab, /* Fts3 table handle */
153638  sqlite3_stmt **ppStmt /* OUT: Statement handle */
153639 ){
153640  sqlite3_stmt *pStmt = 0;
153641  int rc;
153642  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
153643  if( rc==SQLITE_OK ){
153644  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
153645  if( sqlite3_step(pStmt)!=SQLITE_ROW
153646  || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
153647  ){
153648  rc = sqlite3_reset(pStmt);
153649  if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
153650  pStmt = 0;
153651  }
153652  }
153653  *ppStmt = pStmt;
153654  return rc;
153655 }
153656 
153657 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
153658  Fts3Table *pTab, /* Fts3 table handle */
153659  sqlite3_int64 iDocid, /* Docid to read size data for */
153660  sqlite3_stmt **ppStmt /* OUT: Statement handle */
153661 ){
153662  return fts3SelectDocsize(pTab, iDocid, ppStmt);
153663 }
153664 
153665 /*
153666 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
153667 ** array apVal[] to the SQL statement identified by eStmt, the statement
153668 ** is executed.
153669 **
153670 ** Returns SQLITE_OK if the statement is successfully executed, or an
153671 ** SQLite error code otherwise.
153672 */
153673 static void fts3SqlExec(
153674  int *pRC, /* Result code */
153675  Fts3Table *p, /* The FTS3 table */
153676  int eStmt, /* Index of statement to evaluate */
153677  sqlite3_value **apVal /* Parameters to bind */
153678 ){
153679  sqlite3_stmt *pStmt;
153680  int rc;
153681  if( *pRC ) return;
153682  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
153683  if( rc==SQLITE_OK ){
153684  sqlite3_step(pStmt);
153685  rc = sqlite3_reset(pStmt);
153686  }
153687  *pRC = rc;
153688 }
153689 
153690 
153691 /*
153692 ** This function ensures that the caller has obtained an exclusive
153693 ** shared-cache table-lock on the %_segdir table. This is required before
153694 ** writing data to the fts3 table. If this lock is not acquired first, then
153695 ** the caller may end up attempting to take this lock as part of committing
153696 ** a transaction, causing SQLite to return SQLITE_LOCKED or
153697 ** LOCKED_SHAREDCACHEto a COMMIT command.
153698 **
153699 ** It is best to avoid this because if FTS3 returns any error when
153700 ** committing a transaction, the whole transaction will be rolled back.
153701 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
153702 ** It can still happen if the user locks the underlying tables directly
153703 ** instead of accessing them via FTS.
153704 */
153705 static int fts3Writelock(Fts3Table *p){
153706  int rc = SQLITE_OK;
153707 
153708  if( p->nPendingData==0 ){
153709  sqlite3_stmt *pStmt;
153710  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
153711  if( rc==SQLITE_OK ){
153712  sqlite3_bind_null(pStmt, 1);
153713  sqlite3_step(pStmt);
153714  rc = sqlite3_reset(pStmt);
153715  }
153716  }
153717 
153718  return rc;
153719 }
153720 
153721 /*
153722 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
153723 ** Within each language id, a separate index is maintained to store the
153724 ** document terms, and each configured prefix size (configured the FTS
153725 ** "prefix=" option). And each index consists of multiple levels ("relative
153726 ** levels").
153727 **
153728 ** All three of these values (the language id, the specific index and the
153729 ** level within the index) are encoded in 64-bit integer values stored
153730 ** in the %_segdir table on disk. This function is used to convert three
153731 ** separate component values into the single 64-bit integer value that
153732 ** can be used to query the %_segdir table.
153733 **
153734 ** Specifically, each language-id/index combination is allocated 1024
153735 ** 64-bit integer level values ("absolute levels"). The main terms index
153736 ** for language-id 0 is allocate values 0-1023. The first prefix index
153737 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
153738 ** Language 1 indexes are allocated immediately following language 0.
153739 **
153740 ** So, for a system with nPrefix prefix indexes configured, the block of
153741 ** absolute levels that corresponds to language-id iLangid and index
153742 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
153743 */
153744 static sqlite3_int64 getAbsoluteLevel(
153745  Fts3Table *p, /* FTS3 table handle */
153746  int iLangid, /* Language id */
153747  int iIndex, /* Index in p->aIndex[] */
153748  int iLevel /* Level of segments */
153749 ){
153750  sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
153751  assert( iLangid>=0 );
153752  assert( p->nIndex>0 );
153753  assert( iIndex>=0 && iIndex<p->nIndex );
153754 
153755  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
153756  return iBase + iLevel;
153757 }
153758 
153759 /*
153760 ** Set *ppStmt to a statement handle that may be used to iterate through
153761 ** all rows in the %_segdir table, from oldest to newest. If successful,
153762 ** return SQLITE_OK. If an error occurs while preparing the statement,
153763 ** return an SQLite error code.
153764 **
153765 ** There is only ever one instance of this SQL statement compiled for
153766 ** each FTS3 table.
153767 **
153768 ** The statement returns the following columns from the %_segdir table:
153769 **
153770 ** 0: idx
153771 ** 1: start_block
153772 ** 2: leaves_end_block
153773 ** 3: end_block
153774 ** 4: root
153775 */
153776 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
153777  Fts3Table *p, /* FTS3 table */
153778  int iLangid, /* Language being queried */
153779  int iIndex, /* Index for p->aIndex[] */
153780  int iLevel, /* Level to select (relative level) */
153781  sqlite3_stmt **ppStmt /* OUT: Compiled statement */
153782 ){
153783  int rc;
153784  sqlite3_stmt *pStmt = 0;
153785 
153786  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
153787  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
153788  assert( iIndex>=0 && iIndex<p->nIndex );
153789 
153790  if( iLevel<0 ){
153791  /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
153792  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
153793  if( rc==SQLITE_OK ){
153794  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
153795  sqlite3_bind_int64(pStmt, 2,
153796  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
153797  );
153798  }
153799  }else{
153800  /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
153801  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
153802  if( rc==SQLITE_OK ){
153803  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
153804  }
153805  }
153806  *ppStmt = pStmt;
153807  return rc;
153808 }
153809 
153810 
153811 /*
153812 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
153813 ** if successful, or an SQLite error code otherwise.
153814 **
153815 ** This function also serves to allocate the PendingList structure itself.
153816 ** For example, to create a new PendingList structure containing two
153817 ** varints:
153818 **
153819 ** PendingList *p = 0;
153820 ** fts3PendingListAppendVarint(&p, 1);
153821 ** fts3PendingListAppendVarint(&p, 2);
153822 */
153823 static int fts3PendingListAppendVarint(
153824  PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
153825  sqlite3_int64 i /* Value to append to data */
153826 ){
153827  PendingList *p = *pp;
153828 
153829  /* Allocate or grow the PendingList as required. */
153830  if( !p ){
153831  p = sqlite3_malloc(sizeof(*p) + 100);
153832  if( !p ){
153833  return SQLITE_NOMEM;
153834  }
153835  p->nSpace = 100;
153836  p->aData = (char *)&p[1];
153837  p->nData = 0;
153838  }
153839  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
153840  int nNew = p->nSpace * 2;
153841  p = sqlite3_realloc(p, sizeof(*p) + nNew);
153842  if( !p ){
153843  sqlite3_free(*pp);
153844  *pp = 0;
153845  return SQLITE_NOMEM;
153846  }
153847  p->nSpace = nNew;
153848  p->aData = (char *)&p[1];
153849  }
153850 
153851  /* Append the new serialized varint to the end of the list. */
153852  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
153853  p->aData[p->nData] = '\0';
153854  *pp = p;
153855  return SQLITE_OK;
153856 }
153857 
153858 /*
153859 ** Add a docid/column/position entry to a PendingList structure. Non-zero
153860 ** is returned if the structure is sqlite3_realloced as part of adding
153861 ** the entry. Otherwise, zero.
153862 **
153863 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
153864 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
153865 ** it is set to SQLITE_OK.
153866 */
153867 static int fts3PendingListAppend(
153868  PendingList **pp, /* IN/OUT: PendingList structure */
153869  sqlite3_int64 iDocid, /* Docid for entry to add */
153870  sqlite3_int64 iCol, /* Column for entry to add */
153871  sqlite3_int64 iPos, /* Position of term for entry to add */
153872  int *pRc /* OUT: Return code */
153873 ){
153874  PendingList *p = *pp;
153875  int rc = SQLITE_OK;
153876 
153877  assert( !p || p->iLastDocid<=iDocid );
153878 
153879  if( !p || p->iLastDocid!=iDocid ){
153880  sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
153881  if( p ){
153882  assert( p->nData<p->nSpace );
153883  assert( p->aData[p->nData]==0 );
153884  p->nData++;
153885  }
153886  if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
153887  goto pendinglistappend_out;
153888  }
153889  p->iLastCol = -1;
153890  p->iLastPos = 0;
153891  p->iLastDocid = iDocid;
153892  }
153893  if( iCol>0 && p->iLastCol!=iCol ){
153894  if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
153895  || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
153896  ){
153897  goto pendinglistappend_out;
153898  }
153899  p->iLastCol = iCol;
153900  p->iLastPos = 0;
153901  }
153902  if( iCol>=0 ){
153903  assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
153904  rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
153905  if( rc==SQLITE_OK ){
153906  p->iLastPos = iPos;
153907  }
153908  }
153909 
153910  pendinglistappend_out:
153911  *pRc = rc;
153912  if( p!=*pp ){
153913  *pp = p;
153914  return 1;
153915  }
153916  return 0;
153917 }
153918 
153919 /*
153920 ** Free a PendingList object allocated by fts3PendingListAppend().
153921 */
153922 static void fts3PendingListDelete(PendingList *pList){
153923  sqlite3_free(pList);
153924 }
153925 
153926 /*
153927 ** Add an entry to one of the pending-terms hash tables.
153928 */
153929 static int fts3PendingTermsAddOne(
153930  Fts3Table *p,
153931  int iCol,
153932  int iPos,
153933  Fts3Hash *pHash, /* Pending terms hash table to add entry to */
153934  const char *zToken,
153935  int nToken
153936 ){
153937  PendingList *pList;
153938  int rc = SQLITE_OK;
153939 
153940  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
153941  if( pList ){
153942  p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
153943  }
153944  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
153945  if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
153946  /* Malloc failed while inserting the new entry. This can only
153947  ** happen if there was no previous entry for this token.
153948  */
153949  assert( 0==fts3HashFind(pHash, zToken, nToken) );
153950  sqlite3_free(pList);
153951  rc = SQLITE_NOMEM;
153952  }
153953  }
153954  if( rc==SQLITE_OK ){
153955  p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
153956  }
153957  return rc;
153958 }
153959 
153960 /*
153961 ** Tokenize the nul-terminated string zText and add all tokens to the
153962 ** pending-terms hash-table. The docid used is that currently stored in
153963 ** p->iPrevDocid, and the column is specified by argument iCol.
153964 **
153965 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
153966 */
153967 static int fts3PendingTermsAdd(
153968  Fts3Table *p, /* Table into which text will be inserted */
153969  int iLangid, /* Language id to use */
153970  const char *zText, /* Text of document to be inserted */
153971  int iCol, /* Column into which text is being inserted */
153972  u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
153973 ){
153974  int rc;
153975  int iStart = 0;
153976  int iEnd = 0;
153977  int iPos = 0;
153978  int nWord = 0;
153979 
153980  char const *zToken;
153981  int nToken = 0;
153982 
153983  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
153984  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
153985  sqlite3_tokenizer_cursor *pCsr;
153986  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
153987  const char**,int*,int*,int*,int*);
153988 
153989  assert( pTokenizer && pModule );
153990 
153991  /* If the user has inserted a NULL value, this function may be called with
153992  ** zText==0. In this case, add zero token entries to the hash table and
153993  ** return early. */
153994  if( zText==0 ){
153995  *pnWord = 0;
153996  return SQLITE_OK;
153997  }
153998 
153999  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
154000  if( rc!=SQLITE_OK ){
154001  return rc;
154002  }
154003 
154004  xNext = pModule->xNext;
154005  while( SQLITE_OK==rc
154006  && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
154007  ){
154008  int i;
154009  if( iPos>=nWord ) nWord = iPos+1;
154010 
154011  /* Positions cannot be negative; we use -1 as a terminator internally.
154012  ** Tokens must have a non-zero length.
154013  */
154014  if( iPos<0 || !zToken || nToken<=0 ){
154015  rc = SQLITE_ERROR;
154016  break;
154017  }
154018 
154019  /* Add the term to the terms index */
154020  rc = fts3PendingTermsAddOne(
154021  p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
154022  );
154023 
154024  /* Add the term to each of the prefix indexes that it is not too
154025  ** short for. */
154026  for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
154027  struct Fts3Index *pIndex = &p->aIndex[i];
154028  if( nToken<pIndex->nPrefix ) continue;
154029  rc = fts3PendingTermsAddOne(
154030  p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
154031  );
154032  }
154033  }
154034 
154035  pModule->xClose(pCsr);
154036  *pnWord += nWord;
154037  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
154038 }
154039 
154040 /*
154041 ** Calling this function indicates that subsequent calls to
154042 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
154043 ** contents of the document with docid iDocid.
154044 */
154045 static int fts3PendingTermsDocid(
154046  Fts3Table *p, /* Full-text table handle */
154047  int bDelete, /* True if this op is a delete */
154048  int iLangid, /* Language id of row being written */
154049  sqlite_int64 iDocid /* Docid of row being written */
154050 ){
154051  assert( iLangid>=0 );
154052  assert( bDelete==1 || bDelete==0 );
154053 
154054  /* TODO(shess) Explore whether partially flushing the buffer on
154055  ** forced-flush would provide better performance. I suspect that if
154056  ** we ordered the doclists by size and flushed the largest until the
154057  ** buffer was half empty, that would let the less frequent terms
154058  ** generate longer doclists.
154059  */
154060  if( iDocid<p->iPrevDocid
154061  || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
154062  || p->iPrevLangid!=iLangid
154063  || p->nPendingData>p->nMaxPendingData
154064  ){
154065  int rc = sqlite3Fts3PendingTermsFlush(p);
154066  if( rc!=SQLITE_OK ) return rc;
154067  }
154068  p->iPrevDocid = iDocid;
154069  p->iPrevLangid = iLangid;
154070  p->bPrevDelete = bDelete;
154071  return SQLITE_OK;
154072 }
154073 
154074 /*
154075 ** Discard the contents of the pending-terms hash tables.
154076 */
154077 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
154078  int i;
154079  for(i=0; i<p->nIndex; i++){
154080  Fts3HashElem *pElem;
154081  Fts3Hash *pHash = &p->aIndex[i].hPending;
154082  for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
154083  PendingList *pList = (PendingList *)fts3HashData(pElem);
154084  fts3PendingListDelete(pList);
154085  }
154086  fts3HashClear(pHash);
154087  }
154088  p->nPendingData = 0;
154089 }
154090 
154091 /*
154092 ** This function is called by the xUpdate() method as part of an INSERT
154093 ** operation. It adds entries for each term in the new record to the
154094 ** pendingTerms hash table.
154095 **
154096 ** Argument apVal is the same as the similarly named argument passed to
154097 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
154098 */
154099 static int fts3InsertTerms(
154100  Fts3Table *p,
154101  int iLangid,
154102  sqlite3_value **apVal,
154103  u32 *aSz
154104 ){
154105  int i; /* Iterator variable */
154106  for(i=2; i<p->nColumn+2; i++){
154107  int iCol = i-2;
154108  if( p->abNotindexed[iCol]==0 ){
154109  const char *zText = (const char *)sqlite3_value_text(apVal[i]);
154110  int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
154111  if( rc!=SQLITE_OK ){
154112  return rc;
154113  }
154114  aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
154115  }
154116  }
154117  return SQLITE_OK;
154118 }
154119 
154120 /*
154121 ** This function is called by the xUpdate() method for an INSERT operation.
154122 ** The apVal parameter is passed a copy of the apVal argument passed by
154123 ** SQLite to the xUpdate() method. i.e:
154124 **
154125 ** apVal[0] Not used for INSERT.
154126 ** apVal[1] rowid
154127 ** apVal[2] Left-most user-defined column
154128 ** ...
154129 ** apVal[p->nColumn+1] Right-most user-defined column
154130 ** apVal[p->nColumn+2] Hidden column with same name as table
154131 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
154132 ** apVal[p->nColumn+4] Hidden languageid column
154133 */
154134 static int fts3InsertData(
154135  Fts3Table *p, /* Full-text table */
154136  sqlite3_value **apVal, /* Array of values to insert */
154137  sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
154138 ){
154139  int rc; /* Return code */
154140  sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
154141 
154142  if( p->zContentTbl ){
154143  sqlite3_value *pRowid = apVal[p->nColumn+3];
154144  if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
154145  pRowid = apVal[1];
154146  }
154147  if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
154148  return SQLITE_CONSTRAINT;
154149  }
154150  *piDocid = sqlite3_value_int64(pRowid);
154151  return SQLITE_OK;
154152  }
154153 
154154  /* Locate the statement handle used to insert data into the %_content
154155  ** table. The SQL for this statement is:
154156  **
154157  ** INSERT INTO %_content VALUES(?, ?, ?, ...)
154158  **
154159  ** The statement features N '?' variables, where N is the number of user
154160  ** defined columns in the FTS3 table, plus one for the docid field.
154161  */
154162  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
154163  if( rc==SQLITE_OK && p->zLanguageid ){
154164  rc = sqlite3_bind_int(
154165  pContentInsert, p->nColumn+2,
154166  sqlite3_value_int(apVal[p->nColumn+4])
154167  );
154168  }
154169  if( rc!=SQLITE_OK ) return rc;
154170 
154171  /* There is a quirk here. The users INSERT statement may have specified
154172  ** a value for the "rowid" field, for the "docid" field, or for both.
154173  ** Which is a problem, since "rowid" and "docid" are aliases for the
154174  ** same value. For example:
154175  **
154176  ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
154177  **
154178  ** In FTS3, this is an error. It is an error to specify non-NULL values
154179  ** for both docid and some other rowid alias.
154180  */
154181  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
154182  if( SQLITE_NULL==sqlite3_value_type(apVal[0])
154183  && SQLITE_NULL!=sqlite3_value_type(apVal[1])
154184  ){
154185  /* A rowid/docid conflict. */
154186  return SQLITE_ERROR;
154187  }
154188  rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
154189  if( rc!=SQLITE_OK ) return rc;
154190  }
154191 
154192  /* Execute the statement to insert the record. Set *piDocid to the
154193  ** new docid value.
154194  */
154195  sqlite3_step(pContentInsert);
154196  rc = sqlite3_reset(pContentInsert);
154197 
154198  *piDocid = sqlite3_last_insert_rowid(p->db);
154199  return rc;
154200 }
154201 
154202 
154203 
154204 /*
154205 ** Remove all data from the FTS3 table. Clear the hash table containing
154206 ** pending terms.
154207 */
154208 static int fts3DeleteAll(Fts3Table *p, int bContent){
154209  int rc = SQLITE_OK; /* Return code */
154210 
154211  /* Discard the contents of the pending-terms hash table. */
154212  sqlite3Fts3PendingTermsClear(p);
154213 
154214  /* Delete everything from the shadow tables. Except, leave %_content as
154215  ** is if bContent is false. */
154216  assert( p->zContentTbl==0 || bContent==0 );
154217  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
154218  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
154219  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
154220  if( p->bHasDocsize ){
154221  fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
154222  }
154223  if( p->bHasStat ){
154224  fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
154225  }
154226  return rc;
154227 }
154228 
154229 /*
154230 **
154231 */
154232 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
154233  int iLangid = 0;
154234  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
154235  return iLangid;
154236 }
154237 
154238 /*
154239 ** The first element in the apVal[] array is assumed to contain the docid
154240 ** (an integer) of a row about to be deleted. Remove all terms from the
154241 ** full-text index.
154242 */
154243 static void fts3DeleteTerms(
154244  int *pRC, /* Result code */
154245  Fts3Table *p, /* The FTS table to delete from */
154246  sqlite3_value *pRowid, /* The docid to be deleted */
154247  u32 *aSz, /* Sizes of deleted document written here */
154248  int *pbFound /* OUT: Set to true if row really does exist */
154249 ){
154250  int rc;
154251  sqlite3_stmt *pSelect;
154252 
154253  assert( *pbFound==0 );
154254  if( *pRC ) return;
154255  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
154256  if( rc==SQLITE_OK ){
154257  if( SQLITE_ROW==sqlite3_step(pSelect) ){
154258  int i;
154259  int iLangid = langidFromSelect(p, pSelect);
154260  i64 iDocid = sqlite3_column_int64(pSelect, 0);
154261  rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
154262  for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
154263  int iCol = i-1;
154264  if( p->abNotindexed[iCol]==0 ){
154265  const char *zText = (const char *)sqlite3_column_text(pSelect, i);
154266  rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
154267  aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
154268  }
154269  }
154270  if( rc!=SQLITE_OK ){
154271  sqlite3_reset(pSelect);
154272  *pRC = rc;
154273  return;
154274  }
154275  *pbFound = 1;
154276  }
154277  rc = sqlite3_reset(pSelect);
154278  }else{
154279  sqlite3_reset(pSelect);
154280  }
154281  *pRC = rc;
154282 }
154283 
154284 /*
154285 ** Forward declaration to account for the circular dependency between
154286 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
154287 */
154288 static int fts3SegmentMerge(Fts3Table *, int, int, int);
154289 
154290 /*
154291 ** This function allocates a new level iLevel index in the segdir table.
154292 ** Usually, indexes are allocated within a level sequentially starting
154293 ** with 0, so the allocated index is one greater than the value returned
154294 ** by:
154295 **
154296 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
154297 **
154298 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
154299 ** level, they are merged into a single level (iLevel+1) segment and the
154300 ** allocated index is 0.
154301 **
154302 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
154303 ** returned. Otherwise, an SQLite error code is returned.
154304 */
154305 static int fts3AllocateSegdirIdx(
154306  Fts3Table *p,
154307  int iLangid, /* Language id */
154308  int iIndex, /* Index for p->aIndex */
154309  int iLevel,
154310  int *piIdx
154311 ){
154312  int rc; /* Return Code */
154313  sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
154314  int iNext = 0; /* Result of query pNextIdx */
154315 
154316  assert( iLangid>=0 );
154317  assert( p->nIndex>=1 );
154318 
154319  /* Set variable iNext to the next available segdir index at level iLevel. */
154320  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
154321  if( rc==SQLITE_OK ){
154323  pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
154324  );
154325  if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
154326  iNext = sqlite3_column_int(pNextIdx, 0);
154327  }
154328  rc = sqlite3_reset(pNextIdx);
154329  }
154330 
154331  if( rc==SQLITE_OK ){
154332  /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
154333  ** full, merge all segments in level iLevel into a single iLevel+1
154334  ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
154335  ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
154336  */
154337  if( iNext>=FTS3_MERGE_COUNT ){
154338  fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
154339  rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
154340  *piIdx = 0;
154341  }else{
154342  *piIdx = iNext;
154343  }
154344  }
154345 
154346  return rc;
154347 }
154348 
154349 /*
154350 ** The %_segments table is declared as follows:
154351 **
154352 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
154353 **
154354 ** This function reads data from a single row of the %_segments table. The
154355 ** specific row is identified by the iBlockid parameter. If paBlob is not
154356 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
154357 ** with the contents of the blob stored in the "block" column of the
154358 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
154359 ** to the size of the blob in bytes before returning.
154360 **
154361 ** If an error occurs, or the table does not contain the specified row,
154362 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
154363 ** paBlob is non-NULL, then it is the responsibility of the caller to
154364 ** eventually free the returned buffer.
154365 **
154366 ** This function may leave an open sqlite3_blob* handle in the
154367 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
154368 ** to this function. The handle may be closed by calling the
154369 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
154370 ** performance improvement, but the blob handle should always be closed
154371 ** before control is returned to the user (to prevent a lock being held
154372 ** on the database file for longer than necessary). Thus, any virtual table
154373 ** method (xFilter etc.) that may directly or indirectly call this function
154374 ** must call sqlite3Fts3SegmentsClose() before returning.
154375 */
154376 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
154377  Fts3Table *p, /* FTS3 table handle */
154378  sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
154379  char **paBlob, /* OUT: Blob data in malloc'd buffer */
154380  int *pnBlob, /* OUT: Size of blob data */
154381  int *pnLoad /* OUT: Bytes actually loaded */
154382 ){
154383  int rc; /* Return code */
154384 
154385  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
154386  assert( pnBlob );
154387 
154388  if( p->pSegments ){
154389  rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
154390  }else{
154391  if( 0==p->zSegmentsTbl ){
154392  p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
154393  if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
154394  }
154395  rc = sqlite3_blob_open(
154396  p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
154397  );
154398  }
154399 
154400  if( rc==SQLITE_OK ){
154401  int nByte = sqlite3_blob_bytes(p->pSegments);
154402  *pnBlob = nByte;
154403  if( paBlob ){
154404  char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
154405  if( !aByte ){
154406  rc = SQLITE_NOMEM;
154407  }else{
154408  if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
154409  nByte = FTS3_NODE_CHUNKSIZE;
154410  *pnLoad = nByte;
154411  }
154412  rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
154413  memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
154414  if( rc!=SQLITE_OK ){
154415  sqlite3_free(aByte);
154416  aByte = 0;
154417  }
154418  }
154419  *paBlob = aByte;
154420  }
154421  }
154422 
154423  return rc;
154424 }
154425 
154426 /*
154427 ** Close the blob handle at p->pSegments, if it is open. See comments above
154428 ** the sqlite3Fts3ReadBlock() function for details.
154429 */
154430 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
154431  sqlite3_blob_close(p->pSegments);
154432  p->pSegments = 0;
154433 }
154434 
154435 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
154436  int nRead; /* Number of bytes to read */
154437  int rc; /* Return code */
154438 
154439  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
154440  rc = sqlite3_blob_read(
154441  pReader->pBlob,
154442  &pReader->aNode[pReader->nPopulate],
154443  nRead,
154444  pReader->nPopulate
154445  );
154446 
154447  if( rc==SQLITE_OK ){
154448  pReader->nPopulate += nRead;
154449  memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
154450  if( pReader->nPopulate==pReader->nNode ){
154451  sqlite3_blob_close(pReader->pBlob);
154452  pReader->pBlob = 0;
154453  pReader->nPopulate = 0;
154454  }
154455  }
154456  return rc;
154457 }
154458 
154459 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
154460  int rc = SQLITE_OK;
154461  assert( !pReader->pBlob
154462  || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
154463  );
154464  while( pReader->pBlob && rc==SQLITE_OK
154465  && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
154466  ){
154467  rc = fts3SegReaderIncrRead(pReader);
154468  }
154469  return rc;
154470 }
154471 
154472 /*
154473 ** Set an Fts3SegReader cursor to point at EOF.
154474 */
154475 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
154476  if( !fts3SegReaderIsRootOnly(pSeg) ){
154477  sqlite3_free(pSeg->aNode);
154478  sqlite3_blob_close(pSeg->pBlob);
154479  pSeg->pBlob = 0;
154480  }
154481  pSeg->aNode = 0;
154482 }
154483 
154484 /*
154485 ** Move the iterator passed as the first argument to the next term in the
154486 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
154487 ** SQLITE_DONE. Otherwise, an SQLite error code.
154488 */
154489 static int fts3SegReaderNext(
154490  Fts3Table *p,
154491  Fts3SegReader *pReader,
154492  int bIncr
154493 ){
154494  int rc; /* Return code of various sub-routines */
154495  char *pNext; /* Cursor variable */
154496  int nPrefix; /* Number of bytes in term prefix */
154497  int nSuffix; /* Number of bytes in term suffix */
154498 
154499  if( !pReader->aDoclist ){
154500  pNext = pReader->aNode;
154501  }else{
154502  pNext = &pReader->aDoclist[pReader->nDoclist];
154503  }
154504 
154505  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
154506 
154507  if( fts3SegReaderIsPending(pReader) ){
154508  Fts3HashElem *pElem = *(pReader->ppNextElem);
154509  sqlite3_free(pReader->aNode);
154510  pReader->aNode = 0;
154511  if( pElem ){
154512  char *aCopy;
154513  PendingList *pList = (PendingList *)fts3HashData(pElem);
154514  int nCopy = pList->nData+1;
154515  pReader->zTerm = (char *)fts3HashKey(pElem);
154516  pReader->nTerm = fts3HashKeysize(pElem);
154517  aCopy = (char*)sqlite3_malloc(nCopy);
154518  if( !aCopy ) return SQLITE_NOMEM;
154519  memcpy(aCopy, pList->aData, nCopy);
154520  pReader->nNode = pReader->nDoclist = nCopy;
154521  pReader->aNode = pReader->aDoclist = aCopy;
154522  pReader->ppNextElem++;
154523  assert( pReader->aNode );
154524  }
154525  return SQLITE_OK;
154526  }
154527 
154528  fts3SegReaderSetEof(pReader);
154529 
154530  /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
154531  ** blocks have already been traversed. */
154532  assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
154533  if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
154534  return SQLITE_OK;
154535  }
154536 
154537  rc = sqlite3Fts3ReadBlock(
154538  p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
154539  (bIncr ? &pReader->nPopulate : 0)
154540  );
154541  if( rc!=SQLITE_OK ) return rc;
154542  assert( pReader->pBlob==0 );
154543  if( bIncr && pReader->nPopulate<pReader->nNode ){
154544  pReader->pBlob = p->pSegments;
154545  p->pSegments = 0;
154546  }
154547  pNext = pReader->aNode;
154548  }
154549 
154550  assert( !fts3SegReaderIsPending(pReader) );
154551 
154552  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
154553  if( rc!=SQLITE_OK ) return rc;
154554 
154555  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
154556  ** safe (no risk of overread) even if the node data is corrupted. */
154557  pNext += fts3GetVarint32(pNext, &nPrefix);
154558  pNext += fts3GetVarint32(pNext, &nSuffix);
154559  if( nPrefix<0 || nSuffix<=0
154560  || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
154561  ){
154562  return FTS_CORRUPT_VTAB;
154563  }
154564 
154565  if( nPrefix+nSuffix>pReader->nTermAlloc ){
154566  int nNew = (nPrefix+nSuffix)*2;
154567  char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
154568  if( !zNew ){
154569  return SQLITE_NOMEM;
154570  }
154571  pReader->zTerm = zNew;
154572  pReader->nTermAlloc = nNew;
154573  }
154574 
154575  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
154576  if( rc!=SQLITE_OK ) return rc;
154577 
154578  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
154579  pReader->nTerm = nPrefix+nSuffix;
154580  pNext += nSuffix;
154581  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
154582  pReader->aDoclist = pNext;
154583  pReader->pOffsetList = 0;
154584 
154585  /* Check that the doclist does not appear to extend past the end of the
154586  ** b-tree node. And that the final byte of the doclist is 0x00. If either
154587  ** of these statements is untrue, then the data structure is corrupt.
154588  */
154589  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
154590  || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
154591  ){
154592  return FTS_CORRUPT_VTAB;
154593  }
154594  return SQLITE_OK;
154595 }
154596 
154597 /*
154598 ** Set the SegReader to point to the first docid in the doclist associated
154599 ** with the current term.
154600 */
154601 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
154602  int rc = SQLITE_OK;
154603  assert( pReader->aDoclist );
154604  assert( !pReader->pOffsetList );
154605  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
154606  u8 bEof = 0;
154607  pReader->iDocid = 0;
154608  pReader->nOffsetList = 0;
154609  sqlite3Fts3DoclistPrev(0,
154610  pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
154611  &pReader->iDocid, &pReader->nOffsetList, &bEof
154612  );
154613  }else{
154614  rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
154615  if( rc==SQLITE_OK ){
154616  int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
154617  pReader->pOffsetList = &pReader->aDoclist[n];
154618  }
154619  }
154620  return rc;
154621 }
154622 
154623 /*
154624 ** Advance the SegReader to point to the next docid in the doclist
154625 ** associated with the current term.
154626 **
154627 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
154628 ** *ppOffsetList is set to point to the first column-offset list
154629 ** in the doclist entry (i.e. immediately past the docid varint).
154630 ** *pnOffsetList is set to the length of the set of column-offset
154631 ** lists, not including the nul-terminator byte. For example:
154632 */
154633 static int fts3SegReaderNextDocid(
154634  Fts3Table *pTab,
154635  Fts3SegReader *pReader, /* Reader to advance to next docid */
154636  char **ppOffsetList, /* OUT: Pointer to current position-list */
154637  int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
154638 ){
154639  int rc = SQLITE_OK;
154640  char *p = pReader->pOffsetList;
154641  char c = 0;
154642 
154643  assert( p );
154644 
154645  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
154646  /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
154647  ** Pending-terms doclists are always built up in ascending order, so
154648  ** we have to iterate through them backwards here. */
154649  u8 bEof = 0;
154650  if( ppOffsetList ){
154651  *ppOffsetList = pReader->pOffsetList;
154652  *pnOffsetList = pReader->nOffsetList - 1;
154653  }
154654  sqlite3Fts3DoclistPrev(0,
154655  pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
154656  &pReader->nOffsetList, &bEof
154657  );
154658  if( bEof ){
154659  pReader->pOffsetList = 0;
154660  }else{
154661  pReader->pOffsetList = p;
154662  }
154663  }else{
154664  char *pEnd = &pReader->aDoclist[pReader->nDoclist];
154665 
154666  /* Pointer p currently points at the first byte of an offset list. The
154667  ** following block advances it to point one byte past the end of
154668  ** the same offset list. */
154669  while( 1 ){
154670 
154671  /* The following line of code (and the "p++" below the while() loop) is
154672  ** normally all that is required to move pointer p to the desired
154673  ** position. The exception is if this node is being loaded from disk
154674  ** incrementally and pointer "p" now points to the first byte past
154675  ** the populated part of pReader->aNode[].
154676  */
154677  while( *p | c ) c = *p++ & 0x80;
154678  assert( *p==0 );
154679 
154680  if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
154681  rc = fts3SegReaderIncrRead(pReader);
154682  if( rc!=SQLITE_OK ) return rc;
154683  }
154684  p++;
154685 
154686  /* If required, populate the output variables with a pointer to and the
154687  ** size of the previous offset-list.
154688  */
154689  if( ppOffsetList ){
154690  *ppOffsetList = pReader->pOffsetList;
154691  *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
154692  }
154693 
154694  /* List may have been edited in place by fts3EvalNearTrim() */
154695  while( p<pEnd && *p==0 ) p++;
154696 
154697  /* If there are no more entries in the doclist, set pOffsetList to
154698  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
154699  ** Fts3SegReader.pOffsetList to point to the next offset list before
154700  ** returning.
154701  */
154702  if( p>=pEnd ){
154703  pReader->pOffsetList = 0;
154704  }else{
154705  rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
154706  if( rc==SQLITE_OK ){
154707  sqlite3_int64 iDelta;
154708  pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
154709  if( pTab->bDescIdx ){
154710  pReader->iDocid -= iDelta;
154711  }else{
154712  pReader->iDocid += iDelta;
154713  }
154714  }
154715  }
154716  }
154717 
154718  return SQLITE_OK;
154719 }
154720 
154721 
154722 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
154723  Fts3Cursor *pCsr,
154724  Fts3MultiSegReader *pMsr,
154725  int *pnOvfl
154726 ){
154727  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
154728  int nOvfl = 0;
154729  int ii;
154730  int rc = SQLITE_OK;
154731  int pgsz = p->nPgsz;
154732 
154733  assert( p->bFts4 );
154734  assert( pgsz>0 );
154735 
154736  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
154737  Fts3SegReader *pReader = pMsr->apSegment[ii];
154738  if( !fts3SegReaderIsPending(pReader)
154739  && !fts3SegReaderIsRootOnly(pReader)
154740  ){
154741  sqlite3_int64 jj;
154742  for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
154743  int nBlob;
154744  rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
154745  if( rc!=SQLITE_OK ) break;
154746  if( (nBlob+35)>pgsz ){
154747  nOvfl += (nBlob + 34)/pgsz;
154748  }
154749  }
154750  }
154751  }
154752  *pnOvfl = nOvfl;
154753  return rc;
154754 }
154755 
154756 /*
154757 ** Free all allocations associated with the iterator passed as the
154758 ** second argument.
154759 */
154760 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
154761  if( pReader ){
154762  if( !fts3SegReaderIsPending(pReader) ){
154763  sqlite3_free(pReader->zTerm);
154764  }
154765  if( !fts3SegReaderIsRootOnly(pReader) ){
154766  sqlite3_free(pReader->aNode);
154767  }
154768  sqlite3_blob_close(pReader->pBlob);
154769  }
154770  sqlite3_free(pReader);
154771 }
154772 
154773 /*
154774 ** Allocate a new SegReader object.
154775 */
154776 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
154777  int iAge, /* Segment "age". */
154778  int bLookup, /* True for a lookup only */
154779  sqlite3_int64 iStartLeaf, /* First leaf to traverse */
154780  sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
154781  sqlite3_int64 iEndBlock, /* Final block of segment */
154782  const char *zRoot, /* Buffer containing root node */
154783  int nRoot, /* Size of buffer containing root node */
154784  Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
154785 ){
154786  Fts3SegReader *pReader; /* Newly allocated SegReader object */
154787  int nExtra = 0; /* Bytes to allocate segment root node */
154788 
154789  assert( iStartLeaf<=iEndLeaf );
154790  if( iStartLeaf==0 ){
154791  nExtra = nRoot + FTS3_NODE_PADDING;
154792  }
154793 
154794  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
154795  if( !pReader ){
154796  return SQLITE_NOMEM;
154797  }
154798  memset(pReader, 0, sizeof(Fts3SegReader));
154799  pReader->iIdx = iAge;
154800  pReader->bLookup = bLookup!=0;
154801  pReader->iStartBlock = iStartLeaf;
154802  pReader->iLeafEndBlock = iEndLeaf;
154803  pReader->iEndBlock = iEndBlock;
154804 
154805  if( nExtra ){
154806  /* The entire segment is stored in the root node. */
154807  pReader->aNode = (char *)&pReader[1];
154808  pReader->rootOnly = 1;
154809  pReader->nNode = nRoot;
154810  memcpy(pReader->aNode, zRoot, nRoot);
154811  memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
154812  }else{
154813  pReader->iCurrentBlock = iStartLeaf-1;
154814  }
154815  *ppReader = pReader;
154816  return SQLITE_OK;
154817 }
154818 
154819 /*
154820 ** This is a comparison function used as a qsort() callback when sorting
154821 ** an array of pending terms by term. This occurs as part of flushing
154822 ** the contents of the pending-terms hash table to the database.
154823 */
154824 static int SQLITE_CDECL fts3CompareElemByTerm(
154825  const void *lhs,
154826  const void *rhs
154827 ){
154828  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
154829  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
154830  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
154831  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
154832 
154833  int n = (n1<n2 ? n1 : n2);
154834  int c = memcmp(z1, z2, n);
154835  if( c==0 ){
154836  c = n1 - n2;
154837  }
154838  return c;
154839 }
154840 
154841 /*
154842 ** This function is used to allocate an Fts3SegReader that iterates through
154843 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
154844 **
154845 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
154846 ** through each term in the pending-terms table. Or, if isPrefixIter is
154847 ** non-zero, it iterates through each term and its prefixes. For example, if
154848 ** the pending terms hash table contains the terms "sqlite", "mysql" and
154849 ** "firebird", then the iterator visits the following 'terms' (in the order
154850 ** shown):
154851 **
154852 ** f fi fir fire fireb firebi firebir firebird
154853 ** m my mys mysq mysql
154854 ** s sq sql sqli sqlit sqlite
154855 **
154856 ** Whereas if isPrefixIter is zero, the terms visited are:
154857 **
154858 ** firebird mysql sqlite
154859 */
154860 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
154861  Fts3Table *p, /* Virtual table handle */
154862  int iIndex, /* Index for p->aIndex */
154863  const char *zTerm, /* Term to search for */
154864  int nTerm, /* Size of buffer zTerm */
154865  int bPrefix, /* True for a prefix iterator */
154866  Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
154867 ){
154868  Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
154869  Fts3HashElem *pE; /* Iterator variable */
154870  Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
154871  int nElem = 0; /* Size of array at aElem */
154872  int rc = SQLITE_OK; /* Return Code */
154873  Fts3Hash *pHash;
154874 
154875  pHash = &p->aIndex[iIndex].hPending;
154876  if( bPrefix ){
154877  int nAlloc = 0; /* Size of allocated array at aElem */
154878 
154879  for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
154880  char *zKey = (char *)fts3HashKey(pE);
154881  int nKey = fts3HashKeysize(pE);
154882  if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
154883  if( nElem==nAlloc ){
154884  Fts3HashElem **aElem2;
154885  nAlloc += 16;
154886  aElem2 = (Fts3HashElem **)sqlite3_realloc(
154887  aElem, nAlloc*sizeof(Fts3HashElem *)
154888  );
154889  if( !aElem2 ){
154890  rc = SQLITE_NOMEM;
154891  nElem = 0;
154892  break;
154893  }
154894  aElem = aElem2;
154895  }
154896 
154897  aElem[nElem++] = pE;
154898  }
154899  }
154900 
154901  /* If more than one term matches the prefix, sort the Fts3HashElem
154902  ** objects in term order using qsort(). This uses the same comparison
154903  ** callback as is used when flushing terms to disk.
154904  */
154905  if( nElem>1 ){
154906  qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
154907  }
154908 
154909  }else{
154910  /* The query is a simple term lookup that matches at most one term in
154911  ** the index. All that is required is a straight hash-lookup.
154912  **
154913  ** Because the stack address of pE may be accessed via the aElem pointer
154914  ** below, the "Fts3HashElem *pE" must be declared so that it is valid
154915  ** within this entire function, not just this "else{...}" block.
154916  */
154917  pE = fts3HashFindElem(pHash, zTerm, nTerm);
154918  if( pE ){
154919  aElem = &pE;
154920  nElem = 1;
154921  }
154922  }
154923 
154924  if( nElem>0 ){
154925  int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
154926  pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
154927  if( !pReader ){
154928  rc = SQLITE_NOMEM;
154929  }else{
154930  memset(pReader, 0, nByte);
154931  pReader->iIdx = 0x7FFFFFFF;
154932  pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
154933  memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
154934  }
154935  }
154936 
154937  if( bPrefix ){
154938  sqlite3_free(aElem);
154939  }
154940  *ppReader = pReader;
154941  return rc;
154942 }
154943 
154944 /*
154945 ** Compare the entries pointed to by two Fts3SegReader structures.
154946 ** Comparison is as follows:
154947 **
154948 ** 1) EOF is greater than not EOF.
154949 **
154950 ** 2) The current terms (if any) are compared using memcmp(). If one
154951 ** term is a prefix of another, the longer term is considered the
154952 ** larger.
154953 **
154954 ** 3) By segment age. An older segment is considered larger.
154955 */
154956 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
154957  int rc;
154958  if( pLhs->aNode && pRhs->aNode ){
154959  int rc2 = pLhs->nTerm - pRhs->nTerm;
154960  if( rc2<0 ){
154961  rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
154962  }else{
154963  rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
154964  }
154965  if( rc==0 ){
154966  rc = rc2;
154967  }
154968  }else{
154969  rc = (pLhs->aNode==0) - (pRhs->aNode==0);
154970  }
154971  if( rc==0 ){
154972  rc = pRhs->iIdx - pLhs->iIdx;
154973  }
154974  assert( rc!=0 );
154975  return rc;
154976 }
154977 
154978 /*
154979 ** A different comparison function for SegReader structures. In this
154980 ** version, it is assumed that each SegReader points to an entry in
154981 ** a doclist for identical terms. Comparison is made as follows:
154982 **
154983 ** 1) EOF (end of doclist in this case) is greater than not EOF.
154984 **
154985 ** 2) By current docid.
154986 **
154987 ** 3) By segment age. An older segment is considered larger.
154988 */
154989 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
154990  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
154991  if( rc==0 ){
154992  if( pLhs->iDocid==pRhs->iDocid ){
154993  rc = pRhs->iIdx - pLhs->iIdx;
154994  }else{
154995  rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
154996  }
154997  }
154998  assert( pLhs->aNode && pRhs->aNode );
154999  return rc;
155000 }
155001 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
155002  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
155003  if( rc==0 ){
155004  if( pLhs->iDocid==pRhs->iDocid ){
155005  rc = pRhs->iIdx - pLhs->iIdx;
155006  }else{
155007  rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
155008  }
155009  }
155010  assert( pLhs->aNode && pRhs->aNode );
155011  return rc;
155012 }
155013 
155014 /*
155015 ** Compare the term that the Fts3SegReader object passed as the first argument
155016 ** points to with the term specified by arguments zTerm and nTerm.
155017 **
155018 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
155019 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
155020 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
155021 */
155022 static int fts3SegReaderTermCmp(
155023  Fts3SegReader *pSeg, /* Segment reader object */
155024  const char *zTerm, /* Term to compare to */
155025  int nTerm /* Size of term zTerm in bytes */
155026 ){
155027  int res = 0;
155028  if( pSeg->aNode ){
155029  if( pSeg->nTerm>nTerm ){
155030  res = memcmp(pSeg->zTerm, zTerm, nTerm);
155031  }else{
155032  res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
155033  }
155034  if( res==0 ){
155035  res = pSeg->nTerm-nTerm;
155036  }
155037  }
155038  return res;
155039 }
155040 
155041 /*
155042 ** Argument apSegment is an array of nSegment elements. It is known that
155043 ** the final (nSegment-nSuspect) members are already in sorted order
155044 ** (according to the comparison function provided). This function shuffles
155045 ** the array around until all entries are in sorted order.
155046 */
155047 static void fts3SegReaderSort(
155048  Fts3SegReader **apSegment, /* Array to sort entries of */
155049  int nSegment, /* Size of apSegment array */
155050  int nSuspect, /* Unsorted entry count */
155051  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
155052 ){
155053  int i; /* Iterator variable */
155054 
155055  assert( nSuspect<=nSegment );
155056 
155057  if( nSuspect==nSegment ) nSuspect--;
155058  for(i=nSuspect-1; i>=0; i--){
155059  int j;
155060  for(j=i; j<(nSegment-1); j++){
155061  Fts3SegReader *pTmp;
155062  if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
155063  pTmp = apSegment[j+1];
155064  apSegment[j+1] = apSegment[j];
155065  apSegment[j] = pTmp;
155066  }
155067  }
155068 
155069 #ifndef NDEBUG
155070  /* Check that the list really is sorted now. */
155071  for(i=0; i<(nSuspect-1); i++){
155072  assert( xCmp(apSegment[i], apSegment[i+1])<0 );
155073  }
155074 #endif
155075 }
155076 
155077 /*
155078 ** Insert a record into the %_segments table.
155079 */
155080 static int fts3WriteSegment(
155081  Fts3Table *p, /* Virtual table handle */
155082  sqlite3_int64 iBlock, /* Block id for new block */
155083  char *z, /* Pointer to buffer containing block data */
155084  int n /* Size of buffer z in bytes */
155085 ){
155086  sqlite3_stmt *pStmt;
155087  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
155088  if( rc==SQLITE_OK ){
155089  sqlite3_bind_int64(pStmt, 1, iBlock);
155090  sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
155091  sqlite3_step(pStmt);
155092  rc = sqlite3_reset(pStmt);
155093  }
155094  return rc;
155095 }
155096 
155097 /*
155098 ** Find the largest relative level number in the table. If successful, set
155099 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
155100 ** set *pnMax to zero and return an SQLite error code.
155101 */
155102 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
155103  int rc;
155104  int mxLevel = 0;
155105  sqlite3_stmt *pStmt = 0;
155106 
155107  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
155108  if( rc==SQLITE_OK ){
155109  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155110  mxLevel = sqlite3_column_int(pStmt, 0);
155111  }
155112  rc = sqlite3_reset(pStmt);
155113  }
155114  *pnMax = mxLevel;
155115  return rc;
155116 }
155117 
155118 /*
155119 ** Insert a record into the %_segdir table.
155120 */
155121 static int fts3WriteSegdir(
155122  Fts3Table *p, /* Virtual table handle */
155123  sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
155124  int iIdx, /* Value for "idx" field */
155125  sqlite3_int64 iStartBlock, /* Value for "start_block" field */
155126  sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
155127  sqlite3_int64 iEndBlock, /* Value for "end_block" field */
155128  sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
155129  char *zRoot, /* Blob value for "root" field */
155130  int nRoot /* Number of bytes in buffer zRoot */
155131 ){
155132  sqlite3_stmt *pStmt;
155133  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
155134  if( rc==SQLITE_OK ){
155135  sqlite3_bind_int64(pStmt, 1, iLevel);
155136  sqlite3_bind_int(pStmt, 2, iIdx);
155137  sqlite3_bind_int64(pStmt, 3, iStartBlock);
155138  sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
155139  if( nLeafData==0 ){
155140  sqlite3_bind_int64(pStmt, 5, iEndBlock);
155141  }else{
155142  char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
155143  if( !zEnd ) return SQLITE_NOMEM;
155144  sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
155145  }
155146  sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
155147  sqlite3_step(pStmt);
155148  rc = sqlite3_reset(pStmt);
155149  }
155150  return rc;
155151 }
155152 
155153 /*
155154 ** Return the size of the common prefix (if any) shared by zPrev and
155155 ** zNext, in bytes. For example,
155156 **
155157 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
155158 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
155159 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
155160 */
155161 static int fts3PrefixCompress(
155162  const char *zPrev, /* Buffer containing previous term */
155163  int nPrev, /* Size of buffer zPrev in bytes */
155164  const char *zNext, /* Buffer containing next term */
155165  int nNext /* Size of buffer zNext in bytes */
155166 ){
155167  int n;
155168  UNUSED_PARAMETER(nNext);
155169  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
155170  return n;
155171 }
155172 
155173 /*
155174 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
155175 ** (according to memcmp) than the previous term.
155176 */
155177 static int fts3NodeAddTerm(
155178  Fts3Table *p, /* Virtual table handle */
155179  SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
155180  int isCopyTerm, /* True if zTerm/nTerm is transient */
155181  const char *zTerm, /* Pointer to buffer containing term */
155182  int nTerm /* Size of term in bytes */
155183 ){
155184  SegmentNode *pTree = *ppTree;
155185  int rc;
155186  SegmentNode *pNew;
155187 
155188  /* First try to append the term to the current node. Return early if
155189  ** this is possible.
155190  */
155191  if( pTree ){
155192  int nData = pTree->nData; /* Current size of node in bytes */
155193  int nReq = nData; /* Required space after adding zTerm */
155194  int nPrefix; /* Number of bytes of prefix compression */
155195  int nSuffix; /* Suffix length */
155196 
155197  nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
155198  nSuffix = nTerm-nPrefix;
155199 
155200  nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
155201  if( nReq<=p->nNodeSize || !pTree->zTerm ){
155202 
155203  if( nReq>p->nNodeSize ){
155204  /* An unusual case: this is the first term to be added to the node
155205  ** and the static node buffer (p->nNodeSize bytes) is not large
155206  ** enough. Use a separately malloced buffer instead This wastes
155207  ** p->nNodeSize bytes, but since this scenario only comes about when
155208  ** the database contain two terms that share a prefix of almost 2KB,
155209  ** this is not expected to be a serious problem.
155210  */
155211  assert( pTree->aData==(char *)&pTree[1] );
155212  pTree->aData = (char *)sqlite3_malloc(nReq);
155213  if( !pTree->aData ){
155214  return SQLITE_NOMEM;
155215  }
155216  }
155217 
155218  if( pTree->zTerm ){
155219  /* There is no prefix-length field for first term in a node */
155220  nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
155221  }
155222 
155223  nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
155224  memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
155225  pTree->nData = nData + nSuffix;
155226  pTree->nEntry++;
155227 
155228  if( isCopyTerm ){
155229  if( pTree->nMalloc<nTerm ){
155230  char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
155231  if( !zNew ){
155232  return SQLITE_NOMEM;
155233  }
155234  pTree->nMalloc = nTerm*2;
155235  pTree->zMalloc = zNew;
155236  }
155237  pTree->zTerm = pTree->zMalloc;
155238  memcpy(pTree->zTerm, zTerm, nTerm);
155239  pTree->nTerm = nTerm;
155240  }else{
155241  pTree->zTerm = (char *)zTerm;
155242  pTree->nTerm = nTerm;
155243  }
155244  return SQLITE_OK;
155245  }
155246  }
155247 
155248  /* If control flows to here, it was not possible to append zTerm to the
155249  ** current node. Create a new node (a right-sibling of the current node).
155250  ** If this is the first node in the tree, the term is added to it.
155251  **
155252  ** Otherwise, the term is not added to the new node, it is left empty for
155253  ** now. Instead, the term is inserted into the parent of pTree. If pTree
155254  ** has no parent, one is created here.
155255  */
155256  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
155257  if( !pNew ){
155258  return SQLITE_NOMEM;
155259  }
155260  memset(pNew, 0, sizeof(SegmentNode));
155261  pNew->nData = 1 + FTS3_VARINT_MAX;
155262  pNew->aData = (char *)&pNew[1];
155263 
155264  if( pTree ){
155265  SegmentNode *pParent = pTree->pParent;
155266  rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
155267  if( pTree->pParent==0 ){
155268  pTree->pParent = pParent;
155269  }
155270  pTree->pRight = pNew;
155271  pNew->pLeftmost = pTree->pLeftmost;
155272  pNew->pParent = pParent;
155273  pNew->zMalloc = pTree->zMalloc;
155274  pNew->nMalloc = pTree->nMalloc;
155275  pTree->zMalloc = 0;
155276  }else{
155277  pNew->pLeftmost = pNew;
155278  rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
155279  }
155280 
155281  *ppTree = pNew;
155282  return rc;
155283 }
155284 
155285 /*
155286 ** Helper function for fts3NodeWrite().
155287 */
155288 static int fts3TreeFinishNode(
155289  SegmentNode *pTree,
155290  int iHeight,
155291  sqlite3_int64 iLeftChild
155292 ){
155293  int nStart;
155294  assert( iHeight>=1 && iHeight<128 );
155295  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
155296  pTree->aData[nStart] = (char)iHeight;
155297  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
155298  return nStart;
155299 }
155300 
155301 /*
155302 ** Write the buffer for the segment node pTree and all of its peers to the
155303 ** database. Then call this function recursively to write the parent of
155304 ** pTree and its peers to the database.
155305 **
155306 ** Except, if pTree is a root node, do not write it to the database. Instead,
155307 ** set output variables *paRoot and *pnRoot to contain the root node.
155308 **
155309 ** If successful, SQLITE_OK is returned and output variable *piLast is
155310 ** set to the largest blockid written to the database (or zero if no
155311 ** blocks were written to the db). Otherwise, an SQLite error code is
155312 ** returned.
155313 */
155314 static int fts3NodeWrite(
155315  Fts3Table *p, /* Virtual table handle */
155316  SegmentNode *pTree, /* SegmentNode handle */
155317  int iHeight, /* Height of this node in tree */
155318  sqlite3_int64 iLeaf, /* Block id of first leaf node */
155319  sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
155320  sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
155321  char **paRoot, /* OUT: Data for root node */
155322  int *pnRoot /* OUT: Size of root node in bytes */
155323 ){
155324  int rc = SQLITE_OK;
155325 
155326  if( !pTree->pParent ){
155327  /* Root node of the tree. */
155328  int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
155329  *piLast = iFree-1;
155330  *pnRoot = pTree->nData - nStart;
155331  *paRoot = &pTree->aData[nStart];
155332  }else{
155333  SegmentNode *pIter;
155334  sqlite3_int64 iNextFree = iFree;
155335  sqlite3_int64 iNextLeaf = iLeaf;
155336  for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
155337  int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
155338  int nWrite = pIter->nData - nStart;
155339 
155340  rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
155341  iNextFree++;
155342  iNextLeaf += (pIter->nEntry+1);
155343  }
155344  if( rc==SQLITE_OK ){
155345  assert( iNextLeaf==iFree );
155346  rc = fts3NodeWrite(
155347  p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
155348  );
155349  }
155350  }
155351 
155352  return rc;
155353 }
155354 
155355 /*
155356 ** Free all memory allocations associated with the tree pTree.
155357 */
155358 static void fts3NodeFree(SegmentNode *pTree){
155359  if( pTree ){
155360  SegmentNode *p = pTree->pLeftmost;
155361  fts3NodeFree(p->pParent);
155362  while( p ){
155363  SegmentNode *pRight = p->pRight;
155364  if( p->aData!=(char *)&p[1] ){
155365  sqlite3_free(p->aData);
155366  }
155367  assert( pRight==0 || p->zMalloc==0 );
155368  sqlite3_free(p->zMalloc);
155369  sqlite3_free(p);
155370  p = pRight;
155371  }
155372  }
155373 }
155374 
155375 /*
155376 ** Add a term to the segment being constructed by the SegmentWriter object
155377 ** *ppWriter. When adding the first term to a segment, *ppWriter should
155378 ** be passed NULL. This function will allocate a new SegmentWriter object
155379 ** and return it via the input/output variable *ppWriter in this case.
155380 **
155381 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
155382 */
155383 static int fts3SegWriterAdd(
155384  Fts3Table *p, /* Virtual table handle */
155385  SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
155386  int isCopyTerm, /* True if buffer zTerm must be copied */
155387  const char *zTerm, /* Pointer to buffer containing term */
155388  int nTerm, /* Size of term in bytes */
155389  const char *aDoclist, /* Pointer to buffer containing doclist */
155390  int nDoclist /* Size of doclist in bytes */
155391 ){
155392  int nPrefix; /* Size of term prefix in bytes */
155393  int nSuffix; /* Size of term suffix in bytes */
155394  int nReq; /* Number of bytes required on leaf page */
155395  int nData;
155396  SegmentWriter *pWriter = *ppWriter;
155397 
155398  if( !pWriter ){
155399  int rc;
155400  sqlite3_stmt *pStmt;
155401 
155402  /* Allocate the SegmentWriter structure */
155403  pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
155404  if( !pWriter ) return SQLITE_NOMEM;
155405  memset(pWriter, 0, sizeof(SegmentWriter));
155406  *ppWriter = pWriter;
155407 
155408  /* Allocate a buffer in which to accumulate data */
155409  pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
155410  if( !pWriter->aData ) return SQLITE_NOMEM;
155411  pWriter->nSize = p->nNodeSize;
155412 
155413  /* Find the next free blockid in the %_segments table */
155414  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
155415  if( rc!=SQLITE_OK ) return rc;
155416  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155417  pWriter->iFree = sqlite3_column_int64(pStmt, 0);
155418  pWriter->iFirst = pWriter->iFree;
155419  }
155420  rc = sqlite3_reset(pStmt);
155421  if( rc!=SQLITE_OK ) return rc;
155422  }
155423  nData = pWriter->nData;
155424 
155425  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
155426  nSuffix = nTerm-nPrefix;
155427 
155428  /* Figure out how many bytes are required by this new entry */
155429  nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
155430  sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
155431  nSuffix + /* Term suffix */
155432  sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
155433  nDoclist; /* Doclist data */
155434 
155435  if( nData>0 && nData+nReq>p->nNodeSize ){
155436  int rc;
155437 
155438  /* The current leaf node is full. Write it out to the database. */
155439  rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
155440  if( rc!=SQLITE_OK ) return rc;
155441  p->nLeafAdd++;
155442 
155443  /* Add the current term to the interior node tree. The term added to
155444  ** the interior tree must:
155445  **
155446  ** a) be greater than the largest term on the leaf node just written
155447  ** to the database (still available in pWriter->zTerm), and
155448  **
155449  ** b) be less than or equal to the term about to be added to the new
155450  ** leaf node (zTerm/nTerm).
155451  **
155452  ** In other words, it must be the prefix of zTerm 1 byte longer than
155453  ** the common prefix (if any) of zTerm and pWriter->zTerm.
155454  */
155455  assert( nPrefix<nTerm );
155456  rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
155457  if( rc!=SQLITE_OK ) return rc;
155458 
155459  nData = 0;
155460  pWriter->nTerm = 0;
155461 
155462  nPrefix = 0;
155463  nSuffix = nTerm;
155464  nReq = 1 + /* varint containing prefix size */
155465  sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
155466  nTerm + /* Term suffix */
155467  sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
155468  nDoclist; /* Doclist data */
155469  }
155470 
155471  /* Increase the total number of bytes written to account for the new entry. */
155472  pWriter->nLeafData += nReq;
155473 
155474  /* If the buffer currently allocated is too small for this entry, realloc
155475  ** the buffer to make it large enough.
155476  */
155477  if( nReq>pWriter->nSize ){
155478  char *aNew = sqlite3_realloc(pWriter->aData, nReq);
155479  if( !aNew ) return SQLITE_NOMEM;
155480  pWriter->aData = aNew;
155481  pWriter->nSize = nReq;
155482  }
155483  assert( nData+nReq<=pWriter->nSize );
155484 
155485  /* Append the prefix-compressed term and doclist to the buffer. */
155486  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
155487  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
155488  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
155489  nData += nSuffix;
155490  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
155491  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
155492  pWriter->nData = nData + nDoclist;
155493 
155494  /* Save the current term so that it can be used to prefix-compress the next.
155495  ** If the isCopyTerm parameter is true, then the buffer pointed to by
155496  ** zTerm is transient, so take a copy of the term data. Otherwise, just
155497  ** store a copy of the pointer.
155498  */
155499  if( isCopyTerm ){
155500  if( nTerm>pWriter->nMalloc ){
155501  char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
155502  if( !zNew ){
155503  return SQLITE_NOMEM;
155504  }
155505  pWriter->nMalloc = nTerm*2;
155506  pWriter->zMalloc = zNew;
155507  pWriter->zTerm = zNew;
155508  }
155509  assert( pWriter->zTerm==pWriter->zMalloc );
155510  memcpy(pWriter->zTerm, zTerm, nTerm);
155511  }else{
155512  pWriter->zTerm = (char *)zTerm;
155513  }
155514  pWriter->nTerm = nTerm;
155515 
155516  return SQLITE_OK;
155517 }
155518 
155519 /*
155520 ** Flush all data associated with the SegmentWriter object pWriter to the
155521 ** database. This function must be called after all terms have been added
155522 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
155523 ** returned. Otherwise, an SQLite error code.
155524 */
155525 static int fts3SegWriterFlush(
155526  Fts3Table *p, /* Virtual table handle */
155527  SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
155528  sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
155529  int iIdx /* Value for 'idx' column of %_segdir */
155530 ){
155531  int rc; /* Return code */
155532  if( pWriter->pTree ){
155533  sqlite3_int64 iLast = 0; /* Largest block id written to database */
155534  sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
155535  char *zRoot = NULL; /* Pointer to buffer containing root node */
155536  int nRoot = 0; /* Size of buffer zRoot */
155537 
155538  iLastLeaf = pWriter->iFree;
155539  rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
155540  if( rc==SQLITE_OK ){
155541  rc = fts3NodeWrite(p, pWriter->pTree, 1,
155542  pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
155543  }
155544  if( rc==SQLITE_OK ){
155545  rc = fts3WriteSegdir(p, iLevel, iIdx,
155546  pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
155547  }
155548  }else{
155549  /* The entire tree fits on the root node. Write it to the segdir table. */
155550  rc = fts3WriteSegdir(p, iLevel, iIdx,
155551  0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
155552  }
155553  p->nLeafAdd++;
155554  return rc;
155555 }
155556 
155557 /*
155558 ** Release all memory held by the SegmentWriter object passed as the
155559 ** first argument.
155560 */
155561 static void fts3SegWriterFree(SegmentWriter *pWriter){
155562  if( pWriter ){
155563  sqlite3_free(pWriter->aData);
155564  sqlite3_free(pWriter->zMalloc);
155565  fts3NodeFree(pWriter->pTree);
155566  sqlite3_free(pWriter);
155567  }
155568 }
155569 
155570 /*
155571 ** The first value in the apVal[] array is assumed to contain an integer.
155572 ** This function tests if there exist any documents with docid values that
155573 ** are different from that integer. i.e. if deleting the document with docid
155574 ** pRowid would mean the FTS3 table were empty.
155575 **
155576 ** If successful, *pisEmpty is set to true if the table is empty except for
155577 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
155578 ** error occurs, an SQLite error code is returned.
155579 */
155580 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
155581  sqlite3_stmt *pStmt;
155582  int rc;
155583  if( p->zContentTbl ){
155584  /* If using the content=xxx option, assume the table is never empty */
155585  *pisEmpty = 0;
155586  rc = SQLITE_OK;
155587  }else{
155588  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
155589  if( rc==SQLITE_OK ){
155590  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155591  *pisEmpty = sqlite3_column_int(pStmt, 0);
155592  }
155593  rc = sqlite3_reset(pStmt);
155594  }
155595  }
155596  return rc;
155597 }
155598 
155599 /*
155600 ** Set *pnMax to the largest segment level in the database for the index
155601 ** iIndex.
155602 **
155603 ** Segment levels are stored in the 'level' column of the %_segdir table.
155604 **
155605 ** Return SQLITE_OK if successful, or an SQLite error code if not.
155606 */
155607 static int fts3SegmentMaxLevel(
155608  Fts3Table *p,
155609  int iLangid,
155610  int iIndex,
155611  sqlite3_int64 *pnMax
155612 ){
155613  sqlite3_stmt *pStmt;
155614  int rc;
155615  assert( iIndex>=0 && iIndex<p->nIndex );
155616 
155617  /* Set pStmt to the compiled version of:
155618  **
155619  ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
155620  **
155621  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
155622  */
155623  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
155624  if( rc!=SQLITE_OK ) return rc;
155625  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
155626  sqlite3_bind_int64(pStmt, 2,
155627  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
155628  );
155629  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155630  *pnMax = sqlite3_column_int64(pStmt, 0);
155631  }
155632  return sqlite3_reset(pStmt);
155633 }
155634 
155635 /*
155636 ** iAbsLevel is an absolute level that may be assumed to exist within
155637 ** the database. This function checks if it is the largest level number
155638 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
155639 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
155640 ** is returned. If an error occurs, an error code is returned and the
155641 ** final value of *pbMax is undefined.
155642 */
155643 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
155644 
155645  /* Set pStmt to the compiled version of:
155646  **
155647  ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
155648  **
155649  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
155650  */
155651  sqlite3_stmt *pStmt;
155652  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
155653  if( rc!=SQLITE_OK ) return rc;
155654  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
155655  sqlite3_bind_int64(pStmt, 2,
155656  ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
155657  );
155658 
155659  *pbMax = 0;
155660  if( SQLITE_ROW==sqlite3_step(pStmt) ){
155661  *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
155662  }
155663  return sqlite3_reset(pStmt);
155664 }
155665 
155666 /*
155667 ** Delete all entries in the %_segments table associated with the segment
155668 ** opened with seg-reader pSeg. This function does not affect the contents
155669 ** of the %_segdir table.
155670 */
155671 static int fts3DeleteSegment(
155672  Fts3Table *p, /* FTS table handle */
155673  Fts3SegReader *pSeg /* Segment to delete */
155674 ){
155675  int rc = SQLITE_OK; /* Return code */
155676  if( pSeg->iStartBlock ){
155677  sqlite3_stmt *pDelete; /* SQL statement to delete rows */
155678  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
155679  if( rc==SQLITE_OK ){
155680  sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
155681  sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
155682  sqlite3_step(pDelete);
155683  rc = sqlite3_reset(pDelete);
155684  }
155685  }
155686  return rc;
155687 }
155688 
155689 /*
155690 ** This function is used after merging multiple segments into a single large
155691 ** segment to delete the old, now redundant, segment b-trees. Specifically,
155692 ** it:
155693 **
155694 ** 1) Deletes all %_segments entries for the segments associated with
155695 ** each of the SegReader objects in the array passed as the third
155696 ** argument, and
155697 **
155698 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
155699 ** entries regardless of level if (iLevel<0).
155700 **
155701 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
155702 */
155703 static int fts3DeleteSegdir(
155704  Fts3Table *p, /* Virtual table handle */
155705  int iLangid, /* Language id */
155706  int iIndex, /* Index for p->aIndex */
155707  int iLevel, /* Level of %_segdir entries to delete */
155708  Fts3SegReader **apSegment, /* Array of SegReader objects */
155709  int nReader /* Size of array apSegment */
155710 ){
155711  int rc = SQLITE_OK; /* Return Code */
155712  int i; /* Iterator variable */
155713  sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
155714 
155715  for(i=0; rc==SQLITE_OK && i<nReader; i++){
155716  rc = fts3DeleteSegment(p, apSegment[i]);
155717  }
155718  if( rc!=SQLITE_OK ){
155719  return rc;
155720  }
155721 
155722  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
155723  if( iLevel==FTS3_SEGCURSOR_ALL ){
155724  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
155725  if( rc==SQLITE_OK ){
155726  sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
155727  sqlite3_bind_int64(pDelete, 2,
155728  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
155729  );
155730  }
155731  }else{
155732  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
155733  if( rc==SQLITE_OK ){
155735  pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
155736  );
155737  }
155738  }
155739 
155740  if( rc==SQLITE_OK ){
155741  sqlite3_step(pDelete);
155742  rc = sqlite3_reset(pDelete);
155743  }
155744 
155745  return rc;
155746 }
155747 
155748 /*
155749 ** When this function is called, buffer *ppList (size *pnList bytes) contains
155750 ** a position list that may (or may not) feature multiple columns. This
155751 ** function adjusts the pointer *ppList and the length *pnList so that they
155752 ** identify the subset of the position list that corresponds to column iCol.
155753 **
155754 ** If there are no entries in the input position list for column iCol, then
155755 ** *pnList is set to zero before returning.
155756 **
155757 ** If parameter bZero is non-zero, then any part of the input list following
155758 ** the end of the output list is zeroed before returning.
155759 */
155760 static void fts3ColumnFilter(
155761  int iCol, /* Column to filter on */
155762  int bZero, /* Zero out anything following *ppList */
155763  char **ppList, /* IN/OUT: Pointer to position list */
155764  int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
155765 ){
155766  char *pList = *ppList;
155767  int nList = *pnList;
155768  char *pEnd = &pList[nList];
155769  int iCurrent = 0;
155770  char *p = pList;
155771 
155772  assert( iCol>=0 );
155773  while( 1 ){
155774  char c = 0;
155775  while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
155776 
155777  if( iCol==iCurrent ){
155778  nList = (int)(p - pList);
155779  break;
155780  }
155781 
155782  nList -= (int)(p - pList);
155783  pList = p;
155784  if( nList==0 ){
155785  break;
155786  }
155787  p = &pList[1];
155788  p += fts3GetVarint32(p, &iCurrent);
155789  }
155790 
155791  if( bZero && &pList[nList]!=pEnd ){
155792  memset(&pList[nList], 0, pEnd - &pList[nList]);
155793  }
155794  *ppList = pList;
155795  *pnList = nList;
155796 }
155797 
155798 /*
155799 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
155800 ** existing data). Grow the buffer if required.
155801 **
155802 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
155803 ** trying to resize the buffer, return SQLITE_NOMEM.
155804 */
155805 static int fts3MsrBufferData(
155806  Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
155807  char *pList,
155808  int nList
155809 ){
155810  if( nList>pMsr->nBuffer ){
155811  char *pNew;
155812  pMsr->nBuffer = nList*2;
155813  pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
155814  if( !pNew ) return SQLITE_NOMEM;
155815  pMsr->aBuffer = pNew;
155816  }
155817 
155818  memcpy(pMsr->aBuffer, pList, nList);
155819  return SQLITE_OK;
155820 }
155821 
155822 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
155823  Fts3Table *p, /* Virtual table handle */
155824  Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
155825  sqlite3_int64 *piDocid, /* OUT: Docid value */
155826  char **paPoslist, /* OUT: Pointer to position list */
155827  int *pnPoslist /* OUT: Size of position list in bytes */
155828 ){
155829  int nMerge = pMsr->nAdvance;
155830  Fts3SegReader **apSegment = pMsr->apSegment;
155831  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
155832  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
155833  );
155834 
155835  if( nMerge==0 ){
155836  *paPoslist = 0;
155837  return SQLITE_OK;
155838  }
155839 
155840  while( 1 ){
155841  Fts3SegReader *pSeg;
155842  pSeg = pMsr->apSegment[0];
155843 
155844  if( pSeg->pOffsetList==0 ){
155845  *paPoslist = 0;
155846  break;
155847  }else{
155848  int rc;
155849  char *pList;
155850  int nList;
155851  int j;
155852  sqlite3_int64 iDocid = apSegment[0]->iDocid;
155853 
155854  rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
155855  j = 1;
155856  while( rc==SQLITE_OK
155857  && j<nMerge
155858  && apSegment[j]->pOffsetList
155859  && apSegment[j]->iDocid==iDocid
155860  ){
155861  rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
155862  j++;
155863  }
155864  if( rc!=SQLITE_OK ) return rc;
155865  fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
155866 
155867  if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
155868  rc = fts3MsrBufferData(pMsr, pList, nList+1);
155869  if( rc!=SQLITE_OK ) return rc;
155870  assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
155871  pList = pMsr->aBuffer;
155872  }
155873 
155874  if( pMsr->iColFilter>=0 ){
155875  fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
155876  }
155877 
155878  if( nList>0 ){
155879  *paPoslist = pList;
155880  *piDocid = iDocid;
155881  *pnPoslist = nList;
155882  break;
155883  }
155884  }
155885  }
155886 
155887  return SQLITE_OK;
155888 }
155889 
155890 static int fts3SegReaderStart(
155891  Fts3Table *p, /* Virtual table handle */
155892  Fts3MultiSegReader *pCsr, /* Cursor object */
155893  const char *zTerm, /* Term searched for (or NULL) */
155894  int nTerm /* Length of zTerm in bytes */
155895 ){
155896  int i;
155897  int nSeg = pCsr->nSegment;
155898 
155899  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
155900  ** for, then advance each segment iterator until it points to a term of
155901  ** equal or greater value than the specified term. This prevents many
155902  ** unnecessary merge/sort operations for the case where single segment
155903  ** b-tree leaf nodes contain more than one term.
155904  */
155905  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
155906  int res = 0;
155907  Fts3SegReader *pSeg = pCsr->apSegment[i];
155908  do {
155909  int rc = fts3SegReaderNext(p, pSeg, 0);
155910  if( rc!=SQLITE_OK ) return rc;
155911  }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
155912 
155913  if( pSeg->bLookup && res!=0 ){
155914  fts3SegReaderSetEof(pSeg);
155915  }
155916  }
155917  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
155918 
155919  return SQLITE_OK;
155920 }
155921 
155922 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
155923  Fts3Table *p, /* Virtual table handle */
155924  Fts3MultiSegReader *pCsr, /* Cursor object */
155925  Fts3SegFilter *pFilter /* Restrictions on range of iteration */
155926 ){
155927  pCsr->pFilter = pFilter;
155928  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
155929 }
155930 
155931 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
155932  Fts3Table *p, /* Virtual table handle */
155933  Fts3MultiSegReader *pCsr, /* Cursor object */
155934  int iCol, /* Column to match on. */
155935  const char *zTerm, /* Term to iterate through a doclist for */
155936  int nTerm /* Number of bytes in zTerm */
155937 ){
155938  int i;
155939  int rc;
155940  int nSegment = pCsr->nSegment;
155941  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
155942  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
155943  );
155944 
155945  assert( pCsr->pFilter==0 );
155946  assert( zTerm && nTerm>0 );
155947 
155948  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
155949  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
155950  if( rc!=SQLITE_OK ) return rc;
155951 
155952  /* Determine how many of the segments actually point to zTerm/nTerm. */
155953  for(i=0; i<nSegment; i++){
155954  Fts3SegReader *pSeg = pCsr->apSegment[i];
155955  if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
155956  break;
155957  }
155958  }
155959  pCsr->nAdvance = i;
155960 
155961  /* Advance each of the segments to point to the first docid. */
155962  for(i=0; i<pCsr->nAdvance; i++){
155963  rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
155964  if( rc!=SQLITE_OK ) return rc;
155965  }
155966  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
155967 
155968  assert( iCol<0 || iCol<p->nColumn );
155969  pCsr->iColFilter = iCol;
155970 
155971  return SQLITE_OK;
155972 }
155973 
155974 /*
155975 ** This function is called on a MultiSegReader that has been started using
155976 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
155977 ** have been made. Calling this function puts the MultiSegReader in such
155978 ** a state that if the next two calls are:
155979 **
155980 ** sqlite3Fts3SegReaderStart()
155981 ** sqlite3Fts3SegReaderStep()
155982 **
155983 ** then the entire doclist for the term is available in
155984 ** MultiSegReader.aDoclist/nDoclist.
155985 */
155986 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
155987  int i; /* Used to iterate through segment-readers */
155988 
155989  assert( pCsr->zTerm==0 );
155990  assert( pCsr->nTerm==0 );
155991  assert( pCsr->aDoclist==0 );
155992  assert( pCsr->nDoclist==0 );
155993 
155994  pCsr->nAdvance = 0;
155995  pCsr->bRestart = 1;
155996  for(i=0; i<pCsr->nSegment; i++){
155997  pCsr->apSegment[i]->pOffsetList = 0;
155998  pCsr->apSegment[i]->nOffsetList = 0;
155999  pCsr->apSegment[i]->iDocid = 0;
156000  }
156001 
156002  return SQLITE_OK;
156003 }
156004 
156005 
156006 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
156007  Fts3Table *p, /* Virtual table handle */
156008  Fts3MultiSegReader *pCsr /* Cursor object */
156009 ){
156010  int rc = SQLITE_OK;
156011 
156012  int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
156013  int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
156014  int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
156015  int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
156016  int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
156017  int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
156018 
156019  Fts3SegReader **apSegment = pCsr->apSegment;
156020  int nSegment = pCsr->nSegment;
156021  Fts3SegFilter *pFilter = pCsr->pFilter;
156022  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
156023  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
156024  );
156025 
156026  if( pCsr->nSegment==0 ) return SQLITE_OK;
156027 
156028  do {
156029  int nMerge;
156030  int i;
156031 
156032  /* Advance the first pCsr->nAdvance entries in the apSegment[] array
156033  ** forward. Then sort the list in order of current term again.
156034  */
156035  for(i=0; i<pCsr->nAdvance; i++){
156036  Fts3SegReader *pSeg = apSegment[i];
156037  if( pSeg->bLookup ){
156038  fts3SegReaderSetEof(pSeg);
156039  }else{
156040  rc = fts3SegReaderNext(p, pSeg, 0);
156041  }
156042  if( rc!=SQLITE_OK ) return rc;
156043  }
156044  fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
156045  pCsr->nAdvance = 0;
156046 
156047  /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
156048  assert( rc==SQLITE_OK );
156049  if( apSegment[0]->aNode==0 ) break;
156050 
156051  pCsr->nTerm = apSegment[0]->nTerm;
156052  pCsr->zTerm = apSegment[0]->zTerm;
156053 
156054  /* If this is a prefix-search, and if the term that apSegment[0] points
156055  ** to does not share a suffix with pFilter->zTerm/nTerm, then all
156056  ** required callbacks have been made. In this case exit early.
156057  **
156058  ** Similarly, if this is a search for an exact match, and the first term
156059  ** of segment apSegment[0] is not a match, exit early.
156060  */
156061  if( pFilter->zTerm && !isScan ){
156062  if( pCsr->nTerm<pFilter->nTerm
156063  || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
156064  || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
156065  ){
156066  break;
156067  }
156068  }
156069 
156070  nMerge = 1;
156071  while( nMerge<nSegment
156072  && apSegment[nMerge]->aNode
156073  && apSegment[nMerge]->nTerm==pCsr->nTerm
156074  && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
156075  ){
156076  nMerge++;
156077  }
156078 
156079  assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
156080  if( nMerge==1
156081  && !isIgnoreEmpty
156082  && !isFirst
156083  && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
156084  ){
156085  pCsr->nDoclist = apSegment[0]->nDoclist;
156086  if( fts3SegReaderIsPending(apSegment[0]) ){
156087  rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
156088  pCsr->aDoclist = pCsr->aBuffer;
156089  }else{
156090  pCsr->aDoclist = apSegment[0]->aDoclist;
156091  }
156092  if( rc==SQLITE_OK ) rc = SQLITE_ROW;
156093  }else{
156094  int nDoclist = 0; /* Size of doclist */
156095  sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
156096 
156097  /* The current term of the first nMerge entries in the array
156098  ** of Fts3SegReader objects is the same. The doclists must be merged
156099  ** and a single term returned with the merged doclist.
156100  */
156101  for(i=0; i<nMerge; i++){
156102  fts3SegReaderFirstDocid(p, apSegment[i]);
156103  }
156104  fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
156105  while( apSegment[0]->pOffsetList ){
156106  int j; /* Number of segments that share a docid */
156107  char *pList = 0;
156108  int nList = 0;
156109  int nByte;
156110  sqlite3_int64 iDocid = apSegment[0]->iDocid;
156111  fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
156112  j = 1;
156113  while( j<nMerge
156114  && apSegment[j]->pOffsetList
156115  && apSegment[j]->iDocid==iDocid
156116  ){
156117  fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
156118  j++;
156119  }
156120 
156121  if( isColFilter ){
156122  fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
156123  }
156124 
156125  if( !isIgnoreEmpty || nList>0 ){
156126 
156127  /* Calculate the 'docid' delta value to write into the merged
156128  ** doclist. */
156129  sqlite3_int64 iDelta;
156130  if( p->bDescIdx && nDoclist>0 ){
156131  iDelta = iPrev - iDocid;
156132  }else{
156133  iDelta = iDocid - iPrev;
156134  }
156135  assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
156136  assert( nDoclist>0 || iDelta==iDocid );
156137 
156138  nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
156139  if( nDoclist+nByte>pCsr->nBuffer ){
156140  char *aNew;
156141  pCsr->nBuffer = (nDoclist+nByte)*2;
156142  aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
156143  if( !aNew ){
156144  return SQLITE_NOMEM;
156145  }
156146  pCsr->aBuffer = aNew;
156147  }
156148 
156149  if( isFirst ){
156150  char *a = &pCsr->aBuffer[nDoclist];
156151  int nWrite;
156152 
156153  nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
156154  if( nWrite ){
156155  iPrev = iDocid;
156156  nDoclist += nWrite;
156157  }
156158  }else{
156159  nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
156160  iPrev = iDocid;
156161  if( isRequirePos ){
156162  memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
156163  nDoclist += nList;
156164  pCsr->aBuffer[nDoclist++] = '\0';
156165  }
156166  }
156167  }
156168 
156169  fts3SegReaderSort(apSegment, nMerge, j, xCmp);
156170  }
156171  if( nDoclist>0 ){
156172  pCsr->aDoclist = pCsr->aBuffer;
156173  pCsr->nDoclist = nDoclist;
156174  rc = SQLITE_ROW;
156175  }
156176  }
156177  pCsr->nAdvance = nMerge;
156178  }while( rc==SQLITE_OK );
156179 
156180  return rc;
156181 }
156182 
156183 
156184 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
156185  Fts3MultiSegReader *pCsr /* Cursor object */
156186 ){
156187  if( pCsr ){
156188  int i;
156189  for(i=0; i<pCsr->nSegment; i++){
156190  sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
156191  }
156192  sqlite3_free(pCsr->apSegment);
156193  sqlite3_free(pCsr->aBuffer);
156194 
156195  pCsr->nSegment = 0;
156196  pCsr->apSegment = 0;
156197  pCsr->aBuffer = 0;
156198  }
156199 }
156200 
156201 /*
156202 ** Decode the "end_block" field, selected by column iCol of the SELECT
156203 ** statement passed as the first argument.
156204 **
156205 ** The "end_block" field may contain either an integer, or a text field
156206 ** containing the text representation of two non-negative integers separated
156207 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
156208 ** to the integer value and *pnByte to zero before returning. In the second,
156209 ** set *piEndBlock to the first value and *pnByte to the second.
156210 */
156211 static void fts3ReadEndBlockField(
156212  sqlite3_stmt *pStmt,
156213  int iCol,
156214  i64 *piEndBlock,
156215  i64 *pnByte
156216 ){
156217  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
156218  if( zText ){
156219  int i;
156220  int iMul = 1;
156221  i64 iVal = 0;
156222  for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
156223  iVal = iVal*10 + (zText[i] - '0');
156224  }
156225  *piEndBlock = iVal;
156226  while( zText[i]==' ' ) i++;
156227  iVal = 0;
156228  if( zText[i]=='-' ){
156229  i++;
156230  iMul = -1;
156231  }
156232  for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
156233  iVal = iVal*10 + (zText[i] - '0');
156234  }
156235  *pnByte = (iVal * (i64)iMul);
156236  }
156237 }
156238 
156239 
156240 /*
156241 ** A segment of size nByte bytes has just been written to absolute level
156242 ** iAbsLevel. Promote any segments that should be promoted as a result.
156243 */
156244 static int fts3PromoteSegments(
156245  Fts3Table *p, /* FTS table handle */
156246  sqlite3_int64 iAbsLevel, /* Absolute level just updated */
156247  sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
156248 ){
156249  int rc = SQLITE_OK;
156250  sqlite3_stmt *pRange;
156251 
156252  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
156253 
156254  if( rc==SQLITE_OK ){
156255  int bOk = 0;
156256  i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
156257  i64 nLimit = (nByte*3)/2;
156258 
156259  /* Loop through all entries in the %_segdir table corresponding to
156260  ** segments in this index on levels greater than iAbsLevel. If there is
156261  ** at least one such segment, and it is possible to determine that all
156262  ** such segments are smaller than nLimit bytes in size, they will be
156263  ** promoted to level iAbsLevel. */
156264  sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
156265  sqlite3_bind_int64(pRange, 2, iLast);
156266  while( SQLITE_ROW==sqlite3_step(pRange) ){
156267  i64 nSize = 0, dummy;
156268  fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
156269  if( nSize<=0 || nSize>nLimit ){
156270  /* If nSize==0, then the %_segdir.end_block field does not not
156271  ** contain a size value. This happens if it was written by an
156272  ** old version of FTS. In this case it is not possible to determine
156273  ** the size of the segment, and so segment promotion does not
156274  ** take place. */
156275  bOk = 0;
156276  break;
156277  }
156278  bOk = 1;
156279  }
156280  rc = sqlite3_reset(pRange);
156281 
156282  if( bOk ){
156283  int iIdx = 0;
156284  sqlite3_stmt *pUpdate1 = 0;
156285  sqlite3_stmt *pUpdate2 = 0;
156286 
156287  if( rc==SQLITE_OK ){
156288  rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
156289  }
156290  if( rc==SQLITE_OK ){
156291  rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
156292  }
156293 
156294  if( rc==SQLITE_OK ){
156295 
156296  /* Loop through all %_segdir entries for segments in this index with
156297  ** levels equal to or greater than iAbsLevel. As each entry is visited,
156298  ** updated it to set (level = -1) and (idx = N), where N is 0 for the
156299  ** oldest segment in the range, 1 for the next oldest, and so on.
156300  **
156301  ** In other words, move all segments being promoted to level -1,
156302  ** setting the "idx" fields as appropriate to keep them in the same
156303  ** order. The contents of level -1 (which is never used, except
156304  ** transiently here), will be moved back to level iAbsLevel below. */
156305  sqlite3_bind_int64(pRange, 1, iAbsLevel);
156306  while( SQLITE_ROW==sqlite3_step(pRange) ){
156307  sqlite3_bind_int(pUpdate1, 1, iIdx++);
156308  sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
156309  sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
156310  sqlite3_step(pUpdate1);
156311  rc = sqlite3_reset(pUpdate1);
156312  if( rc!=SQLITE_OK ){
156313  sqlite3_reset(pRange);
156314  break;
156315  }
156316  }
156317  }
156318  if( rc==SQLITE_OK ){
156319  rc = sqlite3_reset(pRange);
156320  }
156321 
156322  /* Move level -1 to level iAbsLevel */
156323  if( rc==SQLITE_OK ){
156324  sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
156325  sqlite3_step(pUpdate2);
156326  rc = sqlite3_reset(pUpdate2);
156327  }
156328  }
156329  }
156330 
156331 
156332  return rc;
156333 }
156334 
156335 /*
156336 ** Merge all level iLevel segments in the database into a single
156337 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
156338 ** single segment with a level equal to the numerically largest level
156339 ** currently present in the database.
156340 **
156341 ** If this function is called with iLevel<0, but there is only one
156342 ** segment in the database, SQLITE_DONE is returned immediately.
156343 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
156344 ** an SQLite error code is returned.
156345 */
156346 static int fts3SegmentMerge(
156347  Fts3Table *p,
156348  int iLangid, /* Language id to merge */
156349  int iIndex, /* Index in p->aIndex[] to merge */
156350  int iLevel /* Level to merge */
156351 ){
156352  int rc; /* Return code */
156353  int iIdx = 0; /* Index of new segment */
156354  sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
156355  SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
156356  Fts3SegFilter filter; /* Segment term filter condition */
156357  Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
156358  int bIgnoreEmpty = 0; /* True to ignore empty segments */
156359  i64 iMaxLevel = 0; /* Max level number for this index/langid */
156360 
156361  assert( iLevel==FTS3_SEGCURSOR_ALL
156362  || iLevel==FTS3_SEGCURSOR_PENDING
156363  || iLevel>=0
156364  );
156365  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
156366  assert( iIndex>=0 && iIndex<p->nIndex );
156367 
156368  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
156369  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
156370 
156371  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
156372  rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
156373  if( rc!=SQLITE_OK ) goto finished;
156374  }
156375 
156376  if( iLevel==FTS3_SEGCURSOR_ALL ){
156377  /* This call is to merge all segments in the database to a single
156378  ** segment. The level of the new segment is equal to the numerically
156379  ** greatest segment level currently present in the database for this
156380  ** index. The idx of the new segment is always 0. */
156381  if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
156382  rc = SQLITE_DONE;
156383  goto finished;
156384  }
156385  iNewLevel = iMaxLevel;
156386  bIgnoreEmpty = 1;
156387 
156388  }else{
156389  /* This call is to merge all segments at level iLevel. find the next
156390  ** available segment index at level iLevel+1. The call to
156391  ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
156392  ** a single iLevel+2 segment if necessary. */
156393  assert( FTS3_SEGCURSOR_PENDING==-1 );
156394  iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
156395  rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
156396  bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
156397  }
156398  if( rc!=SQLITE_OK ) goto finished;
156399 
156400  assert( csr.nSegment>0 );
156401  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
156402  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
156403 
156404  memset(&filter, 0, sizeof(Fts3SegFilter));
156405  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
156406  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
156407 
156408  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
156409  while( SQLITE_OK==rc ){
156410  rc = sqlite3Fts3SegReaderStep(p, &csr);
156411  if( rc!=SQLITE_ROW ) break;
156412  rc = fts3SegWriterAdd(p, &pWriter, 1,
156413  csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
156414  }
156415  if( rc!=SQLITE_OK ) goto finished;
156416  assert( pWriter || bIgnoreEmpty );
156417 
156418  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
156419  rc = fts3DeleteSegdir(
156420  p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
156421  );
156422  if( rc!=SQLITE_OK ) goto finished;
156423  }
156424  if( pWriter ){
156425  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
156426  if( rc==SQLITE_OK ){
156427  if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
156428  rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
156429  }
156430  }
156431  }
156432 
156433  finished:
156434  fts3SegWriterFree(pWriter);
156435  sqlite3Fts3SegReaderFinish(&csr);
156436  return rc;
156437 }
156438 
156439 
156440 /*
156441 ** Flush the contents of pendingTerms to level 0 segments.
156442 */
156443 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
156444  int rc = SQLITE_OK;
156445  int i;
156446 
156447  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
156448  rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
156449  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
156450  }
156451  sqlite3Fts3PendingTermsClear(p);
156452 
156453  /* Determine the auto-incr-merge setting if unknown. If enabled,
156454  ** estimate the number of leaf blocks of content to be written
156455  */
156456  if( rc==SQLITE_OK && p->bHasStat
156457  && p->nAutoincrmerge==0xff && p->nLeafAdd>0
156458  ){
156459  sqlite3_stmt *pStmt = 0;
156460  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
156461  if( rc==SQLITE_OK ){
156462  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
156463  rc = sqlite3_step(pStmt);
156464  if( rc==SQLITE_ROW ){
156465  p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
156466  if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
156467  }else if( rc==SQLITE_DONE ){
156468  p->nAutoincrmerge = 0;
156469  }
156470  rc = sqlite3_reset(pStmt);
156471  }
156472  }
156473  return rc;
156474 }
156475 
156476 /*
156477 ** Encode N integers as varints into a blob.
156478 */
156479 static void fts3EncodeIntArray(
156480  int N, /* The number of integers to encode */
156481  u32 *a, /* The integer values */
156482  char *zBuf, /* Write the BLOB here */
156483  int *pNBuf /* Write number of bytes if zBuf[] used here */
156484 ){
156485  int i, j;
156486  for(i=j=0; i<N; i++){
156487  j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
156488  }
156489  *pNBuf = j;
156490 }
156491 
156492 /*
156493 ** Decode a blob of varints into N integers
156494 */
156495 static void fts3DecodeIntArray(
156496  int N, /* The number of integers to decode */
156497  u32 *a, /* Write the integer values */
156498  const char *zBuf, /* The BLOB containing the varints */
156499  int nBuf /* size of the BLOB */
156500 ){
156501  int i, j;
156502  UNUSED_PARAMETER(nBuf);
156503  for(i=j=0; i<N; i++){
156504  sqlite3_int64 x;
156505  j += sqlite3Fts3GetVarint(&zBuf[j], &x);
156506  assert(j<=nBuf);
156507  a[i] = (u32)(x & 0xffffffff);
156508  }
156509 }
156510 
156511 /*
156512 ** Insert the sizes (in tokens) for each column of the document
156513 ** with docid equal to p->iPrevDocid. The sizes are encoded as
156514 ** a blob of varints.
156515 */
156516 static void fts3InsertDocsize(
156517  int *pRC, /* Result code */
156518  Fts3Table *p, /* Table into which to insert */
156519  u32 *aSz /* Sizes of each column, in tokens */
156520 ){
156521  char *pBlob; /* The BLOB encoding of the document size */
156522  int nBlob; /* Number of bytes in the BLOB */
156523  sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
156524  int rc; /* Result code from subfunctions */
156525 
156526  if( *pRC ) return;
156527  pBlob = sqlite3_malloc( 10*p->nColumn );
156528  if( pBlob==0 ){
156529  *pRC = SQLITE_NOMEM;
156530  return;
156531  }
156532  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
156533  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
156534  if( rc ){
156535  sqlite3_free(pBlob);
156536  *pRC = rc;
156537  return;
156538  }
156539  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
156540  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
156541  sqlite3_step(pStmt);
156542  *pRC = sqlite3_reset(pStmt);
156543 }
156544 
156545 /*
156546 ** Record 0 of the %_stat table contains a blob consisting of N varints,
156547 ** where N is the number of user defined columns in the fts3 table plus
156548 ** two. If nCol is the number of user defined columns, then values of the
156549 ** varints are set as follows:
156550 **
156551 ** Varint 0: Total number of rows in the table.
156552 **
156553 ** Varint 1..nCol: For each column, the total number of tokens stored in
156554 ** the column for all rows of the table.
156555 **
156556 ** Varint 1+nCol: The total size, in bytes, of all text values in all
156557 ** columns of all rows of the table.
156558 **
156559 */
156560 static void fts3UpdateDocTotals(
156561  int *pRC, /* The result code */
156562  Fts3Table *p, /* Table being updated */
156563  u32 *aSzIns, /* Size increases */
156564  u32 *aSzDel, /* Size decreases */
156565  int nChng /* Change in the number of documents */
156566 ){
156567  char *pBlob; /* Storage for BLOB written into %_stat */
156568  int nBlob; /* Size of BLOB written into %_stat */
156569  u32 *a; /* Array of integers that becomes the BLOB */
156570  sqlite3_stmt *pStmt; /* Statement for reading and writing */
156571  int i; /* Loop counter */
156572  int rc; /* Result code from subfunctions */
156573 
156574  const int nStat = p->nColumn+2;
156575 
156576  if( *pRC ) return;
156577  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
156578  if( a==0 ){
156579  *pRC = SQLITE_NOMEM;
156580  return;
156581  }
156582  pBlob = (char*)&a[nStat];
156583  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
156584  if( rc ){
156585  sqlite3_free(a);
156586  *pRC = rc;
156587  return;
156588  }
156589  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
156590  if( sqlite3_step(pStmt)==SQLITE_ROW ){
156591  fts3DecodeIntArray(nStat, a,
156592  sqlite3_column_blob(pStmt, 0),
156593  sqlite3_column_bytes(pStmt, 0));
156594  }else{
156595  memset(a, 0, sizeof(u32)*(nStat) );
156596  }
156597  rc = sqlite3_reset(pStmt);
156598  if( rc!=SQLITE_OK ){
156599  sqlite3_free(a);
156600  *pRC = rc;
156601  return;
156602  }
156603  if( nChng<0 && a[0]<(u32)(-nChng) ){
156604  a[0] = 0;
156605  }else{
156606  a[0] += nChng;
156607  }
156608  for(i=0; i<p->nColumn+1; i++){
156609  u32 x = a[i+1];
156610  if( x+aSzIns[i] < aSzDel[i] ){
156611  x = 0;
156612  }else{
156613  x = x + aSzIns[i] - aSzDel[i];
156614  }
156615  a[i+1] = x;
156616  }
156617  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
156618  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
156619  if( rc ){
156620  sqlite3_free(a);
156621  *pRC = rc;
156622  return;
156623  }
156624  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
156625  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
156626  sqlite3_step(pStmt);
156627  *pRC = sqlite3_reset(pStmt);
156628  sqlite3_free(a);
156629 }
156630 
156631 /*
156632 ** Merge the entire database so that there is one segment for each
156633 ** iIndex/iLangid combination.
156634 */
156635 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
156636  int bSeenDone = 0;
156637  int rc;
156638  sqlite3_stmt *pAllLangid = 0;
156639 
156640  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
156641  if( rc==SQLITE_OK ){
156642  int rc2;
156643  sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
156644  sqlite3_bind_int(pAllLangid, 2, p->nIndex);
156645  while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
156646  int i;
156647  int iLangid = sqlite3_column_int(pAllLangid, 0);
156648  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
156649  rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
156650  if( rc==SQLITE_DONE ){
156651  bSeenDone = 1;
156652  rc = SQLITE_OK;
156653  }
156654  }
156655  }
156656  rc2 = sqlite3_reset(pAllLangid);
156657  if( rc==SQLITE_OK ) rc = rc2;
156658  }
156659 
156660  sqlite3Fts3SegmentsClose(p);
156661  sqlite3Fts3PendingTermsClear(p);
156662 
156663  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
156664 }
156665 
156666 /*
156667 ** This function is called when the user executes the following statement:
156668 **
156669 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
156670 **
156671 ** The entire FTS index is discarded and rebuilt. If the table is one
156672 ** created using the content=xxx option, then the new index is based on
156673 ** the current contents of the xxx table. Otherwise, it is rebuilt based
156674 ** on the contents of the %_content table.
156675 */
156676 static int fts3DoRebuild(Fts3Table *p){
156677  int rc; /* Return Code */
156678 
156679  rc = fts3DeleteAll(p, 0);
156680  if( rc==SQLITE_OK ){
156681  u32 *aSz = 0;
156682  u32 *aSzIns = 0;
156683  u32 *aSzDel = 0;
156684  sqlite3_stmt *pStmt = 0;
156685  int nEntry = 0;
156686 
156687  /* Compose and prepare an SQL statement to loop through the content table */
156688  char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
156689  if( !zSql ){
156690  rc = SQLITE_NOMEM;
156691  }else{
156692  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
156693  sqlite3_free(zSql);
156694  }
156695 
156696  if( rc==SQLITE_OK ){
156697  int nByte = sizeof(u32) * (p->nColumn+1)*3;
156698  aSz = (u32 *)sqlite3_malloc(nByte);
156699  if( aSz==0 ){
156700  rc = SQLITE_NOMEM;
156701  }else{
156702  memset(aSz, 0, nByte);
156703  aSzIns = &aSz[p->nColumn+1];
156704  aSzDel = &aSzIns[p->nColumn+1];
156705  }
156706  }
156707 
156708  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
156709  int iCol;
156710  int iLangid = langidFromSelect(p, pStmt);
156711  rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
156712  memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
156713  for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
156714  if( p->abNotindexed[iCol]==0 ){
156715  const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
156716  rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
156717  aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
156718  }
156719  }
156720  if( p->bHasDocsize ){
156721  fts3InsertDocsize(&rc, p, aSz);
156722  }
156723  if( rc!=SQLITE_OK ){
156724  sqlite3_finalize(pStmt);
156725  pStmt = 0;
156726  }else{
156727  nEntry++;
156728  for(iCol=0; iCol<=p->nColumn; iCol++){
156729  aSzIns[iCol] += aSz[iCol];
156730  }
156731  }
156732  }
156733  if( p->bFts4 ){
156734  fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
156735  }
156736  sqlite3_free(aSz);
156737 
156738  if( pStmt ){
156739  int rc2 = sqlite3_finalize(pStmt);
156740  if( rc==SQLITE_OK ){
156741  rc = rc2;
156742  }
156743  }
156744  }
156745 
156746  return rc;
156747 }
156748 
156749 
156750 /*
156751 ** This function opens a cursor used to read the input data for an
156752 ** incremental merge operation. Specifically, it opens a cursor to scan
156753 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
156754 ** level iAbsLevel.
156755 */
156756 static int fts3IncrmergeCsr(
156757  Fts3Table *p, /* FTS3 table handle */
156758  sqlite3_int64 iAbsLevel, /* Absolute level to open */
156759  int nSeg, /* Number of segments to merge */
156760  Fts3MultiSegReader *pCsr /* Cursor object to populate */
156761 ){
156762  int rc; /* Return Code */
156763  sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
156764  int nByte; /* Bytes allocated at pCsr->apSegment[] */
156765 
156766  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
156767  memset(pCsr, 0, sizeof(*pCsr));
156768  nByte = sizeof(Fts3SegReader *) * nSeg;
156769  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
156770 
156771  if( pCsr->apSegment==0 ){
156772  rc = SQLITE_NOMEM;
156773  }else{
156774  memset(pCsr->apSegment, 0, nByte);
156775  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
156776  }
156777  if( rc==SQLITE_OK ){
156778  int i;
156779  int rc2;
156780  sqlite3_bind_int64(pStmt, 1, iAbsLevel);
156781  assert( pCsr->nSegment==0 );
156782  for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
156783  rc = sqlite3Fts3SegReaderNew(i, 0,
156784  sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
156785  sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
156786  sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
156787  sqlite3_column_blob(pStmt, 4), /* segdir.root */
156788  sqlite3_column_bytes(pStmt, 4), /* segdir.root */
156789  &pCsr->apSegment[i]
156790  );
156791  pCsr->nSegment++;
156792  }
156793  rc2 = sqlite3_reset(pStmt);
156794  if( rc==SQLITE_OK ) rc = rc2;
156795  }
156796 
156797  return rc;
156798 }
156799 
156800 typedef struct IncrmergeWriter IncrmergeWriter;
156801 typedef struct NodeWriter NodeWriter;
156802 typedef struct Blob Blob;
156803 typedef struct NodeReader NodeReader;
156804 
156805 /*
156806 ** An instance of the following structure is used as a dynamic buffer
156807 ** to build up nodes or other blobs of data in.
156808 **
156809 ** The function blobGrowBuffer() is used to extend the allocation.
156810 */
156811 struct Blob {
156812  char *a; /* Pointer to allocation */
156813  int n; /* Number of valid bytes of data in a[] */
156814  int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
156815 };
156816 
156817 /*
156818 ** This structure is used to build up buffers containing segment b-tree
156819 ** nodes (blocks).
156820 */
156821 struct NodeWriter {
156822  sqlite3_int64 iBlock; /* Current block id */
156823  Blob key; /* Last key written to the current block */
156824  Blob block; /* Current block image */
156825 };
156826 
156827 /*
156828 ** An object of this type contains the state required to create or append
156829 ** to an appendable b-tree segment.
156830 */
156831 struct IncrmergeWriter {
156832  int nLeafEst; /* Space allocated for leaf blocks */
156833  int nWork; /* Number of leaf pages flushed */
156834  sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
156835  int iIdx; /* Index of *output* segment in iAbsLevel+1 */
156836  sqlite3_int64 iStart; /* Block number of first allocated block */
156837  sqlite3_int64 iEnd; /* Block number of last allocated block */
156838  sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
156839  u8 bNoLeafData; /* If true, store 0 for segment size */
156840  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
156841 };
156842 
156843 /*
156844 ** An object of the following type is used to read data from a single
156845 ** FTS segment node. See the following functions:
156846 **
156847 ** nodeReaderInit()
156848 ** nodeReaderNext()
156849 ** nodeReaderRelease()
156850 */
156851 struct NodeReader {
156852  const char *aNode;
156853  int nNode;
156854  int iOff; /* Current offset within aNode[] */
156855 
156856  /* Output variables. Containing the current node entry. */
156857  sqlite3_int64 iChild; /* Pointer to child node */
156858  Blob term; /* Current term */
156859  const char *aDoclist; /* Pointer to doclist */
156860  int nDoclist; /* Size of doclist in bytes */
156861 };
156862 
156863 /*
156864 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
156865 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
156866 ** bytes in size, extend (realloc) it to be so.
156867 **
156868 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
156869 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
156870 ** to reflect the new size of the pBlob->a[] buffer.
156871 */
156872 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
156873  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
156874  int nAlloc = nMin;
156875  char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
156876  if( a ){
156877  pBlob->nAlloc = nAlloc;
156878  pBlob->a = a;
156879  }else{
156880  *pRc = SQLITE_NOMEM;
156881  }
156882  }
156883 }
156884 
156885 /*
156886 ** Attempt to advance the node-reader object passed as the first argument to
156887 ** the next entry on the node.
156888 **
156889 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
156890 ** Otherwise return SQLITE_OK. If there is no next entry on the node
156891 ** (e.g. because the current entry is the last) set NodeReader->aNode to
156892 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
156893 ** variables for the new entry.
156894 */
156895 static int nodeReaderNext(NodeReader *p){
156896  int bFirst = (p->term.n==0); /* True for first term on the node */
156897  int nPrefix = 0; /* Bytes to copy from previous term */
156898  int nSuffix = 0; /* Bytes to append to the prefix */
156899  int rc = SQLITE_OK; /* Return code */
156900 
156901  assert( p->aNode );
156902  if( p->iChild && bFirst==0 ) p->iChild++;
156903  if( p->iOff>=p->nNode ){
156904  /* EOF */
156905  p->aNode = 0;
156906  }else{
156907  if( bFirst==0 ){
156908  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
156909  }
156910  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
156911 
156912  blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
156913  if( rc==SQLITE_OK ){
156914  memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
156915  p->term.n = nPrefix+nSuffix;
156916  p->iOff += nSuffix;
156917  if( p->iChild==0 ){
156918  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
156919  p->aDoclist = &p->aNode[p->iOff];
156920  p->iOff += p->nDoclist;
156921  }
156922  }
156923  }
156924 
156925  assert( p->iOff<=p->nNode );
156926 
156927  return rc;
156928 }
156929 
156930 /*
156931 ** Release all dynamic resources held by node-reader object *p.
156932 */
156933 static void nodeReaderRelease(NodeReader *p){
156934  sqlite3_free(p->term.a);
156935 }
156936 
156937 /*
156938 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
156939 **
156940 ** If successful, SQLITE_OK is returned and the NodeReader object set to
156941 ** point to the first entry on the node (if any). Otherwise, an SQLite
156942 ** error code is returned.
156943 */
156944 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
156945  memset(p, 0, sizeof(NodeReader));
156946  p->aNode = aNode;
156947  p->nNode = nNode;
156948 
156949  /* Figure out if this is a leaf or an internal node. */
156950  if( p->aNode[0] ){
156951  /* An internal node. */
156952  p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
156953  }else{
156954  p->iOff = 1;
156955  }
156956 
156957  return nodeReaderNext(p);
156958 }
156959 
156960 /*
156961 ** This function is called while writing an FTS segment each time a leaf o
156962 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
156963 ** to be greater than the largest key on the node just written, but smaller
156964 ** than or equal to the first key that will be written to the next leaf
156965 ** node.
156966 **
156967 ** The block id of the leaf node just written to disk may be found in
156968 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
156969 */
156970 static int fts3IncrmergePush(
156971  Fts3Table *p, /* Fts3 table handle */
156972  IncrmergeWriter *pWriter, /* Writer object */
156973  const char *zTerm, /* Term to write to internal node */
156974  int nTerm /* Bytes at zTerm */
156975 ){
156976  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
156977  int iLayer;
156978 
156979  assert( nTerm>0 );
156980  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
156981  sqlite3_int64 iNextPtr = 0;
156982  NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
156983  int rc = SQLITE_OK;
156984  int nPrefix;
156985  int nSuffix;
156986  int nSpace;
156987 
156988  /* Figure out how much space the key will consume if it is written to
156989  ** the current node of layer iLayer. Due to the prefix compression,
156990  ** the space required changes depending on which node the key is to
156991  ** be added to. */
156992  nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
156993  nSuffix = nTerm - nPrefix;
156994  nSpace = sqlite3Fts3VarintLen(nPrefix);
156995  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
156996 
156997  if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
156998  /* If the current node of layer iLayer contains zero keys, or if adding
156999  ** the key to it will not cause it to grow to larger than nNodeSize
157000  ** bytes in size, write the key here. */
157001 
157002  Blob *pBlk = &pNode->block;
157003  if( pBlk->n==0 ){
157004  blobGrowBuffer(pBlk, p->nNodeSize, &rc);
157005  if( rc==SQLITE_OK ){
157006  pBlk->a[0] = (char)iLayer;
157007  pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
157008  }
157009  }
157010  blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
157011  blobGrowBuffer(&pNode->key, nTerm, &rc);
157012 
157013  if( rc==SQLITE_OK ){
157014  if( pNode->key.n ){
157015  pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
157016  }
157017  pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
157018  memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
157019  pBlk->n += nSuffix;
157020 
157021  memcpy(pNode->key.a, zTerm, nTerm);
157022  pNode->key.n = nTerm;
157023  }
157024  }else{
157025  /* Otherwise, flush the current node of layer iLayer to disk.
157026  ** Then allocate a new, empty sibling node. The key will be written
157027  ** into the parent of this node. */
157028  rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
157029 
157030  assert( pNode->block.nAlloc>=p->nNodeSize );
157031  pNode->block.a[0] = (char)iLayer;
157032  pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
157033 
157034  iNextPtr = pNode->iBlock;
157035  pNode->iBlock++;
157036  pNode->key.n = 0;
157037  }
157038 
157039  if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
157040  iPtr = iNextPtr;
157041  }
157042 
157043  assert( 0 );
157044  return 0;
157045 }
157046 
157047 /*
157048 ** Append a term and (optionally) doclist to the FTS segment node currently
157049 ** stored in blob *pNode. The node need not contain any terms, but the
157050 ** header must be written before this function is called.
157051 **
157052 ** A node header is a single 0x00 byte for a leaf node, or a height varint
157053 ** followed by the left-hand-child varint for an internal node.
157054 **
157055 ** The term to be appended is passed via arguments zTerm/nTerm. For a
157056 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
157057 ** node, both aDoclist and nDoclist must be passed 0.
157058 **
157059 ** If the size of the value in blob pPrev is zero, then this is the first
157060 ** term written to the node. Otherwise, pPrev contains a copy of the
157061 ** previous term. Before this function returns, it is updated to contain a
157062 ** copy of zTerm/nTerm.
157063 **
157064 ** It is assumed that the buffer associated with pNode is already large
157065 ** enough to accommodate the new entry. The buffer associated with pPrev
157066 ** is extended by this function if requrired.
157067 **
157068 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
157069 ** returned. Otherwise, SQLITE_OK.
157070 */
157071 static int fts3AppendToNode(
157072  Blob *pNode, /* Current node image to append to */
157073  Blob *pPrev, /* Buffer containing previous term written */
157074  const char *zTerm, /* New term to write */
157075  int nTerm, /* Size of zTerm in bytes */
157076  const char *aDoclist, /* Doclist (or NULL) to write */
157077  int nDoclist /* Size of aDoclist in bytes */
157078 ){
157079  int rc = SQLITE_OK; /* Return code */
157080  int bFirst = (pPrev->n==0); /* True if this is the first term written */
157081  int nPrefix; /* Size of term prefix in bytes */
157082  int nSuffix; /* Size of term suffix in bytes */
157083 
157084  /* Node must have already been started. There must be a doclist for a
157085  ** leaf node, and there must not be a doclist for an internal node. */
157086  assert( pNode->n>0 );
157087  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
157088 
157089  blobGrowBuffer(pPrev, nTerm, &rc);
157090  if( rc!=SQLITE_OK ) return rc;
157091 
157092  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
157093  nSuffix = nTerm - nPrefix;
157094  memcpy(pPrev->a, zTerm, nTerm);
157095  pPrev->n = nTerm;
157096 
157097  if( bFirst==0 ){
157098  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
157099  }
157100  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
157101  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
157102  pNode->n += nSuffix;
157103 
157104  if( aDoclist ){
157105  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
157106  memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
157107  pNode->n += nDoclist;
157108  }
157109 
157110  assert( pNode->n<=pNode->nAlloc );
157111 
157112  return SQLITE_OK;
157113 }
157114 
157115 /*
157116 ** Append the current term and doclist pointed to by cursor pCsr to the
157117 ** appendable b-tree segment opened for writing by pWriter.
157118 **
157119 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
157120 */
157121 static int fts3IncrmergeAppend(
157122  Fts3Table *p, /* Fts3 table handle */
157123  IncrmergeWriter *pWriter, /* Writer object */
157124  Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
157125 ){
157126  const char *zTerm = pCsr->zTerm;
157127  int nTerm = pCsr->nTerm;
157128  const char *aDoclist = pCsr->aDoclist;
157129  int nDoclist = pCsr->nDoclist;
157130  int rc = SQLITE_OK; /* Return code */
157131  int nSpace; /* Total space in bytes required on leaf */
157132  int nPrefix; /* Size of prefix shared with previous term */
157133  int nSuffix; /* Size of suffix (nTerm - nPrefix) */
157134  NodeWriter *pLeaf; /* Object used to write leaf nodes */
157135 
157136  pLeaf = &pWriter->aNodeWriter[0];
157137  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
157138  nSuffix = nTerm - nPrefix;
157139 
157140  nSpace = sqlite3Fts3VarintLen(nPrefix);
157141  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
157142  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
157143 
157144  /* If the current block is not empty, and if adding this term/doclist
157145  ** to the current block would make it larger than Fts3Table.nNodeSize
157146  ** bytes, write this block out to the database. */
157147  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
157148  rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
157149  pWriter->nWork++;
157150 
157151  /* Add the current term to the parent node. The term added to the
157152  ** parent must:
157153  **
157154  ** a) be greater than the largest term on the leaf node just written
157155  ** to the database (still available in pLeaf->key), and
157156  **
157157  ** b) be less than or equal to the term about to be added to the new
157158  ** leaf node (zTerm/nTerm).
157159  **
157160  ** In other words, it must be the prefix of zTerm 1 byte longer than
157161  ** the common prefix (if any) of zTerm and pWriter->zTerm.
157162  */
157163  if( rc==SQLITE_OK ){
157164  rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
157165  }
157166 
157167  /* Advance to the next output block */
157168  pLeaf->iBlock++;
157169  pLeaf->key.n = 0;
157170  pLeaf->block.n = 0;
157171 
157172  nSuffix = nTerm;
157173  nSpace = 1;
157174  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
157175  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
157176  }
157177 
157178  pWriter->nLeafData += nSpace;
157179  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
157180  if( rc==SQLITE_OK ){
157181  if( pLeaf->block.n==0 ){
157182  pLeaf->block.n = 1;
157183  pLeaf->block.a[0] = '\0';
157184  }
157185  rc = fts3AppendToNode(
157186  &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
157187  );
157188  }
157189 
157190  return rc;
157191 }
157192 
157193 /*
157194 ** This function is called to release all dynamic resources held by the
157195 ** merge-writer object pWriter, and if no error has occurred, to flush
157196 ** all outstanding node buffers held by pWriter to disk.
157197 **
157198 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
157199 ** is made to write any data to disk. Instead, this function serves only
157200 ** to release outstanding resources.
157201 **
157202 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
157203 ** flushing buffers to disk, *pRc is set to an SQLite error code before
157204 ** returning.
157205 */
157206 static void fts3IncrmergeRelease(
157207  Fts3Table *p, /* FTS3 table handle */
157208  IncrmergeWriter *pWriter, /* Merge-writer object */
157209  int *pRc /* IN/OUT: Error code */
157210 ){
157211  int i; /* Used to iterate through non-root layers */
157212  int iRoot; /* Index of root in pWriter->aNodeWriter */
157213  NodeWriter *pRoot; /* NodeWriter for root node */
157214  int rc = *pRc; /* Error code */
157215 
157216  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
157217  ** root node. If the segment fits entirely on a single leaf node, iRoot
157218  ** will be set to 0. If the root node is the parent of the leaves, iRoot
157219  ** will be 1. And so on. */
157220  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
157221  NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
157222  if( pNode->block.n>0 ) break;
157223  assert( *pRc || pNode->block.nAlloc==0 );
157224  assert( *pRc || pNode->key.nAlloc==0 );
157225  sqlite3_free(pNode->block.a);
157226  sqlite3_free(pNode->key.a);
157227  }
157228 
157229  /* Empty output segment. This is a no-op. */
157230  if( iRoot<0 ) return;
157231 
157232  /* The entire output segment fits on a single node. Normally, this means
157233  ** the node would be stored as a blob in the "root" column of the %_segdir
157234  ** table. However, this is not permitted in this case. The problem is that
157235  ** space has already been reserved in the %_segments table, and so the
157236  ** start_block and end_block fields of the %_segdir table must be populated.
157237  ** And, by design or by accident, released versions of FTS cannot handle
157238  ** segments that fit entirely on the root node with start_block!=0.
157239  **
157240  ** Instead, create a synthetic root node that contains nothing but a
157241  ** pointer to the single content node. So that the segment consists of a
157242  ** single leaf and a single interior (root) node.
157243  **
157244  ** Todo: Better might be to defer allocating space in the %_segments
157245  ** table until we are sure it is needed.
157246  */
157247  if( iRoot==0 ){
157248  Blob *pBlock = &pWriter->aNodeWriter[1].block;
157249  blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
157250  if( rc==SQLITE_OK ){
157251  pBlock->a[0] = 0x01;
157252  pBlock->n = 1 + sqlite3Fts3PutVarint(
157253  &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
157254  );
157255  }
157256  iRoot = 1;
157257  }
157258  pRoot = &pWriter->aNodeWriter[iRoot];
157259 
157260  /* Flush all currently outstanding nodes to disk. */
157261  for(i=0; i<iRoot; i++){
157262  NodeWriter *pNode = &pWriter->aNodeWriter[i];
157263  if( pNode->block.n>0 && rc==SQLITE_OK ){
157264  rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
157265  }
157266  sqlite3_free(pNode->block.a);
157267  sqlite3_free(pNode->key.a);
157268  }
157269 
157270  /* Write the %_segdir record. */
157271  if( rc==SQLITE_OK ){
157272  rc = fts3WriteSegdir(p,
157273  pWriter->iAbsLevel+1, /* level */
157274  pWriter->iIdx, /* idx */
157275  pWriter->iStart, /* start_block */
157276  pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
157277  pWriter->iEnd, /* end_block */
157278  (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
157279  pRoot->block.a, pRoot->block.n /* root */
157280  );
157281  }
157282  sqlite3_free(pRoot->block.a);
157283  sqlite3_free(pRoot->key.a);
157284 
157285  *pRc = rc;
157286 }
157287 
157288 /*
157289 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
157290 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
157291 ** the other, it is considered to be smaller than the other.
157292 **
157293 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
157294 ** if it is greater.
157295 */
157296 static int fts3TermCmp(
157297  const char *zLhs, int nLhs, /* LHS of comparison */
157298  const char *zRhs, int nRhs /* RHS of comparison */
157299 ){
157300  int nCmp = MIN(nLhs, nRhs);
157301  int res;
157302 
157303  res = memcmp(zLhs, zRhs, nCmp);
157304  if( res==0 ) res = nLhs - nRhs;
157305 
157306  return res;
157307 }
157308 
157309 
157310 /*
157311 ** Query to see if the entry in the %_segments table with blockid iEnd is
157312 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
157313 ** returning. Otherwise, set *pbRes to 0.
157314 **
157315 ** Or, if an error occurs while querying the database, return an SQLite
157316 ** error code. The final value of *pbRes is undefined in this case.
157317 **
157318 ** This is used to test if a segment is an "appendable" segment. If it
157319 ** is, then a NULL entry has been inserted into the %_segments table
157320 ** with blockid %_segdir.end_block.
157321 */
157322 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
157323  int bRes = 0; /* Result to set *pbRes to */
157324  sqlite3_stmt *pCheck = 0; /* Statement to query database with */
157325  int rc; /* Return code */
157326 
157327  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
157328  if( rc==SQLITE_OK ){
157329  sqlite3_bind_int64(pCheck, 1, iEnd);
157330  if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
157331  rc = sqlite3_reset(pCheck);
157332  }
157333 
157334  *pbRes = bRes;
157335  return rc;
157336 }
157337 
157338 /*
157339 ** This function is called when initializing an incremental-merge operation.
157340 ** It checks if the existing segment with index value iIdx at absolute level
157341 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
157342 ** merge-writer object *pWriter is initialized to write to it.
157343 **
157344 ** An existing segment can be appended to by an incremental merge if:
157345 **
157346 ** * It was initially created as an appendable segment (with all required
157347 ** space pre-allocated), and
157348 **
157349 ** * The first key read from the input (arguments zKey and nKey) is
157350 ** greater than the largest key currently stored in the potential
157351 ** output segment.
157352 */
157353 static int fts3IncrmergeLoad(
157354  Fts3Table *p, /* Fts3 table handle */
157355  sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
157356  int iIdx, /* Index of candidate output segment */
157357  const char *zKey, /* First key to write */
157358  int nKey, /* Number of bytes in nKey */
157359  IncrmergeWriter *pWriter /* Populate this object */
157360 ){
157361  int rc; /* Return code */
157362  sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
157363 
157364  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
157365  if( rc==SQLITE_OK ){
157366  sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
157367  sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
157368  sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
157369  const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
157370  int nRoot = 0; /* Size of aRoot[] in bytes */
157371  int rc2; /* Return code from sqlite3_reset() */
157372  int bAppendable = 0; /* Set to true if segment is appendable */
157373 
157374  /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
157375  sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
157376  sqlite3_bind_int(pSelect, 2, iIdx);
157377  if( sqlite3_step(pSelect)==SQLITE_ROW ){
157378  iStart = sqlite3_column_int64(pSelect, 1);
157379  iLeafEnd = sqlite3_column_int64(pSelect, 2);
157380  fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
157381  if( pWriter->nLeafData<0 ){
157382  pWriter->nLeafData = pWriter->nLeafData * -1;
157383  }
157384  pWriter->bNoLeafData = (pWriter->nLeafData==0);
157385  nRoot = sqlite3_column_bytes(pSelect, 4);
157386  aRoot = sqlite3_column_blob(pSelect, 4);
157387  }else{
157388  return sqlite3_reset(pSelect);
157389  }
157390 
157391  /* Check for the zero-length marker in the %_segments table */
157392  rc = fts3IsAppendable(p, iEnd, &bAppendable);
157393 
157394  /* Check that zKey/nKey is larger than the largest key the candidate */
157395  if( rc==SQLITE_OK && bAppendable ){
157396  char *aLeaf = 0;
157397  int nLeaf = 0;
157398 
157399  rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
157400  if( rc==SQLITE_OK ){
157401  NodeReader reader;
157402  for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
157403  rc==SQLITE_OK && reader.aNode;
157404  rc = nodeReaderNext(&reader)
157405  ){
157406  assert( reader.aNode );
157407  }
157408  if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
157409  bAppendable = 0;
157410  }
157411  nodeReaderRelease(&reader);
157412  }
157413  sqlite3_free(aLeaf);
157414  }
157415 
157416  if( rc==SQLITE_OK && bAppendable ){
157417  /* It is possible to append to this segment. Set up the IncrmergeWriter
157418  ** object to do so. */
157419  int i;
157420  int nHeight = (int)aRoot[0];
157421  NodeWriter *pNode;
157422 
157423  pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
157424  pWriter->iStart = iStart;
157425  pWriter->iEnd = iEnd;
157426  pWriter->iAbsLevel = iAbsLevel;
157427  pWriter->iIdx = iIdx;
157428 
157429  for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
157430  pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
157431  }
157432 
157433  pNode = &pWriter->aNodeWriter[nHeight];
157434  pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
157435  blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
157436  if( rc==SQLITE_OK ){
157437  memcpy(pNode->block.a, aRoot, nRoot);
157438  pNode->block.n = nRoot;
157439  }
157440 
157441  for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
157442  NodeReader reader;
157443  pNode = &pWriter->aNodeWriter[i];
157444 
157445  rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
157446  while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
157447  blobGrowBuffer(&pNode->key, reader.term.n, &rc);
157448  if( rc==SQLITE_OK ){
157449  memcpy(pNode->key.a, reader.term.a, reader.term.n);
157450  pNode->key.n = reader.term.n;
157451  if( i>0 ){
157452  char *aBlock = 0;
157453  int nBlock = 0;
157454  pNode = &pWriter->aNodeWriter[i-1];
157455  pNode->iBlock = reader.iChild;
157456  rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
157457  blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
157458  if( rc==SQLITE_OK ){
157459  memcpy(pNode->block.a, aBlock, nBlock);
157460  pNode->block.n = nBlock;
157461  }
157462  sqlite3_free(aBlock);
157463  }
157464  }
157465  nodeReaderRelease(&reader);
157466  }
157467  }
157468 
157469  rc2 = sqlite3_reset(pSelect);
157470  if( rc==SQLITE_OK ) rc = rc2;
157471  }
157472 
157473  return rc;
157474 }
157475 
157476 /*
157477 ** Determine the largest segment index value that exists within absolute
157478 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
157479 ** one before returning SQLITE_OK. Or, if there are no segments at all
157480 ** within level iAbsLevel, set *piIdx to zero.
157481 **
157482 ** If an error occurs, return an SQLite error code. The final value of
157483 ** *piIdx is undefined in this case.
157484 */
157485 static int fts3IncrmergeOutputIdx(
157486  Fts3Table *p, /* FTS Table handle */
157487  sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
157488  int *piIdx /* OUT: Next free index at iAbsLevel+1 */
157489 ){
157490  int rc;
157491  sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
157492 
157493  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
157494  if( rc==SQLITE_OK ){
157495  sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
157496  sqlite3_step(pOutputIdx);
157497  *piIdx = sqlite3_column_int(pOutputIdx, 0);
157498  rc = sqlite3_reset(pOutputIdx);
157499  }
157500 
157501  return rc;
157502 }
157503 
157504 /*
157505 ** Allocate an appendable output segment on absolute level iAbsLevel+1
157506 ** with idx value iIdx.
157507 **
157508 ** In the %_segdir table, a segment is defined by the values in three
157509 ** columns:
157510 **
157511 ** start_block
157512 ** leaves_end_block
157513 ** end_block
157514 **
157515 ** When an appendable segment is allocated, it is estimated that the
157516 ** maximum number of leaf blocks that may be required is the sum of the
157517 ** number of leaf blocks consumed by the input segments, plus the number
157518 ** of input segments, multiplied by two. This value is stored in stack
157519 ** variable nLeafEst.
157520 **
157521 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
157522 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
157523 ** array of leaf nodes starts at the first block allocated. The array
157524 ** of interior nodes that are parents of the leaf nodes start at block
157525 ** (start_block + (1 + end_block - start_block) / 16). And so on.
157526 **
157527 ** In the actual code below, the value "16" is replaced with the
157528 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
157529 */
157530 static int fts3IncrmergeWriter(
157531  Fts3Table *p, /* Fts3 table handle */
157532  sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
157533  int iIdx, /* Index of new output segment */
157534  Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
157535  IncrmergeWriter *pWriter /* Populate this object */
157536 ){
157537  int rc; /* Return Code */
157538  int i; /* Iterator variable */
157539  int nLeafEst = 0; /* Blocks allocated for leaf nodes */
157540  sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
157541  sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
157542 
157543  /* Calculate nLeafEst. */
157544  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
157545  if( rc==SQLITE_OK ){
157546  sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
157547  sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
157548  if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
157549  nLeafEst = sqlite3_column_int(pLeafEst, 0);
157550  }
157551  rc = sqlite3_reset(pLeafEst);
157552  }
157553  if( rc!=SQLITE_OK ) return rc;
157554 
157555  /* Calculate the first block to use in the output segment */
157556  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
157557  if( rc==SQLITE_OK ){
157558  if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
157559  pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
157560  pWriter->iEnd = pWriter->iStart - 1;
157561  pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
157562  }
157563  rc = sqlite3_reset(pFirstBlock);
157564  }
157565  if( rc!=SQLITE_OK ) return rc;
157566 
157567  /* Insert the marker in the %_segments table to make sure nobody tries
157568  ** to steal the space just allocated. This is also used to identify
157569  ** appendable segments. */
157570  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
157571  if( rc!=SQLITE_OK ) return rc;
157572 
157573  pWriter->iAbsLevel = iAbsLevel;
157574  pWriter->nLeafEst = nLeafEst;
157575  pWriter->iIdx = iIdx;
157576 
157577  /* Set up the array of NodeWriter objects */
157578  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
157579  pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
157580  }
157581  return SQLITE_OK;
157582 }
157583 
157584 /*
157585 ** Remove an entry from the %_segdir table. This involves running the
157586 ** following two statements:
157587 **
157588 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
157589 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
157590 **
157591 ** The DELETE statement removes the specific %_segdir level. The UPDATE
157592 ** statement ensures that the remaining segments have contiguously allocated
157593 ** idx values.
157594 */
157595 static int fts3RemoveSegdirEntry(
157596  Fts3Table *p, /* FTS3 table handle */
157597  sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
157598  int iIdx /* Index of %_segdir entry to delete */
157599 ){
157600  int rc; /* Return code */
157601  sqlite3_stmt *pDelete = 0; /* DELETE statement */
157602 
157603  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
157604  if( rc==SQLITE_OK ){
157605  sqlite3_bind_int64(pDelete, 1, iAbsLevel);
157606  sqlite3_bind_int(pDelete, 2, iIdx);
157607  sqlite3_step(pDelete);
157608  rc = sqlite3_reset(pDelete);
157609  }
157610 
157611  return rc;
157612 }
157613 
157614 /*
157615 ** One or more segments have just been removed from absolute level iAbsLevel.
157616 ** Update the 'idx' values of the remaining segments in the level so that
157617 ** the idx values are a contiguous sequence starting from 0.
157618 */
157619 static int fts3RepackSegdirLevel(
157620  Fts3Table *p, /* FTS3 table handle */
157621  sqlite3_int64 iAbsLevel /* Absolute level to repack */
157622 ){
157623  int rc; /* Return code */
157624  int *aIdx = 0; /* Array of remaining idx values */
157625  int nIdx = 0; /* Valid entries in aIdx[] */
157626  int nAlloc = 0; /* Allocated size of aIdx[] */
157627  int i; /* Iterator variable */
157628  sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
157629  sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
157630 
157631  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
157632  if( rc==SQLITE_OK ){
157633  int rc2;
157634  sqlite3_bind_int64(pSelect, 1, iAbsLevel);
157635  while( SQLITE_ROW==sqlite3_step(pSelect) ){
157636  if( nIdx>=nAlloc ){
157637  int *aNew;
157638  nAlloc += 16;
157639  aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
157640  if( !aNew ){
157641  rc = SQLITE_NOMEM;
157642  break;
157643  }
157644  aIdx = aNew;
157645  }
157646  aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
157647  }
157648  rc2 = sqlite3_reset(pSelect);
157649  if( rc==SQLITE_OK ) rc = rc2;
157650  }
157651 
157652  if( rc==SQLITE_OK ){
157653  rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
157654  }
157655  if( rc==SQLITE_OK ){
157656  sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
157657  }
157658 
157659  assert( p->bIgnoreSavepoint==0 );
157660  p->bIgnoreSavepoint = 1;
157661  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
157662  if( aIdx[i]!=i ){
157663  sqlite3_bind_int(pUpdate, 3, aIdx[i]);
157664  sqlite3_bind_int(pUpdate, 1, i);
157665  sqlite3_step(pUpdate);
157666  rc = sqlite3_reset(pUpdate);
157667  }
157668  }
157669  p->bIgnoreSavepoint = 0;
157670 
157671  sqlite3_free(aIdx);
157672  return rc;
157673 }
157674 
157675 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
157676  pNode->a[0] = (char)iHeight;
157677  if( iChild ){
157678  assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
157679  pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
157680  }else{
157681  assert( pNode->nAlloc>=1 );
157682  pNode->n = 1;
157683  }
157684 }
157685 
157686 /*
157687 ** The first two arguments are a pointer to and the size of a segment b-tree
157688 ** node. The node may be a leaf or an internal node.
157689 **
157690 ** This function creates a new node image in blob object *pNew by copying
157691 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
157692 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
157693 */
157694 static int fts3TruncateNode(
157695  const char *aNode, /* Current node image */
157696  int nNode, /* Size of aNode in bytes */
157697  Blob *pNew, /* OUT: Write new node image here */
157698  const char *zTerm, /* Omit all terms smaller than this */
157699  int nTerm, /* Size of zTerm in bytes */
157700  sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
157701 ){
157702  NodeReader reader; /* Reader object */
157703  Blob prev = {0, 0, 0}; /* Previous term written to new node */
157704  int rc = SQLITE_OK; /* Return code */
157705  int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
157706 
157707  /* Allocate required output space */
157708  blobGrowBuffer(pNew, nNode, &rc);
157709  if( rc!=SQLITE_OK ) return rc;
157710  pNew->n = 0;
157711 
157712  /* Populate new node buffer */
157713  for(rc = nodeReaderInit(&reader, aNode, nNode);
157714  rc==SQLITE_OK && reader.aNode;
157715  rc = nodeReaderNext(&reader)
157716  ){
157717  if( pNew->n==0 ){
157718  int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
157719  if( res<0 || (bLeaf==0 && res==0) ) continue;
157720  fts3StartNode(pNew, (int)aNode[0], reader.iChild);
157721  *piBlock = reader.iChild;
157722  }
157723  rc = fts3AppendToNode(
157724  pNew, &prev, reader.term.a, reader.term.n,
157725  reader.aDoclist, reader.nDoclist
157726  );
157727  if( rc!=SQLITE_OK ) break;
157728  }
157729  if( pNew->n==0 ){
157730  fts3StartNode(pNew, (int)aNode[0], reader.iChild);
157731  *piBlock = reader.iChild;
157732  }
157733  assert( pNew->n<=pNew->nAlloc );
157734 
157735  nodeReaderRelease(&reader);
157736  sqlite3_free(prev.a);
157737  return rc;
157738 }
157739 
157740 /*
157741 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
157742 ** level iAbsLevel. This may involve deleting entries from the %_segments
157743 ** table, and modifying existing entries in both the %_segments and %_segdir
157744 ** tables.
157745 **
157746 ** SQLITE_OK is returned if the segment is updated successfully. Or an
157747 ** SQLite error code otherwise.
157748 */
157749 static int fts3TruncateSegment(
157750  Fts3Table *p, /* FTS3 table handle */
157751  sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
157752  int iIdx, /* Index within level of segment to modify */
157753  const char *zTerm, /* Remove terms smaller than this */
157754  int nTerm /* Number of bytes in buffer zTerm */
157755 ){
157756  int rc = SQLITE_OK; /* Return code */
157757  Blob root = {0,0,0}; /* New root page image */
157758  Blob block = {0,0,0}; /* Buffer used for any other block */
157759  sqlite3_int64 iBlock = 0; /* Block id */
157760  sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
157761  sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
157762  sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
157763 
157764  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
157765  if( rc==SQLITE_OK ){
157766  int rc2; /* sqlite3_reset() return code */
157767  sqlite3_bind_int64(pFetch, 1, iAbsLevel);
157768  sqlite3_bind_int(pFetch, 2, iIdx);
157769  if( SQLITE_ROW==sqlite3_step(pFetch) ){
157770  const char *aRoot = sqlite3_column_blob(pFetch, 4);
157771  int nRoot = sqlite3_column_bytes(pFetch, 4);
157772  iOldStart = sqlite3_column_int64(pFetch, 1);
157773  rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
157774  }
157775  rc2 = sqlite3_reset(pFetch);
157776  if( rc==SQLITE_OK ) rc = rc2;
157777  }
157778 
157779  while( rc==SQLITE_OK && iBlock ){
157780  char *aBlock = 0;
157781  int nBlock = 0;
157782  iNewStart = iBlock;
157783 
157784  rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
157785  if( rc==SQLITE_OK ){
157786  rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
157787  }
157788  if( rc==SQLITE_OK ){
157789  rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
157790  }
157791  sqlite3_free(aBlock);
157792  }
157793 
157794  /* Variable iNewStart now contains the first valid leaf node. */
157795  if( rc==SQLITE_OK && iNewStart ){
157796  sqlite3_stmt *pDel = 0;
157797  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
157798  if( rc==SQLITE_OK ){
157799  sqlite3_bind_int64(pDel, 1, iOldStart);
157800  sqlite3_bind_int64(pDel, 2, iNewStart-1);
157801  sqlite3_step(pDel);
157802  rc = sqlite3_reset(pDel);
157803  }
157804  }
157805 
157806  if( rc==SQLITE_OK ){
157807  sqlite3_stmt *pChomp = 0;
157808  rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
157809  if( rc==SQLITE_OK ){
157810  sqlite3_bind_int64(pChomp, 1, iNewStart);
157811  sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
157812  sqlite3_bind_int64(pChomp, 3, iAbsLevel);
157813  sqlite3_bind_int(pChomp, 4, iIdx);
157814  sqlite3_step(pChomp);
157815  rc = sqlite3_reset(pChomp);
157816  }
157817  }
157818 
157819  sqlite3_free(root.a);
157820  sqlite3_free(block.a);
157821  return rc;
157822 }
157823 
157824 /*
157825 ** This function is called after an incrmental-merge operation has run to
157826 ** merge (or partially merge) two or more segments from absolute level
157827 ** iAbsLevel.
157828 **
157829 ** Each input segment is either removed from the db completely (if all of
157830 ** its data was copied to the output segment by the incrmerge operation)
157831 ** or modified in place so that it no longer contains those entries that
157832 ** have been duplicated in the output segment.
157833 */
157834 static int fts3IncrmergeChomp(
157835  Fts3Table *p, /* FTS table handle */
157836  sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
157837  Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
157838  int *pnRem /* Number of segments not deleted */
157839 ){
157840  int i;
157841  int nRem = 0;
157842  int rc = SQLITE_OK;
157843 
157844  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
157845  Fts3SegReader *pSeg = 0;
157846  int j;
157847 
157848  /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
157849  ** somewhere in the pCsr->apSegment[] array. */
157850  for(j=0; ALWAYS(j<pCsr->nSegment); j++){
157851  pSeg = pCsr->apSegment[j];
157852  if( pSeg->iIdx==i ) break;
157853  }
157854  assert( j<pCsr->nSegment && pSeg->iIdx==i );
157855 
157856  if( pSeg->aNode==0 ){
157857  /* Seg-reader is at EOF. Remove the entire input segment. */
157858  rc = fts3DeleteSegment(p, pSeg);
157859  if( rc==SQLITE_OK ){
157860  rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
157861  }
157862  *pnRem = 0;
157863  }else{
157864  /* The incremental merge did not copy all the data from this
157865  ** segment to the upper level. The segment is modified in place
157866  ** so that it contains no keys smaller than zTerm/nTerm. */
157867  const char *zTerm = pSeg->zTerm;
157868  int nTerm = pSeg->nTerm;
157869  rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
157870  nRem++;
157871  }
157872  }
157873 
157874  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
157875  rc = fts3RepackSegdirLevel(p, iAbsLevel);
157876  }
157877 
157878  *pnRem = nRem;
157879  return rc;
157880 }
157881 
157882 /*
157883 ** Store an incr-merge hint in the database.
157884 */
157885 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
157886  sqlite3_stmt *pReplace = 0;
157887  int rc; /* Return code */
157888 
157889  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
157890  if( rc==SQLITE_OK ){
157891  sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
157892  sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
157893  sqlite3_step(pReplace);
157894  rc = sqlite3_reset(pReplace);
157895  }
157896 
157897  return rc;
157898 }
157899 
157900 /*
157901 ** Load an incr-merge hint from the database. The incr-merge hint, if one
157902 ** exists, is stored in the rowid==1 row of the %_stat table.
157903 **
157904 ** If successful, populate blob *pHint with the value read from the %_stat
157905 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
157906 ** SQLite error code.
157907 */
157908 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
157909  sqlite3_stmt *pSelect = 0;
157910  int rc;
157911 
157912  pHint->n = 0;
157913  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
157914  if( rc==SQLITE_OK ){
157915  int rc2;
157916  sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
157917  if( SQLITE_ROW==sqlite3_step(pSelect) ){
157918  const char *aHint = sqlite3_column_blob(pSelect, 0);
157919  int nHint = sqlite3_column_bytes(pSelect, 0);
157920  if( aHint ){
157921  blobGrowBuffer(pHint, nHint, &rc);
157922  if( rc==SQLITE_OK ){
157923  memcpy(pHint->a, aHint, nHint);
157924  pHint->n = nHint;
157925  }
157926  }
157927  }
157928  rc2 = sqlite3_reset(pSelect);
157929  if( rc==SQLITE_OK ) rc = rc2;
157930  }
157931 
157932  return rc;
157933 }
157934 
157935 /*
157936 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
157937 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
157938 ** consists of two varints, the absolute level number of the input segments
157939 ** and the number of input segments.
157940 **
157941 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
157942 ** set *pRc to an SQLite error code before returning.
157943 */
157944 static void fts3IncrmergeHintPush(
157945  Blob *pHint, /* Hint blob to append to */
157946  i64 iAbsLevel, /* First varint to store in hint */
157947  int nInput, /* Second varint to store in hint */
157948  int *pRc /* IN/OUT: Error code */
157949 ){
157950  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
157951  if( *pRc==SQLITE_OK ){
157952  pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
157953  pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
157954  }
157955 }
157956 
157957 /*
157958 ** Read the last entry (most recently pushed) from the hint blob *pHint
157959 ** and then remove the entry. Write the two values read to *piAbsLevel and
157960 ** *pnInput before returning.
157961 **
157962 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
157963 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
157964 */
157965 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
157966  const int nHint = pHint->n;
157967  int i;
157968 
157969  i = pHint->n-2;
157970  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
157971  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
157972 
157973  pHint->n = i;
157974  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
157975  i += fts3GetVarint32(&pHint->a[i], pnInput);
157976  if( i!=nHint ) return FTS_CORRUPT_VTAB;
157977 
157978  return SQLITE_OK;
157979 }
157980 
157981 
157982 /*
157983 ** Attempt an incremental merge that writes nMerge leaf blocks.
157984 **
157985 ** Incremental merges happen nMin segments at a time. The segments
157986 ** to be merged are the nMin oldest segments (the ones with the smallest
157987 ** values for the _segdir.idx field) in the highest level that contains
157988 ** at least nMin segments. Multiple merges might occur in an attempt to
157989 ** write the quota of nMerge leaf blocks.
157990 */
157991 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
157992  int rc; /* Return code */
157993  int nRem = nMerge; /* Number of leaf pages yet to be written */
157994  Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
157995  Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
157996  IncrmergeWriter *pWriter; /* Writer object */
157997  int nSeg = 0; /* Number of input segments */
157998  sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
157999  Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
158000  int bDirtyHint = 0; /* True if blob 'hint' has been modified */
158001 
158002  /* Allocate space for the cursor, filter and writer objects */
158003  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
158004  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
158005  if( !pWriter ) return SQLITE_NOMEM;
158006  pFilter = (Fts3SegFilter *)&pWriter[1];
158007  pCsr = (Fts3MultiSegReader *)&pFilter[1];
158008 
158009  rc = fts3IncrmergeHintLoad(p, &hint);
158010  while( rc==SQLITE_OK && nRem>0 ){
158011  const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
158012  sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
158013  int bUseHint = 0; /* True if attempting to append */
158014  int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
158015 
158016  /* Search the %_segdir table for the absolute level with the smallest
158017  ** relative level number that contains at least nMin segments, if any.
158018  ** If one is found, set iAbsLevel to the absolute level number and
158019  ** nSeg to nMin. If no level with at least nMin segments can be found,
158020  ** set nSeg to -1.
158021  */
158022  rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
158023  sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
158024  if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
158025  iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
158026  nSeg = sqlite3_column_int(pFindLevel, 1);
158027  assert( nSeg>=2 );
158028  }else{
158029  nSeg = -1;
158030  }
158031  rc = sqlite3_reset(pFindLevel);
158032 
158033  /* If the hint read from the %_stat table is not empty, check if the
158034  ** last entry in it specifies a relative level smaller than or equal
158035  ** to the level identified by the block above (if any). If so, this
158036  ** iteration of the loop will work on merging at the hinted level.
158037  */
158038  if( rc==SQLITE_OK && hint.n ){
158039  int nHint = hint.n;
158040  sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
158041  int nHintSeg = 0; /* Hint number of segments */
158042 
158043  rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
158044  if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
158045  iAbsLevel = iHintAbsLevel;
158046  nSeg = nHintSeg;
158047  bUseHint = 1;
158048  bDirtyHint = 1;
158049  }else{
158050  /* This undoes the effect of the HintPop() above - so that no entry
158051  ** is removed from the hint blob. */
158052  hint.n = nHint;
158053  }
158054  }
158055 
158056  /* If nSeg is less that zero, then there is no level with at least
158057  ** nMin segments and no hint in the %_stat table. No work to do.
158058  ** Exit early in this case. */
158059  if( nSeg<0 ) break;
158060 
158061  /* Open a cursor to iterate through the contents of the oldest nSeg
158062  ** indexes of absolute level iAbsLevel. If this cursor is opened using
158063  ** the 'hint' parameters, it is possible that there are less than nSeg
158064  ** segments available in level iAbsLevel. In this case, no work is
158065  ** done on iAbsLevel - fall through to the next iteration of the loop
158066  ** to start work on some other level. */
158067  memset(pWriter, 0, nAlloc);
158068  pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
158069 
158070  if( rc==SQLITE_OK ){
158071  rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
158072  assert( bUseHint==1 || bUseHint==0 );
158073  if( iIdx==0 || (bUseHint && iIdx==1) ){
158074  int bIgnore = 0;
158075  rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
158076  if( bIgnore ){
158077  pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
158078  }
158079  }
158080  }
158081 
158082  if( rc==SQLITE_OK ){
158083  rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
158084  }
158085  if( SQLITE_OK==rc && pCsr->nSegment==nSeg
158086  && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
158087  && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
158088  ){
158089  if( bUseHint && iIdx>0 ){
158090  const char *zKey = pCsr->zTerm;
158091  int nKey = pCsr->nTerm;
158092  rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
158093  }else{
158094  rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
158095  }
158096 
158097  if( rc==SQLITE_OK && pWriter->nLeafEst ){
158098  fts3LogMerge(nSeg, iAbsLevel);
158099  do {
158100  rc = fts3IncrmergeAppend(p, pWriter, pCsr);
158101  if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
158102  if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
158103  }while( rc==SQLITE_ROW );
158104 
158105  /* Update or delete the input segments */
158106  if( rc==SQLITE_OK ){
158107  nRem -= (1 + pWriter->nWork);
158108  rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
158109  if( nSeg!=0 ){
158110  bDirtyHint = 1;
158111  fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
158112  }
158113  }
158114  }
158115 
158116  if( nSeg!=0 ){
158117  pWriter->nLeafData = pWriter->nLeafData * -1;
158118  }
158119  fts3IncrmergeRelease(p, pWriter, &rc);
158120  if( nSeg==0 && pWriter->bNoLeafData==0 ){
158121  fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
158122  }
158123  }
158124 
158125  sqlite3Fts3SegReaderFinish(pCsr);
158126  }
158127 
158128  /* Write the hint values into the %_stat table for the next incr-merger */
158129  if( bDirtyHint && rc==SQLITE_OK ){
158130  rc = fts3IncrmergeHintStore(p, &hint);
158131  }
158132 
158133  sqlite3_free(pWriter);
158134  sqlite3_free(hint.a);
158135  return rc;
158136 }
158137 
158138 /*
158139 ** Convert the text beginning at *pz into an integer and return
158140 ** its value. Advance *pz to point to the first character past
158141 ** the integer.
158142 */
158143 static int fts3Getint(const char **pz){
158144  const char *z = *pz;
158145  int i = 0;
158146  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
158147  *pz = z;
158148  return i;
158149 }
158150 
158151 /*
158152 ** Process statements of the form:
158153 **
158154 ** INSERT INTO table(table) VALUES('merge=A,B');
158155 **
158156 ** A and B are integers that decode to be the number of leaf pages
158157 ** written for the merge, and the minimum number of segments on a level
158158 ** before it will be selected for a merge, respectively.
158159 */
158160 static int fts3DoIncrmerge(
158161  Fts3Table *p, /* FTS3 table handle */
158162  const char *zParam /* Nul-terminated string containing "A,B" */
158163 ){
158164  int rc;
158165  int nMin = (FTS3_MERGE_COUNT / 2);
158166  int nMerge = 0;
158167  const char *z = zParam;
158168 
158169  /* Read the first integer value */
158170  nMerge = fts3Getint(&z);
158171 
158172  /* If the first integer value is followed by a ',', read the second
158173  ** integer value. */
158174  if( z[0]==',' && z[1]!='\0' ){
158175  z++;
158176  nMin = fts3Getint(&z);
158177  }
158178 
158179  if( z[0]!='\0' || nMin<2 ){
158180  rc = SQLITE_ERROR;
158181  }else{
158182  rc = SQLITE_OK;
158183  if( !p->bHasStat ){
158184  assert( p->bFts4==0 );
158185  sqlite3Fts3CreateStatTable(&rc, p);
158186  }
158187  if( rc==SQLITE_OK ){
158188  rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
158189  }
158190  sqlite3Fts3SegmentsClose(p);
158191  }
158192  return rc;
158193 }
158194 
158195 /*
158196 ** Process statements of the form:
158197 **
158198 ** INSERT INTO table(table) VALUES('automerge=X');
158199 **
158200 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
158201 ** turn it on. The setting is persistent.
158202 */
158203 static int fts3DoAutoincrmerge(
158204  Fts3Table *p, /* FTS3 table handle */
158205  const char *zParam /* Nul-terminated string containing boolean */
158206 ){
158207  int rc = SQLITE_OK;
158208  sqlite3_stmt *pStmt = 0;
158209  p->nAutoincrmerge = fts3Getint(&zParam);
158210  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
158211  p->nAutoincrmerge = 8;
158212  }
158213  if( !p->bHasStat ){
158214  assert( p->bFts4==0 );
158215  sqlite3Fts3CreateStatTable(&rc, p);
158216  if( rc ) return rc;
158217  }
158218  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
158219  if( rc ) return rc;
158220  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
158221  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
158222  sqlite3_step(pStmt);
158223  rc = sqlite3_reset(pStmt);
158224  return rc;
158225 }
158226 
158227 /*
158228 ** Return a 64-bit checksum for the FTS index entry specified by the
158229 ** arguments to this function.
158230 */
158231 static u64 fts3ChecksumEntry(
158232  const char *zTerm, /* Pointer to buffer containing term */
158233  int nTerm, /* Size of zTerm in bytes */
158234  int iLangid, /* Language id for current row */
158235  int iIndex, /* Index (0..Fts3Table.nIndex-1) */
158236  i64 iDocid, /* Docid for current row. */
158237  int iCol, /* Column number */
158238  int iPos /* Position */
158239 ){
158240  int i;
158241  u64 ret = (u64)iDocid;
158242 
158243  ret += (ret<<3) + iLangid;
158244  ret += (ret<<3) + iIndex;
158245  ret += (ret<<3) + iCol;
158246  ret += (ret<<3) + iPos;
158247  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
158248 
158249  return ret;
158250 }
158251 
158252 /*
158253 ** Return a checksum of all entries in the FTS index that correspond to
158254 ** language id iLangid. The checksum is calculated by XORing the checksums
158255 ** of each individual entry (see fts3ChecksumEntry()) together.
158256 **
158257 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
158258 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
158259 ** return value is undefined in this case.
158260 */
158261 static u64 fts3ChecksumIndex(
158262  Fts3Table *p, /* FTS3 table handle */
158263  int iLangid, /* Language id to return cksum for */
158264  int iIndex, /* Index to cksum (0..p->nIndex-1) */
158265  int *pRc /* OUT: Return code */
158266 ){
158267  Fts3SegFilter filter;
158268  Fts3MultiSegReader csr;
158269  int rc;
158270  u64 cksum = 0;
158271 
158272  assert( *pRc==SQLITE_OK );
158273 
158274  memset(&filter, 0, sizeof(filter));
158275  memset(&csr, 0, sizeof(csr));
158276  filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
158277  filter.flags |= FTS3_SEGMENT_SCAN;
158278 
158279  rc = sqlite3Fts3SegReaderCursor(
158280  p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
158281  );
158282  if( rc==SQLITE_OK ){
158283  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
158284  }
158285 
158286  if( rc==SQLITE_OK ){
158287  while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
158288  char *pCsr = csr.aDoclist;
158289  char *pEnd = &pCsr[csr.nDoclist];
158290 
158291  i64 iDocid = 0;
158292  i64 iCol = 0;
158293  i64 iPos = 0;
158294 
158295  pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
158296  while( pCsr<pEnd ){
158297  i64 iVal = 0;
158298  pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
158299  if( pCsr<pEnd ){
158300  if( iVal==0 || iVal==1 ){
158301  iCol = 0;
158302  iPos = 0;
158303  if( iVal ){
158304  pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
158305  }else{
158306  pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
158307  iDocid += iVal;
158308  }
158309  }else{
158310  iPos += (iVal - 2);
158311  cksum = cksum ^ fts3ChecksumEntry(
158312  csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
158313  (int)iCol, (int)iPos
158314  );
158315  }
158316  }
158317  }
158318  }
158319  }
158320  sqlite3Fts3SegReaderFinish(&csr);
158321 
158322  *pRc = rc;
158323  return cksum;
158324 }
158325 
158326 /*
158327 ** Check if the contents of the FTS index match the current contents of the
158328 ** content table. If no error occurs and the contents do match, set *pbOk
158329 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
158330 ** to false before returning.
158331 **
158332 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
158333 ** code. The final value of *pbOk is undefined in this case.
158334 */
158335 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
158336  int rc = SQLITE_OK; /* Return code */
158337  u64 cksum1 = 0; /* Checksum based on FTS index contents */
158338  u64 cksum2 = 0; /* Checksum based on %_content contents */
158339  sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
158340 
158341  /* This block calculates the checksum according to the FTS index. */
158342  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
158343  if( rc==SQLITE_OK ){
158344  int rc2;
158345  sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
158346  sqlite3_bind_int(pAllLangid, 2, p->nIndex);
158347  while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
158348  int iLangid = sqlite3_column_int(pAllLangid, 0);
158349  int i;
158350  for(i=0; i<p->nIndex; i++){
158351  cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
158352  }
158353  }
158354  rc2 = sqlite3_reset(pAllLangid);
158355  if( rc==SQLITE_OK ) rc = rc2;
158356  }
158357 
158358  /* This block calculates the checksum according to the %_content table */
158359  if( rc==SQLITE_OK ){
158360  sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
158361  sqlite3_stmt *pStmt = 0;
158362  char *zSql;
158363 
158364  zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
158365  if( !zSql ){
158366  rc = SQLITE_NOMEM;
158367  }else{
158368  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
158369  sqlite3_free(zSql);
158370  }
158371 
158372  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
158373  i64 iDocid = sqlite3_column_int64(pStmt, 0);
158374  int iLang = langidFromSelect(p, pStmt);
158375  int iCol;
158376 
158377  for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
158378  if( p->abNotindexed[iCol]==0 ){
158379  const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
158380  int nText = sqlite3_column_bytes(pStmt, iCol+1);
158381  sqlite3_tokenizer_cursor *pT = 0;
158382 
158383  rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
158384  while( rc==SQLITE_OK ){
158385  char const *zToken; /* Buffer containing token */
158386  int nToken = 0; /* Number of bytes in token */
158387  int iDum1 = 0, iDum2 = 0; /* Dummy variables */
158388  int iPos = 0; /* Position of token in zText */
158389 
158390  rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
158391  if( rc==SQLITE_OK ){
158392  int i;
158393  cksum2 = cksum2 ^ fts3ChecksumEntry(
158394  zToken, nToken, iLang, 0, iDocid, iCol, iPos
158395  );
158396  for(i=1; i<p->nIndex; i++){
158397  if( p->aIndex[i].nPrefix<=nToken ){
158398  cksum2 = cksum2 ^ fts3ChecksumEntry(
158399  zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
158400  );
158401  }
158402  }
158403  }
158404  }
158405  if( pT ) pModule->xClose(pT);
158406  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
158407  }
158408  }
158409  }
158410 
158411  sqlite3_finalize(pStmt);
158412  }
158413 
158414  *pbOk = (cksum1==cksum2);
158415  return rc;
158416 }
158417 
158418 /*
158419 ** Run the integrity-check. If no error occurs and the current contents of
158420 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
158421 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
158422 **
158423 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
158424 ** error code.
158425 **
158426 ** The integrity-check works as follows. For each token and indexed token
158427 ** prefix in the document set, a 64-bit checksum is calculated (by code
158428 ** in fts3ChecksumEntry()) based on the following:
158429 **
158430 ** + The index number (0 for the main index, 1 for the first prefix
158431 ** index etc.),
158432 ** + The token (or token prefix) text itself,
158433 ** + The language-id of the row it appears in,
158434 ** + The docid of the row it appears in,
158435 ** + The column it appears in, and
158436 ** + The tokens position within that column.
158437 **
158438 ** The checksums for all entries in the index are XORed together to create
158439 ** a single checksum for the entire index.
158440 **
158441 ** The integrity-check code calculates the same checksum in two ways:
158442 **
158443 ** 1. By scanning the contents of the FTS index, and
158444 ** 2. By scanning and tokenizing the content table.
158445 **
158446 ** If the two checksums are identical, the integrity-check is deemed to have
158447 ** passed.
158448 */
158449 static int fts3DoIntegrityCheck(
158450  Fts3Table *p /* FTS3 table handle */
158451 ){
158452  int rc;
158453  int bOk = 0;
158454  rc = fts3IntegrityCheck(p, &bOk);
158455  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
158456  return rc;
158457 }
158458 
158459 /*
158460 ** Handle a 'special' INSERT of the form:
158461 **
158462 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
158463 **
158464 ** Argument pVal contains the result of <expr>. Currently the only
158465 ** meaningful value to insert is the text 'optimize'.
158466 */
158467 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
158468  int rc; /* Return Code */
158469  const char *zVal = (const char *)sqlite3_value_text(pVal);
158470  int nVal = sqlite3_value_bytes(pVal);
158471 
158472  if( !zVal ){
158473  return SQLITE_NOMEM;
158474  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
158475  rc = fts3DoOptimize(p, 0);
158476  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
158477  rc = fts3DoRebuild(p);
158478  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
158479  rc = fts3DoIntegrityCheck(p);
158480  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
158481  rc = fts3DoIncrmerge(p, &zVal[6]);
158482  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
158483  rc = fts3DoAutoincrmerge(p, &zVal[10]);
158484 #ifdef SQLITE_TEST
158485  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
158486  p->nNodeSize = atoi(&zVal[9]);
158487  rc = SQLITE_OK;
158488  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
158489  p->nMaxPendingData = atoi(&zVal[11]);
158490  rc = SQLITE_OK;
158491  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
158492  p->bNoIncrDoclist = atoi(&zVal[21]);
158493  rc = SQLITE_OK;
158494 #endif
158495  }else{
158496  rc = SQLITE_ERROR;
158497  }
158498 
158499  return rc;
158500 }
158501 
158502 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
158503 /*
158504 ** Delete all cached deferred doclists. Deferred doclists are cached
158505 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
158506 */
158507 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
158508  Fts3DeferredToken *pDef;
158509  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
158510  fts3PendingListDelete(pDef->pList);
158511  pDef->pList = 0;
158512  }
158513 }
158514 
158515 /*
158516 ** Free all entries in the pCsr->pDeffered list. Entries are added to
158517 ** this list using sqlite3Fts3DeferToken().
158518 */
158519 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
158520  Fts3DeferredToken *pDef;
158521  Fts3DeferredToken *pNext;
158522  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
158523  pNext = pDef->pNext;
158524  fts3PendingListDelete(pDef->pList);
158525  sqlite3_free(pDef);
158526  }
158527  pCsr->pDeferred = 0;
158528 }
158529 
158530 /*
158531 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
158532 ** based on the row that pCsr currently points to.
158533 **
158534 ** A deferred-doclist is like any other doclist with position information
158535 ** included, except that it only contains entries for a single row of the
158536 ** table, not for all rows.
158537 */
158538 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
158539  int rc = SQLITE_OK; /* Return code */
158540  if( pCsr->pDeferred ){
158541  int i; /* Used to iterate through table columns */
158542  sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
158543  Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
158544 
158545  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
158546  sqlite3_tokenizer *pT = p->pTokenizer;
158547  sqlite3_tokenizer_module const *pModule = pT->pModule;
158548 
158549  assert( pCsr->isRequireSeek==0 );
158550  iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
158551 
158552  for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
158553  if( p->abNotindexed[i]==0 ){
158554  const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
158555  sqlite3_tokenizer_cursor *pTC = 0;
158556 
158557  rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
158558  while( rc==SQLITE_OK ){
158559  char const *zToken; /* Buffer containing token */
158560  int nToken = 0; /* Number of bytes in token */
158561  int iDum1 = 0, iDum2 = 0; /* Dummy variables */
158562  int iPos = 0; /* Position of token in zText */
158563 
158564  rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
158565  for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
158566  Fts3PhraseToken *pPT = pDef->pToken;
158567  if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
158568  && (pPT->bFirst==0 || iPos==0)
158569  && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
158570  && (0==memcmp(zToken, pPT->z, pPT->n))
158571  ){
158572  fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
158573  }
158574  }
158575  }
158576  if( pTC ) pModule->xClose(pTC);
158577  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
158578  }
158579  }
158580 
158581  for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
158582  if( pDef->pList ){
158583  rc = fts3PendingListAppendVarint(&pDef->pList, 0);
158584  }
158585  }
158586  }
158587 
158588  return rc;
158589 }
158590 
158591 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
158592  Fts3DeferredToken *p,
158593  char **ppData,
158594  int *pnData
158595 ){
158596  char *pRet;
158597  int nSkip;
158598  sqlite3_int64 dummy;
158599 
158600  *ppData = 0;
158601  *pnData = 0;
158602 
158603  if( p->pList==0 ){
158604  return SQLITE_OK;
158605  }
158606 
158607  pRet = (char *)sqlite3_malloc(p->pList->nData);
158608  if( !pRet ) return SQLITE_NOMEM;
158609 
158610  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
158611  *pnData = p->pList->nData - nSkip;
158612  *ppData = pRet;
158613 
158614  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
158615  return SQLITE_OK;
158616 }
158617 
158618 /*
158619 ** Add an entry for token pToken to the pCsr->pDeferred list.
158620 */
158621 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
158622  Fts3Cursor *pCsr, /* Fts3 table cursor */
158623  Fts3PhraseToken *pToken, /* Token to defer */
158624  int iCol /* Column that token must appear in (or -1) */
158625 ){
158626  Fts3DeferredToken *pDeferred;
158627  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
158628  if( !pDeferred ){
158629  return SQLITE_NOMEM;
158630  }
158631  memset(pDeferred, 0, sizeof(*pDeferred));
158632  pDeferred->pToken = pToken;
158633  pDeferred->pNext = pCsr->pDeferred;
158634  pDeferred->iCol = iCol;
158635  pCsr->pDeferred = pDeferred;
158636 
158637  assert( pToken->pDeferred==0 );
158638  pToken->pDeferred = pDeferred;
158639 
158640  return SQLITE_OK;
158641 }
158642 #endif
158643 
158644 /*
158645 ** SQLite value pRowid contains the rowid of a row that may or may not be
158646 ** present in the FTS3 table. If it is, delete it and adjust the contents
158647 ** of subsiduary data structures accordingly.
158648 */
158649 static int fts3DeleteByRowid(
158650  Fts3Table *p,
158651  sqlite3_value *pRowid,
158652  int *pnChng, /* IN/OUT: Decrement if row is deleted */
158653  u32 *aSzDel
158654 ){
158655  int rc = SQLITE_OK; /* Return code */
158656  int bFound = 0; /* True if *pRowid really is in the table */
158657 
158658  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
158659  if( bFound && rc==SQLITE_OK ){
158660  int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
158661  rc = fts3IsEmpty(p, pRowid, &isEmpty);
158662  if( rc==SQLITE_OK ){
158663  if( isEmpty ){
158664  /* Deleting this row means the whole table is empty. In this case
158665  ** delete the contents of all three tables and throw away any
158666  ** data in the pendingTerms hash table. */
158667  rc = fts3DeleteAll(p, 1);
158668  *pnChng = 0;
158669  memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
158670  }else{
158671  *pnChng = *pnChng - 1;
158672  if( p->zContentTbl==0 ){
158673  fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
158674  }
158675  if( p->bHasDocsize ){
158676  fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
158677  }
158678  }
158679  }
158680  }
158681 
158682  return rc;
158683 }
158684 
158685 /*
158686 ** This function does the work for the xUpdate method of FTS3 virtual
158687 ** tables. The schema of the virtual table being:
158688 **
158689 ** CREATE TABLE <table name>(
158690 ** <user columns>,
158691 ** <table name> HIDDEN,
158692 ** docid HIDDEN,
158693 ** <langid> HIDDEN
158694 ** );
158695 **
158696 **
158697 */
158698 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
158699  sqlite3_vtab *pVtab, /* FTS3 vtab object */
158700  int nArg, /* Size of argument array */
158701  sqlite3_value **apVal, /* Array of arguments */
158702  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
158703 ){
158704  Fts3Table *p = (Fts3Table *)pVtab;
158705  int rc = SQLITE_OK; /* Return Code */
158706  int isRemove = 0; /* True for an UPDATE or DELETE */
158707  u32 *aSzIns = 0; /* Sizes of inserted documents */
158708  u32 *aSzDel = 0; /* Sizes of deleted documents */
158709  int nChng = 0; /* Net change in number of documents */
158710  int bInsertDone = 0;
158711 
158712  /* At this point it must be known if the %_stat table exists or not.
158713  ** So bHasStat may not be 2. */
158714  assert( p->bHasStat==0 || p->bHasStat==1 );
158715 
158716  assert( p->pSegments==0 );
158717  assert(
158718  nArg==1 /* DELETE operations */
158719  || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
158720  );
158721 
158722  /* Check for a "special" INSERT operation. One of the form:
158723  **
158724  ** INSERT INTO xyz(xyz) VALUES('command');
158725  */
158726  if( nArg>1
158727  && sqlite3_value_type(apVal[0])==SQLITE_NULL
158728  && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
158729  ){
158730  rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
158731  goto update_out;
158732  }
158733 
158734  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
158735  rc = SQLITE_CONSTRAINT;
158736  goto update_out;
158737  }
158738 
158739  /* Allocate space to hold the change in document sizes */
158740  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
158741  if( aSzDel==0 ){
158742  rc = SQLITE_NOMEM;
158743  goto update_out;
158744  }
158745  aSzIns = &aSzDel[p->nColumn+1];
158746  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
158747 
158748  rc = fts3Writelock(p);
158749  if( rc!=SQLITE_OK ) goto update_out;
158750 
158751  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
158752  ** value, then this operation requires constraint handling.
158753  **
158754  ** If the on-conflict mode is REPLACE, this means that the existing row
158755  ** should be deleted from the database before inserting the new row. Or,
158756  ** if the on-conflict mode is other than REPLACE, then this method must
158757  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
158758  ** modify the database file.
158759  */
158760  if( nArg>1 && p->zContentTbl==0 ){
158761  /* Find the value object that holds the new rowid value. */
158762  sqlite3_value *pNewRowid = apVal[3+p->nColumn];
158763  if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
158764  pNewRowid = apVal[1];
158765  }
158766 
158767  if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
158768  sqlite3_value_type(apVal[0])==SQLITE_NULL
158769  || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
158770  )){
158771  /* The new rowid is not NULL (in this case the rowid will be
158772  ** automatically assigned and there is no chance of a conflict), and
158773  ** the statement is either an INSERT or an UPDATE that modifies the
158774  ** rowid column. So if the conflict mode is REPLACE, then delete any
158775  ** existing row with rowid=pNewRowid.
158776  **
158777  ** Or, if the conflict mode is not REPLACE, insert the new record into
158778  ** the %_content table. If we hit the duplicate rowid constraint (or any
158779  ** other error) while doing so, return immediately.
158780  **
158781  ** This branch may also run if pNewRowid contains a value that cannot
158782  ** be losslessly converted to an integer. In this case, the eventual
158783  ** call to fts3InsertData() (either just below or further on in this
158784  ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
158785  ** invoked, it will delete zero rows (since no row will have
158786  ** docid=$pNewRowid if $pNewRowid is not an integer value).
158787  */
158789  rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
158790  }else{
158791  rc = fts3InsertData(p, apVal, pRowid);
158792  bInsertDone = 1;
158793  }
158794  }
158795  }
158796  if( rc!=SQLITE_OK ){
158797  goto update_out;
158798  }
158799 
158800  /* If this is a DELETE or UPDATE operation, remove the old record. */
158801  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
158802  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
158803  rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
158804  isRemove = 1;
158805  }
158806 
158807  /* If this is an INSERT or UPDATE operation, insert the new record. */
158808  if( nArg>1 && rc==SQLITE_OK ){
158809  int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
158810  if( bInsertDone==0 ){
158811  rc = fts3InsertData(p, apVal, pRowid);
158812  if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
158813  rc = FTS_CORRUPT_VTAB;
158814  }
158815  }
158816  if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
158817  rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
158818  }
158819  if( rc==SQLITE_OK ){
158820  assert( p->iPrevDocid==*pRowid );
158821  rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
158822  }
158823  if( p->bHasDocsize ){
158824  fts3InsertDocsize(&rc, p, aSzIns);
158825  }
158826  nChng++;
158827  }
158828 
158829  if( p->bFts4 ){
158830  fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
158831  }
158832 
158833  update_out:
158834  sqlite3_free(aSzDel);
158835  sqlite3Fts3SegmentsClose(p);
158836  return rc;
158837 }
158838 
158839 /*
158840 ** Flush any data in the pending-terms hash table to disk. If successful,
158841 ** merge all segments in the database (including the new segment, if
158842 ** there was any data to flush) into a single segment.
158843 */
158844 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
158845  int rc;
158846  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
158847  if( rc==SQLITE_OK ){
158848  rc = fts3DoOptimize(p, 1);
158849  if( rc==SQLITE_OK || rc==SQLITE_DONE ){
158850  int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
158851  if( rc2!=SQLITE_OK ) rc = rc2;
158852  }else{
158853  sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
158854  sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
158855  }
158856  }
158857  sqlite3Fts3SegmentsClose(p);
158858  return rc;
158859 }
158860 
158861 #endif
158862 
158863 /************** End of fts3_write.c ******************************************/
158864 /************** Begin file fts3_snippet.c ************************************/
158865 /*
158866 ** 2009 Oct 23
158867 **
158868 ** The author disclaims copyright to this source code. In place of
158869 ** a legal notice, here is a blessing:
158870 **
158871 ** May you do good and not evil.
158872 ** May you find forgiveness for yourself and forgive others.
158873 ** May you share freely, never taking more than you give.
158874 **
158875 ******************************************************************************
158876 */
158877 
158878 /* #include "fts3Int.h" */
158879 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
158880 
158881 /* #include <string.h> */
158882 /* #include <assert.h> */
158883 
158884 /*
158885 ** Characters that may appear in the second argument to matchinfo().
158886 */
158887 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
158888 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
158889 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
158890 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
158891 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
158892 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
158893 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
158894 #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
158895 #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
158896 
158897 /*
158898 ** The default value for the second argument to matchinfo().
158899 */
158900 #define FTS3_MATCHINFO_DEFAULT "pcx"
158901 
158902 
158903 /*
158904 ** Used as an fts3ExprIterate() context when loading phrase doclists to
158905 ** Fts3Expr.aDoclist[]/nDoclist.
158906 */
158907 typedef struct LoadDoclistCtx LoadDoclistCtx;
158908 struct LoadDoclistCtx {
158909  Fts3Cursor *pCsr; /* FTS3 Cursor */
158910  int nPhrase; /* Number of phrases seen so far */
158911  int nToken; /* Number of tokens seen so far */
158912 };
158913 
158914 /*
158915 ** The following types are used as part of the implementation of the
158916 ** fts3BestSnippet() routine.
158917 */
158918 typedef struct SnippetIter SnippetIter;
158919 typedef struct SnippetPhrase SnippetPhrase;
158920 typedef struct SnippetFragment SnippetFragment;
158921 
158922 struct SnippetIter {
158923  Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
158924  int iCol; /* Extract snippet from this column */
158925  int nSnippet; /* Requested snippet length (in tokens) */
158926  int nPhrase; /* Number of phrases in query */
158927  SnippetPhrase *aPhrase; /* Array of size nPhrase */
158928  int iCurrent; /* First token of current snippet */
158929 };
158930 
158931 struct SnippetPhrase {
158932  int nToken; /* Number of tokens in phrase */
158933  char *pList; /* Pointer to start of phrase position list */
158934  int iHead; /* Next value in position list */
158935  char *pHead; /* Position list data following iHead */
158936  int iTail; /* Next value in trailing position list */
158937  char *pTail; /* Position list data following iTail */
158938 };
158939 
158940 struct SnippetFragment {
158941  int iCol; /* Column snippet is extracted from */
158942  int iPos; /* Index of first token in snippet */
158943  u64 covered; /* Mask of query phrases covered */
158944  u64 hlmask; /* Mask of snippet terms to highlight */
158945 };
158946 
158947 /*
158948 ** This type is used as an fts3ExprIterate() context object while
158949 ** accumulating the data returned by the matchinfo() function.
158950 */
158951 typedef struct MatchInfo MatchInfo;
158952 struct MatchInfo {
158953  Fts3Cursor *pCursor; /* FTS3 Cursor */
158954  int nCol; /* Number of columns in table */
158955  int nPhrase; /* Number of matchable phrases in query */
158956  sqlite3_int64 nDoc; /* Number of docs in database */
158957  char flag;
158958  u32 *aMatchinfo; /* Pre-allocated buffer */
158959 };
158960 
158961 /*
158962 ** An instance of this structure is used to manage a pair of buffers, each
158963 ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
158964 ** for details.
158965 */
158966 struct MatchinfoBuffer {
158967  u8 aRef[3];
158968  int nElem;
158969  int bGlobal; /* Set if global data is loaded */
158970  char *zMatchinfo;
158971  u32 aMatchinfo[1];
158972 };
158973 
158974 
158975 /*
158976 ** The snippet() and offsets() functions both return text values. An instance
158977 ** of the following structure is used to accumulate those values while the
158978 ** functions are running. See fts3StringAppend() for details.
158979 */
158980 typedef struct StrBuffer StrBuffer;
158981 struct StrBuffer {
158982  char *z; /* Pointer to buffer containing string */
158983  int n; /* Length of z in bytes (excl. nul-term) */
158984  int nAlloc; /* Allocated size of buffer z in bytes */
158985 };
158986 
158987 
158988 /*************************************************************************
158989 ** Start of MatchinfoBuffer code.
158990 */
158991 
158992 /*
158993 ** Allocate a two-slot MatchinfoBuffer object.
158994 */
158995 static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
158996  MatchinfoBuffer *pRet;
158997  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
158998  int nStr = (int)strlen(zMatchinfo);
158999 
159000  pRet = sqlite3_malloc(nByte + nStr+1);
159001  if( pRet ){
159002  memset(pRet, 0, nByte);
159003  pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
159004  pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
159005  pRet->nElem = nElem;
159006  pRet->zMatchinfo = ((char*)pRet) + nByte;
159007  memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
159008  pRet->aRef[0] = 1;
159009  }
159010 
159011  return pRet;
159012 }
159013 
159014 static void fts3MIBufferFree(void *p){
159015  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
159016 
159017  assert( (u32*)p==&pBuf->aMatchinfo[1]
159018  || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
159019  );
159020  if( (u32*)p==&pBuf->aMatchinfo[1] ){
159021  pBuf->aRef[1] = 0;
159022  }else{
159023  pBuf->aRef[2] = 0;
159024  }
159025 
159026  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
159027  sqlite3_free(pBuf);
159028  }
159029 }
159030 
159031 static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
159032  void (*xRet)(void*) = 0;
159033  u32 *aOut = 0;
159034 
159035  if( p->aRef[1]==0 ){
159036  p->aRef[1] = 1;
159037  aOut = &p->aMatchinfo[1];
159038  xRet = fts3MIBufferFree;
159039  }
159040  else if( p->aRef[2]==0 ){
159041  p->aRef[2] = 1;
159042  aOut = &p->aMatchinfo[p->nElem+2];
159043  xRet = fts3MIBufferFree;
159044  }else{
159045  aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
159046  if( aOut ){
159047  xRet = sqlite3_free;
159048  if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
159049  }
159050  }
159051 
159052  *paOut = aOut;
159053  return xRet;
159054 }
159055 
159056 static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
159057  p->bGlobal = 1;
159058  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
159059 }
159060 
159061 /*
159062 ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
159063 */
159064 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
159065  if( p ){
159066  assert( p->aRef[0]==1 );
159067  p->aRef[0] = 0;
159068  if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
159069  sqlite3_free(p);
159070  }
159071  }
159072 }
159073 
159074 /*
159075 ** End of MatchinfoBuffer code.
159076 *************************************************************************/
159077 
159078 
159079 /*
159080 ** This function is used to help iterate through a position-list. A position
159081 ** list is a list of unique integers, sorted from smallest to largest. Each
159082 ** element of the list is represented by an FTS3 varint that takes the value
159083 ** of the difference between the current element and the previous one plus
159084 ** two. For example, to store the position-list:
159085 **
159086 ** 4 9 113
159087 **
159088 ** the three varints:
159089 **
159090 ** 6 7 106
159091 **
159092 ** are encoded.
159093 **
159094 ** When this function is called, *pp points to the start of an element of
159095 ** the list. *piPos contains the value of the previous entry in the list.
159096 ** After it returns, *piPos contains the value of the next element of the
159097 ** list and *pp is advanced to the following varint.
159098 */
159099 static void fts3GetDeltaPosition(char **pp, int *piPos){
159100  int iVal;
159101  *pp += fts3GetVarint32(*pp, &iVal);
159102  *piPos += (iVal-2);
159103 }
159104 
159105 /*
159106 ** Helper function for fts3ExprIterate() (see below).
159107 */
159108 static int fts3ExprIterate2(
159109  Fts3Expr *pExpr, /* Expression to iterate phrases of */
159110  int *piPhrase, /* Pointer to phrase counter */
159111  int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
159112  void *pCtx /* Second argument to pass to callback */
159113 ){
159114  int rc; /* Return code */
159115  int eType = pExpr->eType; /* Type of expression node pExpr */
159116 
159117  if( eType!=FTSQUERY_PHRASE ){
159118  assert( pExpr->pLeft && pExpr->pRight );
159119  rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
159120  if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
159121  rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
159122  }
159123  }else{
159124  rc = x(pExpr, *piPhrase, pCtx);
159125  (*piPhrase)++;
159126  }
159127  return rc;
159128 }
159129 
159130 /*
159131 ** Iterate through all phrase nodes in an FTS3 query, except those that
159132 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
159133 ** For each phrase node found, the supplied callback function is invoked.
159134 **
159135 ** If the callback function returns anything other than SQLITE_OK,
159136 ** the iteration is abandoned and the error code returned immediately.
159137 ** Otherwise, SQLITE_OK is returned after a callback has been made for
159138 ** all eligible phrase nodes.
159139 */
159140 static int fts3ExprIterate(
159141  Fts3Expr *pExpr, /* Expression to iterate phrases of */
159142  int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
159143  void *pCtx /* Second argument to pass to callback */
159144 ){
159145  int iPhrase = 0; /* Variable used as the phrase counter */
159146  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
159147 }
159148 
159149 
159150 /*
159151 ** This is an fts3ExprIterate() callback used while loading the doclists
159152 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
159153 ** fts3ExprLoadDoclists().
159154 */
159155 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
159156  int rc = SQLITE_OK;
159157  Fts3Phrase *pPhrase = pExpr->pPhrase;
159158  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
159159 
159160  UNUSED_PARAMETER(iPhrase);
159161 
159162  p->nPhrase++;
159163  p->nToken += pPhrase->nToken;
159164 
159165  return rc;
159166 }
159167 
159168 /*
159169 ** Load the doclists for each phrase in the query associated with FTS3 cursor
159170 ** pCsr.
159171 **
159172 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
159173 ** phrases in the expression (all phrases except those directly or
159174 ** indirectly descended from the right-hand-side of a NOT operator). If
159175 ** pnToken is not NULL, then it is set to the number of tokens in all
159176 ** matchable phrases of the expression.
159177 */
159178 static int fts3ExprLoadDoclists(
159179  Fts3Cursor *pCsr, /* Fts3 cursor for current query */
159180  int *pnPhrase, /* OUT: Number of phrases in query */
159181  int *pnToken /* OUT: Number of tokens in query */
159182 ){
159183  int rc; /* Return Code */
159184  LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
159185  sCtx.pCsr = pCsr;
159186  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
159187  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
159188  if( pnToken ) *pnToken = sCtx.nToken;
159189  return rc;
159190 }
159191 
159192 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
159193  (*(int *)ctx)++;
159194  pExpr->iPhrase = iPhrase;
159195  return SQLITE_OK;
159196 }
159197 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
159198  int nPhrase = 0;
159199  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
159200  return nPhrase;
159201 }
159202 
159203 /*
159204 ** Advance the position list iterator specified by the first two
159205 ** arguments so that it points to the first element with a value greater
159206 ** than or equal to parameter iNext.
159207 */
159208 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
159209  char *pIter = *ppIter;
159210  if( pIter ){
159211  int iIter = *piIter;
159212 
159213  while( iIter<iNext ){
159214  if( 0==(*pIter & 0xFE) ){
159215  iIter = -1;
159216  pIter = 0;
159217  break;
159218  }
159219  fts3GetDeltaPosition(&pIter, &iIter);
159220  }
159221 
159222  *piIter = iIter;
159223  *ppIter = pIter;
159224  }
159225 }
159226 
159227 /*
159228 ** Advance the snippet iterator to the next candidate snippet.
159229 */
159230 static int fts3SnippetNextCandidate(SnippetIter *pIter){
159231  int i; /* Loop counter */
159232 
159233  if( pIter->iCurrent<0 ){
159234  /* The SnippetIter object has just been initialized. The first snippet
159235  ** candidate always starts at offset 0 (even if this candidate has a
159236  ** score of 0.0).
159237  */
159238  pIter->iCurrent = 0;
159239 
159240  /* Advance the 'head' iterator of each phrase to the first offset that
159241  ** is greater than or equal to (iNext+nSnippet).
159242  */
159243  for(i=0; i<pIter->nPhrase; i++){
159244  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159245  fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
159246  }
159247  }else{
159248  int iStart;
159249  int iEnd = 0x7FFFFFFF;
159250 
159251  for(i=0; i<pIter->nPhrase; i++){
159252  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159253  if( pPhrase->pHead && pPhrase->iHead<iEnd ){
159254  iEnd = pPhrase->iHead;
159255  }
159256  }
159257  if( iEnd==0x7FFFFFFF ){
159258  return 1;
159259  }
159260 
159261  pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
159262  for(i=0; i<pIter->nPhrase; i++){
159263  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159264  fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
159265  fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
159266  }
159267  }
159268 
159269  return 0;
159270 }
159271 
159272 /*
159273 ** Retrieve information about the current candidate snippet of snippet
159274 ** iterator pIter.
159275 */
159276 static void fts3SnippetDetails(
159277  SnippetIter *pIter, /* Snippet iterator */
159278  u64 mCovered, /* Bitmask of phrases already covered */
159279  int *piToken, /* OUT: First token of proposed snippet */
159280  int *piScore, /* OUT: "Score" for this snippet */
159281  u64 *pmCover, /* OUT: Bitmask of phrases covered */
159282  u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
159283 ){
159284  int iStart = pIter->iCurrent; /* First token of snippet */
159285  int iScore = 0; /* Score of this snippet */
159286  int i; /* Loop counter */
159287  u64 mCover = 0; /* Mask of phrases covered by this snippet */
159288  u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
159289 
159290  for(i=0; i<pIter->nPhrase; i++){
159291  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
159292  if( pPhrase->pTail ){
159293  char *pCsr = pPhrase->pTail;
159294  int iCsr = pPhrase->iTail;
159295 
159296  while( iCsr<(iStart+pIter->nSnippet) ){
159297  int j;
159298  u64 mPhrase = (u64)1 << i;
159299  u64 mPos = (u64)1 << (iCsr - iStart);
159300  assert( iCsr>=iStart );
159301  if( (mCover|mCovered)&mPhrase ){
159302  iScore++;
159303  }else{
159304  iScore += 1000;
159305  }
159306  mCover |= mPhrase;
159307 
159308  for(j=0; j<pPhrase->nToken; j++){
159309  mHighlight |= (mPos>>j);
159310  }
159311 
159312  if( 0==(*pCsr & 0x0FE) ) break;
159313  fts3GetDeltaPosition(&pCsr, &iCsr);
159314  }
159315  }
159316  }
159317 
159318  /* Set the output variables before returning. */
159319  *piToken = iStart;
159320  *piScore = iScore;
159321  *pmCover = mCover;
159322  *pmHighlight = mHighlight;
159323 }
159324 
159325 /*
159326 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
159327 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
159328 */
159329 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
159330  SnippetIter *p = (SnippetIter *)ctx;
159331  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
159332  char *pCsr;
159333  int rc;
159334 
159335  pPhrase->nToken = pExpr->pPhrase->nToken;
159336  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
159337  assert( rc==SQLITE_OK || pCsr==0 );
159338  if( pCsr ){
159339  int iFirst = 0;
159340  pPhrase->pList = pCsr;
159341  fts3GetDeltaPosition(&pCsr, &iFirst);
159342  assert( iFirst>=0 );
159343  pPhrase->pHead = pCsr;
159344  pPhrase->pTail = pCsr;
159345  pPhrase->iHead = iFirst;
159346  pPhrase->iTail = iFirst;
159347  }else{
159348  assert( rc!=SQLITE_OK || (
159349  pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
159350  ));
159351  }
159352 
159353  return rc;
159354 }
159355 
159356 /*
159357 ** Select the fragment of text consisting of nFragment contiguous tokens
159358 ** from column iCol that represent the "best" snippet. The best snippet
159359 ** is the snippet with the highest score, where scores are calculated
159360 ** by adding:
159361 **
159362 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
159363 **
159364 ** (b) +1000 points for the first occurrence of each matchable phrase in
159365 ** the snippet for which the corresponding mCovered bit is not set.
159366 **
159367 ** The selected snippet parameters are stored in structure *pFragment before
159368 ** returning. The score of the selected snippet is stored in *piScore
159369 ** before returning.
159370 */
159371 static int fts3BestSnippet(
159372  int nSnippet, /* Desired snippet length */
159373  Fts3Cursor *pCsr, /* Cursor to create snippet for */
159374  int iCol, /* Index of column to create snippet from */
159375  u64 mCovered, /* Mask of phrases already covered */
159376  u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
159377  SnippetFragment *pFragment, /* OUT: Best snippet found */
159378  int *piScore /* OUT: Score of snippet pFragment */
159379 ){
159380  int rc; /* Return Code */
159381  int nList; /* Number of phrases in expression */
159382  SnippetIter sIter; /* Iterates through snippet candidates */
159383  int nByte; /* Number of bytes of space to allocate */
159384  int iBestScore = -1; /* Best snippet score found so far */
159385  int i; /* Loop counter */
159386 
159387  memset(&sIter, 0, sizeof(sIter));
159388 
159389  /* Iterate through the phrases in the expression to count them. The same
159390  ** callback makes sure the doclists are loaded for each phrase.
159391  */
159392  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
159393  if( rc!=SQLITE_OK ){
159394  return rc;
159395  }
159396 
159397  /* Now that it is known how many phrases there are, allocate and zero
159398  ** the required space using malloc().
159399  */
159400  nByte = sizeof(SnippetPhrase) * nList;
159401  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
159402  if( !sIter.aPhrase ){
159403  return SQLITE_NOMEM;
159404  }
159405  memset(sIter.aPhrase, 0, nByte);
159406 
159407  /* Initialize the contents of the SnippetIter object. Then iterate through
159408  ** the set of phrases in the expression to populate the aPhrase[] array.
159409  */
159410  sIter.pCsr = pCsr;
159411  sIter.iCol = iCol;
159412  sIter.nSnippet = nSnippet;
159413  sIter.nPhrase = nList;
159414  sIter.iCurrent = -1;
159415  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
159416  if( rc==SQLITE_OK ){
159417 
159418  /* Set the *pmSeen output variable. */
159419  for(i=0; i<nList; i++){
159420  if( sIter.aPhrase[i].pHead ){
159421  *pmSeen |= (u64)1 << i;
159422  }
159423  }
159424 
159425  /* Loop through all candidate snippets. Store the best snippet in
159426  ** *pFragment. Store its associated 'score' in iBestScore.
159427  */
159428  pFragment->iCol = iCol;
159429  while( !fts3SnippetNextCandidate(&sIter) ){
159430  int iPos;
159431  int iScore;
159432  u64 mCover;
159433  u64 mHighlite;
159434  fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
159435  assert( iScore>=0 );
159436  if( iScore>iBestScore ){
159437  pFragment->iPos = iPos;
159438  pFragment->hlmask = mHighlite;
159439  pFragment->covered = mCover;
159440  iBestScore = iScore;
159441  }
159442  }
159443 
159444  *piScore = iBestScore;
159445  }
159446  sqlite3_free(sIter.aPhrase);
159447  return rc;
159448 }
159449 
159450 
159451 /*
159452 ** Append a string to the string-buffer passed as the first argument.
159453 **
159454 ** If nAppend is negative, then the length of the string zAppend is
159455 ** determined using strlen().
159456 */
159457 static int fts3StringAppend(
159458  StrBuffer *pStr, /* Buffer to append to */
159459  const char *zAppend, /* Pointer to data to append to buffer */
159460  int nAppend /* Size of zAppend in bytes (or -1) */
159461 ){
159462  if( nAppend<0 ){
159463  nAppend = (int)strlen(zAppend);
159464  }
159465 
159466  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
159467  ** to grow the buffer until so that it is big enough to accomadate the
159468  ** appended data.
159469  */
159470  if( pStr->n+nAppend+1>=pStr->nAlloc ){
159471  int nAlloc = pStr->nAlloc+nAppend+100;
159472  char *zNew = sqlite3_realloc(pStr->z, nAlloc);
159473  if( !zNew ){
159474  return SQLITE_NOMEM;
159475  }
159476  pStr->z = zNew;
159477  pStr->nAlloc = nAlloc;
159478  }
159479  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
159480 
159481  /* Append the data to the string buffer. */
159482  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
159483  pStr->n += nAppend;
159484  pStr->z[pStr->n] = '\0';
159485 
159486  return SQLITE_OK;
159487 }
159488 
159489 /*
159490 ** The fts3BestSnippet() function often selects snippets that end with a
159491 ** query term. That is, the final term of the snippet is always a term
159492 ** that requires highlighting. For example, if 'X' is a highlighted term
159493 ** and '.' is a non-highlighted term, BestSnippet() may select:
159494 **
159495 ** ........X.....X
159496 **
159497 ** This function "shifts" the beginning of the snippet forward in the
159498 ** document so that there are approximately the same number of
159499 ** non-highlighted terms to the right of the final highlighted term as there
159500 ** are to the left of the first highlighted term. For example, to this:
159501 **
159502 ** ....X.....X....
159503 **
159504 ** This is done as part of extracting the snippet text, not when selecting
159505 ** the snippet. Snippet selection is done based on doclists only, so there
159506 ** is no way for fts3BestSnippet() to know whether or not the document
159507 ** actually contains terms that follow the final highlighted term.
159508 */
159509 static int fts3SnippetShift(
159510  Fts3Table *pTab, /* FTS3 table snippet comes from */
159511  int iLangid, /* Language id to use in tokenizing */
159512  int nSnippet, /* Number of tokens desired for snippet */
159513  const char *zDoc, /* Document text to extract snippet from */
159514  int nDoc, /* Size of buffer zDoc in bytes */
159515  int *piPos, /* IN/OUT: First token of snippet */
159516  u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
159517 ){
159518  u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
159519 
159520  if( hlmask ){
159521  int nLeft; /* Tokens to the left of first highlight */
159522  int nRight; /* Tokens to the right of last highlight */
159523  int nDesired; /* Ideal number of tokens to shift forward */
159524 
159525  for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
159526  for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
159527  nDesired = (nLeft-nRight)/2;
159528 
159529  /* Ideally, the start of the snippet should be pushed forward in the
159530  ** document nDesired tokens. This block checks if there are actually
159531  ** nDesired tokens to the right of the snippet. If so, *piPos and
159532  ** *pHlMask are updated to shift the snippet nDesired tokens to the
159533  ** right. Otherwise, the snippet is shifted by the number of tokens
159534  ** available.
159535  */
159536  if( nDesired>0 ){
159537  int nShift; /* Number of tokens to shift snippet by */
159538  int iCurrent = 0; /* Token counter */
159539  int rc; /* Return Code */
159540  sqlite3_tokenizer_module *pMod;
159541  sqlite3_tokenizer_cursor *pC;
159542  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
159543 
159544  /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
159545  ** or more tokens in zDoc/nDoc.
159546  */
159547  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
159548  if( rc!=SQLITE_OK ){
159549  return rc;
159550  }
159551  while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
159552  const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
159553  rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
159554  }
159555  pMod->xClose(pC);
159556  if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
159557 
159558  nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
159559  assert( nShift<=nDesired );
159560  if( nShift>0 ){
159561  *piPos += nShift;
159562  *pHlmask = hlmask >> nShift;
159563  }
159564  }
159565  }
159566  return SQLITE_OK;
159567 }
159568 
159569 /*
159570 ** Extract the snippet text for fragment pFragment from cursor pCsr and
159571 ** append it to string buffer pOut.
159572 */
159573 static int fts3SnippetText(
159574  Fts3Cursor *pCsr, /* FTS3 Cursor */
159575  SnippetFragment *pFragment, /* Snippet to extract */
159576  int iFragment, /* Fragment number */
159577  int isLast, /* True for final fragment in snippet */
159578  int nSnippet, /* Number of tokens in extracted snippet */
159579  const char *zOpen, /* String inserted before highlighted term */
159580  const char *zClose, /* String inserted after highlighted term */
159581  const char *zEllipsis, /* String inserted between snippets */
159582  StrBuffer *pOut /* Write output here */
159583 ){
159584  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159585  int rc; /* Return code */
159586  const char *zDoc; /* Document text to extract snippet from */
159587  int nDoc; /* Size of zDoc in bytes */
159588  int iCurrent = 0; /* Current token number of document */
159589  int iEnd = 0; /* Byte offset of end of current token */
159590  int isShiftDone = 0; /* True after snippet is shifted */
159591  int iPos = pFragment->iPos; /* First token of snippet */
159592  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
159593  int iCol = pFragment->iCol+1; /* Query column to extract text from */
159594  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
159595  sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
159596 
159597  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
159598  if( zDoc==0 ){
159599  if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
159600  return SQLITE_NOMEM;
159601  }
159602  return SQLITE_OK;
159603  }
159604  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
159605 
159606  /* Open a token cursor on the document. */
159607  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
159608  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
159609  if( rc!=SQLITE_OK ){
159610  return rc;
159611  }
159612 
159613  while( rc==SQLITE_OK ){
159614  const char *ZDUMMY; /* Dummy argument used with tokenizer */
159615  int DUMMY1 = -1; /* Dummy argument used with tokenizer */
159616  int iBegin = 0; /* Offset in zDoc of start of token */
159617  int iFin = 0; /* Offset in zDoc of end of token */
159618  int isHighlight = 0; /* True for highlighted terms */
159619 
159620  /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
159621  ** in the FTS code the variable that the third argument to xNext points to
159622  ** is initialized to zero before the first (*but not necessarily
159623  ** subsequent*) call to xNext(). This is done for a particular application
159624  ** that needs to know whether or not the tokenizer is being used for
159625  ** snippet generation or for some other purpose.
159626  **
159627  ** Extreme care is required when writing code to depend on this
159628  ** initialization. It is not a documented part of the tokenizer interface.
159629  ** If a tokenizer is used directly by any code outside of FTS, this
159630  ** convention might not be respected. */
159631  rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
159632  if( rc!=SQLITE_OK ){
159633  if( rc==SQLITE_DONE ){
159634  /* Special case - the last token of the snippet is also the last token
159635  ** of the column. Append any punctuation that occurred between the end
159636  ** of the previous token and the end of the document to the output.
159637  ** Then break out of the loop. */
159638  rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
159639  }
159640  break;
159641  }
159642  if( iCurrent<iPos ){ continue; }
159643 
159644  if( !isShiftDone ){
159645  int n = nDoc - iBegin;
159646  rc = fts3SnippetShift(
159647  pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
159648  );
159649  isShiftDone = 1;
159650 
159651  /* Now that the shift has been done, check if the initial "..." are
159652  ** required. They are required if (a) this is not the first fragment,
159653  ** or (b) this fragment does not begin at position 0 of its column.
159654  */
159655  if( rc==SQLITE_OK ){
159656  if( iPos>0 || iFragment>0 ){
159657  rc = fts3StringAppend(pOut, zEllipsis, -1);
159658  }else if( iBegin ){
159659  rc = fts3StringAppend(pOut, zDoc, iBegin);
159660  }
159661  }
159662  if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
159663  }
159664 
159665  if( iCurrent>=(iPos+nSnippet) ){
159666  if( isLast ){
159667  rc = fts3StringAppend(pOut, zEllipsis, -1);
159668  }
159669  break;
159670  }
159671 
159672  /* Set isHighlight to true if this term should be highlighted. */
159673  isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
159674 
159675  if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
159676  if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
159677  if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
159678  if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
159679 
159680  iEnd = iFin;
159681  }
159682 
159683  pMod->xClose(pC);
159684  return rc;
159685 }
159686 
159687 
159688 /*
159689 ** This function is used to count the entries in a column-list (a
159690 ** delta-encoded list of term offsets within a single column of a single
159691 ** row). When this function is called, *ppCollist should point to the
159692 ** beginning of the first varint in the column-list (the varint that
159693 ** contains the position of the first matching term in the column data).
159694 ** Before returning, *ppCollist is set to point to the first byte after
159695 ** the last varint in the column-list (either the 0x00 signifying the end
159696 ** of the position-list, or the 0x01 that precedes the column number of
159697 ** the next column in the position-list).
159698 **
159699 ** The number of elements in the column-list is returned.
159700 */
159701 static int fts3ColumnlistCount(char **ppCollist){
159702  char *pEnd = *ppCollist;
159703  char c = 0;
159704  int nEntry = 0;
159705 
159706  /* A column-list is terminated by either a 0x01 or 0x00. */
159707  while( 0xFE & (*pEnd | c) ){
159708  c = *pEnd++ & 0x80;
159709  if( !c ) nEntry++;
159710  }
159711 
159712  *ppCollist = pEnd;
159713  return nEntry;
159714 }
159715 
159716 /*
159717 ** This function gathers 'y' or 'b' data for a single phrase.
159718 */
159719 static void fts3ExprLHits(
159720  Fts3Expr *pExpr, /* Phrase expression node */
159721  MatchInfo *p /* Matchinfo context */
159722 ){
159723  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
159724  int iStart;
159725  Fts3Phrase *pPhrase = pExpr->pPhrase;
159726  char *pIter = pPhrase->doclist.pList;
159727  int iCol = 0;
159728 
159729  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
159730  if( p->flag==FTS3_MATCHINFO_LHITS ){
159731  iStart = pExpr->iPhrase * p->nCol;
159732  }else{
159733  iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
159734  }
159735 
159736  while( 1 ){
159737  int nHit = fts3ColumnlistCount(&pIter);
159738  if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
159739  if( p->flag==FTS3_MATCHINFO_LHITS ){
159740  p->aMatchinfo[iStart + iCol] = (u32)nHit;
159741  }else if( nHit ){
159742  p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
159743  }
159744  }
159745  assert( *pIter==0x00 || *pIter==0x01 );
159746  if( *pIter!=0x01 ) break;
159747  pIter++;
159748  pIter += fts3GetVarint32(pIter, &iCol);
159749  }
159750 }
159751 
159752 /*
159753 ** Gather the results for matchinfo directives 'y' and 'b'.
159754 */
159755 static void fts3ExprLHitGather(
159756  Fts3Expr *pExpr,
159757  MatchInfo *p
159758 ){
159759  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
159760  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
159761  if( pExpr->pLeft ){
159762  fts3ExprLHitGather(pExpr->pLeft, p);
159763  fts3ExprLHitGather(pExpr->pRight, p);
159764  }else{
159765  fts3ExprLHits(pExpr, p);
159766  }
159767  }
159768 }
159769 
159770 /*
159771 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
159772 ** for a single query.
159773 **
159774 ** fts3ExprIterate() callback to load the 'global' elements of a
159775 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
159776 ** of the matchinfo array that are constant for all rows returned by the
159777 ** current query.
159778 **
159779 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
159780 ** function populates Matchinfo.aMatchinfo[] as follows:
159781 **
159782 ** for(iCol=0; iCol<nCol; iCol++){
159783 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
159784 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
159785 ** }
159786 **
159787 ** where X is the number of matches for phrase iPhrase is column iCol of all
159788 ** rows of the table. Y is the number of rows for which column iCol contains
159789 ** at least one instance of phrase iPhrase.
159790 **
159791 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
159792 ** Y values are set to nDoc, where nDoc is the number of documents in the
159793 ** file system. This is done because the full-text index doclist is required
159794 ** to calculate these values properly, and the full-text index doclist is
159795 ** not available for deferred tokens.
159796 */
159797 static int fts3ExprGlobalHitsCb(
159798  Fts3Expr *pExpr, /* Phrase expression node */
159799  int iPhrase, /* Phrase number (numbered from zero) */
159800  void *pCtx /* Pointer to MatchInfo structure */
159801 ){
159802  MatchInfo *p = (MatchInfo *)pCtx;
159803  return sqlite3Fts3EvalPhraseStats(
159804  p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
159805  );
159806 }
159807 
159808 /*
159809 ** fts3ExprIterate() callback used to collect the "local" part of the
159810 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
159811 ** array that are different for each row returned by the query.
159812 */
159813 static int fts3ExprLocalHitsCb(
159814  Fts3Expr *pExpr, /* Phrase expression node */
159815  int iPhrase, /* Phrase number */
159816  void *pCtx /* Pointer to MatchInfo structure */
159817 ){
159818  int rc = SQLITE_OK;
159819  MatchInfo *p = (MatchInfo *)pCtx;
159820  int iStart = iPhrase * p->nCol * 3;
159821  int i;
159822 
159823  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
159824  char *pCsr;
159825  rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
159826  if( pCsr ){
159827  p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
159828  }else{
159829  p->aMatchinfo[iStart+i*3] = 0;
159830  }
159831  }
159832 
159833  return rc;
159834 }
159835 
159836 static int fts3MatchinfoCheck(
159837  Fts3Table *pTab,
159838  char cArg,
159839  char **pzErr
159840 ){
159841  if( (cArg==FTS3_MATCHINFO_NPHRASE)
159842  || (cArg==FTS3_MATCHINFO_NCOL)
159843  || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
159844  || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
159845  || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
159846  || (cArg==FTS3_MATCHINFO_LCS)
159847  || (cArg==FTS3_MATCHINFO_HITS)
159848  || (cArg==FTS3_MATCHINFO_LHITS)
159849  || (cArg==FTS3_MATCHINFO_LHITS_BM)
159850  ){
159851  return SQLITE_OK;
159852  }
159853  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
159854  return SQLITE_ERROR;
159855 }
159856 
159857 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
159858  int nVal; /* Number of integers output by cArg */
159859 
159860  switch( cArg ){
159861  case FTS3_MATCHINFO_NDOC:
159862  case FTS3_MATCHINFO_NPHRASE:
159863  case FTS3_MATCHINFO_NCOL:
159864  nVal = 1;
159865  break;
159866 
159867  case FTS3_MATCHINFO_AVGLENGTH:
159868  case FTS3_MATCHINFO_LENGTH:
159869  case FTS3_MATCHINFO_LCS:
159870  nVal = pInfo->nCol;
159871  break;
159872 
159873  case FTS3_MATCHINFO_LHITS:
159874  nVal = pInfo->nCol * pInfo->nPhrase;
159875  break;
159876 
159877  case FTS3_MATCHINFO_LHITS_BM:
159878  nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
159879  break;
159880 
159881  default:
159882  assert( cArg==FTS3_MATCHINFO_HITS );
159883  nVal = pInfo->nCol * pInfo->nPhrase * 3;
159884  break;
159885  }
159886 
159887  return nVal;
159888 }
159889 
159890 static int fts3MatchinfoSelectDoctotal(
159891  Fts3Table *pTab,
159892  sqlite3_stmt **ppStmt,
159893  sqlite3_int64 *pnDoc,
159894  const char **paLen
159895 ){
159896  sqlite3_stmt *pStmt;
159897  const char *a;
159898  sqlite3_int64 nDoc;
159899 
159900  if( !*ppStmt ){
159901  int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
159902  if( rc!=SQLITE_OK ) return rc;
159903  }
159904  pStmt = *ppStmt;
159905  assert( sqlite3_data_count(pStmt)==1 );
159906 
159907  a = sqlite3_column_blob(pStmt, 0);
159908  a += sqlite3Fts3GetVarint(a, &nDoc);
159909  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
159910  *pnDoc = (u32)nDoc;
159911 
159912  if( paLen ) *paLen = a;
159913  return SQLITE_OK;
159914 }
159915 
159916 /*
159917 ** An instance of the following structure is used to store state while
159918 ** iterating through a multi-column position-list corresponding to the
159919 ** hits for a single phrase on a single row in order to calculate the
159920 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
159921 */
159922 typedef struct LcsIterator LcsIterator;
159923 struct LcsIterator {
159924  Fts3Expr *pExpr; /* Pointer to phrase expression */
159925  int iPosOffset; /* Tokens count up to end of this phrase */
159926  char *pRead; /* Cursor used to iterate through aDoclist */
159927  int iPos; /* Current position */
159928 };
159929 
159930 /*
159931 ** If LcsIterator.iCol is set to the following value, the iterator has
159932 ** finished iterating through all offsets for all columns.
159933 */
159934 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
159935 
159936 static int fts3MatchinfoLcsCb(
159937  Fts3Expr *pExpr, /* Phrase expression node */
159938  int iPhrase, /* Phrase number (numbered from zero) */
159939  void *pCtx /* Pointer to MatchInfo structure */
159940 ){
159941  LcsIterator *aIter = (LcsIterator *)pCtx;
159942  aIter[iPhrase].pExpr = pExpr;
159943  return SQLITE_OK;
159944 }
159945 
159946 /*
159947 ** Advance the iterator passed as an argument to the next position. Return
159948 ** 1 if the iterator is at EOF or if it now points to the start of the
159949 ** position list for the next column.
159950 */
159951 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
159952  char *pRead = pIter->pRead;
159953  sqlite3_int64 iRead;
159954  int rc = 0;
159955 
159956  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
159957  if( iRead==0 || iRead==1 ){
159958  pRead = 0;
159959  rc = 1;
159960  }else{
159961  pIter->iPos += (int)(iRead-2);
159962  }
159963 
159964  pIter->pRead = pRead;
159965  return rc;
159966 }
159967 
159968 /*
159969 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
159970 **
159971 ** If the call is successful, the longest-common-substring lengths for each
159972 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
159973 ** array before returning. SQLITE_OK is returned in this case.
159974 **
159975 ** Otherwise, if an error occurs, an SQLite error code is returned and the
159976 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
159977 ** undefined.
159978 */
159979 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
159980  LcsIterator *aIter;
159981  int i;
159982  int iCol;
159983  int nToken = 0;
159984 
159985  /* Allocate and populate the array of LcsIterator objects. The array
159986  ** contains one element for each matchable phrase in the query.
159987  **/
159988  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
159989  if( !aIter ) return SQLITE_NOMEM;
159990  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
159991  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
159992 
159993  for(i=0; i<pInfo->nPhrase; i++){
159994  LcsIterator *pIter = &aIter[i];
159995  nToken -= pIter->pExpr->pPhrase->nToken;
159996  pIter->iPosOffset = nToken;
159997  }
159998 
159999  for(iCol=0; iCol<pInfo->nCol; iCol++){
160000  int nLcs = 0; /* LCS value for this column */
160001  int nLive = 0; /* Number of iterators in aIter not at EOF */
160002 
160003  for(i=0; i<pInfo->nPhrase; i++){
160004  int rc;
160005  LcsIterator *pIt = &aIter[i];
160006  rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
160007  if( rc!=SQLITE_OK ) return rc;
160008  if( pIt->pRead ){
160009  pIt->iPos = pIt->iPosOffset;
160010  fts3LcsIteratorAdvance(&aIter[i]);
160011  nLive++;
160012  }
160013  }
160014 
160015  while( nLive>0 ){
160016  LcsIterator *pAdv = 0; /* The iterator to advance by one position */
160017  int nThisLcs = 0; /* LCS for the current iterator positions */
160018 
160019  for(i=0; i<pInfo->nPhrase; i++){
160020  LcsIterator *pIter = &aIter[i];
160021  if( pIter->pRead==0 ){
160022  /* This iterator is already at EOF for this column. */
160023  nThisLcs = 0;
160024  }else{
160025  if( pAdv==0 || pIter->iPos<pAdv->iPos ){
160026  pAdv = pIter;
160027  }
160028  if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
160029  nThisLcs++;
160030  }else{
160031  nThisLcs = 1;
160032  }
160033  if( nThisLcs>nLcs ) nLcs = nThisLcs;
160034  }
160035  }
160036  if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
160037  }
160038 
160039  pInfo->aMatchinfo[iCol] = nLcs;
160040  }
160041 
160042  sqlite3_free(aIter);
160043  return SQLITE_OK;
160044 }
160045 
160046 /*
160047 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
160048 ** be returned by the matchinfo() function. Argument zArg contains the
160049 ** format string passed as the second argument to matchinfo (or the
160050 ** default value "pcx" if no second argument was specified). The format
160051 ** string has already been validated and the pInfo->aMatchinfo[] array
160052 ** is guaranteed to be large enough for the output.
160053 **
160054 ** If bGlobal is true, then populate all fields of the matchinfo() output.
160055 ** If it is false, then assume that those fields that do not change between
160056 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
160057 ** have already been populated.
160058 **
160059 ** Return SQLITE_OK if successful, or an SQLite error code if an error
160060 ** occurs. If a value other than SQLITE_OK is returned, the state the
160061 ** pInfo->aMatchinfo[] buffer is left in is undefined.
160062 */
160063 static int fts3MatchinfoValues(
160064  Fts3Cursor *pCsr, /* FTS3 cursor object */
160065  int bGlobal, /* True to grab the global stats */
160066  MatchInfo *pInfo, /* Matchinfo context object */
160067  const char *zArg /* Matchinfo format string */
160068 ){
160069  int rc = SQLITE_OK;
160070  int i;
160071  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160072  sqlite3_stmt *pSelect = 0;
160073 
160074  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
160075  pInfo->flag = zArg[i];
160076  switch( zArg[i] ){
160077  case FTS3_MATCHINFO_NPHRASE:
160078  if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
160079  break;
160080 
160081  case FTS3_MATCHINFO_NCOL:
160082  if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
160083  break;
160084 
160085  case FTS3_MATCHINFO_NDOC:
160086  if( bGlobal ){
160087  sqlite3_int64 nDoc = 0;
160088  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
160089  pInfo->aMatchinfo[0] = (u32)nDoc;
160090  }
160091  break;
160092 
160093  case FTS3_MATCHINFO_AVGLENGTH:
160094  if( bGlobal ){
160095  sqlite3_int64 nDoc; /* Number of rows in table */
160096  const char *a; /* Aggregate column length array */
160097 
160098  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
160099  if( rc==SQLITE_OK ){
160100  int iCol;
160101  for(iCol=0; iCol<pInfo->nCol; iCol++){
160102  u32 iVal;
160103  sqlite3_int64 nToken;
160104  a += sqlite3Fts3GetVarint(a, &nToken);
160105  iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
160106  pInfo->aMatchinfo[iCol] = iVal;
160107  }
160108  }
160109  }
160110  break;
160111 
160112  case FTS3_MATCHINFO_LENGTH: {
160113  sqlite3_stmt *pSelectDocsize = 0;
160114  rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
160115  if( rc==SQLITE_OK ){
160116  int iCol;
160117  const char *a = sqlite3_column_blob(pSelectDocsize, 0);
160118  for(iCol=0; iCol<pInfo->nCol; iCol++){
160119  sqlite3_int64 nToken;
160120  a += sqlite3Fts3GetVarint(a, &nToken);
160121  pInfo->aMatchinfo[iCol] = (u32)nToken;
160122  }
160123  }
160124  sqlite3_reset(pSelectDocsize);
160125  break;
160126  }
160127 
160128  case FTS3_MATCHINFO_LCS:
160129  rc = fts3ExprLoadDoclists(pCsr, 0, 0);
160130  if( rc==SQLITE_OK ){
160131  rc = fts3MatchinfoLcs(pCsr, pInfo);
160132  }
160133  break;
160134 
160135  case FTS3_MATCHINFO_LHITS_BM:
160136  case FTS3_MATCHINFO_LHITS: {
160137  int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
160138  memset(pInfo->aMatchinfo, 0, nZero);
160139  fts3ExprLHitGather(pCsr->pExpr, pInfo);
160140  break;
160141  }
160142 
160143  default: {
160144  Fts3Expr *pExpr;
160145  assert( zArg[i]==FTS3_MATCHINFO_HITS );
160146  pExpr = pCsr->pExpr;
160147  rc = fts3ExprLoadDoclists(pCsr, 0, 0);
160148  if( rc!=SQLITE_OK ) break;
160149  if( bGlobal ){
160150  if( pCsr->pDeferred ){
160151  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
160152  if( rc!=SQLITE_OK ) break;
160153  }
160154  rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
160155  sqlite3Fts3EvalTestDeferred(pCsr, &rc);
160156  if( rc!=SQLITE_OK ) break;
160157  }
160158  (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
160159  break;
160160  }
160161  }
160162 
160163  pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
160164  }
160165 
160166  sqlite3_reset(pSelect);
160167  return rc;
160168 }
160169 
160170 
160171 /*
160172 ** Populate pCsr->aMatchinfo[] with data for the current row. The
160173 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
160174 */
160175 static void fts3GetMatchinfo(
160176  sqlite3_context *pCtx, /* Return results here */
160177  Fts3Cursor *pCsr, /* FTS3 Cursor object */
160178  const char *zArg /* Second argument to matchinfo() function */
160179 ){
160180  MatchInfo sInfo;
160181  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160182  int rc = SQLITE_OK;
160183  int bGlobal = 0; /* Collect 'global' stats as well as local */
160184 
160185  u32 *aOut = 0;
160186  void (*xDestroyOut)(void*) = 0;
160187 
160188  memset(&sInfo, 0, sizeof(MatchInfo));
160189  sInfo.pCursor = pCsr;
160190  sInfo.nCol = pTab->nColumn;
160191 
160192  /* If there is cached matchinfo() data, but the format string for the
160193  ** cache does not match the format string for this request, discard
160194  ** the cached data. */
160195  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
160196  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
160197  pCsr->pMIBuffer = 0;
160198  }
160199 
160200  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
160201  ** matchinfo function has been called for this query. In this case
160202  ** allocate the array used to accumulate the matchinfo data and
160203  ** initialize those elements that are constant for every row.
160204  */
160205  if( pCsr->pMIBuffer==0 ){
160206  int nMatchinfo = 0; /* Number of u32 elements in match-info */
160207  int i; /* Used to iterate through zArg */
160208 
160209  /* Determine the number of phrases in the query */
160210  pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
160211  sInfo.nPhrase = pCsr->nPhrase;
160212 
160213  /* Determine the number of integers in the buffer returned by this call. */
160214  for(i=0; zArg[i]; i++){
160215  char *zErr = 0;
160216  if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
160217  sqlite3_result_error(pCtx, zErr, -1);
160218  sqlite3_free(zErr);
160219  return;
160220  }
160221  nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
160222  }
160223 
160224  /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
160225  pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
160226  if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
160227 
160228  pCsr->isMatchinfoNeeded = 1;
160229  bGlobal = 1;
160230  }
160231 
160232  if( rc==SQLITE_OK ){
160233  xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
160234  if( xDestroyOut==0 ){
160235  rc = SQLITE_NOMEM;
160236  }
160237  }
160238 
160239  if( rc==SQLITE_OK ){
160240  sInfo.aMatchinfo = aOut;
160241  sInfo.nPhrase = pCsr->nPhrase;
160242  rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
160243  if( bGlobal ){
160244  fts3MIBufferSetGlobal(pCsr->pMIBuffer);
160245  }
160246  }
160247 
160248  if( rc!=SQLITE_OK ){
160249  sqlite3_result_error_code(pCtx, rc);
160250  if( xDestroyOut ) xDestroyOut(aOut);
160251  }else{
160252  int n = pCsr->pMIBuffer->nElem * sizeof(u32);
160253  sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
160254  }
160255 }
160256 
160257 /*
160258 ** Implementation of snippet() function.
160259 */
160260 SQLITE_PRIVATE void sqlite3Fts3Snippet(
160261  sqlite3_context *pCtx, /* SQLite function call context */
160262  Fts3Cursor *pCsr, /* Cursor object */
160263  const char *zStart, /* Snippet start text - "<b>" */
160264  const char *zEnd, /* Snippet end text - "</b>" */
160265  const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
160266  int iCol, /* Extract snippet from this column */
160267  int nToken /* Approximate number of tokens in snippet */
160268 ){
160269  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160270  int rc = SQLITE_OK;
160271  int i;
160272  StrBuffer res = {0, 0, 0};
160273 
160274  /* The returned text includes up to four fragments of text extracted from
160275  ** the data in the current row. The first iteration of the for(...) loop
160276  ** below attempts to locate a single fragment of text nToken tokens in
160277  ** size that contains at least one instance of all phrases in the query
160278  ** expression that appear in the current row. If such a fragment of text
160279  ** cannot be found, the second iteration of the loop attempts to locate
160280  ** a pair of fragments, and so on.
160281  */
160282  int nSnippet = 0; /* Number of fragments in this snippet */
160283  SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
160284  int nFToken = -1; /* Number of tokens in each fragment */
160285 
160286  if( !pCsr->pExpr ){
160287  sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
160288  return;
160289  }
160290 
160291  for(nSnippet=1; 1; nSnippet++){
160292 
160293  int iSnip; /* Loop counter 0..nSnippet-1 */
160294  u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
160295  u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
160296 
160297  if( nToken>=0 ){
160298  nFToken = (nToken+nSnippet-1) / nSnippet;
160299  }else{
160300  nFToken = -1 * nToken;
160301  }
160302 
160303  for(iSnip=0; iSnip<nSnippet; iSnip++){
160304  int iBestScore = -1; /* Best score of columns checked so far */
160305  int iRead; /* Used to iterate through columns */
160306  SnippetFragment *pFragment = &aSnippet[iSnip];
160307 
160308  memset(pFragment, 0, sizeof(*pFragment));
160309 
160310  /* Loop through all columns of the table being considered for snippets.
160311  ** If the iCol argument to this function was negative, this means all
160312  ** columns of the FTS3 table. Otherwise, only column iCol is considered.
160313  */
160314  for(iRead=0; iRead<pTab->nColumn; iRead++){
160315  SnippetFragment sF = {0, 0, 0, 0};
160316  int iS = 0;
160317  if( iCol>=0 && iRead!=iCol ) continue;
160318 
160319  /* Find the best snippet of nFToken tokens in column iRead. */
160320  rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
160321  if( rc!=SQLITE_OK ){
160322  goto snippet_out;
160323  }
160324  if( iS>iBestScore ){
160325  *pFragment = sF;
160326  iBestScore = iS;
160327  }
160328  }
160329 
160330  mCovered |= pFragment->covered;
160331  }
160332 
160333  /* If all query phrases seen by fts3BestSnippet() are present in at least
160334  ** one of the nSnippet snippet fragments, break out of the loop.
160335  */
160336  assert( (mCovered&mSeen)==mCovered );
160337  if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
160338  }
160339 
160340  assert( nFToken>0 );
160341 
160342  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
160343  rc = fts3SnippetText(pCsr, &aSnippet[i],
160344  i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
160345  );
160346  }
160347 
160348  snippet_out:
160349  sqlite3Fts3SegmentsClose(pTab);
160350  if( rc!=SQLITE_OK ){
160351  sqlite3_result_error_code(pCtx, rc);
160352  sqlite3_free(res.z);
160353  }else{
160354  sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
160355  }
160356 }
160357 
160358 
160359 typedef struct TermOffset TermOffset;
160360 typedef struct TermOffsetCtx TermOffsetCtx;
160361 
160362 struct TermOffset {
160363  char *pList; /* Position-list */
160364  int iPos; /* Position just read from pList */
160365  int iOff; /* Offset of this term from read positions */
160366 };
160367 
160368 struct TermOffsetCtx {
160369  Fts3Cursor *pCsr;
160370  int iCol; /* Column of table to populate aTerm for */
160371  int iTerm;
160372  sqlite3_int64 iDocid;
160373  TermOffset *aTerm;
160374 };
160375 
160376 /*
160377 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
160378 */
160379 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
160380  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
160381  int nTerm; /* Number of tokens in phrase */
160382  int iTerm; /* For looping through nTerm phrase terms */
160383  char *pList; /* Pointer to position list for phrase */
160384  int iPos = 0; /* First position in position-list */
160385  int rc;
160386 
160387  UNUSED_PARAMETER(iPhrase);
160388  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
160389  nTerm = pExpr->pPhrase->nToken;
160390  if( pList ){
160391  fts3GetDeltaPosition(&pList, &iPos);
160392  assert( iPos>=0 );
160393  }
160394 
160395  for(iTerm=0; iTerm<nTerm; iTerm++){
160396  TermOffset *pT = &p->aTerm[p->iTerm++];
160397  pT->iOff = nTerm-iTerm-1;
160398  pT->pList = pList;
160399  pT->iPos = iPos;
160400  }
160401 
160402  return rc;
160403 }
160404 
160405 /*
160406 ** Implementation of offsets() function.
160407 */
160408 SQLITE_PRIVATE void sqlite3Fts3Offsets(
160409  sqlite3_context *pCtx, /* SQLite function call context */
160410  Fts3Cursor *pCsr /* Cursor object */
160411 ){
160412  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160413  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
160414  int rc; /* Return Code */
160415  int nToken; /* Number of tokens in query */
160416  int iCol; /* Column currently being processed */
160417  StrBuffer res = {0, 0, 0}; /* Result string */
160418  TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
160419 
160420  if( !pCsr->pExpr ){
160421  sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
160422  return;
160423  }
160424 
160425  memset(&sCtx, 0, sizeof(sCtx));
160426  assert( pCsr->isRequireSeek==0 );
160427 
160428  /* Count the number of terms in the query */
160429  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
160430  if( rc!=SQLITE_OK ) goto offsets_out;
160431 
160432  /* Allocate the array of TermOffset iterators. */
160433  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
160434  if( 0==sCtx.aTerm ){
160435  rc = SQLITE_NOMEM;
160436  goto offsets_out;
160437  }
160438  sCtx.iDocid = pCsr->iPrevId;
160439  sCtx.pCsr = pCsr;
160440 
160441  /* Loop through the table columns, appending offset information to
160442  ** string-buffer res for each column.
160443  */
160444  for(iCol=0; iCol<pTab->nColumn; iCol++){
160445  sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
160446  const char *ZDUMMY; /* Dummy argument used with xNext() */
160447  int NDUMMY = 0; /* Dummy argument used with xNext() */
160448  int iStart = 0;
160449  int iEnd = 0;
160450  int iCurrent = 0;
160451  const char *zDoc;
160452  int nDoc;
160453 
160454  /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
160455  ** no way that this operation can fail, so the return code from
160456  ** fts3ExprIterate() can be discarded.
160457  */
160458  sCtx.iCol = iCol;
160459  sCtx.iTerm = 0;
160460  (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
160461 
160462  /* Retreive the text stored in column iCol. If an SQL NULL is stored
160463  ** in column iCol, jump immediately to the next iteration of the loop.
160464  ** If an OOM occurs while retrieving the data (this can happen if SQLite
160465  ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
160466  ** to the caller.
160467  */
160468  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
160469  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
160470  if( zDoc==0 ){
160471  if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
160472  continue;
160473  }
160474  rc = SQLITE_NOMEM;
160475  goto offsets_out;
160476  }
160477 
160478  /* Initialize a tokenizer iterator to iterate through column iCol. */
160479  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
160480  zDoc, nDoc, &pC
160481  );
160482  if( rc!=SQLITE_OK ) goto offsets_out;
160483 
160484  rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
160485  while( rc==SQLITE_OK ){
160486  int i; /* Used to loop through terms */
160487  int iMinPos = 0x7FFFFFFF; /* Position of next token */
160488  TermOffset *pTerm = 0; /* TermOffset associated with next token */
160489 
160490  for(i=0; i<nToken; i++){
160491  TermOffset *pT = &sCtx.aTerm[i];
160492  if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
160493  iMinPos = pT->iPos-pT->iOff;
160494  pTerm = pT;
160495  }
160496  }
160497 
160498  if( !pTerm ){
160499  /* All offsets for this column have been gathered. */
160500  rc = SQLITE_DONE;
160501  }else{
160502  assert( iCurrent<=iMinPos );
160503  if( 0==(0xFE&*pTerm->pList) ){
160504  pTerm->pList = 0;
160505  }else{
160506  fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
160507  }
160508  while( rc==SQLITE_OK && iCurrent<iMinPos ){
160509  rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
160510  }
160511  if( rc==SQLITE_OK ){
160512  char aBuffer[64];
160513  sqlite3_snprintf(sizeof(aBuffer), aBuffer,
160514  "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
160515  );
160516  rc = fts3StringAppend(&res, aBuffer, -1);
160517  }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
160518  rc = FTS_CORRUPT_VTAB;
160519  }
160520  }
160521  }
160522  if( rc==SQLITE_DONE ){
160523  rc = SQLITE_OK;
160524  }
160525 
160526  pMod->xClose(pC);
160527  if( rc!=SQLITE_OK ) goto offsets_out;
160528  }
160529 
160530  offsets_out:
160531  sqlite3_free(sCtx.aTerm);
160532  assert( rc!=SQLITE_DONE );
160533  sqlite3Fts3SegmentsClose(pTab);
160534  if( rc!=SQLITE_OK ){
160535  sqlite3_result_error_code(pCtx, rc);
160536  sqlite3_free(res.z);
160537  }else{
160538  sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
160539  }
160540  return;
160541 }
160542 
160543 /*
160544 ** Implementation of matchinfo() function.
160545 */
160546 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
160547  sqlite3_context *pContext, /* Function call context */
160548  Fts3Cursor *pCsr, /* FTS3 table cursor */
160549  const char *zArg /* Second arg to matchinfo() function */
160550 ){
160551  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
160552  const char *zFormat;
160553 
160554  if( zArg ){
160555  zFormat = zArg;
160556  }else{
160557  zFormat = FTS3_MATCHINFO_DEFAULT;
160558  }
160559 
160560  if( !pCsr->pExpr ){
160561  sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
160562  return;
160563  }else{
160564  /* Retrieve matchinfo() data. */
160565  fts3GetMatchinfo(pContext, pCsr, zFormat);
160566  sqlite3Fts3SegmentsClose(pTab);
160567  }
160568 }
160569 
160570 #endif
160571 
160572 /************** End of fts3_snippet.c ****************************************/
160573 /************** Begin file fts3_unicode.c ************************************/
160574 /*
160575 ** 2012 May 24
160576 **
160577 ** The author disclaims copyright to this source code. In place of
160578 ** a legal notice, here is a blessing:
160579 **
160580 ** May you do good and not evil.
160581 ** May you find forgiveness for yourself and forgive others.
160582 ** May you share freely, never taking more than you give.
160583 **
160584 ******************************************************************************
160585 **
160586 ** Implementation of the "unicode" full-text-search tokenizer.
160587 */
160588 
160589 #ifndef SQLITE_DISABLE_FTS3_UNICODE
160590 
160591 /* #include "fts3Int.h" */
160592 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
160593 
160594 /* #include <assert.h> */
160595 /* #include <stdlib.h> */
160596 /* #include <stdio.h> */
160597 /* #include <string.h> */
160598 
160599 /* #include "fts3_tokenizer.h" */
160600 
160601 /*
160602 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
160603 ** from the sqlite3 source file utf.c. If this file is compiled as part
160604 ** of the amalgamation, they are not required.
160605 */
160606 #ifndef SQLITE_AMALGAMATION
160607 
160608 static const unsigned char sqlite3Utf8Trans1[] = {
160609  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
160610  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
160611  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
160612  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
160613  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
160614  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
160615  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
160616  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
160617 };
160618 
160619 #define READ_UTF8(zIn, zTerm, c) \
160620  c = *(zIn++); \
160621  if( c>=0xc0 ){ \
160622  c = sqlite3Utf8Trans1[c-0xc0]; \
160623  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
160624  c = (c<<6) + (0x3f & *(zIn++)); \
160625  } \
160626  if( c<0x80 \
160627  || (c&0xFFFFF800)==0xD800 \
160628  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
160629  }
160630 
160631 #define WRITE_UTF8(zOut, c) { \
160632  if( c<0x00080 ){ \
160633  *zOut++ = (u8)(c&0xFF); \
160634  } \
160635  else if( c<0x00800 ){ \
160636  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
160637  *zOut++ = 0x80 + (u8)(c & 0x3F); \
160638  } \
160639  else if( c<0x10000 ){ \
160640  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
160641  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
160642  *zOut++ = 0x80 + (u8)(c & 0x3F); \
160643  }else{ \
160644  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
160645  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
160646  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
160647  *zOut++ = 0x80 + (u8)(c & 0x3F); \
160648  } \
160649 }
160650 
160651 #endif /* ifndef SQLITE_AMALGAMATION */
160652 
160653 typedef struct unicode_tokenizer unicode_tokenizer;
160654 typedef struct unicode_cursor unicode_cursor;
160655 
160656 struct unicode_tokenizer {
160657  sqlite3_tokenizer base;
160658  int bRemoveDiacritic;
160659  int nException;
160660  int *aiException;
160661 };
160662 
160663 struct unicode_cursor {
160664  sqlite3_tokenizer_cursor base;
160665  const unsigned char *aInput; /* Input text being tokenized */
160666  int nInput; /* Size of aInput[] in bytes */
160667  int iOff; /* Current offset within aInput[] */
160668  int iToken; /* Index of next token to be returned */
160669  char *zToken; /* storage for current token */
160670  int nAlloc; /* space allocated at zToken */
160671 };
160672 
160673 
160674 /*
160675 ** Destroy a tokenizer allocated by unicodeCreate().
160676 */
160677 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
160678  if( pTokenizer ){
160679  unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
160680  sqlite3_free(p->aiException);
160681  sqlite3_free(p);
160682  }
160683  return SQLITE_OK;
160684 }
160685 
160686 /*
160687 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
160688 ** statement has specified that the tokenizer for this table shall consider
160689 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
160690 ** token characters (if bAlnum==1).
160691 **
160692 ** For each codepoint in the zIn/nIn string, this function checks if the
160693 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
160694 ** If so, no action is taken. Otherwise, the codepoint is added to the
160695 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
160696 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
160697 ** codepoints in the aiException[] array.
160698 **
160699 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
160700 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
160701 ** It is not possible to change the behavior of the tokenizer with respect
160702 ** to these codepoints.
160703 */
160704 static int unicodeAddExceptions(
160705  unicode_tokenizer *p, /* Tokenizer to add exceptions to */
160706  int bAlnum, /* Replace Isalnum() return value with this */
160707  const char *zIn, /* Array of characters to make exceptions */
160708  int nIn /* Length of z in bytes */
160709 ){
160710  const unsigned char *z = (const unsigned char *)zIn;
160711  const unsigned char *zTerm = &z[nIn];
160712  int iCode;
160713  int nEntry = 0;
160714 
160715  assert( bAlnum==0 || bAlnum==1 );
160716 
160717  while( z<zTerm ){
160718  READ_UTF8(z, zTerm, iCode);
160719  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
160720  if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
160721  && sqlite3FtsUnicodeIsdiacritic(iCode)==0
160722  ){
160723  nEntry++;
160724  }
160725  }
160726 
160727  if( nEntry ){
160728  int *aNew; /* New aiException[] array */
160729  int nNew; /* Number of valid entries in array aNew[] */
160730 
160731  aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
160732  if( aNew==0 ) return SQLITE_NOMEM;
160733  nNew = p->nException;
160734 
160735  z = (const unsigned char *)zIn;
160736  while( z<zTerm ){
160737  READ_UTF8(z, zTerm, iCode);
160738  if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
160739  && sqlite3FtsUnicodeIsdiacritic(iCode)==0
160740  ){
160741  int i, j;
160742  for(i=0; i<nNew && aNew[i]<iCode; i++);
160743  for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
160744  aNew[i] = iCode;
160745  nNew++;
160746  }
160747  }
160748  p->aiException = aNew;
160749  p->nException = nNew;
160750  }
160751 
160752  return SQLITE_OK;
160753 }
160754 
160755 /*
160756 ** Return true if the p->aiException[] array contains the value iCode.
160757 */
160758 static int unicodeIsException(unicode_tokenizer *p, int iCode){
160759  if( p->nException>0 ){
160760  int *a = p->aiException;
160761  int iLo = 0;
160762  int iHi = p->nException-1;
160763 
160764  while( iHi>=iLo ){
160765  int iTest = (iHi + iLo) / 2;
160766  if( iCode==a[iTest] ){
160767  return 1;
160768  }else if( iCode>a[iTest] ){
160769  iLo = iTest+1;
160770  }else{
160771  iHi = iTest-1;
160772  }
160773  }
160774  }
160775 
160776  return 0;
160777 }
160778 
160779 /*
160780 ** Return true if, for the purposes of tokenization, codepoint iCode is
160781 ** considered a token character (not a separator).
160782 */
160783 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
160784  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
160785  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
160786 }
160787 
160788 /*
160789 ** Create a new tokenizer instance.
160790 */
160791 static int unicodeCreate(
160792  int nArg, /* Size of array argv[] */
160793  const char * const *azArg, /* Tokenizer creation arguments */
160794  sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
160795 ){
160796  unicode_tokenizer *pNew; /* New tokenizer object */
160797  int i;
160798  int rc = SQLITE_OK;
160799 
160800  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
160801  if( pNew==NULL ) return SQLITE_NOMEM;
160802  memset(pNew, 0, sizeof(unicode_tokenizer));
160803  pNew->bRemoveDiacritic = 1;
160804 
160805  for(i=0; rc==SQLITE_OK && i<nArg; i++){
160806  const char *z = azArg[i];
160807  int n = (int)strlen(z);
160808 
160809  if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
160810  pNew->bRemoveDiacritic = 1;
160811  }
160812  else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
160813  pNew->bRemoveDiacritic = 0;
160814  }
160815  else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
160816  rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
160817  }
160818  else if( n>=11 && memcmp("separators=", z, 11)==0 ){
160819  rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
160820  }
160821  else{
160822  /* Unrecognized argument */
160823  rc = SQLITE_ERROR;
160824  }
160825  }
160826 
160827  if( rc!=SQLITE_OK ){
160828  unicodeDestroy((sqlite3_tokenizer *)pNew);
160829  pNew = 0;
160830  }
160831  *pp = (sqlite3_tokenizer *)pNew;
160832  return rc;
160833 }
160834 
160835 /*
160836 ** Prepare to begin tokenizing a particular string. The input
160837 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
160838 ** used to incrementally tokenize this string is returned in
160839 ** *ppCursor.
160840 */
160841 static int unicodeOpen(
160842  sqlite3_tokenizer *p, /* The tokenizer */
160843  const char *aInput, /* Input string */
160844  int nInput, /* Size of string aInput in bytes */
160845  sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
160846 ){
160847  unicode_cursor *pCsr;
160848 
160849  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
160850  if( pCsr==0 ){
160851  return SQLITE_NOMEM;
160852  }
160853  memset(pCsr, 0, sizeof(unicode_cursor));
160854 
160855  pCsr->aInput = (const unsigned char *)aInput;
160856  if( aInput==0 ){
160857  pCsr->nInput = 0;
160858  }else if( nInput<0 ){
160859  pCsr->nInput = (int)strlen(aInput);
160860  }else{
160861  pCsr->nInput = nInput;
160862  }
160863 
160864  *pp = &pCsr->base;
160865  UNUSED_PARAMETER(p);
160866  return SQLITE_OK;
160867 }
160868 
160869 /*
160870 ** Close a tokenization cursor previously opened by a call to
160871 ** simpleOpen() above.
160872 */
160873 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
160874  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
160875  sqlite3_free(pCsr->zToken);
160876  sqlite3_free(pCsr);
160877  return SQLITE_OK;
160878 }
160879 
160880 /*
160881 ** Extract the next token from a tokenization cursor. The cursor must
160882 ** have been opened by a prior call to simpleOpen().
160883 */
160884 static int unicodeNext(
160885  sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
160886  const char **paToken, /* OUT: Token text */
160887  int *pnToken, /* OUT: Number of bytes at *paToken */
160888  int *piStart, /* OUT: Starting offset of token */
160889  int *piEnd, /* OUT: Ending offset of token */
160890  int *piPos /* OUT: Position integer of token */
160891 ){
160892  unicode_cursor *pCsr = (unicode_cursor *)pC;
160893  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
160894  int iCode = 0;
160895  char *zOut;
160896  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
160897  const unsigned char *zStart = z;
160898  const unsigned char *zEnd;
160899  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
160900 
160901  /* Scan past any delimiter characters before the start of the next token.
160902  ** Return SQLITE_DONE early if this takes us all the way to the end of
160903  ** the input. */
160904  while( z<zTerm ){
160905  READ_UTF8(z, zTerm, iCode);
160906  if( unicodeIsAlnum(p, iCode) ) break;
160907  zStart = z;
160908  }
160909  if( zStart>=zTerm ) return SQLITE_DONE;
160910 
160911  zOut = pCsr->zToken;
160912  do {
160913  int iOut;
160914 
160915  /* Grow the output buffer if required. */
160916  if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
160917  char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
160918  if( !zNew ) return SQLITE_NOMEM;
160919  zOut = &zNew[zOut - pCsr->zToken];
160920  pCsr->zToken = zNew;
160921  pCsr->nAlloc += 64;
160922  }
160923 
160924  /* Write the folded case of the last character read to the output */
160925  zEnd = z;
160926  iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
160927  if( iOut ){
160928  WRITE_UTF8(zOut, iOut);
160929  }
160930 
160931  /* If the cursor is not at EOF, read the next character */
160932  if( z>=zTerm ) break;
160933  READ_UTF8(z, zTerm, iCode);
160934  }while( unicodeIsAlnum(p, iCode)
160935  || sqlite3FtsUnicodeIsdiacritic(iCode)
160936  );
160937 
160938  /* Set the output variables and return. */
160939  pCsr->iOff = (int)(z - pCsr->aInput);
160940  *paToken = pCsr->zToken;
160941  *pnToken = (int)(zOut - pCsr->zToken);
160942  *piStart = (int)(zStart - pCsr->aInput);
160943  *piEnd = (int)(zEnd - pCsr->aInput);
160944  *piPos = pCsr->iToken++;
160945  return SQLITE_OK;
160946 }
160947 
160948 /*
160949 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
160950 ** structure for the unicode tokenizer.
160951 */
160952 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
160953  static const sqlite3_tokenizer_module module = {
160954  0,
160955  unicodeCreate,
160956  unicodeDestroy,
160957  unicodeOpen,
160958  unicodeClose,
160959  unicodeNext,
160960  0,
160961  };
160962  *ppModule = &module;
160963 }
160964 
160965 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
160966 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
160967 
160968 /************** End of fts3_unicode.c ****************************************/
160969 /************** Begin file fts3_unicode2.c ***********************************/
160970 /*
160971 ** 2012 May 25
160972 **
160973 ** The author disclaims copyright to this source code. In place of
160974 ** a legal notice, here is a blessing:
160975 **
160976 ** May you do good and not evil.
160977 ** May you find forgiveness for yourself and forgive others.
160978 ** May you share freely, never taking more than you give.
160979 **
160980 ******************************************************************************
160981 */
160982 
160983 /*
160984 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
160985 */
160986 
160987 #ifndef SQLITE_DISABLE_FTS3_UNICODE
160988 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
160989 
160990 /* #include <assert.h> */
160991 
160992 /*
160993 ** Return true if the argument corresponds to a unicode codepoint
160994 ** classified as either a letter or a number. Otherwise false.
160995 **
160996 ** The results are undefined if the value passed to this function
160997 ** is less than zero.
160998 */
160999 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
161000  /* Each unsigned integer in the following array corresponds to a contiguous
161001  ** range of unicode codepoints that are not either letters or numbers (i.e.
161002  ** codepoints for which this function should return 0).
161003  **
161004  ** The most significant 22 bits in each 32-bit value contain the first
161005  ** codepoint in the range. The least significant 10 bits are used to store
161006  ** the size of the range (always at least 1). In other words, the value
161007  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
161008  ** C. It is not possible to represent a range larger than 1023 codepoints
161009  ** using this format.
161010  */
161011  static const unsigned int aEntry[] = {
161012  0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
161013  0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
161014  0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
161015  0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
161016  0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
161017  0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
161018  0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
161019  0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
161020  0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
161021  0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
161022  0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
161023  0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
161024  0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
161025  0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
161026  0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
161027  0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
161028  0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
161029  0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
161030  0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
161031  0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
161032  0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
161033  0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
161034  0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
161035  0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
161036  0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
161037  0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
161038  0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
161039  0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
161040  0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
161041  0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
161042  0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
161043  0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
161044  0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
161045  0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
161046  0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
161047  0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
161048  0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
161049  0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
161050  0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
161051  0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
161052  0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
161053  0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
161054  0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
161055  0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
161056  0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
161057  0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
161058  0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
161059  0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
161060  0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
161061  0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
161062  0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
161063  0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
161064  0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
161065  0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
161066  0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
161067  0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
161068  0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
161069  0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
161070  0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
161071  0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
161072  0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
161073  0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
161074  0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
161075  0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
161076  0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
161077  0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
161078  0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
161079  0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
161080  0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
161081  0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
161082  0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
161083  0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
161084  0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
161085  0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
161086  0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
161087  0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
161088  0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
161089  0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
161090  0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
161091  0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
161092  0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
161093  0x380400F0,
161094  };
161095  static const unsigned int aAscii[4] = {
161096  0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
161097  };
161098 
161099  if( c<128 ){
161100  return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
161101  }else if( c<(1<<22) ){
161102  unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
161103  int iRes = 0;
161104  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
161105  int iLo = 0;
161106  while( iHi>=iLo ){
161107  int iTest = (iHi + iLo) / 2;
161108  if( key >= aEntry[iTest] ){
161109  iRes = iTest;
161110  iLo = iTest+1;
161111  }else{
161112  iHi = iTest-1;
161113  }
161114  }
161115  assert( aEntry[0]<key );
161116  assert( key>=aEntry[iRes] );
161117  return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
161118  }
161119  return 1;
161120 }
161121 
161122 
161123 /*
161124 ** If the argument is a codepoint corresponding to a lowercase letter
161125 ** in the ASCII range with a diacritic added, return the codepoint
161126 ** of the ASCII letter only. For example, if passed 235 - "LATIN
161127 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
161128 ** E"). The resuls of passing a codepoint that corresponds to an
161129 ** uppercase letter are undefined.
161130 */
161131 static int remove_diacritic(int c){
161132  unsigned short aDia[] = {
161133  0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
161134  2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
161135  2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
161136  2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
161137  3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
161138  3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
161139  4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
161140  6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
161141  61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
161142  61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
161143  62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
161144  62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
161145  62924, 63050, 63082, 63274, 63390,
161146  };
161147  char aChar[] = {
161148  '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
161149  'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
161150  's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
161151  'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
161152  'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
161153  '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
161154  'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
161155  'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
161156  'e', 'i', 'o', 'u', 'y',
161157  };
161158 
161159  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
161160  int iRes = 0;
161161  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
161162  int iLo = 0;
161163  while( iHi>=iLo ){
161164  int iTest = (iHi + iLo) / 2;
161165  if( key >= aDia[iTest] ){
161166  iRes = iTest;
161167  iLo = iTest+1;
161168  }else{
161169  iHi = iTest-1;
161170  }
161171  }
161172  assert( key>=aDia[iRes] );
161173  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
161174 }
161175 
161176 
161177 /*
161178 ** Return true if the argument interpreted as a unicode codepoint
161179 ** is a diacritical modifier character.
161180 */
161181 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
161182  unsigned int mask0 = 0x08029FDF;
161183  unsigned int mask1 = 0x000361F8;
161184  if( c<768 || c>817 ) return 0;
161185  return (c < 768+32) ?
161186  (mask0 & (1 << (c-768))) :
161187  (mask1 & (1 << (c-768-32)));
161188 }
161189 
161190 
161191 /*
161192 ** Interpret the argument as a unicode codepoint. If the codepoint
161193 ** is an upper case character that has a lower case equivalent,
161194 ** return the codepoint corresponding to the lower case version.
161195 ** Otherwise, return a copy of the argument.
161196 **
161197 ** The results are undefined if the value passed to this function
161198 ** is less than zero.
161199 */
161200 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
161201  /* Each entry in the following array defines a rule for folding a range
161202  ** of codepoints to lower case. The rule applies to a range of nRange
161203  ** codepoints starting at codepoint iCode.
161204  **
161205  ** If the least significant bit in flags is clear, then the rule applies
161206  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
161207  ** need to be folded). Or, if it is set, then the rule only applies to
161208  ** every second codepoint in the range, starting with codepoint C.
161209  **
161210  ** The 7 most significant bits in flags are an index into the aiOff[]
161211  ** array. If a specific codepoint C does require folding, then its lower
161212  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
161213  **
161214  ** The contents of this array are generated by parsing the CaseFolding.txt
161215  ** file distributed as part of the "Unicode Character Database". See
161216  ** http://www.unicode.org for details.
161217  */
161218  static const struct TableEntry {
161219  unsigned short iCode;
161220  unsigned char flags;
161221  unsigned char nRange;
161222  } aEntry[] = {
161223  {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
161224  {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
161225  {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
161226  {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
161227  {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
161228  {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
161229  {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
161230  {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
161231  {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
161232  {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
161233  {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
161234  {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
161235  {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
161236  {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
161237  {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
161238  {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
161239  {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
161240  {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
161241  {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
161242  {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
161243  {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
161244  {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
161245  {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
161246  {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
161247  {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
161248  {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
161249  {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
161250  {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
161251  {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
161252  {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
161253  {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
161254  {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
161255  {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
161256  {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
161257  {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
161258  {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
161259  {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
161260  {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
161261  {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
161262  {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
161263  {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
161264  {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
161265  {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
161266  {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
161267  {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
161268  {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
161269  {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
161270  {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
161271  {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
161272  {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
161273  {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
161274  {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
161275  {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
161276  {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
161277  {65313, 14, 26},
161278  };
161279  static const unsigned short aiOff[] = {
161280  1, 2, 8, 15, 16, 26, 28, 32,
161281  37, 38, 40, 48, 63, 64, 69, 71,
161282  79, 80, 116, 202, 203, 205, 206, 207,
161283  209, 210, 211, 213, 214, 217, 218, 219,
161284  775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
161285  54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
161286  57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
161287  65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
161288  65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
161289  65514, 65521, 65527, 65528, 65529,
161290  };
161291 
161292  int ret = c;
161293 
161294  assert( c>=0 );
161295  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
161296 
161297  if( c<128 ){
161298  if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
161299  }else if( c<65536 ){
161300  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
161301  int iLo = 0;
161302  int iRes = -1;
161303 
161304  while( iHi>=iLo ){
161305  int iTest = (iHi + iLo) / 2;
161306  int cmp = (c - aEntry[iTest].iCode);
161307  if( cmp>=0 ){
161308  iRes = iTest;
161309  iLo = iTest+1;
161310  }else{
161311  iHi = iTest-1;
161312  }
161313  }
161314  assert( iRes<0 || c>=aEntry[iRes].iCode );
161315 
161316  if( iRes>=0 ){
161317  const struct TableEntry *p = &aEntry[iRes];
161318  if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
161319  ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
161320  assert( ret>0 );
161321  }
161322  }
161323 
161324  if( bRemoveDiacritic ) ret = remove_diacritic(ret);
161325  }
161326 
161327  else if( c>=66560 && c<66600 ){
161328  ret = c + 40;
161329  }
161330 
161331  return ret;
161332 }
161333 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
161334 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
161335 
161336 /************** End of fts3_unicode2.c ***************************************/
161337 /************** Begin file rtree.c *******************************************/
161338 /*
161339 ** 2001 September 15
161340 **
161341 ** The author disclaims copyright to this source code. In place of
161342 ** a legal notice, here is a blessing:
161343 **
161344 ** May you do good and not evil.
161345 ** May you find forgiveness for yourself and forgive others.
161346 ** May you share freely, never taking more than you give.
161347 **
161348 *************************************************************************
161349 ** This file contains code for implementations of the r-tree and r*-tree
161350 ** algorithms packaged as an SQLite virtual table module.
161351 */
161352 
161353 /*
161354 ** Database Format of R-Tree Tables
161355 ** --------------------------------
161356 **
161357 ** The data structure for a single virtual r-tree table is stored in three
161358 ** native SQLite tables declared as follows. In each case, the '%' character
161359 ** in the table name is replaced with the user-supplied name of the r-tree
161360 ** table.
161361 **
161362 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
161363 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
161364 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
161365 **
161366 ** The data for each node of the r-tree structure is stored in the %_node
161367 ** table. For each node that is not the root node of the r-tree, there is
161368 ** an entry in the %_parent table associating the node with its parent.
161369 ** And for each row of data in the table, there is an entry in the %_rowid
161370 ** table that maps from the entries rowid to the id of the node that it
161371 ** is stored on.
161372 **
161373 ** The root node of an r-tree always exists, even if the r-tree table is
161374 ** empty. The nodeno of the root node is always 1. All other nodes in the
161375 ** table must be the same size as the root node. The content of each node
161376 ** is formatted as follows:
161377 **
161378 ** 1. If the node is the root node (node 1), then the first 2 bytes
161379 ** of the node contain the tree depth as a big-endian integer.
161380 ** For non-root nodes, the first 2 bytes are left unused.
161381 **
161382 ** 2. The next 2 bytes contain the number of entries currently
161383 ** stored in the node.
161384 **
161385 ** 3. The remainder of the node contains the node entries. Each entry
161386 ** consists of a single 8-byte integer followed by an even number
161387 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
161388 ** of a record. For internal nodes it is the node number of a
161389 ** child page.
161390 */
161391 
161392 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
161393 
161394 #ifndef SQLITE_CORE
161395 /* #include "sqlite3ext.h" */
161397 #else
161398 /* #include "sqlite3.h" */
161399 #endif
161400 
161401 /* #include <string.h> */
161402 /* #include <assert.h> */
161403 /* #include <stdio.h> */
161404 
161405 #ifndef SQLITE_AMALGAMATION
161406 #include "sqlite3rtree.h"
161407 typedef sqlite3_int64 i64;
161408 typedef unsigned char u8;
161409 typedef unsigned short u16;
161410 typedef unsigned int u32;
161411 #endif
161412 
161413 /* The following macro is used to suppress compiler warnings.
161414 */
161415 #ifndef UNUSED_PARAMETER
161416 # define UNUSED_PARAMETER(x) (void)(x)
161417 #endif
161418 
161419 typedef struct Rtree Rtree;
161420 typedef struct RtreeCursor RtreeCursor;
161421 typedef struct RtreeNode RtreeNode;
161422 typedef struct RtreeCell RtreeCell;
161423 typedef struct RtreeConstraint RtreeConstraint;
161424 typedef struct RtreeMatchArg RtreeMatchArg;
161425 typedef struct RtreeGeomCallback RtreeGeomCallback;
161426 typedef union RtreeCoord RtreeCoord;
161427 typedef struct RtreeSearchPoint RtreeSearchPoint;
161428 
161429 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
161430 #define RTREE_MAX_DIMENSIONS 5
161431 
161432 /* Size of hash table Rtree.aHash. This hash table is not expected to
161433 ** ever contain very many entries, so a fixed number of buckets is
161434 ** used.
161435 */
161436 #define HASHSIZE 97
161437 
161438 /* The xBestIndex method of this virtual table requires an estimate of
161439 ** the number of rows in the virtual table to calculate the costs of
161440 ** various strategies. If possible, this estimate is loaded from the
161441 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
161442 ** Otherwise, if no sqlite_stat1 entry is available, use
161443 ** RTREE_DEFAULT_ROWEST.
161444 */
161445 #define RTREE_DEFAULT_ROWEST 1048576
161446 #define RTREE_MIN_ROWEST 100
161447 
161448 /*
161449 ** An rtree virtual-table object.
161450 */
161451 struct Rtree {
161452  sqlite3_vtab base; /* Base class. Must be first */
161453  sqlite3 *db; /* Host database connection */
161454  int iNodeSize; /* Size in bytes of each node in the node table */
161455  u8 nDim; /* Number of dimensions */
161456  u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
161457  u8 nBytesPerCell; /* Bytes consumed per cell */
161458  int iDepth; /* Current depth of the r-tree structure */
161459  char *zDb; /* Name of database containing r-tree table */
161460  char *zName; /* Name of r-tree table */
161461  int nBusy; /* Current number of users of this structure */
161462  i64 nRowEst; /* Estimated number of rows in this table */
161463 
161464  /* List of nodes removed during a CondenseTree operation. List is
161465  ** linked together via the pointer normally used for hash chains -
161466  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
161467  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
161468  */
161469  RtreeNode *pDeleted;
161470  int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
161471 
161472  /* Statements to read/write/delete a record from xxx_node */
161473  sqlite3_stmt *pReadNode;
161474  sqlite3_stmt *pWriteNode;
161475  sqlite3_stmt *pDeleteNode;
161476 
161477  /* Statements to read/write/delete a record from xxx_rowid */
161478  sqlite3_stmt *pReadRowid;
161479  sqlite3_stmt *pWriteRowid;
161480  sqlite3_stmt *pDeleteRowid;
161481 
161482  /* Statements to read/write/delete a record from xxx_parent */
161483  sqlite3_stmt *pReadParent;
161484  sqlite3_stmt *pWriteParent;
161485  sqlite3_stmt *pDeleteParent;
161486 
161487  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
161488 };
161489 
161490 /* Possible values for Rtree.eCoordType: */
161491 #define RTREE_COORD_REAL32 0
161492 #define RTREE_COORD_INT32 1
161493 
161494 /*
161495 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
161496 ** only deal with integer coordinates. No floating point operations
161497 ** will be done.
161498 */
161499 #ifdef SQLITE_RTREE_INT_ONLY
161500  typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
161501  typedef int RtreeValue; /* Low accuracy coordinate */
161502 # define RTREE_ZERO 0
161503 #else
161504  typedef double RtreeDValue; /* High accuracy coordinate */
161505  typedef float RtreeValue; /* Low accuracy coordinate */
161506 # define RTREE_ZERO 0.0
161507 #endif
161508 
161509 /*
161510 ** When doing a search of an r-tree, instances of the following structure
161511 ** record intermediate results from the tree walk.
161512 **
161513 ** The id is always a node-id. For iLevel>=1 the id is the node-id of
161514 ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
161515 ** the id is of the parent node and the cell that RtreeSearchPoint
161516 ** represents is the iCell-th entry in the parent node.
161517 */
161518 struct RtreeSearchPoint {
161519  RtreeDValue rScore; /* The score for this node. Smallest goes first. */
161520  sqlite3_int64 id; /* Node ID */
161521  u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
161522  u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
161523  u8 iCell; /* Cell index within the node */
161524 };
161525 
161526 /*
161527 ** The minimum number of cells allowed for a node is a third of the
161528 ** maximum. In Gutman's notation:
161529 **
161530 ** m = M/3
161531 **
161532 ** If an R*-tree "Reinsert" operation is required, the same number of
161533 ** cells are removed from the overfull node and reinserted into the tree.
161534 */
161535 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
161536 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
161537 #define RTREE_MAXCELLS 51
161538 
161539 /*
161540 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
161541 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
161542 ** Therefore all non-root nodes must contain at least 3 entries. Since
161543 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
161544 ** 40 or less.
161545 */
161546 #define RTREE_MAX_DEPTH 40
161547 
161548 
161549 /*
161550 ** Number of entries in the cursor RtreeNode cache. The first entry is
161551 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
161552 ** entries cache the RtreeNode for the first elements of the priority queue.
161553 */
161554 #define RTREE_CACHE_SZ 5
161555 
161556 /*
161557 ** An rtree cursor object.
161558 */
161559 struct RtreeCursor {
161560  sqlite3_vtab_cursor base; /* Base class. Must be first */
161561  u8 atEOF; /* True if at end of search */
161562  u8 bPoint; /* True if sPoint is valid */
161563  int iStrategy; /* Copy of idxNum search parameter */
161564  int nConstraint; /* Number of entries in aConstraint */
161565  RtreeConstraint *aConstraint; /* Search constraints. */
161566  int nPointAlloc; /* Number of slots allocated for aPoint[] */
161567  int nPoint; /* Number of slots used in aPoint[] */
161568  int mxLevel; /* iLevel value for root of the tree */
161569  RtreeSearchPoint *aPoint; /* Priority queue for search points */
161570  RtreeSearchPoint sPoint; /* Cached next search point */
161571  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
161572  u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
161573 };
161574 
161575 /* Return the Rtree of a RtreeCursor */
161576 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
161577 
161578 /*
161579 ** A coordinate can be either a floating point number or a integer. All
161580 ** coordinates within a single R-Tree are always of the same time.
161581 */
161582 union RtreeCoord {
161583  RtreeValue f; /* Floating point value */
161584  int i; /* Integer value */
161585  u32 u; /* Unsigned for byte-order conversions */
161586 };
161587 
161588 /*
161589 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
161590 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
161591 ** variable pRtree points to the Rtree structure associated with the
161592 ** RtreeCoord.
161593 */
161594 #ifdef SQLITE_RTREE_INT_ONLY
161595 # define DCOORD(coord) ((RtreeDValue)coord.i)
161596 #else
161597 # define DCOORD(coord) ( \
161598  (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
161599  ((double)coord.f) : \
161600  ((double)coord.i) \
161601  )
161602 #endif
161603 
161604 /*
161605 ** A search constraint.
161606 */
161607 struct RtreeConstraint {
161608  int iCoord; /* Index of constrained coordinate */
161609  int op; /* Constraining operation */
161610  union {
161611  RtreeDValue rValue; /* Constraint value. */
161612  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
161613  int (*xQueryFunc)(sqlite3_rtree_query_info*);
161614  } u;
161615  sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
161616 };
161617 
161618 /* Possible values for RtreeConstraint.op */
161619 #define RTREE_EQ 0x41 /* A */
161620 #define RTREE_LE 0x42 /* B */
161621 #define RTREE_LT 0x43 /* C */
161622 #define RTREE_GE 0x44 /* D */
161623 #define RTREE_GT 0x45 /* E */
161624 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
161625 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
161626 
161627 
161628 /*
161629 ** An rtree structure node.
161630 */
161631 struct RtreeNode {
161632  RtreeNode *pParent; /* Parent node */
161633  i64 iNode; /* The node number */
161634  int nRef; /* Number of references to this node */
161635  int isDirty; /* True if the node needs to be written to disk */
161636  u8 *zData; /* Content of the node, as should be on disk */
161637  RtreeNode *pNext; /* Next node in this hash collision chain */
161638 };
161639 
161640 /* Return the number of cells in a node */
161641 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
161642 
161643 /*
161644 ** A single cell from a node, deserialized
161645 */
161646 struct RtreeCell {
161647  i64 iRowid; /* Node or entry ID */
161648  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
161649 };
161650 
161651 
161652 /*
161653 ** This object becomes the sqlite3_user_data() for the SQL functions
161654 ** that are created by sqlite3_rtree_geometry_callback() and
161655 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
161656 ** operators in order to constrain a search.
161657 **
161658 ** xGeom and xQueryFunc are the callback functions. Exactly one of
161659 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
161660 ** SQL function was created using sqlite3_rtree_geometry_callback() or
161661 ** sqlite3_rtree_query_callback().
161662 **
161663 ** This object is deleted automatically by the destructor mechanism in
161664 ** sqlite3_create_function_v2().
161665 */
161666 struct RtreeGeomCallback {
161667  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
161668  int (*xQueryFunc)(sqlite3_rtree_query_info*);
161669  void (*xDestructor)(void*);
161670  void *pContext;
161671 };
161672 
161673 
161674 /*
161675 ** Value for the first field of every RtreeMatchArg object. The MATCH
161676 ** operator tests that the first field of a blob operand matches this
161677 ** value to avoid operating on invalid blobs (which could cause a segfault).
161678 */
161679 #define RTREE_GEOMETRY_MAGIC 0x891245AB
161680 
161681 /*
161682 ** An instance of this structure (in the form of a BLOB) is returned by
161683 ** the SQL functions that sqlite3_rtree_geometry_callback() and
161684 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
161685 ** operand to the MATCH operator of an R-Tree.
161686 */
161687 struct RtreeMatchArg {
161688  u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
161689  RtreeGeomCallback cb; /* Info about the callback functions */
161690  int nParam; /* Number of parameters to the SQL function */
161691  sqlite3_value **apSqlParam; /* Original SQL parameter values */
161692  RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
161693 };
161694 
161695 #ifndef MAX
161696 # define MAX(x,y) ((x) < (y) ? (y) : (x))
161697 #endif
161698 #ifndef MIN
161699 # define MIN(x,y) ((x) > (y) ? (y) : (x))
161700 #endif
161701 
161702 /*
161703 ** Functions to deserialize a 16 bit integer, 32 bit real number and
161704 ** 64 bit integer. The deserialized value is returned.
161705 */
161706 static int readInt16(u8 *p){
161707  return (p[0]<<8) + p[1];
161708 }
161709 static void readCoord(u8 *p, RtreeCoord *pCoord){
161710  pCoord->u = (
161711  (((u32)p[0]) << 24) +
161712  (((u32)p[1]) << 16) +
161713  (((u32)p[2]) << 8) +
161714  (((u32)p[3]) << 0)
161715  );
161716 }
161717 static i64 readInt64(u8 *p){
161718  return (
161719  (((i64)p[0]) << 56) +
161720  (((i64)p[1]) << 48) +
161721  (((i64)p[2]) << 40) +
161722  (((i64)p[3]) << 32) +
161723  (((i64)p[4]) << 24) +
161724  (((i64)p[5]) << 16) +
161725  (((i64)p[6]) << 8) +
161726  (((i64)p[7]) << 0)
161727  );
161728 }
161729 
161730 /*
161731 ** Functions to serialize a 16 bit integer, 32 bit real number and
161732 ** 64 bit integer. The value returned is the number of bytes written
161733 ** to the argument buffer (always 2, 4 and 8 respectively).
161734 */
161735 static int writeInt16(u8 *p, int i){
161736  p[0] = (i>> 8)&0xFF;
161737  p[1] = (i>> 0)&0xFF;
161738  return 2;
161739 }
161740 static int writeCoord(u8 *p, RtreeCoord *pCoord){
161741  u32 i;
161742  assert( sizeof(RtreeCoord)==4 );
161743  assert( sizeof(u32)==4 );
161744  i = pCoord->u;
161745  p[0] = (i>>24)&0xFF;
161746  p[1] = (i>>16)&0xFF;
161747  p[2] = (i>> 8)&0xFF;
161748  p[3] = (i>> 0)&0xFF;
161749  return 4;
161750 }
161751 static int writeInt64(u8 *p, i64 i){
161752  p[0] = (i>>56)&0xFF;
161753  p[1] = (i>>48)&0xFF;
161754  p[2] = (i>>40)&0xFF;
161755  p[3] = (i>>32)&0xFF;
161756  p[4] = (i>>24)&0xFF;
161757  p[5] = (i>>16)&0xFF;
161758  p[6] = (i>> 8)&0xFF;
161759  p[7] = (i>> 0)&0xFF;
161760  return 8;
161761 }
161762 
161763 /*
161764 ** Increment the reference count of node p.
161765 */
161766 static void nodeReference(RtreeNode *p){
161767  if( p ){
161768  p->nRef++;
161769  }
161770 }
161771 
161772 /*
161773 ** Clear the content of node p (set all bytes to 0x00).
161774 */
161775 static void nodeZero(Rtree *pRtree, RtreeNode *p){
161776  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
161777  p->isDirty = 1;
161778 }
161779 
161780 /*
161781 ** Given a node number iNode, return the corresponding key to use
161782 ** in the Rtree.aHash table.
161783 */
161784 static int nodeHash(i64 iNode){
161785  return iNode % HASHSIZE;
161786 }
161787 
161788 /*
161789 ** Search the node hash table for node iNode. If found, return a pointer
161790 ** to it. Otherwise, return 0.
161791 */
161792 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
161793  RtreeNode *p;
161794  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
161795  return p;
161796 }
161797 
161798 /*
161799 ** Add node pNode to the node hash table.
161800 */
161801 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
161802  int iHash;
161803  assert( pNode->pNext==0 );
161804  iHash = nodeHash(pNode->iNode);
161805  pNode->pNext = pRtree->aHash[iHash];
161806  pRtree->aHash[iHash] = pNode;
161807 }
161808 
161809 /*
161810 ** Remove node pNode from the node hash table.
161811 */
161812 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
161813  RtreeNode **pp;
161814  if( pNode->iNode!=0 ){
161815  pp = &pRtree->aHash[nodeHash(pNode->iNode)];
161816  for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
161817  *pp = pNode->pNext;
161818  pNode->pNext = 0;
161819  }
161820 }
161821 
161822 /*
161823 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
161824 ** indicating that node has not yet been assigned a node number. It is
161825 ** assigned a node number when nodeWrite() is called to write the
161826 ** node contents out to the database.
161827 */
161828 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
161829  RtreeNode *pNode;
161830  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
161831  if( pNode ){
161832  memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
161833  pNode->zData = (u8 *)&pNode[1];
161834  pNode->nRef = 1;
161835  pNode->pParent = pParent;
161836  pNode->isDirty = 1;
161837  nodeReference(pParent);
161838  }
161839  return pNode;
161840 }
161841 
161842 /*
161843 ** Obtain a reference to an r-tree node.
161844 */
161845 static int nodeAcquire(
161846  Rtree *pRtree, /* R-tree structure */
161847  i64 iNode, /* Node number to load */
161848  RtreeNode *pParent, /* Either the parent node or NULL */
161849  RtreeNode **ppNode /* OUT: Acquired node */
161850 ){
161851  int rc;
161852  int rc2 = SQLITE_OK;
161853  RtreeNode *pNode;
161854 
161855  /* Check if the requested node is already in the hash table. If so,
161856  ** increase its reference count and return it.
161857  */
161858  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
161859  assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
161860  if( pParent && !pNode->pParent ){
161861  nodeReference(pParent);
161862  pNode->pParent = pParent;
161863  }
161864  pNode->nRef++;
161865  *ppNode = pNode;
161866  return SQLITE_OK;
161867  }
161868 
161869  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
161870  rc = sqlite3_step(pRtree->pReadNode);
161871  if( rc==SQLITE_ROW ){
161872  const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
161873  if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
161874  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
161875  if( !pNode ){
161876  rc2 = SQLITE_NOMEM;
161877  }else{
161878  pNode->pParent = pParent;
161879  pNode->zData = (u8 *)&pNode[1];
161880  pNode->nRef = 1;
161881  pNode->iNode = iNode;
161882  pNode->isDirty = 0;
161883  pNode->pNext = 0;
161884  memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
161885  nodeReference(pParent);
161886  }
161887  }
161888  }
161889  rc = sqlite3_reset(pRtree->pReadNode);
161890  if( rc==SQLITE_OK ) rc = rc2;
161891 
161892  /* If the root node was just loaded, set pRtree->iDepth to the height
161893  ** of the r-tree structure. A height of zero means all data is stored on
161894  ** the root node. A height of one means the children of the root node
161895  ** are the leaves, and so on. If the depth as specified on the root node
161896  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
161897  */
161898  if( pNode && iNode==1 ){
161899  pRtree->iDepth = readInt16(pNode->zData);
161900  if( pRtree->iDepth>RTREE_MAX_DEPTH ){
161901  rc = SQLITE_CORRUPT_VTAB;
161902  }
161903  }
161904 
161905  /* If no error has occurred so far, check if the "number of entries"
161906  ** field on the node is too large. If so, set the return code to
161907  ** SQLITE_CORRUPT_VTAB.
161908  */
161909  if( pNode && rc==SQLITE_OK ){
161910  if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
161911  rc = SQLITE_CORRUPT_VTAB;
161912  }
161913  }
161914 
161915  if( rc==SQLITE_OK ){
161916  if( pNode!=0 ){
161917  nodeHashInsert(pRtree, pNode);
161918  }else{
161919  rc = SQLITE_CORRUPT_VTAB;
161920  }
161921  *ppNode = pNode;
161922  }else{
161923  sqlite3_free(pNode);
161924  *ppNode = 0;
161925  }
161926 
161927  return rc;
161928 }
161929 
161930 /*
161931 ** Overwrite cell iCell of node pNode with the contents of pCell.
161932 */
161933 static void nodeOverwriteCell(
161934  Rtree *pRtree, /* The overall R-Tree */
161935  RtreeNode *pNode, /* The node into which the cell is to be written */
161936  RtreeCell *pCell, /* The cell to write */
161937  int iCell /* Index into pNode into which pCell is written */
161938 ){
161939  int ii;
161940  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
161941  p += writeInt64(p, pCell->iRowid);
161942  for(ii=0; ii<(pRtree->nDim*2); ii++){
161943  p += writeCoord(p, &pCell->aCoord[ii]);
161944  }
161945  pNode->isDirty = 1;
161946 }
161947 
161948 /*
161949 ** Remove the cell with index iCell from node pNode.
161950 */
161951 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
161952  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
161953  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
161954  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
161955  memmove(pDst, pSrc, nByte);
161956  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
161957  pNode->isDirty = 1;
161958 }
161959 
161960 /*
161961 ** Insert the contents of cell pCell into node pNode. If the insert
161962 ** is successful, return SQLITE_OK.
161963 **
161964 ** If there is not enough free space in pNode, return SQLITE_FULL.
161965 */
161966 static int nodeInsertCell(
161967  Rtree *pRtree, /* The overall R-Tree */
161968  RtreeNode *pNode, /* Write new cell into this node */
161969  RtreeCell *pCell /* The cell to be inserted */
161970 ){
161971  int nCell; /* Current number of cells in pNode */
161972  int nMaxCell; /* Maximum number of cells for pNode */
161973 
161974  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
161975  nCell = NCELL(pNode);
161976 
161977  assert( nCell<=nMaxCell );
161978  if( nCell<nMaxCell ){
161979  nodeOverwriteCell(pRtree, pNode, pCell, nCell);
161980  writeInt16(&pNode->zData[2], nCell+1);
161981  pNode->isDirty = 1;
161982  }
161983 
161984  return (nCell==nMaxCell);
161985 }
161986 
161987 /*
161988 ** If the node is dirty, write it out to the database.
161989 */
161990 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
161991  int rc = SQLITE_OK;
161992  if( pNode->isDirty ){
161993  sqlite3_stmt *p = pRtree->pWriteNode;
161994  if( pNode->iNode ){
161995  sqlite3_bind_int64(p, 1, pNode->iNode);
161996  }else{
161997  sqlite3_bind_null(p, 1);
161998  }
161999  sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
162000  sqlite3_step(p);
162001  pNode->isDirty = 0;
162002  rc = sqlite3_reset(p);
162003  if( pNode->iNode==0 && rc==SQLITE_OK ){
162004  pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
162005  nodeHashInsert(pRtree, pNode);
162006  }
162007  }
162008  return rc;
162009 }
162010 
162011 /*
162012 ** Release a reference to a node. If the node is dirty and the reference
162013 ** count drops to zero, the node data is written to the database.
162014 */
162015 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
162016  int rc = SQLITE_OK;
162017  if( pNode ){
162018  assert( pNode->nRef>0 );
162019  pNode->nRef--;
162020  if( pNode->nRef==0 ){
162021  if( pNode->iNode==1 ){
162022  pRtree->iDepth = -1;
162023  }
162024  if( pNode->pParent ){
162025  rc = nodeRelease(pRtree, pNode->pParent);
162026  }
162027  if( rc==SQLITE_OK ){
162028  rc = nodeWrite(pRtree, pNode);
162029  }
162030  nodeHashDelete(pRtree, pNode);
162031  sqlite3_free(pNode);
162032  }
162033  }
162034  return rc;
162035 }
162036 
162037 /*
162038 ** Return the 64-bit integer value associated with cell iCell of
162039 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
162040 ** an internal node, then the 64-bit integer is a child page number.
162041 */
162042 static i64 nodeGetRowid(
162043  Rtree *pRtree, /* The overall R-Tree */
162044  RtreeNode *pNode, /* The node from which to extract the ID */
162045  int iCell /* The cell index from which to extract the ID */
162046 ){
162047  assert( iCell<NCELL(pNode) );
162048  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
162049 }
162050 
162051 /*
162052 ** Return coordinate iCoord from cell iCell in node pNode.
162053 */
162054 static void nodeGetCoord(
162055  Rtree *pRtree, /* The overall R-Tree */
162056  RtreeNode *pNode, /* The node from which to extract a coordinate */
162057  int iCell, /* The index of the cell within the node */
162058  int iCoord, /* Which coordinate to extract */
162059  RtreeCoord *pCoord /* OUT: Space to write result to */
162060 ){
162061  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
162062 }
162063 
162064 /*
162065 ** Deserialize cell iCell of node pNode. Populate the structure pointed
162066 ** to by pCell with the results.
162067 */
162068 static void nodeGetCell(
162069  Rtree *pRtree, /* The overall R-Tree */
162070  RtreeNode *pNode, /* The node containing the cell to be read */
162071  int iCell, /* Index of the cell within the node */
162072  RtreeCell *pCell /* OUT: Write the cell contents here */
162073 ){
162074  u8 *pData;
162075  RtreeCoord *pCoord;
162076  int ii;
162077  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
162078  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
162079  pCoord = pCell->aCoord;
162080  for(ii=0; ii<pRtree->nDim*2; ii++){
162081  readCoord(&pData[ii*4], &pCoord[ii]);
162082  }
162083 }
162084 
162085 
162086 /* Forward declaration for the function that does the work of
162087 ** the virtual table module xCreate() and xConnect() methods.
162088 */
162089 static int rtreeInit(
162090  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
162091 );
162092 
162093 /*
162094 ** Rtree virtual table module xCreate method.
162095 */
162096 static int rtreeCreate(
162097  sqlite3 *db,
162098  void *pAux,
162099  int argc, const char *const*argv,
162100  sqlite3_vtab **ppVtab,
162101  char **pzErr
162102 ){
162103  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
162104 }
162105 
162106 /*
162107 ** Rtree virtual table module xConnect method.
162108 */
162109 static int rtreeConnect(
162110  sqlite3 *db,
162111  void *pAux,
162112  int argc, const char *const*argv,
162113  sqlite3_vtab **ppVtab,
162114  char **pzErr
162115 ){
162116  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
162117 }
162118 
162119 /*
162120 ** Increment the r-tree reference count.
162121 */
162122 static void rtreeReference(Rtree *pRtree){
162123  pRtree->nBusy++;
162124 }
162125 
162126 /*
162127 ** Decrement the r-tree reference count. When the reference count reaches
162128 ** zero the structure is deleted.
162129 */
162130 static void rtreeRelease(Rtree *pRtree){
162131  pRtree->nBusy--;
162132  if( pRtree->nBusy==0 ){
162133  sqlite3_finalize(pRtree->pReadNode);
162134  sqlite3_finalize(pRtree->pWriteNode);
162135  sqlite3_finalize(pRtree->pDeleteNode);
162136  sqlite3_finalize(pRtree->pReadRowid);
162137  sqlite3_finalize(pRtree->pWriteRowid);
162138  sqlite3_finalize(pRtree->pDeleteRowid);
162139  sqlite3_finalize(pRtree->pReadParent);
162140  sqlite3_finalize(pRtree->pWriteParent);
162141  sqlite3_finalize(pRtree->pDeleteParent);
162142  sqlite3_free(pRtree);
162143  }
162144 }
162145 
162146 /*
162147 ** Rtree virtual table module xDisconnect method.
162148 */
162149 static int rtreeDisconnect(sqlite3_vtab *pVtab){
162150  rtreeRelease((Rtree *)pVtab);
162151  return SQLITE_OK;
162152 }
162153 
162154 /*
162155 ** Rtree virtual table module xDestroy method.
162156 */
162157 static int rtreeDestroy(sqlite3_vtab *pVtab){
162158  Rtree *pRtree = (Rtree *)pVtab;
162159  int rc;
162160  char *zCreate = sqlite3_mprintf(
162161  "DROP TABLE '%q'.'%q_node';"
162162  "DROP TABLE '%q'.'%q_rowid';"
162163  "DROP TABLE '%q'.'%q_parent';",
162164  pRtree->zDb, pRtree->zName,
162165  pRtree->zDb, pRtree->zName,
162166  pRtree->zDb, pRtree->zName
162167  );
162168  if( !zCreate ){
162169  rc = SQLITE_NOMEM;
162170  }else{
162171  rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
162172  sqlite3_free(zCreate);
162173  }
162174  if( rc==SQLITE_OK ){
162175  rtreeRelease(pRtree);
162176  }
162177 
162178  return rc;
162179 }
162180 
162181 /*
162182 ** Rtree virtual table module xOpen method.
162183 */
162184 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
162185  int rc = SQLITE_NOMEM;
162186  RtreeCursor *pCsr;
162187 
162188  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
162189  if( pCsr ){
162190  memset(pCsr, 0, sizeof(RtreeCursor));
162191  pCsr->base.pVtab = pVTab;
162192  rc = SQLITE_OK;
162193  }
162194  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
162195 
162196  return rc;
162197 }
162198 
162199 
162200 /*
162201 ** Free the RtreeCursor.aConstraint[] array and its contents.
162202 */
162203 static void freeCursorConstraints(RtreeCursor *pCsr){
162204  if( pCsr->aConstraint ){
162205  int i; /* Used to iterate through constraint array */
162206  for(i=0; i<pCsr->nConstraint; i++){
162207  sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
162208  if( pInfo ){
162209  if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
162210  sqlite3_free(pInfo);
162211  }
162212  }
162213  sqlite3_free(pCsr->aConstraint);
162214  pCsr->aConstraint = 0;
162215  }
162216 }
162217 
162218 /*
162219 ** Rtree virtual table module xClose method.
162220 */
162221 static int rtreeClose(sqlite3_vtab_cursor *cur){
162222  Rtree *pRtree = (Rtree *)(cur->pVtab);
162223  int ii;
162224  RtreeCursor *pCsr = (RtreeCursor *)cur;
162225  freeCursorConstraints(pCsr);
162226  sqlite3_free(pCsr->aPoint);
162227  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
162228  sqlite3_free(pCsr);
162229  return SQLITE_OK;
162230 }
162231 
162232 /*
162233 ** Rtree virtual table module xEof method.
162234 **
162235 ** Return non-zero if the cursor does not currently point to a valid
162236 ** record (i.e if the scan has finished), or zero otherwise.
162237 */
162238 static int rtreeEof(sqlite3_vtab_cursor *cur){
162239  RtreeCursor *pCsr = (RtreeCursor *)cur;
162240  return pCsr->atEOF;
162241 }
162242 
162243 /*
162244 ** Convert raw bits from the on-disk RTree record into a coordinate value.
162245 ** The on-disk format is big-endian and needs to be converted for little-
162246 ** endian platforms. The on-disk record stores integer coordinates if
162247 ** eInt is true and it stores 32-bit floating point records if eInt is
162248 ** false. a[] is the four bytes of the on-disk record to be decoded.
162249 ** Store the results in "r".
162250 **
162251 ** There are three versions of this macro, one each for little-endian and
162252 ** big-endian processors and a third generic implementation. The endian-
162253 ** specific implementations are much faster and are preferred if the
162254 ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
162255 ** macro is part of sqliteInt.h and hence the endian-specific
162256 ** implementation will only be used if this module is compiled as part
162257 ** of the amalgamation.
162258 */
162259 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
162260 #define RTREE_DECODE_COORD(eInt, a, r) { \
162261  RtreeCoord c; /* Coordinate decoded */ \
162262  memcpy(&c.u,a,4); \
162263  c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
162264  ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
162265  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
162266 }
162267 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
162268 #define RTREE_DECODE_COORD(eInt, a, r) { \
162269  RtreeCoord c; /* Coordinate decoded */ \
162270  memcpy(&c.u,a,4); \
162271  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
162272 }
162273 #else
162274 #define RTREE_DECODE_COORD(eInt, a, r) { \
162275  RtreeCoord c; /* Coordinate decoded */ \
162276  c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
162277  +((u32)a[2]<<8) + a[3]; \
162278  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
162279 }
162280 #endif
162281 
162282 /*
162283 ** Check the RTree node or entry given by pCellData and p against the MATCH
162284 ** constraint pConstraint.
162285 */
162286 static int rtreeCallbackConstraint(
162287  RtreeConstraint *pConstraint, /* The constraint to test */
162288  int eInt, /* True if RTree holding integer coordinates */
162289  u8 *pCellData, /* Raw cell content */
162290  RtreeSearchPoint *pSearch, /* Container of this cell */
162291  sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
162292  int *peWithin /* OUT: visibility of the cell */
162293 ){
162294  int i; /* Loop counter */
162295  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
162296  int nCoord = pInfo->nCoord; /* No. of coordinates */
162297  int rc; /* Callback return code */
162298  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
162299 
162300  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
162301  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
162302 
162303  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
162304  pInfo->iRowid = readInt64(pCellData);
162305  }
162306  pCellData += 8;
162307  for(i=0; i<nCoord; i++, pCellData += 4){
162308  RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
162309  }
162310  if( pConstraint->op==RTREE_MATCH ){
162311  rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
162312  nCoord, aCoord, &i);
162313  if( i==0 ) *peWithin = NOT_WITHIN;
162314  *prScore = RTREE_ZERO;
162315  }else{
162316  pInfo->aCoord = aCoord;
162317  pInfo->iLevel = pSearch->iLevel - 1;
162318  pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
162319  pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
162320  rc = pConstraint->u.xQueryFunc(pInfo);
162321  if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
162322  if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
162323  *prScore = pInfo->rScore;
162324  }
162325  }
162326  return rc;
162327 }
162328 
162329 /*
162330 ** Check the internal RTree node given by pCellData against constraint p.
162331 ** If this constraint cannot be satisfied by any child within the node,
162332 ** set *peWithin to NOT_WITHIN.
162333 */
162334 static void rtreeNonleafConstraint(
162335  RtreeConstraint *p, /* The constraint to test */
162336  int eInt, /* True if RTree holds integer coordinates */
162337  u8 *pCellData, /* Raw cell content as appears on disk */
162338  int *peWithin /* Adjust downward, as appropriate */
162339 ){
162340  sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
162341 
162342  /* p->iCoord might point to either a lower or upper bound coordinate
162343  ** in a coordinate pair. But make pCellData point to the lower bound.
162344  */
162345  pCellData += 8 + 4*(p->iCoord&0xfe);
162346 
162347  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
162348  || p->op==RTREE_GT || p->op==RTREE_EQ );
162349  switch( p->op ){
162350  case RTREE_LE:
162351  case RTREE_LT:
162352  case RTREE_EQ:
162353  RTREE_DECODE_COORD(eInt, pCellData, val);
162354  /* val now holds the lower bound of the coordinate pair */
162355  if( p->u.rValue>=val ) return;
162356  if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
162357  /* Fall through for the RTREE_EQ case */
162358 
162359  default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
162360  pCellData += 4;
162361  RTREE_DECODE_COORD(eInt, pCellData, val);
162362  /* val now holds the upper bound of the coordinate pair */
162363  if( p->u.rValue<=val ) return;
162364  }
162365  *peWithin = NOT_WITHIN;
162366 }
162367 
162368 /*
162369 ** Check the leaf RTree cell given by pCellData against constraint p.
162370 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
162371 ** If the constraint is satisfied, leave *peWithin unchanged.
162372 **
162373 ** The constraint is of the form: xN op $val
162374 **
162375 ** The op is given by p->op. The xN is p->iCoord-th coordinate in
162376 ** pCellData. $val is given by p->u.rValue.
162377 */
162378 static void rtreeLeafConstraint(
162379  RtreeConstraint *p, /* The constraint to test */
162380  int eInt, /* True if RTree holds integer coordinates */
162381  u8 *pCellData, /* Raw cell content as appears on disk */
162382  int *peWithin /* Adjust downward, as appropriate */
162383 ){
162384  RtreeDValue xN; /* Coordinate value converted to a double */
162385 
162386  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
162387  || p->op==RTREE_GT || p->op==RTREE_EQ );
162388  pCellData += 8 + p->iCoord*4;
162389  RTREE_DECODE_COORD(eInt, pCellData, xN);
162390  switch( p->op ){
162391  case RTREE_LE: if( xN <= p->u.rValue ) return; break;
162392  case RTREE_LT: if( xN < p->u.rValue ) return; break;
162393  case RTREE_GE: if( xN >= p->u.rValue ) return; break;
162394  case RTREE_GT: if( xN > p->u.rValue ) return; break;
162395  default: if( xN == p->u.rValue ) return; break;
162396  }
162397  *peWithin = NOT_WITHIN;
162398 }
162399 
162400 /*
162401 ** One of the cells in node pNode is guaranteed to have a 64-bit
162402 ** integer value equal to iRowid. Return the index of this cell.
162403 */
162404 static int nodeRowidIndex(
162405  Rtree *pRtree,
162406  RtreeNode *pNode,
162407  i64 iRowid,
162408  int *piIndex
162409 ){
162410  int ii;
162411  int nCell = NCELL(pNode);
162412  assert( nCell<200 );
162413  for(ii=0; ii<nCell; ii++){
162414  if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
162415  *piIndex = ii;
162416  return SQLITE_OK;
162417  }
162418  }
162419  return SQLITE_CORRUPT_VTAB;
162420 }
162421 
162422 /*
162423 ** Return the index of the cell containing a pointer to node pNode
162424 ** in its parent. If pNode is the root node, return -1.
162425 */
162426 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
162427  RtreeNode *pParent = pNode->pParent;
162428  if( pParent ){
162429  return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
162430  }
162431  *piIndex = -1;
162432  return SQLITE_OK;
162433 }
162434 
162435 /*
162436 ** Compare two search points. Return negative, zero, or positive if the first
162437 ** is less than, equal to, or greater than the second.
162438 **
162439 ** The rScore is the primary key. Smaller rScore values come first.
162440 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
162441 ** iLevel values coming first. In this way, if rScore is the same for all
162442 ** SearchPoints, then iLevel becomes the deciding factor and the result
162443 ** is a depth-first search, which is the desired default behavior.
162444 */
162445 static int rtreeSearchPointCompare(
162446  const RtreeSearchPoint *pA,
162447  const RtreeSearchPoint *pB
162448 ){
162449  if( pA->rScore<pB->rScore ) return -1;
162450  if( pA->rScore>pB->rScore ) return +1;
162451  if( pA->iLevel<pB->iLevel ) return -1;
162452  if( pA->iLevel>pB->iLevel ) return +1;
162453  return 0;
162454 }
162455 
162456 /*
162457 ** Interchange to search points in a cursor.
162458 */
162459 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
162460  RtreeSearchPoint t = p->aPoint[i];
162461  assert( i<j );
162462  p->aPoint[i] = p->aPoint[j];
162463  p->aPoint[j] = t;
162464  i++; j++;
162465  if( i<RTREE_CACHE_SZ ){
162466  if( j>=RTREE_CACHE_SZ ){
162467  nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
162468  p->aNode[i] = 0;
162469  }else{
162470  RtreeNode *pTemp = p->aNode[i];
162471  p->aNode[i] = p->aNode[j];
162472  p->aNode[j] = pTemp;
162473  }
162474  }
162475 }
162476 
162477 /*
162478 ** Return the search point with the lowest current score.
162479 */
162480 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
162481  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
162482 }
162483 
162484 /*
162485 ** Get the RtreeNode for the search point with the lowest score.
162486 */
162487 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
162488  sqlite3_int64 id;
162489  int ii = 1 - pCur->bPoint;
162490  assert( ii==0 || ii==1 );
162491  assert( pCur->bPoint || pCur->nPoint );
162492  if( pCur->aNode[ii]==0 ){
162493  assert( pRC!=0 );
162494  id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
162495  *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
162496  }
162497  return pCur->aNode[ii];
162498 }
162499 
162500 /*
162501 ** Push a new element onto the priority queue
162502 */
162503 static RtreeSearchPoint *rtreeEnqueue(
162504  RtreeCursor *pCur, /* The cursor */
162505  RtreeDValue rScore, /* Score for the new search point */
162506  u8 iLevel /* Level for the new search point */
162507 ){
162508  int i, j;
162509  RtreeSearchPoint *pNew;
162510  if( pCur->nPoint>=pCur->nPointAlloc ){
162511  int nNew = pCur->nPointAlloc*2 + 8;
162512  pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
162513  if( pNew==0 ) return 0;
162514  pCur->aPoint = pNew;
162515  pCur->nPointAlloc = nNew;
162516  }
162517  i = pCur->nPoint++;
162518  pNew = pCur->aPoint + i;
162519  pNew->rScore = rScore;
162520  pNew->iLevel = iLevel;
162521  assert( iLevel<=RTREE_MAX_DEPTH );
162522  while( i>0 ){
162523  RtreeSearchPoint *pParent;
162524  j = (i-1)/2;
162525  pParent = pCur->aPoint + j;
162526  if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
162527  rtreeSearchPointSwap(pCur, j, i);
162528  i = j;
162529  pNew = pParent;
162530  }
162531  return pNew;
162532 }
162533 
162534 /*
162535 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
162536 ** NULL if malloc fails.
162537 */
162538 static RtreeSearchPoint *rtreeSearchPointNew(
162539  RtreeCursor *pCur, /* The cursor */
162540  RtreeDValue rScore, /* Score for the new search point */
162541  u8 iLevel /* Level for the new search point */
162542 ){
162543  RtreeSearchPoint *pNew, *pFirst;
162544  pFirst = rtreeSearchPointFirst(pCur);
162545  pCur->anQueue[iLevel]++;
162546  if( pFirst==0
162547  || pFirst->rScore>rScore
162548  || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
162549  ){
162550  if( pCur->bPoint ){
162551  int ii;
162552  pNew = rtreeEnqueue(pCur, rScore, iLevel);
162553  if( pNew==0 ) return 0;
162554  ii = (int)(pNew - pCur->aPoint) + 1;
162555  if( ii<RTREE_CACHE_SZ ){
162556  assert( pCur->aNode[ii]==0 );
162557  pCur->aNode[ii] = pCur->aNode[0];
162558  }else{
162559  nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
162560  }
162561  pCur->aNode[0] = 0;
162562  *pNew = pCur->sPoint;
162563  }
162564  pCur->sPoint.rScore = rScore;
162565  pCur->sPoint.iLevel = iLevel;
162566  pCur->bPoint = 1;
162567  return &pCur->sPoint;
162568  }else{
162569  return rtreeEnqueue(pCur, rScore, iLevel);
162570  }
162571 }
162572 
162573 #if 0
162574 /* Tracing routines for the RtreeSearchPoint queue */
162575 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
162576  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
162577  printf(" %d.%05lld.%02d %g %d",
162578  p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
162579  );
162580  idx++;
162581  if( idx<RTREE_CACHE_SZ ){
162582  printf(" %p\n", pCur->aNode[idx]);
162583  }else{
162584  printf("\n");
162585  }
162586 }
162587 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
162588  int ii;
162589  printf("=== %9s ", zPrefix);
162590  if( pCur->bPoint ){
162591  tracePoint(&pCur->sPoint, -1, pCur);
162592  }
162593  for(ii=0; ii<pCur->nPoint; ii++){
162594  if( ii>0 || pCur->bPoint ) printf(" ");
162595  tracePoint(&pCur->aPoint[ii], ii, pCur);
162596  }
162597 }
162598 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
162599 #else
162600 # define RTREE_QUEUE_TRACE(A,B) /* no-op */
162601 #endif
162602 
162603 /* Remove the search point with the lowest current score.
162604 */
162605 static void rtreeSearchPointPop(RtreeCursor *p){
162606  int i, j, k, n;
162607  i = 1 - p->bPoint;
162608  assert( i==0 || i==1 );
162609  if( p->aNode[i] ){
162610  nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
162611  p->aNode[i] = 0;
162612  }
162613  if( p->bPoint ){
162614  p->anQueue[p->sPoint.iLevel]--;
162615  p->bPoint = 0;
162616  }else if( p->nPoint ){
162617  p->anQueue[p->aPoint[0].iLevel]--;
162618  n = --p->nPoint;
162619  p->aPoint[0] = p->aPoint[n];
162620  if( n<RTREE_CACHE_SZ-1 ){
162621  p->aNode[1] = p->aNode[n+1];
162622  p->aNode[n+1] = 0;
162623  }
162624  i = 0;
162625  while( (j = i*2+1)<n ){
162626  k = j+1;
162627  if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
162628  if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
162629  rtreeSearchPointSwap(p, i, k);
162630  i = k;
162631  }else{
162632  break;
162633  }
162634  }else{
162635  if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
162636  rtreeSearchPointSwap(p, i, j);
162637  i = j;
162638  }else{
162639  break;
162640  }
162641  }
162642  }
162643  }
162644 }
162645 
162646 
162647 /*
162648 ** Continue the search on cursor pCur until the front of the queue
162649 ** contains an entry suitable for returning as a result-set row,
162650 ** or until the RtreeSearchPoint queue is empty, indicating that the
162651 ** query has completed.
162652 */
162653 static int rtreeStepToLeaf(RtreeCursor *pCur){
162654  RtreeSearchPoint *p;
162655  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
162656  RtreeNode *pNode;
162657  int eWithin;
162658  int rc = SQLITE_OK;
162659  int nCell;
162660  int nConstraint = pCur->nConstraint;
162661  int ii;
162662  int eInt;
162663  RtreeSearchPoint x;
162664 
162665  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
162666  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
162667  pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
162668  if( rc ) return rc;
162669  nCell = NCELL(pNode);
162670  assert( nCell<200 );
162671  while( p->iCell<nCell ){
162672  sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
162673  u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
162674  eWithin = FULLY_WITHIN;
162675  for(ii=0; ii<nConstraint; ii++){
162676  RtreeConstraint *pConstraint = pCur->aConstraint + ii;
162677  if( pConstraint->op>=RTREE_MATCH ){
162678  rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
162679  &rScore, &eWithin);
162680  if( rc ) return rc;
162681  }else if( p->iLevel==1 ){
162682  rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
162683  }else{
162684  rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
162685  }
162686  if( eWithin==NOT_WITHIN ) break;
162687  }
162688  p->iCell++;
162689  if( eWithin==NOT_WITHIN ) continue;
162690  x.iLevel = p->iLevel - 1;
162691  if( x.iLevel ){
162692  x.id = readInt64(pCellData);
162693  x.iCell = 0;
162694  }else{
162695  x.id = p->id;
162696  x.iCell = p->iCell - 1;
162697  }
162698  if( p->iCell>=nCell ){
162699  RTREE_QUEUE_TRACE(pCur, "POP-S:");
162700  rtreeSearchPointPop(pCur);
162701  }
162702  if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
162703  p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
162704  if( p==0 ) return SQLITE_NOMEM;
162705  p->eWithin = eWithin;
162706  p->id = x.id;
162707  p->iCell = x.iCell;
162708  RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
162709  break;
162710  }
162711  if( p->iCell>=nCell ){
162712  RTREE_QUEUE_TRACE(pCur, "POP-Se:");
162713  rtreeSearchPointPop(pCur);
162714  }
162715  }
162716  pCur->atEOF = p==0;
162717  return SQLITE_OK;
162718 }
162719 
162720 /*
162721 ** Rtree virtual table module xNext method.
162722 */
162723 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
162724  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
162725  int rc = SQLITE_OK;
162726 
162727  /* Move to the next entry that matches the configured constraints. */
162728  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
162729  rtreeSearchPointPop(pCsr);
162730  rc = rtreeStepToLeaf(pCsr);
162731  return rc;
162732 }
162733 
162734 /*
162735 ** Rtree virtual table module xRowid method.
162736 */
162737 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
162738  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
162739  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
162740  int rc = SQLITE_OK;
162741  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
162742  if( rc==SQLITE_OK && p ){
162743  *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
162744  }
162745  return rc;
162746 }
162747 
162748 /*
162749 ** Rtree virtual table module xColumn method.
162750 */
162751 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
162752  Rtree *pRtree = (Rtree *)cur->pVtab;
162753  RtreeCursor *pCsr = (RtreeCursor *)cur;
162754  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
162755  RtreeCoord c;
162756  int rc = SQLITE_OK;
162757  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
162758 
162759  if( rc ) return rc;
162760  if( p==0 ) return SQLITE_OK;
162761  if( i==0 ){
162762  sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
162763  }else{
162764  if( rc ) return rc;
162765  nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
162766 #ifndef SQLITE_RTREE_INT_ONLY
162767  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
162768  sqlite3_result_double(ctx, c.f);
162769  }else
162770 #endif
162771  {
162772  assert( pRtree->eCoordType==RTREE_COORD_INT32 );
162773  sqlite3_result_int(ctx, c.i);
162774  }
162775  }
162776  return SQLITE_OK;
162777 }
162778 
162779 /*
162780 ** Use nodeAcquire() to obtain the leaf node containing the record with
162781 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
162782 ** return SQLITE_OK. If there is no such record in the table, set
162783 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
162784 ** to zero and return an SQLite error code.
162785 */
162786 static int findLeafNode(
162787  Rtree *pRtree, /* RTree to search */
162788  i64 iRowid, /* The rowid searching for */
162789  RtreeNode **ppLeaf, /* Write the node here */
162790  sqlite3_int64 *piNode /* Write the node-id here */
162791 ){
162792  int rc;
162793  *ppLeaf = 0;
162794  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
162795  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
162796  i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
162797  if( piNode ) *piNode = iNode;
162798  rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
162799  sqlite3_reset(pRtree->pReadRowid);
162800  }else{
162801  rc = sqlite3_reset(pRtree->pReadRowid);
162802  }
162803  return rc;
162804 }
162805 
162806 /*
162807 ** This function is called to configure the RtreeConstraint object passed
162808 ** as the second argument for a MATCH constraint. The value passed as the
162809 ** first argument to this function is the right-hand operand to the MATCH
162810 ** operator.
162811 */
162812 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
162813  RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
162814  sqlite3_rtree_query_info *pInfo; /* Callback information */
162815  int nBlob; /* Size of the geometry function blob */
162816  int nExpected; /* Expected size of the BLOB */
162817 
162818  /* Check that value is actually a blob. */
162819  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
162820 
162821  /* Check that the blob is roughly the right size. */
162822  nBlob = sqlite3_value_bytes(pValue);
162823  if( nBlob<(int)sizeof(RtreeMatchArg) ){
162824  return SQLITE_ERROR;
162825  }
162826 
162827  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
162828  if( !pInfo ) return SQLITE_NOMEM;
162829  memset(pInfo, 0, sizeof(*pInfo));
162830  pBlob = (RtreeMatchArg*)&pInfo[1];
162831 
162832  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
162833  nExpected = (int)(sizeof(RtreeMatchArg) +
162834  pBlob->nParam*sizeof(sqlite3_value*) +
162835  (pBlob->nParam-1)*sizeof(RtreeDValue));
162836  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
162837  sqlite3_free(pInfo);
162838  return SQLITE_ERROR;
162839  }
162840  pInfo->pContext = pBlob->cb.pContext;
162841  pInfo->nParam = pBlob->nParam;
162842  pInfo->aParam = pBlob->aParam;
162843  pInfo->apSqlParam = pBlob->apSqlParam;
162844 
162845  if( pBlob->cb.xGeom ){
162846  pCons->u.xGeom = pBlob->cb.xGeom;
162847  }else{
162848  pCons->op = RTREE_QUERY;
162849  pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
162850  }
162851  pCons->pInfo = pInfo;
162852  return SQLITE_OK;
162853 }
162854 
162855 /*
162856 ** Rtree virtual table module xFilter method.
162857 */
162858 static int rtreeFilter(
162859  sqlite3_vtab_cursor *pVtabCursor,
162860  int idxNum, const char *idxStr,
162861  int argc, sqlite3_value **argv
162862 ){
162863  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
162864  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
162865  RtreeNode *pRoot = 0;
162866  int ii;
162867  int rc = SQLITE_OK;
162868  int iCell = 0;
162869 
162870  rtreeReference(pRtree);
162871 
162872  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
162873  freeCursorConstraints(pCsr);
162874  sqlite3_free(pCsr->aPoint);
162875  memset(pCsr, 0, sizeof(RtreeCursor));
162876  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
162877 
162878  pCsr->iStrategy = idxNum;
162879  if( idxNum==1 ){
162880  /* Special case - lookup by rowid. */
162881  RtreeNode *pLeaf; /* Leaf on which the required cell resides */
162882  RtreeSearchPoint *p; /* Search point for the leaf */
162883  i64 iRowid = sqlite3_value_int64(argv[0]);
162884  i64 iNode = 0;
162885  rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
162886  if( rc==SQLITE_OK && pLeaf!=0 ){
162887  p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
162888  assert( p!=0 ); /* Always returns pCsr->sPoint */
162889  pCsr->aNode[0] = pLeaf;
162890  p->id = iNode;
162891  p->eWithin = PARTLY_WITHIN;
162892  rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
162893  p->iCell = iCell;
162894  RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
162895  }else{
162896  pCsr->atEOF = 1;
162897  }
162898  }else{
162899  /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
162900  ** with the configured constraints.
162901  */
162902  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
162903  if( rc==SQLITE_OK && argc>0 ){
162904  pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
162905  pCsr->nConstraint = argc;
162906  if( !pCsr->aConstraint ){
162907  rc = SQLITE_NOMEM;
162908  }else{
162909  memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
162910  memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
162911  assert( (idxStr==0 && argc==0)
162912  || (idxStr && (int)strlen(idxStr)==argc*2) );
162913  for(ii=0; ii<argc; ii++){
162914  RtreeConstraint *p = &pCsr->aConstraint[ii];
162915  p->op = idxStr[ii*2];
162916  p->iCoord = idxStr[ii*2+1]-'0';
162917  if( p->op>=RTREE_MATCH ){
162918  /* A MATCH operator. The right-hand-side must be a blob that
162919  ** can be cast into an RtreeMatchArg object. One created using
162920  ** an sqlite3_rtree_geometry_callback() SQL user function.
162921  */
162922  rc = deserializeGeometry(argv[ii], p);
162923  if( rc!=SQLITE_OK ){
162924  break;
162925  }
162926  p->pInfo->nCoord = pRtree->nDim*2;
162927  p->pInfo->anQueue = pCsr->anQueue;
162928  p->pInfo->mxLevel = pRtree->iDepth + 1;
162929  }else{
162930 #ifdef SQLITE_RTREE_INT_ONLY
162931  p->u.rValue = sqlite3_value_int64(argv[ii]);
162932 #else
162933  p->u.rValue = sqlite3_value_double(argv[ii]);
162934 #endif
162935  }
162936  }
162937  }
162938  }
162939  if( rc==SQLITE_OK ){
162940  RtreeSearchPoint *pNew;
162941  pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
162942  if( pNew==0 ) return SQLITE_NOMEM;
162943  pNew->id = 1;
162944  pNew->iCell = 0;
162945  pNew->eWithin = PARTLY_WITHIN;
162946  assert( pCsr->bPoint==1 );
162947  pCsr->aNode[0] = pRoot;
162948  pRoot = 0;
162949  RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
162950  rc = rtreeStepToLeaf(pCsr);
162951  }
162952  }
162953 
162954  nodeRelease(pRtree, pRoot);
162955  rtreeRelease(pRtree);
162956  return rc;
162957 }
162958 
162959 /*
162960 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
162961 ** extension is currently being used by a version of SQLite too old to
162962 ** support estimatedRows. In that case this function is a no-op.
162963 */
162964 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
162965 #if SQLITE_VERSION_NUMBER>=3008002
162966  if( sqlite3_libversion_number()>=3008002 ){
162967  pIdxInfo->estimatedRows = nRow;
162968  }
162969 #endif
162970 }
162971 
162972 /*
162973 ** Rtree virtual table module xBestIndex method. There are three
162974 ** table scan strategies to choose from (in order from most to
162975 ** least desirable):
162976 **
162977 ** idxNum idxStr Strategy
162978 ** ------------------------------------------------
162979 ** 1 Unused Direct lookup by rowid.
162980 ** 2 See below R-tree query or full-table scan.
162981 ** ------------------------------------------------
162982 **
162983 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
162984 ** 2 is used, idxStr is formatted to contain 2 bytes for each
162985 ** constraint used. The first two bytes of idxStr correspond to
162986 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
162987 ** (argvIndex==1) etc.
162988 **
162989 ** The first of each pair of bytes in idxStr identifies the constraint
162990 ** operator as follows:
162991 **
162992 ** Operator Byte Value
162993 ** ----------------------
162994 ** = 0x41 ('A')
162995 ** <= 0x42 ('B')
162996 ** < 0x43 ('C')
162997 ** >= 0x44 ('D')
162998 ** > 0x45 ('E')
162999 ** MATCH 0x46 ('F')
163000 ** ----------------------
163001 **
163002 ** The second of each pair of bytes identifies the coordinate column
163003 ** to which the constraint applies. The leftmost coordinate column
163004 ** is 'a', the second from the left 'b' etc.
163005 */
163006 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
163007  Rtree *pRtree = (Rtree*)tab;
163008  int rc = SQLITE_OK;
163009  int ii;
163010  int bMatch = 0; /* True if there exists a MATCH constraint */
163011  i64 nRow; /* Estimated rows returned by this scan */
163012 
163013  int iIdx = 0;
163014  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
163015  memset(zIdxStr, 0, sizeof(zIdxStr));
163016 
163017  /* Check if there exists a MATCH constraint - even an unusable one. If there
163018  ** is, do not consider the lookup-by-rowid plan as using such a plan would
163019  ** require the VDBE to evaluate the MATCH constraint, which is not currently
163020  ** possible. */
163021  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
163022  if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
163023  bMatch = 1;
163024  }
163025  }
163026 
163027  assert( pIdxInfo->idxStr==0 );
163028  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
163029  struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
163030 
163031  if( bMatch==0 && p->usable
163032  && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
163033  ){
163034  /* We have an equality constraint on the rowid. Use strategy 1. */
163035  int jj;
163036  for(jj=0; jj<ii; jj++){
163037  pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
163038  pIdxInfo->aConstraintUsage[jj].omit = 0;
163039  }
163040  pIdxInfo->idxNum = 1;
163041  pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
163042  pIdxInfo->aConstraintUsage[jj].omit = 1;
163043 
163044  /* This strategy involves a two rowid lookups on an B-Tree structures
163045  ** and then a linear search of an R-Tree node. This should be
163046  ** considered almost as quick as a direct rowid lookup (for which
163047  ** sqlite uses an internal cost of 0.0). It is expected to return
163048  ** a single row.
163049  */
163050  pIdxInfo->estimatedCost = 30.0;
163051  setEstimatedRows(pIdxInfo, 1);
163052  return SQLITE_OK;
163053  }
163054 
163055  if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
163056  u8 op;
163057  switch( p->op ){
163058  case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
163059  case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
163060  case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
163061  case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
163062  case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
163063  default:
163064  assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
163065  op = RTREE_MATCH;
163066  break;
163067  }
163068  zIdxStr[iIdx++] = op;
163069  zIdxStr[iIdx++] = p->iColumn - 1 + '0';
163070  pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
163071  pIdxInfo->aConstraintUsage[ii].omit = 1;
163072  }
163073  }
163074 
163075  pIdxInfo->idxNum = 2;
163076  pIdxInfo->needToFreeIdxStr = 1;
163077  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
163078  return SQLITE_NOMEM;
163079  }
163080 
163081  nRow = pRtree->nRowEst >> (iIdx/2);
163082  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
163083  setEstimatedRows(pIdxInfo, nRow);
163084 
163085  return rc;
163086 }
163087 
163088 /*
163089 ** Return the N-dimensional volumn of the cell stored in *p.
163090 */
163091 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
163092  RtreeDValue area = (RtreeDValue)1;
163093  int ii;
163094  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163095  area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
163096  }
163097  return area;
163098 }
163099 
163100 /*
163101 ** Return the margin length of cell p. The margin length is the sum
163102 ** of the objects size in each dimension.
163103 */
163104 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
163105  RtreeDValue margin = (RtreeDValue)0;
163106  int ii;
163107  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163108  margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
163109  }
163110  return margin;
163111 }
163112 
163113 /*
163114 ** Store the union of cells p1 and p2 in p1.
163115 */
163116 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
163117  int ii;
163118  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
163119  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163120  p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
163121  p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
163122  }
163123  }else{
163124  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163125  p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
163126  p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
163127  }
163128  }
163129 }
163130 
163131 /*
163132 ** Return true if the area covered by p2 is a subset of the area covered
163133 ** by p1. False otherwise.
163134 */
163135 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
163136  int ii;
163137  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
163138  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
163139  RtreeCoord *a1 = &p1->aCoord[ii];
163140  RtreeCoord *a2 = &p2->aCoord[ii];
163141  if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
163142  || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
163143  ){
163144  return 0;
163145  }
163146  }
163147  return 1;
163148 }
163149 
163150 /*
163151 ** Return the amount cell p would grow by if it were unioned with pCell.
163152 */
163153 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
163154  RtreeDValue area;
163155  RtreeCell cell;
163156  memcpy(&cell, p, sizeof(RtreeCell));
163157  area = cellArea(pRtree, &cell);
163158  cellUnion(pRtree, &cell, pCell);
163159  return (cellArea(pRtree, &cell)-area);
163160 }
163161 
163162 static RtreeDValue cellOverlap(
163163  Rtree *pRtree,
163164  RtreeCell *p,
163165  RtreeCell *aCell,
163166  int nCell
163167 ){
163168  int ii;
163169  RtreeDValue overlap = RTREE_ZERO;
163170  for(ii=0; ii<nCell; ii++){
163171  int jj;
163172  RtreeDValue o = (RtreeDValue)1;
163173  for(jj=0; jj<(pRtree->nDim*2); jj+=2){
163174  RtreeDValue x1, x2;
163175  x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
163176  x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
163177  if( x2<x1 ){
163178  o = (RtreeDValue)0;
163179  break;
163180  }else{
163181  o = o * (x2-x1);
163182  }
163183  }
163184  overlap += o;
163185  }
163186  return overlap;
163187 }
163188 
163189 
163190 /*
163191 ** This function implements the ChooseLeaf algorithm from Gutman[84].
163192 ** ChooseSubTree in r*tree terminology.
163193 */
163194 static int ChooseLeaf(
163195  Rtree *pRtree, /* Rtree table */
163196  RtreeCell *pCell, /* Cell to insert into rtree */
163197  int iHeight, /* Height of sub-tree rooted at pCell */
163198  RtreeNode **ppLeaf /* OUT: Selected leaf page */
163199 ){
163200  int rc;
163201  int ii;
163202  RtreeNode *pNode;
163203  rc = nodeAcquire(pRtree, 1, 0, &pNode);
163204 
163205  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
163206  int iCell;
163207  sqlite3_int64 iBest = 0;
163208 
163209  RtreeDValue fMinGrowth = RTREE_ZERO;
163210  RtreeDValue fMinArea = RTREE_ZERO;
163211 
163212  int nCell = NCELL(pNode);
163213  RtreeCell cell;
163214  RtreeNode *pChild;
163215 
163216  RtreeCell *aCell = 0;
163217 
163218  /* Select the child node which will be enlarged the least if pCell
163219  ** is inserted into it. Resolve ties by choosing the entry with
163220  ** the smallest area.
163221  */
163222  for(iCell=0; iCell<nCell; iCell++){
163223  int bBest = 0;
163224  RtreeDValue growth;
163225  RtreeDValue area;
163226  nodeGetCell(pRtree, pNode, iCell, &cell);
163227  growth = cellGrowth(pRtree, &cell, pCell);
163228  area = cellArea(pRtree, &cell);
163229  if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
163230  bBest = 1;
163231  }
163232  if( bBest ){
163233  fMinGrowth = growth;
163234  fMinArea = area;
163235  iBest = cell.iRowid;
163236  }
163237  }
163238 
163239  sqlite3_free(aCell);
163240  rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
163241  nodeRelease(pRtree, pNode);
163242  pNode = pChild;
163243  }
163244 
163245  *ppLeaf = pNode;
163246  return rc;
163247 }
163248 
163249 /*
163250 ** A cell with the same content as pCell has just been inserted into
163251 ** the node pNode. This function updates the bounding box cells in
163252 ** all ancestor elements.
163253 */
163254 static int AdjustTree(
163255  Rtree *pRtree, /* Rtree table */
163256  RtreeNode *pNode, /* Adjust ancestry of this node. */
163257  RtreeCell *pCell /* This cell was just inserted */
163258 ){
163259  RtreeNode *p = pNode;
163260  while( p->pParent ){
163261  RtreeNode *pParent = p->pParent;
163262  RtreeCell cell;
163263  int iCell;
163264 
163265  if( nodeParentIndex(pRtree, p, &iCell) ){
163266  return SQLITE_CORRUPT_VTAB;
163267  }
163268 
163269  nodeGetCell(pRtree, pParent, iCell, &cell);
163270  if( !cellContains(pRtree, &cell, pCell) ){
163271  cellUnion(pRtree, &cell, pCell);
163272  nodeOverwriteCell(pRtree, pParent, &cell, iCell);
163273  }
163274 
163275  p = pParent;
163276  }
163277  return SQLITE_OK;
163278 }
163279 
163280 /*
163281 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
163282 */
163283 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
163284  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
163285  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
163286  sqlite3_step(pRtree->pWriteRowid);
163287  return sqlite3_reset(pRtree->pWriteRowid);
163288 }
163289 
163290 /*
163291 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
163292 */
163293 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
163294  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
163295  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
163296  sqlite3_step(pRtree->pWriteParent);
163297  return sqlite3_reset(pRtree->pWriteParent);
163298 }
163299 
163300 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
163301 
163302 
163303 /*
163304 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
163305 ** nIdx. The aIdx array contains the set of integers from 0 to
163306 ** (nIdx-1) in no particular order. This function sorts the values
163307 ** in aIdx according to the indexed values in aDistance. For
163308 ** example, assuming the inputs:
163309 **
163310 ** aIdx = { 0, 1, 2, 3 }
163311 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
163312 **
163313 ** this function sets the aIdx array to contain:
163314 **
163315 ** aIdx = { 0, 1, 2, 3 }
163316 **
163317 ** The aSpare array is used as temporary working space by the
163318 ** sorting algorithm.
163319 */
163320 static void SortByDistance(
163321  int *aIdx,
163322  int nIdx,
163323  RtreeDValue *aDistance,
163324  int *aSpare
163325 ){
163326  if( nIdx>1 ){
163327  int iLeft = 0;
163328  int iRight = 0;
163329 
163330  int nLeft = nIdx/2;
163331  int nRight = nIdx-nLeft;
163332  int *aLeft = aIdx;
163333  int *aRight = &aIdx[nLeft];
163334 
163335  SortByDistance(aLeft, nLeft, aDistance, aSpare);
163336  SortByDistance(aRight, nRight, aDistance, aSpare);
163337 
163338  memcpy(aSpare, aLeft, sizeof(int)*nLeft);
163339  aLeft = aSpare;
163340 
163341  while( iLeft<nLeft || iRight<nRight ){
163342  if( iLeft==nLeft ){
163343  aIdx[iLeft+iRight] = aRight[iRight];
163344  iRight++;
163345  }else if( iRight==nRight ){
163346  aIdx[iLeft+iRight] = aLeft[iLeft];
163347  iLeft++;
163348  }else{
163349  RtreeDValue fLeft = aDistance[aLeft[iLeft]];
163350  RtreeDValue fRight = aDistance[aRight[iRight]];
163351  if( fLeft<fRight ){
163352  aIdx[iLeft+iRight] = aLeft[iLeft];
163353  iLeft++;
163354  }else{
163355  aIdx[iLeft+iRight] = aRight[iRight];
163356  iRight++;
163357  }
163358  }
163359  }
163360 
163361 #if 0
163362  /* Check that the sort worked */
163363  {
163364  int jj;
163365  for(jj=1; jj<nIdx; jj++){
163366  RtreeDValue left = aDistance[aIdx[jj-1]];
163367  RtreeDValue right = aDistance[aIdx[jj]];
163368  assert( left<=right );
163369  }
163370  }
163371 #endif
163372  }
163373 }
163374 
163375 /*
163376 ** Arguments aIdx, aCell and aSpare all point to arrays of size
163377 ** nIdx. The aIdx array contains the set of integers from 0 to
163378 ** (nIdx-1) in no particular order. This function sorts the values
163379 ** in aIdx according to dimension iDim of the cells in aCell. The
163380 ** minimum value of dimension iDim is considered first, the
163381 ** maximum used to break ties.
163382 **
163383 ** The aSpare array is used as temporary working space by the
163384 ** sorting algorithm.
163385 */
163386 static void SortByDimension(
163387  Rtree *pRtree,
163388  int *aIdx,
163389  int nIdx,
163390  int iDim,
163391  RtreeCell *aCell,
163392  int *aSpare
163393 ){
163394  if( nIdx>1 ){
163395 
163396  int iLeft = 0;
163397  int iRight = 0;
163398 
163399  int nLeft = nIdx/2;
163400  int nRight = nIdx-nLeft;
163401  int *aLeft = aIdx;
163402  int *aRight = &aIdx[nLeft];
163403 
163404  SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
163405  SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
163406 
163407  memcpy(aSpare, aLeft, sizeof(int)*nLeft);
163408  aLeft = aSpare;
163409  while( iLeft<nLeft || iRight<nRight ){
163410  RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
163411  RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
163412  RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
163413  RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
163414  if( (iLeft!=nLeft) && ((iRight==nRight)
163415  || (xleft1<xright1)
163416  || (xleft1==xright1 && xleft2<xright2)
163417  )){
163418  aIdx[iLeft+iRight] = aLeft[iLeft];
163419  iLeft++;
163420  }else{
163421  aIdx[iLeft+iRight] = aRight[iRight];
163422  iRight++;
163423  }
163424  }
163425 
163426 #if 0
163427  /* Check that the sort worked */
163428  {
163429  int jj;
163430  for(jj=1; jj<nIdx; jj++){
163431  RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
163432  RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
163433  RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
163434  RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
163435  assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
163436  }
163437  }
163438 #endif
163439  }
163440 }
163441 
163442 /*
163443 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
163444 */
163445 static int splitNodeStartree(
163446  Rtree *pRtree,
163447  RtreeCell *aCell,
163448  int nCell,
163449  RtreeNode *pLeft,
163450  RtreeNode *pRight,
163451  RtreeCell *pBboxLeft,
163452  RtreeCell *pBboxRight
163453 ){
163454  int **aaSorted;
163455  int *aSpare;
163456  int ii;
163457 
163458  int iBestDim = 0;
163459  int iBestSplit = 0;
163460  RtreeDValue fBestMargin = RTREE_ZERO;
163461 
163462  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
163463 
163464  aaSorted = (int **)sqlite3_malloc(nByte);
163465  if( !aaSorted ){
163466  return SQLITE_NOMEM;
163467  }
163468 
163469  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
163470  memset(aaSorted, 0, nByte);
163471  for(ii=0; ii<pRtree->nDim; ii++){
163472  int jj;
163473  aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
163474  for(jj=0; jj<nCell; jj++){
163475  aaSorted[ii][jj] = jj;
163476  }
163477  SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
163478  }
163479 
163480  for(ii=0; ii<pRtree->nDim; ii++){
163481  RtreeDValue margin = RTREE_ZERO;
163482  RtreeDValue fBestOverlap = RTREE_ZERO;
163483  RtreeDValue fBestArea = RTREE_ZERO;
163484  int iBestLeft = 0;
163485  int nLeft;
163486 
163487  for(
163488  nLeft=RTREE_MINCELLS(pRtree);
163489  nLeft<=(nCell-RTREE_MINCELLS(pRtree));
163490  nLeft++
163491  ){
163492  RtreeCell left;
163493  RtreeCell right;
163494  int kk;
163495  RtreeDValue overlap;
163496  RtreeDValue area;
163497 
163498  memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
163499  memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
163500  for(kk=1; kk<(nCell-1); kk++){
163501  if( kk<nLeft ){
163502  cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
163503  }else{
163504  cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
163505  }
163506  }
163507  margin += cellMargin(pRtree, &left);
163508  margin += cellMargin(pRtree, &right);
163509  overlap = cellOverlap(pRtree, &left, &right, 1);
163510  area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
163511  if( (nLeft==RTREE_MINCELLS(pRtree))
163512  || (overlap<fBestOverlap)
163513  || (overlap==fBestOverlap && area<fBestArea)
163514  ){
163515  iBestLeft = nLeft;
163516  fBestOverlap = overlap;
163517  fBestArea = area;
163518  }
163519  }
163520 
163521  if( ii==0 || margin<fBestMargin ){
163522  iBestDim = ii;
163523  fBestMargin = margin;
163524  iBestSplit = iBestLeft;
163525  }
163526  }
163527 
163528  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
163529  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
163530  for(ii=0; ii<nCell; ii++){
163531  RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
163532  RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
163533  RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
163534  nodeInsertCell(pRtree, pTarget, pCell);
163535  cellUnion(pRtree, pBbox, pCell);
163536  }
163537 
163538  sqlite3_free(aaSorted);
163539  return SQLITE_OK;
163540 }
163541 
163542 
163543 static int updateMapping(
163544  Rtree *pRtree,
163545  i64 iRowid,
163546  RtreeNode *pNode,
163547  int iHeight
163548 ){
163549  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
163550  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
163551  if( iHeight>0 ){
163552  RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
163553  if( pChild ){
163554  nodeRelease(pRtree, pChild->pParent);
163555  nodeReference(pNode);
163556  pChild->pParent = pNode;
163557  }
163558  }
163559  return xSetMapping(pRtree, iRowid, pNode->iNode);
163560 }
163561 
163562 static int SplitNode(
163563  Rtree *pRtree,
163564  RtreeNode *pNode,
163565  RtreeCell *pCell,
163566  int iHeight
163567 ){
163568  int i;
163569  int newCellIsRight = 0;
163570 
163571  int rc = SQLITE_OK;
163572  int nCell = NCELL(pNode);
163573  RtreeCell *aCell;
163574  int *aiUsed;
163575 
163576  RtreeNode *pLeft = 0;
163577  RtreeNode *pRight = 0;
163578 
163579  RtreeCell leftbbox;
163580  RtreeCell rightbbox;
163581 
163582  /* Allocate an array and populate it with a copy of pCell and
163583  ** all cells from node pLeft. Then zero the original node.
163584  */
163585  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
163586  if( !aCell ){
163587  rc = SQLITE_NOMEM;
163588  goto splitnode_out;
163589  }
163590  aiUsed = (int *)&aCell[nCell+1];
163591  memset(aiUsed, 0, sizeof(int)*(nCell+1));
163592  for(i=0; i<nCell; i++){
163593  nodeGetCell(pRtree, pNode, i, &aCell[i]);
163594  }
163595  nodeZero(pRtree, pNode);
163596  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
163597  nCell++;
163598 
163599  if( pNode->iNode==1 ){
163600  pRight = nodeNew(pRtree, pNode);
163601  pLeft = nodeNew(pRtree, pNode);
163602  pRtree->iDepth++;
163603  pNode->isDirty = 1;
163604  writeInt16(pNode->zData, pRtree->iDepth);
163605  }else{
163606  pLeft = pNode;
163607  pRight = nodeNew(pRtree, pLeft->pParent);
163608  nodeReference(pLeft);
163609  }
163610 
163611  if( !pLeft || !pRight ){
163612  rc = SQLITE_NOMEM;
163613  goto splitnode_out;
163614  }
163615 
163616  memset(pLeft->zData, 0, pRtree->iNodeSize);
163617  memset(pRight->zData, 0, pRtree->iNodeSize);
163618 
163619  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
163620  &leftbbox, &rightbbox);
163621  if( rc!=SQLITE_OK ){
163622  goto splitnode_out;
163623  }
163624 
163625  /* Ensure both child nodes have node numbers assigned to them by calling
163626  ** nodeWrite(). Node pRight always needs a node number, as it was created
163627  ** by nodeNew() above. But node pLeft sometimes already has a node number.
163628  ** In this case avoid the all to nodeWrite().
163629  */
163630  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
163631  || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
163632  ){
163633  goto splitnode_out;
163634  }
163635 
163636  rightbbox.iRowid = pRight->iNode;
163637  leftbbox.iRowid = pLeft->iNode;
163638 
163639  if( pNode->iNode==1 ){
163640  rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
163641  if( rc!=SQLITE_OK ){
163642  goto splitnode_out;
163643  }
163644  }else{
163645  RtreeNode *pParent = pLeft->pParent;
163646  int iCell;
163647  rc = nodeParentIndex(pRtree, pLeft, &iCell);
163648  if( rc==SQLITE_OK ){
163649  nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
163650  rc = AdjustTree(pRtree, pParent, &leftbbox);
163651  }
163652  if( rc!=SQLITE_OK ){
163653  goto splitnode_out;
163654  }
163655  }
163656  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
163657  goto splitnode_out;
163658  }
163659 
163660  for(i=0; i<NCELL(pRight); i++){
163661  i64 iRowid = nodeGetRowid(pRtree, pRight, i);
163662  rc = updateMapping(pRtree, iRowid, pRight, iHeight);
163663  if( iRowid==pCell->iRowid ){
163664  newCellIsRight = 1;
163665  }
163666  if( rc!=SQLITE_OK ){
163667  goto splitnode_out;
163668  }
163669  }
163670  if( pNode->iNode==1 ){
163671  for(i=0; i<NCELL(pLeft); i++){
163672  i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
163673  rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
163674  if( rc!=SQLITE_OK ){
163675  goto splitnode_out;
163676  }
163677  }
163678  }else if( newCellIsRight==0 ){
163679  rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
163680  }
163681 
163682  if( rc==SQLITE_OK ){
163683  rc = nodeRelease(pRtree, pRight);
163684  pRight = 0;
163685  }
163686  if( rc==SQLITE_OK ){
163687  rc = nodeRelease(pRtree, pLeft);
163688  pLeft = 0;
163689  }
163690 
163691 splitnode_out:
163692  nodeRelease(pRtree, pRight);
163693  nodeRelease(pRtree, pLeft);
163694  sqlite3_free(aCell);
163695  return rc;
163696 }
163697 
163698 /*
163699 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
163700 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
163701 ** the pLeaf->pParent chain all the way up to the root node.
163702 **
163703 ** This operation is required when a row is deleted (or updated - an update
163704 ** is implemented as a delete followed by an insert). SQLite provides the
163705 ** rowid of the row to delete, which can be used to find the leaf on which
163706 ** the entry resides (argument pLeaf). Once the leaf is located, this
163707 ** function is called to determine its ancestry.
163708 */
163709 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
163710  int rc = SQLITE_OK;
163711  RtreeNode *pChild = pLeaf;
163712  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
163713  int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
163714  sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
163715  rc = sqlite3_step(pRtree->pReadParent);
163716  if( rc==SQLITE_ROW ){
163717  RtreeNode *pTest; /* Used to test for reference loops */
163718  i64 iNode; /* Node number of parent node */
163719 
163720  /* Before setting pChild->pParent, test that we are not creating a
163721  ** loop of references (as we would if, say, pChild==pParent). We don't
163722  ** want to do this as it leads to a memory leak when trying to delete
163723  ** the referenced counted node structures.
163724  */
163725  iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
163726  for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
163727  if( !pTest ){
163728  rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
163729  }
163730  }
163731  rc = sqlite3_reset(pRtree->pReadParent);
163732  if( rc==SQLITE_OK ) rc = rc2;
163733  if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
163734  pChild = pChild->pParent;
163735  }
163736  return rc;
163737 }
163738 
163739 static int deleteCell(Rtree *, RtreeNode *, int, int);
163740 
163741 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
163742  int rc;
163743  int rc2;
163744  RtreeNode *pParent = 0;
163745  int iCell;
163746 
163747  assert( pNode->nRef==1 );
163748 
163749  /* Remove the entry in the parent cell. */
163750  rc = nodeParentIndex(pRtree, pNode, &iCell);
163751  if( rc==SQLITE_OK ){
163752  pParent = pNode->pParent;
163753  pNode->pParent = 0;
163754  rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
163755  }
163756  rc2 = nodeRelease(pRtree, pParent);
163757  if( rc==SQLITE_OK ){
163758  rc = rc2;
163759  }
163760  if( rc!=SQLITE_OK ){
163761  return rc;
163762  }
163763 
163764  /* Remove the xxx_node entry. */
163765  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
163766  sqlite3_step(pRtree->pDeleteNode);
163767  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
163768  return rc;
163769  }
163770 
163771  /* Remove the xxx_parent entry. */
163772  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
163773  sqlite3_step(pRtree->pDeleteParent);
163774  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
163775  return rc;
163776  }
163777 
163778  /* Remove the node from the in-memory hash table and link it into
163779  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
163780  */
163781  nodeHashDelete(pRtree, pNode);
163782  pNode->iNode = iHeight;
163783  pNode->pNext = pRtree->pDeleted;
163784  pNode->nRef++;
163785  pRtree->pDeleted = pNode;
163786 
163787  return SQLITE_OK;
163788 }
163789 
163790 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
163791  RtreeNode *pParent = pNode->pParent;
163792  int rc = SQLITE_OK;
163793  if( pParent ){
163794  int ii;
163795  int nCell = NCELL(pNode);
163796  RtreeCell box; /* Bounding box for pNode */
163797  nodeGetCell(pRtree, pNode, 0, &box);
163798  for(ii=1; ii<nCell; ii++){
163799  RtreeCell cell;
163800  nodeGetCell(pRtree, pNode, ii, &cell);
163801  cellUnion(pRtree, &box, &cell);
163802  }
163803  box.iRowid = pNode->iNode;
163804  rc = nodeParentIndex(pRtree, pNode, &ii);
163805  if( rc==SQLITE_OK ){
163806  nodeOverwriteCell(pRtree, pParent, &box, ii);
163807  rc = fixBoundingBox(pRtree, pParent);
163808  }
163809  }
163810  return rc;
163811 }
163812 
163813 /*
163814 ** Delete the cell at index iCell of node pNode. After removing the
163815 ** cell, adjust the r-tree data structure if required.
163816 */
163817 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
163818  RtreeNode *pParent;
163819  int rc;
163820 
163821  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
163822  return rc;
163823  }
163824 
163825  /* Remove the cell from the node. This call just moves bytes around
163826  ** the in-memory node image, so it cannot fail.
163827  */
163828  nodeDeleteCell(pRtree, pNode, iCell);
163829 
163830  /* If the node is not the tree root and now has less than the minimum
163831  ** number of cells, remove it from the tree. Otherwise, update the
163832  ** cell in the parent node so that it tightly contains the updated
163833  ** node.
163834  */
163835  pParent = pNode->pParent;
163836  assert( pParent || pNode->iNode==1 );
163837  if( pParent ){
163838  if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
163839  rc = removeNode(pRtree, pNode, iHeight);
163840  }else{
163841  rc = fixBoundingBox(pRtree, pNode);
163842  }
163843  }
163844 
163845  return rc;
163846 }
163847 
163848 static int Reinsert(
163849  Rtree *pRtree,
163850  RtreeNode *pNode,
163851  RtreeCell *pCell,
163852  int iHeight
163853 ){
163854  int *aOrder;
163855  int *aSpare;
163856  RtreeCell *aCell;
163857  RtreeDValue *aDistance;
163858  int nCell;
163859  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
163860  int iDim;
163861  int ii;
163862  int rc = SQLITE_OK;
163863  int n;
163864 
163865  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
163866 
163867  nCell = NCELL(pNode)+1;
163868  n = (nCell+1)&(~1);
163869 
163870  /* Allocate the buffers used by this operation. The allocation is
163871  ** relinquished before this function returns.
163872  */
163873  aCell = (RtreeCell *)sqlite3_malloc(n * (
163874  sizeof(RtreeCell) + /* aCell array */
163875  sizeof(int) + /* aOrder array */
163876  sizeof(int) + /* aSpare array */
163877  sizeof(RtreeDValue) /* aDistance array */
163878  ));
163879  if( !aCell ){
163880  return SQLITE_NOMEM;
163881  }
163882  aOrder = (int *)&aCell[n];
163883  aSpare = (int *)&aOrder[n];
163884  aDistance = (RtreeDValue *)&aSpare[n];
163885 
163886  for(ii=0; ii<nCell; ii++){
163887  if( ii==(nCell-1) ){
163888  memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
163889  }else{
163890  nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
163891  }
163892  aOrder[ii] = ii;
163893  for(iDim=0; iDim<pRtree->nDim; iDim++){
163894  aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
163895  aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
163896  }
163897  }
163898  for(iDim=0; iDim<pRtree->nDim; iDim++){
163899  aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
163900  }
163901 
163902  for(ii=0; ii<nCell; ii++){
163903  aDistance[ii] = RTREE_ZERO;
163904  for(iDim=0; iDim<pRtree->nDim; iDim++){
163905  RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
163906  DCOORD(aCell[ii].aCoord[iDim*2]));
163907  aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
163908  }
163909  }
163910 
163911  SortByDistance(aOrder, nCell, aDistance, aSpare);
163912  nodeZero(pRtree, pNode);
163913 
163914  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
163915  RtreeCell *p = &aCell[aOrder[ii]];
163916  nodeInsertCell(pRtree, pNode, p);
163917  if( p->iRowid==pCell->iRowid ){
163918  if( iHeight==0 ){
163919  rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
163920  }else{
163921  rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
163922  }
163923  }
163924  }
163925  if( rc==SQLITE_OK ){
163926  rc = fixBoundingBox(pRtree, pNode);
163927  }
163928  for(; rc==SQLITE_OK && ii<nCell; ii++){
163929  /* Find a node to store this cell in. pNode->iNode currently contains
163930  ** the height of the sub-tree headed by the cell.
163931  */
163932  RtreeNode *pInsert;
163933  RtreeCell *p = &aCell[aOrder[ii]];
163934  rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
163935  if( rc==SQLITE_OK ){
163936  int rc2;
163937  rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
163938  rc2 = nodeRelease(pRtree, pInsert);
163939  if( rc==SQLITE_OK ){
163940  rc = rc2;
163941  }
163942  }
163943  }
163944 
163945  sqlite3_free(aCell);
163946  return rc;
163947 }
163948 
163949 /*
163950 ** Insert cell pCell into node pNode. Node pNode is the head of a
163951 ** subtree iHeight high (leaf nodes have iHeight==0).
163952 */
163953 static int rtreeInsertCell(
163954  Rtree *pRtree,
163955  RtreeNode *pNode,
163956  RtreeCell *pCell,
163957  int iHeight
163958 ){
163959  int rc = SQLITE_OK;
163960  if( iHeight>0 ){
163961  RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
163962  if( pChild ){
163963  nodeRelease(pRtree, pChild->pParent);
163964  nodeReference(pNode);
163965  pChild->pParent = pNode;
163966  }
163967  }
163968  if( nodeInsertCell(pRtree, pNode, pCell) ){
163969  if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
163970  rc = SplitNode(pRtree, pNode, pCell, iHeight);
163971  }else{
163972  pRtree->iReinsertHeight = iHeight;
163973  rc = Reinsert(pRtree, pNode, pCell, iHeight);
163974  }
163975  }else{
163976  rc = AdjustTree(pRtree, pNode, pCell);
163977  if( rc==SQLITE_OK ){
163978  if( iHeight==0 ){
163979  rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
163980  }else{
163981  rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
163982  }
163983  }
163984  }
163985  return rc;
163986 }
163987 
163988 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
163989  int ii;
163990  int rc = SQLITE_OK;
163991  int nCell = NCELL(pNode);
163992 
163993  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
163994  RtreeNode *pInsert;
163995  RtreeCell cell;
163996  nodeGetCell(pRtree, pNode, ii, &cell);
163997 
163998  /* Find a node to store this cell in. pNode->iNode currently contains
163999  ** the height of the sub-tree headed by the cell.
164000  */
164001  rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
164002  if( rc==SQLITE_OK ){
164003  int rc2;
164004  rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
164005  rc2 = nodeRelease(pRtree, pInsert);
164006  if( rc==SQLITE_OK ){
164007  rc = rc2;
164008  }
164009  }
164010  }
164011  return rc;
164012 }
164013 
164014 /*
164015 ** Select a currently unused rowid for a new r-tree record.
164016 */
164017 static int newRowid(Rtree *pRtree, i64 *piRowid){
164018  int rc;
164019  sqlite3_bind_null(pRtree->pWriteRowid, 1);
164020  sqlite3_bind_null(pRtree->pWriteRowid, 2);
164021  sqlite3_step(pRtree->pWriteRowid);
164022  rc = sqlite3_reset(pRtree->pWriteRowid);
164023  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
164024  return rc;
164025 }
164026 
164027 /*
164028 ** Remove the entry with rowid=iDelete from the r-tree structure.
164029 */
164030 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
164031  int rc; /* Return code */
164032  RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
164033  int iCell; /* Index of iDelete cell in pLeaf */
164034  RtreeNode *pRoot; /* Root node of rtree structure */
164035 
164036 
164037  /* Obtain a reference to the root node to initialize Rtree.iDepth */
164038  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
164039 
164040  /* Obtain a reference to the leaf node that contains the entry
164041  ** about to be deleted.
164042  */
164043  if( rc==SQLITE_OK ){
164044  rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
164045  }
164046 
164047  /* Delete the cell in question from the leaf node. */
164048  if( rc==SQLITE_OK ){
164049  int rc2;
164050  rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
164051  if( rc==SQLITE_OK ){
164052  rc = deleteCell(pRtree, pLeaf, iCell, 0);
164053  }
164054  rc2 = nodeRelease(pRtree, pLeaf);
164055  if( rc==SQLITE_OK ){
164056  rc = rc2;
164057  }
164058  }
164059 
164060  /* Delete the corresponding entry in the <rtree>_rowid table. */
164061  if( rc==SQLITE_OK ){
164062  sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
164063  sqlite3_step(pRtree->pDeleteRowid);
164064  rc = sqlite3_reset(pRtree->pDeleteRowid);
164065  }
164066 
164067  /* Check if the root node now has exactly one child. If so, remove
164068  ** it, schedule the contents of the child for reinsertion and
164069  ** reduce the tree height by one.
164070  **
164071  ** This is equivalent to copying the contents of the child into
164072  ** the root node (the operation that Gutman's paper says to perform
164073  ** in this scenario).
164074  */
164075  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
164076  int rc2;
164077  RtreeNode *pChild;
164078  i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
164079  rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
164080  if( rc==SQLITE_OK ){
164081  rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
164082  }
164083  rc2 = nodeRelease(pRtree, pChild);
164084  if( rc==SQLITE_OK ) rc = rc2;
164085  if( rc==SQLITE_OK ){
164086  pRtree->iDepth--;
164087  writeInt16(pRoot->zData, pRtree->iDepth);
164088  pRoot->isDirty = 1;
164089  }
164090  }
164091 
164092  /* Re-insert the contents of any underfull nodes removed from the tree. */
164093  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
164094  if( rc==SQLITE_OK ){
164095  rc = reinsertNodeContent(pRtree, pLeaf);
164096  }
164097  pRtree->pDeleted = pLeaf->pNext;
164098  sqlite3_free(pLeaf);
164099  }
164100 
164101  /* Release the reference to the root node. */
164102  if( rc==SQLITE_OK ){
164103  rc = nodeRelease(pRtree, pRoot);
164104  }else{
164105  nodeRelease(pRtree, pRoot);
164106  }
164107 
164108  return rc;
164109 }
164110 
164111 /*
164112 ** Rounding constants for float->double conversion.
164113 */
164114 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
164115 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
164116 
164117 #if !defined(SQLITE_RTREE_INT_ONLY)
164118 /*
164119 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
164120 ** while taking care to round toward negative or positive, respectively.
164121 */
164122 static RtreeValue rtreeValueDown(sqlite3_value *v){
164123  double d = sqlite3_value_double(v);
164124  float f = (float)d;
164125  if( f>d ){
164126  f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
164127  }
164128  return f;
164129 }
164130 static RtreeValue rtreeValueUp(sqlite3_value *v){
164131  double d = sqlite3_value_double(v);
164132  float f = (float)d;
164133  if( f<d ){
164134  f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
164135  }
164136  return f;
164137 }
164138 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
164139 
164140 /*
164141 ** A constraint has failed while inserting a row into an rtree table.
164142 ** Assuming no OOM error occurs, this function sets the error message
164143 ** (at pRtree->base.zErrMsg) to an appropriate value and returns
164144 ** SQLITE_CONSTRAINT.
164145 **
164146 ** Parameter iCol is the index of the leftmost column involved in the
164147 ** constraint failure. If it is 0, then the constraint that failed is
164148 ** the unique constraint on the id column. Otherwise, it is the rtree
164149 ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
164150 **
164151 ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
164152 */
164153 static int rtreeConstraintError(Rtree *pRtree, int iCol){
164154  sqlite3_stmt *pStmt = 0;
164155  char *zSql;
164156  int rc;
164157 
164158  assert( iCol==0 || iCol%2 );
164159  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
164160  if( zSql ){
164161  rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
164162  }else{
164163  rc = SQLITE_NOMEM;
164164  }
164165  sqlite3_free(zSql);
164166 
164167  if( rc==SQLITE_OK ){
164168  if( iCol==0 ){
164169  const char *zCol = sqlite3_column_name(pStmt, 0);
164170  pRtree->base.zErrMsg = sqlite3_mprintf(
164171  "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
164172  );
164173  }else{
164174  const char *zCol1 = sqlite3_column_name(pStmt, iCol);
164175  const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
164176  pRtree->base.zErrMsg = sqlite3_mprintf(
164177  "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
164178  );
164179  }
164180  }
164181 
164182  sqlite3_finalize(pStmt);
164183  return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
164184 }
164185 
164186 
164187 
164188 /*
164189 ** The xUpdate method for rtree module virtual tables.
164190 */
164191 static int rtreeUpdate(
164192  sqlite3_vtab *pVtab,
164193  int nData,
164194  sqlite3_value **azData,
164195  sqlite_int64 *pRowid
164196 ){
164197  Rtree *pRtree = (Rtree *)pVtab;
164198  int rc = SQLITE_OK;
164199  RtreeCell cell; /* New cell to insert if nData>1 */
164200  int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
164201 
164202  rtreeReference(pRtree);
164203  assert(nData>=1);
164204 
164205  cell.iRowid = 0; /* Used only to suppress a compiler warning */
164206 
164207  /* Constraint handling. A write operation on an r-tree table may return
164208  ** SQLITE_CONSTRAINT for two reasons:
164209  **
164210  ** 1. A duplicate rowid value, or
164211  ** 2. The supplied data violates the "x2>=x1" constraint.
164212  **
164213  ** In the first case, if the conflict-handling mode is REPLACE, then
164214  ** the conflicting row can be removed before proceeding. In the second
164215  ** case, SQLITE_CONSTRAINT must be returned regardless of the
164216  ** conflict-handling mode specified by the user.
164217  */
164218  if( nData>1 ){
164219  int ii;
164220 
164221  /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
164222  **
164223  ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
164224  ** with "column" that are interpreted as table constraints.
164225  ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
164226  ** This problem was discovered after years of use, so we silently ignore
164227  ** these kinds of misdeclared tables to avoid breaking any legacy.
164228  */
164229  assert( nData<=(pRtree->nDim*2 + 3) );
164230 
164231 #ifndef SQLITE_RTREE_INT_ONLY
164232  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
164233  for(ii=0; ii<nData-4; ii+=2){
164234  cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
164235  cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
164236  if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
164237  rc = rtreeConstraintError(pRtree, ii+1);
164238  goto constraint;
164239  }
164240  }
164241  }else
164242 #endif
164243  {
164244  for(ii=0; ii<nData-4; ii+=2){
164245  cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
164246  cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
164247  if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
164248  rc = rtreeConstraintError(pRtree, ii+1);
164249  goto constraint;
164250  }
164251  }
164252  }
164253 
164254  /* If a rowid value was supplied, check if it is already present in
164255  ** the table. If so, the constraint has failed. */
164256  if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
164257  cell.iRowid = sqlite3_value_int64(azData[2]);
164258  if( sqlite3_value_type(azData[0])==SQLITE_NULL
164259  || sqlite3_value_int64(azData[0])!=cell.iRowid
164260  ){
164261  int steprc;
164262  sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
164263  steprc = sqlite3_step(pRtree->pReadRowid);
164264  rc = sqlite3_reset(pRtree->pReadRowid);
164265  if( SQLITE_ROW==steprc ){
164266  if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
164267  rc = rtreeDeleteRowid(pRtree, cell.iRowid);
164268  }else{
164269  rc = rtreeConstraintError(pRtree, 0);
164270  goto constraint;
164271  }
164272  }
164273  }
164274  bHaveRowid = 1;
164275  }
164276  }
164277 
164278  /* If azData[0] is not an SQL NULL value, it is the rowid of a
164279  ** record to delete from the r-tree table. The following block does
164280  ** just that.
164281  */
164282  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
164283  rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
164284  }
164285 
164286  /* If the azData[] array contains more than one element, elements
164287  ** (azData[2]..azData[argc-1]) contain a new record to insert into
164288  ** the r-tree structure.
164289  */
164290  if( rc==SQLITE_OK && nData>1 ){
164291  /* Insert the new record into the r-tree */
164292  RtreeNode *pLeaf = 0;
164293 
164294  /* Figure out the rowid of the new row. */
164295  if( bHaveRowid==0 ){
164296  rc = newRowid(pRtree, &cell.iRowid);
164297  }
164298  *pRowid = cell.iRowid;
164299 
164300  if( rc==SQLITE_OK ){
164301  rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
164302  }
164303  if( rc==SQLITE_OK ){
164304  int rc2;
164305  pRtree->iReinsertHeight = -1;
164306  rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
164307  rc2 = nodeRelease(pRtree, pLeaf);
164308  if( rc==SQLITE_OK ){
164309  rc = rc2;
164310  }
164311  }
164312  }
164313 
164314 constraint:
164315  rtreeRelease(pRtree);
164316  return rc;
164317 }
164318 
164319 /*
164320 ** The xRename method for rtree module virtual tables.
164321 */
164322 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
164323  Rtree *pRtree = (Rtree *)pVtab;
164324  int rc = SQLITE_NOMEM;
164325  char *zSql = sqlite3_mprintf(
164326  "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
164327  "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
164328  "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
164329  , pRtree->zDb, pRtree->zName, zNewName
164330  , pRtree->zDb, pRtree->zName, zNewName
164331  , pRtree->zDb, pRtree->zName, zNewName
164332  );
164333  if( zSql ){
164334  rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
164335  sqlite3_free(zSql);
164336  }
164337  return rc;
164338 }
164339 
164340 /*
164341 ** This function populates the pRtree->nRowEst variable with an estimate
164342 ** of the number of rows in the virtual table. If possible, this is based
164343 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
164344 */
164345 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
164346  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
164347  char *zSql;
164348  sqlite3_stmt *p;
164349  int rc;
164350  i64 nRow = 0;
164351 
164353  db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
164354  );
164355  if( rc!=SQLITE_OK ){
164356  pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
164357  return rc==SQLITE_ERROR ? SQLITE_OK : rc;
164358  }
164359  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
164360  if( zSql==0 ){
164361  rc = SQLITE_NOMEM;
164362  }else{
164363  rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
164364  if( rc==SQLITE_OK ){
164365  if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
164366  rc = sqlite3_finalize(p);
164367  }else if( rc!=SQLITE_NOMEM ){
164368  rc = SQLITE_OK;
164369  }
164370 
164371  if( rc==SQLITE_OK ){
164372  if( nRow==0 ){
164373  pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
164374  }else{
164375  pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
164376  }
164377  }
164378  sqlite3_free(zSql);
164379  }
164380 
164381  return rc;
164382 }
164383 
164384 static sqlite3_module rtreeModule = {
164385  0, /* iVersion */
164386  rtreeCreate, /* xCreate - create a table */
164387  rtreeConnect, /* xConnect - connect to an existing table */
164388  rtreeBestIndex, /* xBestIndex - Determine search strategy */
164389  rtreeDisconnect, /* xDisconnect - Disconnect from a table */
164390  rtreeDestroy, /* xDestroy - Drop a table */
164391  rtreeOpen, /* xOpen - open a cursor */
164392  rtreeClose, /* xClose - close a cursor */
164393  rtreeFilter, /* xFilter - configure scan constraints */
164394  rtreeNext, /* xNext - advance a cursor */
164395  rtreeEof, /* xEof */
164396  rtreeColumn, /* xColumn - read data */
164397  rtreeRowid, /* xRowid - read data */
164398  rtreeUpdate, /* xUpdate - write data */
164399  0, /* xBegin - begin transaction */
164400  0, /* xSync - sync transaction */
164401  0, /* xCommit - commit transaction */
164402  0, /* xRollback - rollback transaction */
164403  0, /* xFindFunction - function overloading */
164404  rtreeRename, /* xRename - rename the table */
164405  0, /* xSavepoint */
164406  0, /* xRelease */
164407  0 /* xRollbackTo */
164408 };
164409 
164410 static int rtreeSqlInit(
164411  Rtree *pRtree,
164412  sqlite3 *db,
164413  const char *zDb,
164414  const char *zPrefix,
164415  int isCreate
164416 ){
164417  int rc = SQLITE_OK;
164418 
164419  #define N_STATEMENT 9
164420  static const char *azSql[N_STATEMENT] = {
164421  /* Read and write the xxx_node table */
164422  "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
164423  "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
164424  "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
164425 
164426  /* Read and write the xxx_rowid table */
164427  "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
164428  "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
164429  "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
164430 
164431  /* Read and write the xxx_parent table */
164432  "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
164433  "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
164434  "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
164435  };
164436  sqlite3_stmt **appStmt[N_STATEMENT];
164437  int i;
164438 
164439  pRtree->db = db;
164440 
164441  if( isCreate ){
164442  char *zCreate = sqlite3_mprintf(
164443 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
164444 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
164445 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
164446  " parentnode INTEGER);"
164447 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
164448  zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
164449  );
164450  if( !zCreate ){
164451  return SQLITE_NOMEM;
164452  }
164453  rc = sqlite3_exec(db, zCreate, 0, 0, 0);
164454  sqlite3_free(zCreate);
164455  if( rc!=SQLITE_OK ){
164456  return rc;
164457  }
164458  }
164459 
164460  appStmt[0] = &pRtree->pReadNode;
164461  appStmt[1] = &pRtree->pWriteNode;
164462  appStmt[2] = &pRtree->pDeleteNode;
164463  appStmt[3] = &pRtree->pReadRowid;
164464  appStmt[4] = &pRtree->pWriteRowid;
164465  appStmt[5] = &pRtree->pDeleteRowid;
164466  appStmt[6] = &pRtree->pReadParent;
164467  appStmt[7] = &pRtree->pWriteParent;
164468  appStmt[8] = &pRtree->pDeleteParent;
164469 
164470  rc = rtreeQueryStat1(db, pRtree);
164471  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
164472  char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
164473  if( zSql ){
164474  rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
164475  }else{
164476  rc = SQLITE_NOMEM;
164477  }
164478  sqlite3_free(zSql);
164479  }
164480 
164481  return rc;
164482 }
164483 
164484 /*
164485 ** The second argument to this function contains the text of an SQL statement
164486 ** that returns a single integer value. The statement is compiled and executed
164487 ** using database connection db. If successful, the integer value returned
164488 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
164489 ** code is returned and the value of *piVal after returning is not defined.
164490 */
164491 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
164492  int rc = SQLITE_NOMEM;
164493  if( zSql ){
164494  sqlite3_stmt *pStmt = 0;
164495  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
164496  if( rc==SQLITE_OK ){
164497  if( SQLITE_ROW==sqlite3_step(pStmt) ){
164498  *piVal = sqlite3_column_int(pStmt, 0);
164499  }
164500  rc = sqlite3_finalize(pStmt);
164501  }
164502  }
164503  return rc;
164504 }
164505 
164506 /*
164507 ** This function is called from within the xConnect() or xCreate() method to
164508 ** determine the node-size used by the rtree table being created or connected
164509 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
164510 ** Otherwise, an SQLite error code is returned.
164511 **
164512 ** If this function is being called as part of an xConnect(), then the rtree
164513 ** table already exists. In this case the node-size is determined by inspecting
164514 ** the root node of the tree.
164515 **
164516 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
164517 ** This ensures that each node is stored on a single database page. If the
164518 ** database page-size is so large that more than RTREE_MAXCELLS entries
164519 ** would fit in a single node, use a smaller node-size.
164520 */
164521 static int getNodeSize(
164522  sqlite3 *db, /* Database handle */
164523  Rtree *pRtree, /* Rtree handle */
164524  int isCreate, /* True for xCreate, false for xConnect */
164525  char **pzErr /* OUT: Error message, if any */
164526 ){
164527  int rc;
164528  char *zSql;
164529  if( isCreate ){
164530  int iPageSize = 0;
164531  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
164532  rc = getIntFromStmt(db, zSql, &iPageSize);
164533  if( rc==SQLITE_OK ){
164534  pRtree->iNodeSize = iPageSize-64;
164535  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
164536  pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
164537  }
164538  }else{
164539  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164540  }
164541  }else{
164542  zSql = sqlite3_mprintf(
164543  "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
164544  pRtree->zDb, pRtree->zName
164545  );
164546  rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
164547  if( rc!=SQLITE_OK ){
164548  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164549  }
164550  }
164551 
164552  sqlite3_free(zSql);
164553  return rc;
164554 }
164555 
164556 /*
164557 ** This function is the implementation of both the xConnect and xCreate
164558 ** methods of the r-tree virtual table.
164559 **
164560 ** argv[0] -> module name
164561 ** argv[1] -> database name
164562 ** argv[2] -> table name
164563 ** argv[...] -> column names...
164564 */
164565 static int rtreeInit(
164566  sqlite3 *db, /* Database connection */
164567  void *pAux, /* One of the RTREE_COORD_* constants */
164568  int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
164569  sqlite3_vtab **ppVtab, /* OUT: New virtual table */
164570  char **pzErr, /* OUT: Error message, if any */
164571  int isCreate /* True for xCreate, false for xConnect */
164572 ){
164573  int rc = SQLITE_OK;
164574  Rtree *pRtree;
164575  int nDb; /* Length of string argv[1] */
164576  int nName; /* Length of string argv[2] */
164577  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
164578 
164579  const char *aErrMsg[] = {
164580  0, /* 0 */
164581  "Wrong number of columns for an rtree table", /* 1 */
164582  "Too few columns for an rtree table", /* 2 */
164583  "Too many columns for an rtree table" /* 3 */
164584  };
164585 
164586  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
164587  if( aErrMsg[iErr] ){
164588  *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
164589  return SQLITE_ERROR;
164590  }
164591 
164593 
164594  /* Allocate the sqlite3_vtab structure */
164595  nDb = (int)strlen(argv[1]);
164596  nName = (int)strlen(argv[2]);
164597  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
164598  if( !pRtree ){
164599  return SQLITE_NOMEM;
164600  }
164601  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
164602  pRtree->nBusy = 1;
164603  pRtree->base.pModule = &rtreeModule;
164604  pRtree->zDb = (char *)&pRtree[1];
164605  pRtree->zName = &pRtree->zDb[nDb+1];
164606  pRtree->nDim = (argc-4)/2;
164607  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
164608  pRtree->eCoordType = eCoordType;
164609  memcpy(pRtree->zDb, argv[1], nDb);
164610  memcpy(pRtree->zName, argv[2], nName);
164611 
164612  /* Figure out the node size to use. */
164613  rc = getNodeSize(db, pRtree, isCreate, pzErr);
164614 
164615  /* Create/Connect to the underlying relational database schema. If
164616  ** that is successful, call sqlite3_declare_vtab() to configure
164617  ** the r-tree table schema.
164618  */
164619  if( rc==SQLITE_OK ){
164620  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
164621  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164622  }else{
164623  char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
164624  char *zTmp;
164625  int ii;
164626  for(ii=4; zSql && ii<argc; ii++){
164627  zTmp = zSql;
164628  zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
164629  sqlite3_free(zTmp);
164630  }
164631  if( zSql ){
164632  zTmp = zSql;
164633  zSql = sqlite3_mprintf("%s);", zTmp);
164634  sqlite3_free(zTmp);
164635  }
164636  if( !zSql ){
164637  rc = SQLITE_NOMEM;
164638  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
164639  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164640  }
164641  sqlite3_free(zSql);
164642  }
164643  }
164644 
164645  if( rc==SQLITE_OK ){
164646  *ppVtab = (sqlite3_vtab *)pRtree;
164647  }else{
164648  assert( *ppVtab==0 );
164649  assert( pRtree->nBusy==1 );
164650  rtreeRelease(pRtree);
164651  }
164652  return rc;
164653 }
164654 
164655 
164656 /*
164657 ** Implementation of a scalar function that decodes r-tree nodes to
164658 ** human readable strings. This can be used for debugging and analysis.
164659 **
164660 ** The scalar function takes two arguments: (1) the number of dimensions
164661 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
164662 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
164663 ** deserialize all nodes, a statement like:
164664 **
164665 ** SELECT rtreenode(2, data) FROM rt_node;
164666 **
164667 ** The human readable string takes the form of a Tcl list with one
164668 ** entry for each cell in the r-tree node. Each entry is itself a
164669 ** list, containing the 8-byte rowid/pageno followed by the
164670 ** <num-dimension>*2 coordinates.
164671 */
164672 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
164673  char *zText = 0;
164674  RtreeNode node;
164675  Rtree tree;
164676  int ii;
164677 
164678  UNUSED_PARAMETER(nArg);
164679  memset(&node, 0, sizeof(RtreeNode));
164680  memset(&tree, 0, sizeof(Rtree));
164681  tree.nDim = sqlite3_value_int(apArg[0]);
164682  tree.nBytesPerCell = 8 + 8 * tree.nDim;
164683  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
164684 
164685  for(ii=0; ii<NCELL(&node); ii++){
164686  char zCell[512];
164687  int nCell = 0;
164688  RtreeCell cell;
164689  int jj;
164690 
164691  nodeGetCell(&tree, &node, ii, &cell);
164692  sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
164693  nCell = (int)strlen(zCell);
164694  for(jj=0; jj<tree.nDim*2; jj++){
164695 #ifndef SQLITE_RTREE_INT_ONLY
164696  sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
164697  (double)cell.aCoord[jj].f);
164698 #else
164699  sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
164700  cell.aCoord[jj].i);
164701 #endif
164702  nCell = (int)strlen(zCell);
164703  }
164704 
164705  if( zText ){
164706  char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
164707  sqlite3_free(zText);
164708  zText = zTextNew;
164709  }else{
164710  zText = sqlite3_mprintf("{%s}", zCell);
164711  }
164712  }
164713 
164714  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
164715 }
164716 
164717 /* This routine implements an SQL function that returns the "depth" parameter
164718 ** from the front of a blob that is an r-tree node. For example:
164719 **
164720 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
164721 **
164722 ** The depth value is 0 for all nodes other than the root node, and the root
164723 ** node always has nodeno=1, so the example above is the primary use for this
164724 ** routine. This routine is intended for testing and analysis only.
164725 */
164726 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
164727  UNUSED_PARAMETER(nArg);
164728  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
164729  || sqlite3_value_bytes(apArg[0])<2
164730  ){
164731  sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
164732  }else{
164733  u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
164734  sqlite3_result_int(ctx, readInt16(zBlob));
164735  }
164736 }
164737 
164738 /*
164739 ** Register the r-tree module with database handle db. This creates the
164740 ** virtual table module "rtree" and the debugging/analysis scalar
164741 ** function "rtreenode".
164742 */
164743 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
164744  const int utf8 = SQLITE_UTF8;
164745  int rc;
164746 
164747  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
164748  if( rc==SQLITE_OK ){
164749  rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
164750  }
164751  if( rc==SQLITE_OK ){
164752 #ifdef SQLITE_RTREE_INT_ONLY
164753  void *c = (void *)RTREE_COORD_INT32;
164754 #else
164755  void *c = (void *)RTREE_COORD_REAL32;
164756 #endif
164757  rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
164758  }
164759  if( rc==SQLITE_OK ){
164760  void *c = (void *)RTREE_COORD_INT32;
164761  rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
164762  }
164763 
164764  return rc;
164765 }
164766 
164767 /*
164768 ** This routine deletes the RtreeGeomCallback object that was attached
164769 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
164770 ** or sqlite3_rtree_query_callback(). In other words, this routine is the
164771 ** destructor for an RtreeGeomCallback objecct. This routine is called when
164772 ** the corresponding SQL function is deleted.
164773 */
164774 static void rtreeFreeCallback(void *p){
164775  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
164776  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
164777  sqlite3_free(p);
164778 }
164779 
164780 /*
164781 ** This routine frees the BLOB that is returned by geomCallback().
164782 */
164783 static void rtreeMatchArgFree(void *pArg){
164784  int i;
164785  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
164786  for(i=0; i<p->nParam; i++){
164787  sqlite3_value_free(p->apSqlParam[i]);
164788  }
164789  sqlite3_free(p);
164790 }
164791 
164792 /*
164793 ** Each call to sqlite3_rtree_geometry_callback() or
164794 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
164795 ** scalar function that is implemented by this routine.
164796 **
164797 ** All this function does is construct an RtreeMatchArg object that
164798 ** contains the geometry-checking callback routines and a list of
164799 ** parameters to this function, then return that RtreeMatchArg object
164800 ** as a BLOB.
164801 **
164802 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
164803 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
164804 ** out which elements of the R-Tree should be returned by the query.
164805 */
164806 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
164807  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
164808  RtreeMatchArg *pBlob;
164809  int nBlob;
164810  int memErr = 0;
164811 
164812  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
164813  + nArg*sizeof(sqlite3_value*);
164814  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
164815  if( !pBlob ){
164817  }else{
164818  int i;
164819  pBlob->magic = RTREE_GEOMETRY_MAGIC;
164820  pBlob->cb = pGeomCtx[0];
164821  pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
164822  pBlob->nParam = nArg;
164823  for(i=0; i<nArg; i++){
164824  pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
164825  if( pBlob->apSqlParam[i]==0 ) memErr = 1;
164826 #ifdef SQLITE_RTREE_INT_ONLY
164827  pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
164828 #else
164829  pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
164830 #endif
164831  }
164832  if( memErr ){
164834  rtreeMatchArgFree(pBlob);
164835  }else{
164836  sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
164837  }
164838  }
164839 }
164840 
164841 /*
164842 ** Register a new geometry function for use with the r-tree MATCH operator.
164843 */
164845  sqlite3 *db, /* Register SQL function on this connection */
164846  const char *zGeom, /* Name of the new SQL function */
164847  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
164848  void *pContext /* Extra data associated with the callback */
164849 ){
164850  RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
164851 
164852  /* Allocate and populate the context object. */
164853  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
164854  if( !pGeomCtx ) return SQLITE_NOMEM;
164855  pGeomCtx->xGeom = xGeom;
164856  pGeomCtx->xQueryFunc = 0;
164857  pGeomCtx->xDestructor = 0;
164858  pGeomCtx->pContext = pContext;
164859  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
164860  (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
164861  );
164862 }
164863 
164864 /*
164865 ** Register a new 2nd-generation geometry function for use with the
164866 ** r-tree MATCH operator.
164867 */
164869  sqlite3 *db, /* Register SQL function on this connection */
164870  const char *zQueryFunc, /* Name of new SQL function */
164871  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
164872  void *pContext, /* Extra data passed into the callback */
164873  void (*xDestructor)(void*) /* Destructor for the extra data */
164874 ){
164875  RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
164876 
164877  /* Allocate and populate the context object. */
164878  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
164879  if( !pGeomCtx ) return SQLITE_NOMEM;
164880  pGeomCtx->xGeom = 0;
164881  pGeomCtx->xQueryFunc = xQueryFunc;
164882  pGeomCtx->xDestructor = xDestructor;
164883  pGeomCtx->pContext = pContext;
164884  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
164885  (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
164886  );
164887 }
164888 
164889 #if !SQLITE_CORE
164890 #ifdef _WIN32
164891 __declspec(dllexport)
164892 #endif
164893 SQLITE_API int sqlite3_rtree_init(
164894  sqlite3 *db,
164895  char **pzErrMsg,
164896  const sqlite3_api_routines *pApi
164897 ){
164898  SQLITE_EXTENSION_INIT2(pApi)
164899  return sqlite3RtreeInit(db);
164900 }
164901 #endif
164902 
164903 #endif
164904 
164905 /************** End of rtree.c ***********************************************/
164906 /************** Begin file icu.c *********************************************/
164907 /*
164908 ** 2007 May 6
164909 **
164910 ** The author disclaims copyright to this source code. In place of
164911 ** a legal notice, here is a blessing:
164912 **
164913 ** May you do good and not evil.
164914 ** May you find forgiveness for yourself and forgive others.
164915 ** May you share freely, never taking more than you give.
164916 **
164917 *************************************************************************
164918 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
164919 **
164920 ** This file implements an integration between the ICU library
164921 ** ("International Components for Unicode", an open-source library
164922 ** for handling unicode data) and SQLite. The integration uses
164923 ** ICU to provide the following to SQLite:
164924 **
164925 ** * An implementation of the SQL regexp() function (and hence REGEXP
164926 ** operator) using the ICU uregex_XX() APIs.
164927 **
164928 ** * Implementations of the SQL scalar upper() and lower() functions
164929 ** for case mapping.
164930 **
164931 ** * Integration of ICU and SQLite collation sequences.
164932 **
164933 ** * An implementation of the LIKE operator that uses ICU to
164934 ** provide case-independent matching.
164935 */
164936 
164937 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
164938 
164939 /* Include ICU headers */
164940 #include <unicode/utypes.h>
164941 #include <unicode/uregex.h>
164942 #include <unicode/ustring.h>
164943 #include <unicode/ucol.h>
164944 
164945 /* #include <assert.h> */
164946 
164947 #ifndef SQLITE_CORE
164948 /* #include "sqlite3ext.h" */
164950 #else
164951 /* #include "sqlite3.h" */
164952 #endif
164953 
164954 /*
164955 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
164956 ** operator.
164957 */
164958 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
164959 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
164960 #endif
164961 
164962 /*
164963 ** Version of sqlite3_free() that is always a function, never a macro.
164964 */
164965 static void xFree(void *p){
164966  sqlite3_free(p);
164967 }
164968 
164969 /*
164970 ** This lookup table is used to help decode the first byte of
164971 ** a multi-byte UTF8 character. It is copied here from SQLite source
164972 ** code file utf8.c.
164973 */
164974 static const unsigned char icuUtf8Trans1[] = {
164975  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164976  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164977  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
164978  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
164979  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164980  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
164981  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
164982  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
164983 };
164984 
164985 #define SQLITE_ICU_READ_UTF8(zIn, c) \
164986  c = *(zIn++); \
164987  if( c>=0xc0 ){ \
164988  c = icuUtf8Trans1[c-0xc0]; \
164989  while( (*zIn & 0xc0)==0x80 ){ \
164990  c = (c<<6) + (0x3f & *(zIn++)); \
164991  } \
164992  }
164993 
164994 #define SQLITE_ICU_SKIP_UTF8(zIn) \
164995  assert( *zIn ); \
164996  if( *(zIn++)>=0xc0 ){ \
164997  while( (*zIn & 0xc0)==0x80 ){zIn++;} \
164998  }
164999 
165000 
165001 /*
165002 ** Compare two UTF-8 strings for equality where the first string is
165003 ** a "LIKE" expression. Return true (1) if they are the same and
165004 ** false (0) if they are different.
165005 */
165006 static int icuLikeCompare(
165007  const uint8_t *zPattern, /* LIKE pattern */
165008  const uint8_t *zString, /* The UTF-8 string to compare against */
165009  const UChar32 uEsc /* The escape character */
165010 ){
165011  static const int MATCH_ONE = (UChar32)'_';
165012  static const int MATCH_ALL = (UChar32)'%';
165013 
165014  int prevEscape = 0; /* True if the previous character was uEsc */
165015 
165016  while( 1 ){
165017 
165018  /* Read (and consume) the next character from the input pattern. */
165019  UChar32 uPattern;
165020  SQLITE_ICU_READ_UTF8(zPattern, uPattern);
165021  if( uPattern==0 ) break;
165022 
165023  /* There are now 4 possibilities:
165024  **
165025  ** 1. uPattern is an unescaped match-all character "%",
165026  ** 2. uPattern is an unescaped match-one character "_",
165027  ** 3. uPattern is an unescaped escape character, or
165028  ** 4. uPattern is to be handled as an ordinary character
165029  */
165030  if( !prevEscape && uPattern==MATCH_ALL ){
165031  /* Case 1. */
165032  uint8_t c;
165033 
165034  /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
165035  ** MATCH_ALL. For each MATCH_ONE, skip one character in the
165036  ** test string.
165037  */
165038  while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
165039  if( c==MATCH_ONE ){
165040  if( *zString==0 ) return 0;
165041  SQLITE_ICU_SKIP_UTF8(zString);
165042  }
165043  zPattern++;
165044  }
165045 
165046  if( *zPattern==0 ) return 1;
165047 
165048  while( *zString ){
165049  if( icuLikeCompare(zPattern, zString, uEsc) ){
165050  return 1;
165051  }
165052  SQLITE_ICU_SKIP_UTF8(zString);
165053  }
165054  return 0;
165055 
165056  }else if( !prevEscape && uPattern==MATCH_ONE ){
165057  /* Case 2. */
165058  if( *zString==0 ) return 0;
165059  SQLITE_ICU_SKIP_UTF8(zString);
165060 
165061  }else if( !prevEscape && uPattern==uEsc){
165062  /* Case 3. */
165063  prevEscape = 1;
165064 
165065  }else{
165066  /* Case 4. */
165067  UChar32 uString;
165068  SQLITE_ICU_READ_UTF8(zString, uString);
165069  uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
165070  uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
165071  if( uString!=uPattern ){
165072  return 0;
165073  }
165074  prevEscape = 0;
165075  }
165076  }
165077 
165078  return *zString==0;
165079 }
165080 
165081 /*
165082 ** Implementation of the like() SQL function. This function implements
165083 ** the build-in LIKE operator. The first argument to the function is the
165084 ** pattern and the second argument is the string. So, the SQL statements:
165085 **
165086 ** A LIKE B
165087 **
165088 ** is implemented as like(B, A). If there is an escape character E,
165089 **
165090 ** A LIKE B ESCAPE E
165091 **
165092 ** is mapped to like(B, A, E).
165093 */
165094 static void icuLikeFunc(
165095  sqlite3_context *context,
165096  int argc,
165097  sqlite3_value **argv
165098 ){
165099  const unsigned char *zA = sqlite3_value_text(argv[0]);
165100  const unsigned char *zB = sqlite3_value_text(argv[1]);
165101  UChar32 uEsc = 0;
165102 
165103  /* Limit the length of the LIKE or GLOB pattern to avoid problems
165104  ** of deep recursion and N*N behavior in patternCompare().
165105  */
165107  sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
165108  return;
165109  }
165110 
165111 
165112  if( argc==3 ){
165113  /* The escape character string must consist of a single UTF-8 character.
165114  ** Otherwise, return an error.
165115  */
165116  int nE= sqlite3_value_bytes(argv[2]);
165117  const unsigned char *zE = sqlite3_value_text(argv[2]);
165118  int i = 0;
165119  if( zE==0 ) return;
165120  U8_NEXT(zE, i, nE, uEsc);
165121  if( i!=nE){
165122  sqlite3_result_error(context,
165123  "ESCAPE expression must be a single character", -1);
165124  return;
165125  }
165126  }
165127 
165128  if( zA && zB ){
165129  sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
165130  }
165131 }
165132 
165133 /*
165134 ** This function is called when an ICU function called from within
165135 ** the implementation of an SQL scalar function returns an error.
165136 **
165137 ** The scalar function context passed as the first argument is
165138 ** loaded with an error message based on the following two args.
165139 */
165140 static void icuFunctionError(
165141  sqlite3_context *pCtx, /* SQLite scalar function context */
165142  const char *zName, /* Name of ICU function that failed */
165143  UErrorCode e /* Error code returned by ICU function */
165144 ){
165145  char zBuf[128];
165146  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
165147  zBuf[127] = '\0';
165148  sqlite3_result_error(pCtx, zBuf, -1);
165149 }
165150 
165151 /*
165152 ** Function to delete compiled regexp objects. Registered as
165153 ** a destructor function with sqlite3_set_auxdata().
165154 */
165155 static void icuRegexpDelete(void *p){
165156  URegularExpression *pExpr = (URegularExpression *)p;
165157  uregex_close(pExpr);
165158 }
165159 
165160 /*
165161 ** Implementation of SQLite REGEXP operator. This scalar function takes
165162 ** two arguments. The first is a regular expression pattern to compile
165163 ** the second is a string to match against that pattern. If either
165164 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
165165 ** is 1 if the string matches the pattern, or 0 otherwise.
165166 **
165167 ** SQLite maps the regexp() function to the regexp() operator such
165168 ** that the following two are equivalent:
165169 **
165170 ** zString REGEXP zPattern
165171 ** regexp(zPattern, zString)
165172 **
165173 ** Uses the following ICU regexp APIs:
165174 **
165175 ** uregex_open()
165176 ** uregex_matches()
165177 ** uregex_close()
165178 */
165179 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
165180  UErrorCode status = U_ZERO_ERROR;
165181  URegularExpression *pExpr;
165182  UBool res;
165183  const UChar *zString = sqlite3_value_text16(apArg[1]);
165184 
165185  (void)nArg; /* Unused parameter */
165186 
165187  /* If the left hand side of the regexp operator is NULL,
165188  ** then the result is also NULL.
165189  */
165190  if( !zString ){
165191  return;
165192  }
165193 
165194  pExpr = sqlite3_get_auxdata(p, 0);
165195  if( !pExpr ){
165196  const UChar *zPattern = sqlite3_value_text16(apArg[0]);
165197  if( !zPattern ){
165198  return;
165199  }
165200  pExpr = uregex_open(zPattern, -1, 0, 0, &status);
165201 
165202  if( U_SUCCESS(status) ){
165203  sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
165204  }else{
165205  assert(!pExpr);
165206  icuFunctionError(p, "uregex_open", status);
165207  return;
165208  }
165209  }
165210 
165211  /* Configure the text that the regular expression operates on. */
165212  uregex_setText(pExpr, zString, -1, &status);
165213  if( !U_SUCCESS(status) ){
165214  icuFunctionError(p, "uregex_setText", status);
165215  return;
165216  }
165217 
165218  /* Attempt the match */
165219  res = uregex_matches(pExpr, 0, &status);
165220  if( !U_SUCCESS(status) ){
165221  icuFunctionError(p, "uregex_matches", status);
165222  return;
165223  }
165224 
165225  /* Set the text that the regular expression operates on to a NULL
165226  ** pointer. This is not really necessary, but it is tidier than
165227  ** leaving the regular expression object configured with an invalid
165228  ** pointer after this function returns.
165229  */
165230  uregex_setText(pExpr, 0, 0, &status);
165231 
165232  /* Return 1 or 0. */
165233  sqlite3_result_int(p, res ? 1 : 0);
165234 }
165235 
165236 /*
165237 ** Implementations of scalar functions for case mapping - upper() and
165238 ** lower(). Function upper() converts its input to upper-case (ABC).
165239 ** Function lower() converts to lower-case (abc).
165240 **
165241 ** ICU provides two types of case mapping, "general" case mapping and
165242 ** "language specific". Refer to ICU documentation for the differences
165243 ** between the two.
165244 **
165245 ** To utilise "general" case mapping, the upper() or lower() scalar
165246 ** functions are invoked with one argument:
165247 **
165248 ** upper('ABC') -> 'abc'
165249 ** lower('abc') -> 'ABC'
165250 **
165251 ** To access ICU "language specific" case mapping, upper() or lower()
165252 ** should be invoked with two arguments. The second argument is the name
165253 ** of the locale to use. Passing an empty string ("") or SQL NULL value
165254 ** as the second argument is the same as invoking the 1 argument version
165255 ** of upper() or lower().
165256 **
165257 ** lower('I', 'en_us') -> 'i'
165258 ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
165259 **
165260 ** http://www.icu-project.org/userguide/posix.html#case_mappings
165261 */
165262 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
165263  const UChar *zInput; /* Pointer to input string */
165264  UChar *zOutput = 0; /* Pointer to output buffer */
165265  int nInput; /* Size of utf-16 input string in bytes */
165266  int nOut; /* Size of output buffer in bytes */
165267  int cnt;
165268  int bToUpper; /* True for toupper(), false for tolower() */
165269  UErrorCode status;
165270  const char *zLocale = 0;
165271 
165272  assert(nArg==1 || nArg==2);
165273  bToUpper = (sqlite3_user_data(p)!=0);
165274  if( nArg==2 ){
165275  zLocale = (const char *)sqlite3_value_text(apArg[1]);
165276  }
165277 
165278  zInput = sqlite3_value_text16(apArg[0]);
165279  if( !zInput ){
165280  return;
165281  }
165282  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
165283  if( nOut==0 ){
165285  return;
165286  }
165287 
165288  for(cnt=0; cnt<2; cnt++){
165289  UChar *zNew = sqlite3_realloc(zOutput, nOut);
165290  if( zNew==0 ){
165291  sqlite3_free(zOutput);
165293  return;
165294  }
165295  zOutput = zNew;
165296  status = U_ZERO_ERROR;
165297  if( bToUpper ){
165298  nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
165299  }else{
165300  nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
165301  }
165302 
165303  if( U_SUCCESS(status) ){
165304  sqlite3_result_text16(p, zOutput, nOut, xFree);
165305  }else if( status==U_BUFFER_OVERFLOW_ERROR ){
165306  assert( cnt==0 );
165307  continue;
165308  }else{
165309  icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
165310  }
165311  return;
165312  }
165313  assert( 0 ); /* Unreachable */
165314 }
165315 
165316 /*
165317 ** Collation sequence destructor function. The pCtx argument points to
165318 ** a UCollator structure previously allocated using ucol_open().
165319 */
165320 static void icuCollationDel(void *pCtx){
165321  UCollator *p = (UCollator *)pCtx;
165322  ucol_close(p);
165323 }
165324 
165325 /*
165326 ** Collation sequence comparison function. The pCtx argument points to
165327 ** a UCollator structure previously allocated using ucol_open().
165328 */
165329 static int icuCollationColl(
165330  void *pCtx,
165331  int nLeft,
165332  const void *zLeft,
165333  int nRight,
165334  const void *zRight
165335 ){
165336  UCollationResult res;
165337  UCollator *p = (UCollator *)pCtx;
165338  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
165339  switch( res ){
165340  case UCOL_LESS: return -1;
165341  case UCOL_GREATER: return +1;
165342  case UCOL_EQUAL: return 0;
165343  }
165344  assert(!"Unexpected return value from ucol_strcoll()");
165345  return 0;
165346 }
165347 
165348 /*
165349 ** Implementation of the scalar function icu_load_collation().
165350 **
165351 ** This scalar function is used to add ICU collation based collation
165352 ** types to an SQLite database connection. It is intended to be called
165353 ** as follows:
165354 **
165355 ** SELECT icu_load_collation(<locale>, <collation-name>);
165356 **
165357 ** Where <locale> is a string containing an ICU locale identifier (i.e.
165358 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
165359 ** collation sequence to create.
165360 */
165361 static void icuLoadCollation(
165362  sqlite3_context *p,
165363  int nArg,
165364  sqlite3_value **apArg
165365 ){
165366  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
165367  UErrorCode status = U_ZERO_ERROR;
165368  const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
165369  const char *zName; /* SQL Collation sequence name (eg. "japanese") */
165370  UCollator *pUCollator; /* ICU library collation object */
165371  int rc; /* Return code from sqlite3_create_collation_x() */
165372 
165373  assert(nArg==2);
165374  (void)nArg; /* Unused parameter */
165375  zLocale = (const char *)sqlite3_value_text(apArg[0]);
165376  zName = (const char *)sqlite3_value_text(apArg[1]);
165377 
165378  if( !zLocale || !zName ){
165379  return;
165380  }
165381 
165382  pUCollator = ucol_open(zLocale, &status);
165383  if( !U_SUCCESS(status) ){
165384  icuFunctionError(p, "ucol_open", status);
165385  return;
165386  }
165387  assert(p);
165388 
165389  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
165390  icuCollationColl, icuCollationDel
165391  );
165392  if( rc!=SQLITE_OK ){
165393  ucol_close(pUCollator);
165394  sqlite3_result_error(p, "Error registering collation function", -1);
165395  }
165396 }
165397 
165398 /*
165399 ** Register the ICU extension functions with database db.
165400 */
165401 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
165402  struct IcuScalar {
165403  const char *zName; /* Function name */
165404  int nArg; /* Number of arguments */
165405  int enc; /* Optimal text encoding */
165406  void *pContext; /* sqlite3_user_data() context */
165407  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
165408  } scalars[] = {
165409  {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
165410 
165411  {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
165412  {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
165413  {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16},
165414  {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16},
165415 
165416  {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
165417  {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
165418  {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16},
165419  {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, (void*)1, icuCaseFunc16},
165420 
165421  {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
165422  {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
165423 
165424  {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
165425  };
165426 
165427  int rc = SQLITE_OK;
165428  int i;
165429 
165430  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
165431  struct IcuScalar *p = &scalars[i];
165433  db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
165434  );
165435  }
165436 
165437  return rc;
165438 }
165439 
165440 #if !SQLITE_CORE
165441 #ifdef _WIN32
165442 __declspec(dllexport)
165443 #endif
165444 SQLITE_API int sqlite3_icu_init(
165445  sqlite3 *db,
165446  char **pzErrMsg,
165447  const sqlite3_api_routines *pApi
165448 ){
165449  SQLITE_EXTENSION_INIT2(pApi)
165450  return sqlite3IcuInit(db);
165451 }
165452 #endif
165453 
165454 #endif
165455 
165456 /************** End of icu.c *************************************************/
165457 /************** Begin file fts3_icu.c ****************************************/
165458 /*
165459 ** 2007 June 22
165460 **
165461 ** The author disclaims copyright to this source code. In place of
165462 ** a legal notice, here is a blessing:
165463 **
165464 ** May you do good and not evil.
165465 ** May you find forgiveness for yourself and forgive others.
165466 ** May you share freely, never taking more than you give.
165467 **
165468 *************************************************************************
165469 ** This file implements a tokenizer for fts3 based on the ICU library.
165470 */
165471 /* #include "fts3Int.h" */
165472 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
165473 #ifdef SQLITE_ENABLE_ICU
165474 
165475 /* #include <assert.h> */
165476 /* #include <string.h> */
165477 /* #include "fts3_tokenizer.h" */
165478 
165479 #include <unicode/ubrk.h>
165480 /* #include <unicode/ucol.h> */
165481 /* #include <unicode/ustring.h> */
165482 #include <unicode/utf16.h>
165483 
165484 typedef struct IcuTokenizer IcuTokenizer;
165485 typedef struct IcuCursor IcuCursor;
165486 
165487 struct IcuTokenizer {
165488  sqlite3_tokenizer base;
165489  char *zLocale;
165490 };
165491 
165492 struct IcuCursor {
165493  sqlite3_tokenizer_cursor base;
165494 
165495  UBreakIterator *pIter; /* ICU break-iterator object */
165496  int nChar; /* Number of UChar elements in pInput */
165497  UChar *aChar; /* Copy of input using utf-16 encoding */
165498  int *aOffset; /* Offsets of each character in utf-8 input */
165499 
165500  int nBuffer;
165501  char *zBuffer;
165502 
165503  int iToken;
165504 };
165505 
165506 /*
165507 ** Create a new tokenizer instance.
165508 */
165509 static int icuCreate(
165510  int argc, /* Number of entries in argv[] */
165511  const char * const *argv, /* Tokenizer creation arguments */
165512  sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
165513 ){
165514  IcuTokenizer *p;
165515  int n = 0;
165516 
165517  if( argc>0 ){
165518  n = strlen(argv[0])+1;
165519  }
165520  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
165521  if( !p ){
165522  return SQLITE_NOMEM;
165523  }
165524  memset(p, 0, sizeof(IcuTokenizer));
165525 
165526  if( n ){
165527  p->zLocale = (char *)&p[1];
165528  memcpy(p->zLocale, argv[0], n);
165529  }
165530 
165531  *ppTokenizer = (sqlite3_tokenizer *)p;
165532 
165533  return SQLITE_OK;
165534 }
165535 
165536 /*
165537 ** Destroy a tokenizer
165538 */
165539 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
165540  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
165541  sqlite3_free(p);
165542  return SQLITE_OK;
165543 }
165544 
165545 /*
165546 ** Prepare to begin tokenizing a particular string. The input
165547 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
165548 ** used to incrementally tokenize this string is returned in
165549 ** *ppCursor.
165550 */
165551 static int icuOpen(
165552  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
165553  const char *zInput, /* Input string */
165554  int nInput, /* Length of zInput in bytes */
165555  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
165556 ){
165557  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
165558  IcuCursor *pCsr;
165559 
165560  const int32_t opt = U_FOLD_CASE_DEFAULT;
165561  UErrorCode status = U_ZERO_ERROR;
165562  int nChar;
165563 
165564  UChar32 c;
165565  int iInput = 0;
165566  int iOut = 0;
165567 
165568  *ppCursor = 0;
165569 
165570  if( zInput==0 ){
165571  nInput = 0;
165572  zInput = "";
165573  }else if( nInput<0 ){
165574  nInput = strlen(zInput);
165575  }
165576  nChar = nInput+1;
165577  pCsr = (IcuCursor *)sqlite3_malloc(
165578  sizeof(IcuCursor) + /* IcuCursor */
165579  ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
165580  (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
165581  );
165582  if( !pCsr ){
165583  return SQLITE_NOMEM;
165584  }
165585  memset(pCsr, 0, sizeof(IcuCursor));
165586  pCsr->aChar = (UChar *)&pCsr[1];
165587  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
165588 
165589  pCsr->aOffset[iOut] = iInput;
165590  U8_NEXT(zInput, iInput, nInput, c);
165591  while( c>0 ){
165592  int isError = 0;
165593  c = u_foldCase(c, opt);
165594  U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
165595  if( isError ){
165596  sqlite3_free(pCsr);
165597  return SQLITE_ERROR;
165598  }
165599  pCsr->aOffset[iOut] = iInput;
165600 
165601  if( iInput<nInput ){
165602  U8_NEXT(zInput, iInput, nInput, c);
165603  }else{
165604  c = 0;
165605  }
165606  }
165607 
165608  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
165609  if( !U_SUCCESS(status) ){
165610  sqlite3_free(pCsr);
165611  return SQLITE_ERROR;
165612  }
165613  pCsr->nChar = iOut;
165614 
165615  ubrk_first(pCsr->pIter);
165616  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
165617  return SQLITE_OK;
165618 }
165619 
165620 /*
165621 ** Close a tokenization cursor previously opened by a call to icuOpen().
165622 */
165623 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
165624  IcuCursor *pCsr = (IcuCursor *)pCursor;
165625  ubrk_close(pCsr->pIter);
165626  sqlite3_free(pCsr->zBuffer);
165627  sqlite3_free(pCsr);
165628  return SQLITE_OK;
165629 }
165630 
165631 /*
165632 ** Extract the next token from a tokenization cursor.
165633 */
165634 static int icuNext(
165635  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
165636  const char **ppToken, /* OUT: *ppToken is the token text */
165637  int *pnBytes, /* OUT: Number of bytes in token */
165638  int *piStartOffset, /* OUT: Starting offset of token */
165639  int *piEndOffset, /* OUT: Ending offset of token */
165640  int *piPosition /* OUT: Position integer of token */
165641 ){
165642  IcuCursor *pCsr = (IcuCursor *)pCursor;
165643 
165644  int iStart = 0;
165645  int iEnd = 0;
165646  int nByte = 0;
165647 
165648  while( iStart==iEnd ){
165649  UChar32 c;
165650 
165651  iStart = ubrk_current(pCsr->pIter);
165652  iEnd = ubrk_next(pCsr->pIter);
165653  if( iEnd==UBRK_DONE ){
165654  return SQLITE_DONE;
165655  }
165656 
165657  while( iStart<iEnd ){
165658  int iWhite = iStart;
165659  U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
165660  if( u_isspace(c) ){
165661  iStart = iWhite;
165662  }else{
165663  break;
165664  }
165665  }
165666  assert(iStart<=iEnd);
165667  }
165668 
165669  do {
165670  UErrorCode status = U_ZERO_ERROR;
165671  if( nByte ){
165672  char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
165673  if( !zNew ){
165674  return SQLITE_NOMEM;
165675  }
165676  pCsr->zBuffer = zNew;
165677  pCsr->nBuffer = nByte;
165678  }
165679 
165680  u_strToUTF8(
165681  pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
165682  &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
165683  &status /* Output success/failure */
165684  );
165685  } while( nByte>pCsr->nBuffer );
165686 
165687  *ppToken = pCsr->zBuffer;
165688  *pnBytes = nByte;
165689  *piStartOffset = pCsr->aOffset[iStart];
165690  *piEndOffset = pCsr->aOffset[iEnd];
165691  *piPosition = pCsr->iToken++;
165692 
165693  return SQLITE_OK;
165694 }
165695 
165696 /*
165697 ** The set of routines that implement the simple tokenizer
165698 */
165699 static const sqlite3_tokenizer_module icuTokenizerModule = {
165700  0, /* iVersion */
165701  icuCreate, /* xCreate */
165702  icuDestroy, /* xCreate */
165703  icuOpen, /* xOpen */
165704  icuClose, /* xClose */
165705  icuNext, /* xNext */
165706  0, /* xLanguageid */
165707 };
165708 
165709 /*
165710 ** Set *ppModule to point at the implementation of the ICU tokenizer.
165711 */
165712 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
165713  sqlite3_tokenizer_module const**ppModule
165714 ){
165715  *ppModule = &icuTokenizerModule;
165716 }
165717 
165718 #endif /* defined(SQLITE_ENABLE_ICU) */
165719 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
165720 
165721 /************** End of fts3_icu.c ********************************************/
165722 /************** Begin file sqlite3rbu.c **************************************/
165723 /*
165724 ** 2014 August 30
165725 **
165726 ** The author disclaims copyright to this source code. In place of
165727 ** a legal notice, here is a blessing:
165728 **
165729 ** May you do good and not evil.
165730 ** May you find forgiveness for yourself and forgive others.
165731 ** May you share freely, never taking more than you give.
165732 **
165733 *************************************************************************
165734 **
165735 **
165736 ** OVERVIEW
165737 **
165738 ** The RBU extension requires that the RBU update be packaged as an
165739 ** SQLite database. The tables it expects to find are described in
165740 ** sqlite3rbu.h. Essentially, for each table xyz in the target database
165741 ** that the user wishes to write to, a corresponding data_xyz table is
165742 ** created in the RBU database and populated with one row for each row to
165743 ** update, insert or delete from the target table.
165744 **
165745 ** The update proceeds in three stages:
165746 **
165747 ** 1) The database is updated. The modified database pages are written
165748 ** to a *-oal file. A *-oal file is just like a *-wal file, except
165749 ** that it is named "<database>-oal" instead of "<database>-wal".
165750 ** Because regular SQLite clients do not look for file named
165751 ** "<database>-oal", they go on using the original database in
165752 ** rollback mode while the *-oal file is being generated.
165753 **
165754 ** During this stage RBU does not update the database by writing
165755 ** directly to the target tables. Instead it creates "imposter"
165756 ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
165757 ** to update each b-tree individually. All updates required by each
165758 ** b-tree are completed before moving on to the next, and all
165759 ** updates are done in sorted key order.
165760 **
165761 ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
165762 ** location using a call to rename(2). Before doing this the RBU
165763 ** module takes an EXCLUSIVE lock on the database file, ensuring
165764 ** that there are no other active readers.
165765 **
165766 ** Once the EXCLUSIVE lock is released, any other database readers
165767 ** detect the new *-wal file and read the database in wal mode. At
165768 ** this point they see the new version of the database - including
165769 ** the updates made as part of the RBU update.
165770 **
165771 ** 3) The new *-wal file is checkpointed. This proceeds in the same way
165772 ** as a regular database checkpoint, except that a single frame is
165773 ** checkpointed each time sqlite3rbu_step() is called. If the RBU
165774 ** handle is closed before the entire *-wal file is checkpointed,
165775 ** the checkpoint progress is saved in the RBU database and the
165776 ** checkpoint can be resumed by another RBU client at some point in
165777 ** the future.
165778 **
165779 ** POTENTIAL PROBLEMS
165780 **
165781 ** The rename() call might not be portable. And RBU is not currently
165782 ** syncing the directory after renaming the file.
165783 **
165784 ** When state is saved, any commit to the *-oal file and the commit to
165785 ** the RBU update database are not atomic. So if the power fails at the
165786 ** wrong moment they might get out of sync. As the main database will be
165787 ** committed before the RBU update database this will likely either just
165788 ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
165789 ** constraint violations).
165790 **
165791 ** If some client does modify the target database mid RBU update, or some
165792 ** other error occurs, the RBU extension will keep throwing errors. It's
165793 ** not really clear how to get out of this state. The system could just
165794 ** by delete the RBU update database and *-oal file and have the device
165795 ** download the update again and start over.
165796 **
165797 ** At present, for an UPDATE, both the new.* and old.* records are
165798 ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
165799 ** fields are collected. This means we're probably writing a lot more
165800 ** data to disk when saving the state of an ongoing update to the RBU
165801 ** update database than is strictly necessary.
165802 **
165803 */
165804 
165805 /* #include <assert.h> */
165806 /* #include <string.h> */
165807 /* #include <stdio.h> */
165808 
165809 /* #include "sqlite3.h" */
165810 
165811 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
165812 /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
165813 /************** Begin file sqlite3rbu.h **************************************/
165814 /*
165815 ** 2014 August 30
165816 **
165817 ** The author disclaims copyright to this source code. In place of
165818 ** a legal notice, here is a blessing:
165819 **
165820 ** May you do good and not evil.
165821 ** May you find forgiveness for yourself and forgive others.
165822 ** May you share freely, never taking more than you give.
165823 **
165824 *************************************************************************
165825 **
165826 ** This file contains the public interface for the RBU extension.
165827 */
165828 
165829 /*
165830 ** SUMMARY
165831 **
165832 ** Writing a transaction containing a large number of operations on
165833 ** b-tree indexes that are collectively larger than the available cache
165834 ** memory can be very inefficient.
165835 **
165836 ** The problem is that in order to update a b-tree, the leaf page (at least)
165837 ** containing the entry being inserted or deleted must be modified. If the
165838 ** working set of leaves is larger than the available cache memory, then a
165839 ** single leaf that is modified more than once as part of the transaction
165840 ** may be loaded from or written to the persistent media multiple times.
165841 ** Additionally, because the index updates are likely to be applied in
165842 ** random order, access to pages within the database is also likely to be in
165843 ** random order, which is itself quite inefficient.
165844 **
165845 ** One way to improve the situation is to sort the operations on each index
165846 ** by index key before applying them to the b-tree. This leads to an IO
165847 ** pattern that resembles a single linear scan through the index b-tree,
165848 ** and all but guarantees each modified leaf page is loaded and stored
165849 ** exactly once. SQLite uses this trick to improve the performance of
165850 ** CREATE INDEX commands. This extension allows it to be used to improve
165851 ** the performance of large transactions on existing databases.
165852 **
165853 ** Additionally, this extension allows the work involved in writing the
165854 ** large transaction to be broken down into sub-transactions performed
165855 ** sequentially by separate processes. This is useful if the system cannot
165856 ** guarantee that a single update process will run for long enough to apply
165857 ** the entire update, for example because the update is being applied on a
165858 ** mobile device that is frequently rebooted. Even after the writer process
165859 ** has committed one or more sub-transactions, other database clients continue
165860 ** to read from the original database snapshot. In other words, partially
165861 ** applied transactions are not visible to other clients.
165862 **
165863 ** "RBU" stands for "Resumable Bulk Update". As in a large database update
165864 ** transmitted via a wireless network to a mobile device. A transaction
165865 ** applied using this extension is hence refered to as an "RBU update".
165866 **
165867 **
165868 ** LIMITATIONS
165869 **
165870 ** An "RBU update" transaction is subject to the following limitations:
165871 **
165872 ** * The transaction must consist of INSERT, UPDATE and DELETE operations
165873 ** only.
165874 **
165875 ** * INSERT statements may not use any default values.
165876 **
165877 ** * UPDATE and DELETE statements must identify their target rows by
165878 ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
165879 ** KEY fields may not be updated or deleted. If the table being written
165880 ** has no PRIMARY KEY, affected rows must be identified by rowid.
165881 **
165882 ** * UPDATE statements may not modify PRIMARY KEY columns.
165883 **
165884 ** * No triggers will be fired.
165885 **
165886 ** * No foreign key violations are detected or reported.
165887 **
165888 ** * CHECK constraints are not enforced.
165889 **
165890 ** * No constraint handling mode except for "OR ROLLBACK" is supported.
165891 **
165892 **
165893 ** PREPARATION
165894 **
165895 ** An "RBU update" is stored as a separate SQLite database. A database
165896 ** containing an RBU update is an "RBU database". For each table in the
165897 ** target database to be updated, the RBU database should contain a table
165898 ** named "data_<target name>" containing the same set of columns as the
165899 ** target table, and one more - "rbu_control". The data_% table should
165900 ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
165901 ** the same type as the corresponding column in the target database.
165902 ** The "rbu_control" column should have no type at all. For example, if
165903 ** the target database contains:
165904 **
165905 ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
165906 **
165907 ** Then the RBU database should contain:
165908 **
165909 ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
165910 **
165911 ** The order of the columns in the data_% table does not matter.
165912 **
165913 ** Instead of a regular table, the RBU database may also contain virtual
165914 ** tables or view named using the data_<target> naming scheme.
165915 **
165916 ** Instead of the plain data_<target> naming scheme, RBU database tables
165917 ** may also be named data<integer>_<target>, where <integer> is any sequence
165918 ** of zero or more numeric characters (0-9). This can be significant because
165919 ** tables within the RBU database are always processed in order sorted by
165920 ** name. By judicious selection of the <integer> portion of the names
165921 ** of the RBU tables the user can therefore control the order in which they
165922 ** are processed. This can be useful, for example, to ensure that "external
165923 ** content" FTS4 tables are updated before their underlying content tables.
165924 **
165925 ** If the target database table is a virtual table or a table that has no
165926 ** PRIMARY KEY declaration, the data_% table must also contain a column
165927 ** named "rbu_rowid". This column is mapped to the tables implicit primary
165928 ** key column - "rowid". Virtual tables for which the "rowid" column does
165929 ** not function like a primary key value cannot be updated using RBU. For
165930 ** example, if the target db contains either of the following:
165931 **
165932 ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
165933 ** CREATE TABLE x1(a, b)
165934 **
165935 ** then the RBU database should contain:
165936 **
165937 ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
165938 **
165939 ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
165940 ** target table must be present in the input table. For virtual tables,
165941 ** hidden columns are optional - they are updated by RBU if present in
165942 ** the input table, or not otherwise. For example, to write to an fts4
165943 ** table with a hidden languageid column such as:
165944 **
165945 ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
165946 **
165947 ** Either of the following input table schemas may be used:
165948 **
165949 ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
165950 ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
165951 **
165952 ** For each row to INSERT into the target database as part of the RBU
165953 ** update, the corresponding data_% table should contain a single record
165954 ** with the "rbu_control" column set to contain integer value 0. The
165955 ** other columns should be set to the values that make up the new record
165956 ** to insert.
165957 **
165958 ** If the target database table has an INTEGER PRIMARY KEY, it is not
165959 ** possible to insert a NULL value into the IPK column. Attempting to
165960 ** do so results in an SQLITE_MISMATCH error.
165961 **
165962 ** For each row to DELETE from the target database as part of the RBU
165963 ** update, the corresponding data_% table should contain a single record
165964 ** with the "rbu_control" column set to contain integer value 1. The
165965 ** real primary key values of the row to delete should be stored in the
165966 ** corresponding columns of the data_% table. The values stored in the
165967 ** other columns are not used.
165968 **
165969 ** For each row to UPDATE from the target database as part of the RBU
165970 ** update, the corresponding data_% table should contain a single record
165971 ** with the "rbu_control" column set to contain a value of type text.
165972 ** The real primary key values identifying the row to update should be
165973 ** stored in the corresponding columns of the data_% table row, as should
165974 ** the new values of all columns being update. The text value in the
165975 ** "rbu_control" column must contain the same number of characters as
165976 ** there are columns in the target database table, and must consist entirely
165977 ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
165978 ** each column that is being updated, the corresponding character is set to
165979 ** 'x'. For those that remain as they are, the corresponding character of the
165980 ** rbu_control value should be set to '.'. For example, given the tables
165981 ** above, the update statement:
165982 **
165983 ** UPDATE t1 SET c = 'usa' WHERE a = 4;
165984 **
165985 ** is represented by the data_t1 row created by:
165986 **
165987 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
165988 **
165989 ** Instead of an 'x' character, characters of the rbu_control value specified
165990 ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
165991 ** target table with the value stored in the corresponding data_% column, the
165992 ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
165993 ** the target table column. rbu_delta() is invoked with two arguments - the
165994 ** original value currently stored in the target table column and the
165995 ** value specified in the data_xxx table.
165996 **
165997 ** For example, this row:
165998 **
165999 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
166000 **
166001 ** is similar to an UPDATE statement such as:
166002 **
166003 ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
166004 **
166005 ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
166006 ** ota_control string, the contents of the data_xxx table column is assumed
166007 ** to be a "fossil delta" - a patch to be applied to a blob value in the
166008 ** format used by the fossil source-code management system. In this case
166009 ** the existing value within the target database table must be of type BLOB.
166010 ** It is replaced by the result of applying the specified fossil delta to
166011 ** itself.
166012 **
166013 ** If the target database table is a virtual table or a table with no PRIMARY
166014 ** KEY, the rbu_control value should not include a character corresponding
166015 ** to the rbu_rowid value. For example, this:
166016 **
166017 ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
166018 ** VALUES(NULL, 'usa', 12, '.x');
166019 **
166020 ** causes a result similar to:
166021 **
166022 ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
166023 **
166024 ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
166025 ** However, RBU is more efficient if reading the rows in from each data_xxx
166026 ** table in "rowid" order is roughly the same as reading them sorted by
166027 ** the PRIMARY KEY of the corresponding target database table. In other
166028 ** words, rows should be sorted using the destination table PRIMARY KEY
166029 ** fields before they are inserted into the data_xxx tables.
166030 **
166031 ** USAGE
166032 **
166033 ** The API declared below allows an application to apply an RBU update
166034 ** stored on disk to an existing target database. Essentially, the
166035 ** application:
166036 **
166037 ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
166038 **
166039 ** 2) Registers any required virtual table modules with the database
166040 ** handle returned by sqlite3rbu_db(). Also, if required, register
166041 ** the rbu_delta() implementation.
166042 **
166043 ** 3) Calls the sqlite3rbu_step() function one or more times on
166044 ** the new handle. Each call to sqlite3rbu_step() performs a single
166045 ** b-tree operation, so thousands of calls may be required to apply
166046 ** a complete update.
166047 **
166048 ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
166049 ** sqlite3rbu_step() has been called enough times to completely
166050 ** apply the update to the target database, then the RBU database
166051 ** is marked as fully applied. Otherwise, the state of the RBU
166052 ** update application is saved in the RBU database for later
166053 ** resumption.
166054 **
166055 ** See comments below for more detail on APIs.
166056 **
166057 ** If an update is only partially applied to the target database by the
166058 ** time sqlite3rbu_close() is called, various state information is saved
166059 ** within the RBU database. This allows subsequent processes to automatically
166060 ** resume the RBU update from where it left off.
166061 **
166062 ** To remove all RBU extension state information, returning an RBU database
166063 ** to its original contents, it is sufficient to drop all tables that begin
166064 ** with the prefix "rbu_"
166065 **
166066 ** DATABASE LOCKING
166067 **
166068 ** An RBU update may not be applied to a database in WAL mode. Attempting
166069 ** to do so is an error (SQLITE_ERROR).
166070 **
166071 ** While an RBU handle is open, a SHARED lock may be held on the target
166072 ** database file. This means it is possible for other clients to read the
166073 ** database, but not to write it.
166074 **
166075 ** If an RBU update is started and then suspended before it is completed,
166076 ** then an external client writes to the database, then attempting to resume
166077 ** the suspended RBU update is also an error (SQLITE_BUSY).
166078 */
166079 
166080 #ifndef _SQLITE3RBU_H
166081 #define _SQLITE3RBU_H
166082 
166083 /* #include "sqlite3.h" ** Required for error code definitions ** */
166084 
166085 #if 0
166086 extern "C" {
166087 #endif
166088 
166089 typedef struct sqlite3rbu sqlite3rbu;
166090 
166091 /*
166092 ** Open an RBU handle.
166093 **
166094 ** Argument zTarget is the path to the target database. Argument zRbu is
166095 ** the path to the RBU database. Each call to this function must be matched
166096 ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
166097 ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
166098 ** or zRbu begin with "file:", it will be interpreted as an SQLite
166099 ** database URI, not a regular file name.
166100 **
166101 ** If the zState argument is passed a NULL value, the RBU extension stores
166102 ** the current state of the update (how many rows have been updated, which
166103 ** indexes are yet to be updated etc.) within the RBU database itself. This
166104 ** can be convenient, as it means that the RBU application does not need to
166105 ** organize removing a separate state file after the update is concluded.
166106 ** Or, if zState is non-NULL, it must be a path to a database file in which
166107 ** the RBU extension can store the state of the update.
166108 **
166109 ** When resuming an RBU update, the zState argument must be passed the same
166110 ** value as when the RBU update was started.
166111 **
166112 ** Once the RBU update is finished, the RBU extension does not
166113 ** automatically remove any zState database file, even if it created it.
166114 **
166115 ** By default, RBU uses the default VFS to access the files on disk. To
166116 ** use a VFS other than the default, an SQLite "file:" URI containing a
166117 ** "vfs=..." option may be passed as the zTarget option.
166118 **
166119 ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
166120 ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
166121 ** not work out of the box with zipvfs. Refer to the comment describing
166122 ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
166123 */
166124 SQLITE_API sqlite3rbu *sqlite3rbu_open(
166125  const char *zTarget,
166126  const char *zRbu,
166127  const char *zState
166128 );
166129 
166130 /*
166131 ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
166132 ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
166133 ** that it can be suspended and resumed like an RBU update.
166134 **
166135 ** The second argument to this function identifies a database in which
166136 ** to store the state of the RBU vacuum operation if it is suspended. The
166137 ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
166138 ** operation, the state database should either not exist or be empty
166139 ** (contain no tables). If an RBU vacuum is suspended by calling
166140 ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
166141 ** returned SQLITE_DONE, the vacuum state is stored in the state database.
166142 ** The vacuum can be resumed by calling this function to open a new RBU
166143 ** handle specifying the same target and state databases.
166144 **
166145 ** If the second argument passed to this function is NULL, then the
166146 ** name of the state database is "<database>-vacuum", where <database>
166147 ** is the name of the target database file. In this case, on UNIX, if the
166148 ** state database is not already present in the file-system, it is created
166149 ** with the same permissions as the target db is made.
166150 **
166151 ** This function does not delete the state database after an RBU vacuum
166152 ** is completed, even if it created it. However, if the call to
166153 ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
166154 ** of the state tables within the state database are zeroed. This way,
166155 ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
166156 ** new RBU vacuum operation.
166157 **
166158 ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
166159 ** describing the sqlite3rbu_create_vfs() API function below for
166160 ** a description of the complications associated with using RBU with
166161 ** zipvfs databases.
166162 */
166163 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
166164  const char *zTarget,
166165  const char *zState
166166 );
166167 
166168 /*
166169 ** Internally, each RBU connection uses a separate SQLite database
166170 ** connection to access the target and rbu update databases. This
166171 ** API allows the application direct access to these database handles.
166172 **
166173 ** The first argument passed to this function must be a valid, open, RBU
166174 ** handle. The second argument should be passed zero to access the target
166175 ** database handle, or non-zero to access the rbu update database handle.
166176 ** Accessing the underlying database handles may be useful in the
166177 ** following scenarios:
166178 **
166179 ** * If any target tables are virtual tables, it may be necessary to
166180 ** call sqlite3_create_module() on the target database handle to
166181 ** register the required virtual table implementations.
166182 **
166183 ** * If the data_xxx tables in the RBU source database are virtual
166184 ** tables, the application may need to call sqlite3_create_module() on
166185 ** the rbu update db handle to any required virtual table
166186 ** implementations.
166187 **
166188 ** * If the application uses the "rbu_delta()" feature described above,
166189 ** it must use sqlite3_create_function() or similar to register the
166190 ** rbu_delta() implementation with the target database handle.
166191 **
166192 ** If an error has occurred, either while opening or stepping the RBU object,
166193 ** this function may return NULL. The error code and message may be collected
166194 ** when sqlite3rbu_close() is called.
166195 **
166196 ** Database handles returned by this function remain valid until the next
166197 ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
166198 */
166199 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
166200 
166201 /*
166202 ** Do some work towards applying the RBU update to the target db.
166203 **
166204 ** Return SQLITE_DONE if the update has been completely applied, or
166205 ** SQLITE_OK if no error occurs but there remains work to do to apply
166206 ** the RBU update. If an error does occur, some other error code is
166207 ** returned.
166208 **
166209 ** Once a call to sqlite3rbu_step() has returned a value other than
166210 ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
166211 ** that immediately return the same value.
166212 */
166213 SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
166214 
166215 /*
166216 ** Force RBU to save its state to disk.
166217 **
166218 ** If a power failure or application crash occurs during an update, following
166219 ** system recovery RBU may resume the update from the point at which the state
166220 ** was last saved. In other words, from the most recent successful call to
166221 ** sqlite3rbu_close() or this function.
166222 **
166223 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
166224 */
166225 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
166226 
166227 /*
166228 ** Close an RBU handle.
166229 **
166230 ** If the RBU update has been completely applied, mark the RBU database
166231 ** as fully applied. Otherwise, assuming no error has occurred, save the
166232 ** current state of the RBU update appliation to the RBU database.
166233 **
166234 ** If an error has already occurred as part of an sqlite3rbu_step()
166235 ** or sqlite3rbu_open() call, or if one occurs within this function, an
166236 ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
166237 ** point to a buffer containing a utf-8 formatted English language error
166238 ** message. It is the responsibility of the caller to eventually free any
166239 ** such buffer using sqlite3_free().
166240 **
166241 ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
166242 ** update has been partially applied, or SQLITE_DONE if it has been
166243 ** completely applied.
166244 */
166245 SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
166246 
166247 /*
166248 ** Return the total number of key-value operations (inserts, deletes or
166249 ** updates) that have been performed on the target database since the
166250 ** current RBU update was started.
166251 */
166252 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
166253 
166254 /*
166255 ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
166256 ** progress indications for the two stages of an RBU update. This API may
166257 ** be useful for driving GUI progress indicators and similar.
166258 **
166259 ** An RBU update is divided into two stages:
166260 **
166261 ** * Stage 1, in which changes are accumulated in an oal/wal file, and
166262 ** * Stage 2, in which the contents of the wal file are copied into the
166263 ** main database.
166264 **
166265 ** The update is visible to non-RBU clients during stage 2. During stage 1
166266 ** non-RBU reader clients may see the original database.
166267 **
166268 ** If this API is called during stage 2 of the update, output variable
166269 ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
166270 ** to a value between 0 and 10000 to indicate the permyriadage progress of
166271 ** stage 2. A value of 5000 indicates that stage 2 is half finished,
166272 ** 9000 indicates that it is 90% finished, and so on.
166273 **
166274 ** If this API is called during stage 1 of the update, output variable
166275 ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
166276 ** value to which (*pnOne) is set depends on whether or not the RBU
166277 ** database contains an "rbu_count" table. The rbu_count table, if it
166278 ** exists, must contain the same columns as the following:
166279 **
166280 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
166281 **
166282 ** There must be one row in the table for each source (data_xxx) table within
166283 ** the RBU database. The 'tbl' column should contain the name of the source
166284 ** table. The 'cnt' column should contain the number of rows within the
166285 ** source table.
166286 **
166287 ** If the rbu_count table is present and populated correctly and this
166288 ** API is called during stage 1, the *pnOne output variable is set to the
166289 ** permyriadage progress of the same stage. If the rbu_count table does
166290 ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
166291 ** table exists but is not correctly populated, the value of the *pnOne
166292 ** output variable during stage 1 is undefined.
166293 */
166294 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
166295 
166296 /*
166297 ** Obtain an indication as to the current stage of an RBU update or vacuum.
166298 ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
166299 ** defined in this file. Return values should be interpreted as follows:
166300 **
166301 ** SQLITE_RBU_STATE_OAL:
166302 ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
166303 ** may either add further data to the *-oal file, or compute data that will
166304 ** be added by a subsequent call.
166305 **
166306 ** SQLITE_RBU_STATE_MOVE:
166307 ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
166308 ** will move the *-oal file to the equivalent *-wal path. If the current
166309 ** operation is an RBU update, then the updated version of the database
166310 ** file will become visible to ordinary SQLite clients following the next
166311 ** call to sqlite3rbu_step().
166312 **
166313 ** SQLITE_RBU_STATE_CHECKPOINT:
166314 ** RBU is currently performing an incremental checkpoint. The next call to
166315 ** sqlite3rbu_step() will copy a page of data from the *-wal file into
166316 ** the target database file.
166317 **
166318 ** SQLITE_RBU_STATE_DONE:
166319 ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
166320 ** will immediately return SQLITE_DONE.
166321 **
166322 ** SQLITE_RBU_STATE_ERROR:
166323 ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
166324 ** immediately return the SQLite error code associated with the error.
166325 */
166326 #define SQLITE_RBU_STATE_OAL 1
166327 #define SQLITE_RBU_STATE_MOVE 2
166328 #define SQLITE_RBU_STATE_CHECKPOINT 3
166329 #define SQLITE_RBU_STATE_DONE 4
166330 #define SQLITE_RBU_STATE_ERROR 5
166331 
166332 SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
166333 
166334 /*
166335 ** Create an RBU VFS named zName that accesses the underlying file-system
166336 ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
166337 ** then the new RBU VFS uses the default system VFS to access the file-system.
166338 ** The new object is registered as a non-default VFS with SQLite before
166339 ** returning.
166340 **
166341 ** Part of the RBU implementation uses a custom VFS object. Usually, this
166342 ** object is created and deleted automatically by RBU.
166343 **
166344 ** The exception is for applications that also use zipvfs. In this case,
166345 ** the custom VFS must be explicitly created by the user before the RBU
166346 ** handle is opened. The RBU VFS should be installed so that the zipvfs
166347 ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
166348 ** (for example multiplexor) to access the file-system. For example,
166349 ** to assemble an RBU enabled VFS stack that uses both zipvfs and
166350 ** multiplexor (error checking omitted):
166351 **
166352 ** // Create a VFS named "multiplex" (not the default).
166353 ** sqlite3_multiplex_initialize(0, 0);
166354 **
166355 ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
166356 ** // second argument were replaced with NULL, the "rbu" VFS would
166357 ** // access the file-system via the system default VFS, bypassing the
166358 ** // multiplexor.
166359 ** sqlite3rbu_create_vfs("rbu", "multiplex");
166360 **
166361 ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
166362 ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
166363 **
166364 ** // Make zipvfs the default VFS.
166365 ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
166366 **
166367 ** Because the default VFS created above includes a RBU functionality, it
166368 ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
166369 ** that does not include the RBU layer results in an error.
166370 **
166371 ** The overhead of adding the "rbu" VFS to the system is negligible for
166372 ** non-RBU users. There is no harm in an application accessing the
166373 ** file-system via "rbu" all the time, even if it only uses RBU functionality
166374 ** occasionally.
166375 */
166376 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
166377 
166378 /*
166379 ** Deregister and destroy an RBU vfs created by an earlier call to
166380 ** sqlite3rbu_create_vfs().
166381 **
166382 ** VFS objects are not reference counted. If a VFS object is destroyed
166383 ** before all database handles that use it have been closed, the results
166384 ** are undefined.
166385 */
166386 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
166387 
166388 #if 0
166389 } /* end of the 'extern "C"' block */
166390 #endif
166391 
166392 #endif /* _SQLITE3RBU_H */
166393 
166394 /************** End of sqlite3rbu.h ******************************************/
166395 /************** Continuing where we left off in sqlite3rbu.c *****************/
166396 
166397 #if defined(_WIN32_WCE)
166398 /* #include "windows.h" */
166399 #endif
166400 
166401 /* Maximum number of prepared UPDATE statements held by this module */
166402 #define SQLITE_RBU_UPDATE_CACHESIZE 16
166403 
166404 /*
166405 ** Swap two objects of type TYPE.
166406 */
166407 #if !defined(SQLITE_AMALGAMATION)
166408 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
166409 #endif
166410 
166411 /*
166412 ** The rbu_state table is used to save the state of a partially applied
166413 ** update so that it can be resumed later. The table consists of integer
166414 ** keys mapped to values as follows:
166415 **
166416 ** RBU_STATE_STAGE:
166417 ** May be set to integer values 1, 2, 4 or 5. As follows:
166418 ** 1: the *-rbu file is currently under construction.
166419 ** 2: the *-rbu file has been constructed, but not yet moved
166420 ** to the *-wal path.
166421 ** 4: the checkpoint is underway.
166422 ** 5: the rbu update has been checkpointed.
166423 **
166424 ** RBU_STATE_TBL:
166425 ** Only valid if STAGE==1. The target database name of the table
166426 ** currently being written.
166427 **
166428 ** RBU_STATE_IDX:
166429 ** Only valid if STAGE==1. The target database name of the index
166430 ** currently being written, or NULL if the main table is currently being
166431 ** updated.
166432 **
166433 ** RBU_STATE_ROW:
166434 ** Only valid if STAGE==1. Number of rows already processed for the current
166435 ** table/index.
166436 **
166437 ** RBU_STATE_PROGRESS:
166438 ** Trbul number of sqlite3rbu_step() calls made so far as part of this
166439 ** rbu update.
166440 **
166441 ** RBU_STATE_CKPT:
166442 ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
166443 ** header created by recovering the *-wal file. This is used to detect
166444 ** cases when another client appends frames to the *-wal file in the
166445 ** middle of an incremental checkpoint (an incremental checkpoint cannot
166446 ** be continued if this happens).
166447 **
166448 ** RBU_STATE_COOKIE:
166449 ** Valid if STAGE==1. The current change-counter cookie value in the
166450 ** target db file.
166451 **
166452 ** RBU_STATE_OALSZ:
166453 ** Valid if STAGE==1. The size in bytes of the *-oal file.
166454 */
166455 #define RBU_STATE_STAGE 1
166456 #define RBU_STATE_TBL 2
166457 #define RBU_STATE_IDX 3
166458 #define RBU_STATE_ROW 4
166459 #define RBU_STATE_PROGRESS 5
166460 #define RBU_STATE_CKPT 6
166461 #define RBU_STATE_COOKIE 7
166462 #define RBU_STATE_OALSZ 8
166463 #define RBU_STATE_PHASEONESTEP 9
166464 
166465 #define RBU_STAGE_OAL 1
166466 #define RBU_STAGE_MOVE 2
166467 #define RBU_STAGE_CAPTURE 3
166468 #define RBU_STAGE_CKPT 4
166469 #define RBU_STAGE_DONE 5
166470 
166471 
166472 #define RBU_CREATE_STATE \
166473  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
166474 
166475 typedef struct RbuFrame RbuFrame;
166476 typedef struct RbuObjIter RbuObjIter;
166477 typedef struct RbuState RbuState;
166478 typedef struct rbu_vfs rbu_vfs;
166479 typedef struct rbu_file rbu_file;
166480 typedef struct RbuUpdateStmt RbuUpdateStmt;
166481 
166482 #if !defined(SQLITE_AMALGAMATION)
166483 typedef unsigned int u32;
166484 typedef unsigned short u16;
166485 typedef unsigned char u8;
166486 typedef sqlite3_int64 i64;
166487 #endif
166488 
166489 /*
166490 ** These values must match the values defined in wal.c for the equivalent
166491 ** locks. These are not magic numbers as they are part of the SQLite file
166492 ** format.
166493 */
166494 #define WAL_LOCK_WRITE 0
166495 #define WAL_LOCK_CKPT 1
166496 #define WAL_LOCK_READ0 3
166497 
166498 #define SQLITE_FCNTL_RBUCNT 5149216
166499 
166500 /*
166501 ** A structure to store values read from the rbu_state table in memory.
166502 */
166503 struct RbuState {
166504  int eStage;
166505  char *zTbl;
166506  char *zIdx;
166507  i64 iWalCksum;
166508  int nRow;
166509  i64 nProgress;
166510  u32 iCookie;
166511  i64 iOalSz;
166512  i64 nPhaseOneStep;
166513 };
166514 
166515 struct RbuUpdateStmt {
166516  char *zMask; /* Copy of update mask used with pUpdate */
166517  sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
166518  RbuUpdateStmt *pNext;
166519 };
166520 
166521 /*
166522 ** An iterator of this type is used to iterate through all objects in
166523 ** the target database that require updating. For each such table, the
166524 ** iterator visits, in order:
166525 **
166526 ** * the table itself,
166527 ** * each index of the table (zero or more points to visit), and
166528 ** * a special "cleanup table" state.
166529 **
166530 ** abIndexed:
166531 ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
166532 ** it points to an array of flags nTblCol elements in size. The flag is
166533 ** set for each column that is either a part of the PK or a part of an
166534 ** index. Or clear otherwise.
166535 **
166536 */
166537 struct RbuObjIter {
166538  sqlite3_stmt *pTblIter; /* Iterate through tables */
166539  sqlite3_stmt *pIdxIter; /* Index iterator */
166540  int nTblCol; /* Size of azTblCol[] array */
166541  char **azTblCol; /* Array of unquoted target column names */
166542  char **azTblType; /* Array of target column types */
166543  int *aiSrcOrder; /* src table col -> target table col */
166544  u8 *abTblPk; /* Array of flags, set on target PK columns */
166545  u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
166546  u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
166547  int eType; /* Table type - an RBU_PK_XXX value */
166548 
166549  /* Output variables. zTbl==0 implies EOF. */
166550  int bCleanup; /* True in "cleanup" state */
166551  const char *zTbl; /* Name of target db table */
166552  const char *zDataTbl; /* Name of rbu db table (or null) */
166553  const char *zIdx; /* Name of target db index (or null) */
166554  int iTnum; /* Root page of current object */
166555  int iPkTnum; /* If eType==EXTERNAL, root of PK index */
166556  int bUnique; /* Current index is unique */
166557  int nIndex; /* Number of aux. indexes on table zTbl */
166558 
166559  /* Statements created by rbuObjIterPrepareAll() */
166560  int nCol; /* Number of columns in current object */
166561  sqlite3_stmt *pSelect; /* Source data */
166562  sqlite3_stmt *pInsert; /* Statement for INSERT operations */
166563  sqlite3_stmt *pDelete; /* Statement for DELETE ops */
166564  sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
166565 
166566  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
166567  RbuUpdateStmt *pRbuUpdate;
166568 };
166569 
166570 /*
166571 ** Values for RbuObjIter.eType
166572 **
166573 ** 0: Table does not exist (error)
166574 ** 1: Table has an implicit rowid.
166575 ** 2: Table has an explicit IPK column.
166576 ** 3: Table has an external PK index.
166577 ** 4: Table is WITHOUT ROWID.
166578 ** 5: Table is a virtual table.
166579 */
166580 #define RBU_PK_NOTABLE 0
166581 #define RBU_PK_NONE 1
166582 #define RBU_PK_IPK 2
166583 #define RBU_PK_EXTERNAL 3
166584 #define RBU_PK_WITHOUT_ROWID 4
166585 #define RBU_PK_VTAB 5
166586 
166587 
166588 /*
166589 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
166590 ** one of the following operations.
166591 */
166592 #define RBU_INSERT 1 /* Insert on a main table b-tree */
166593 #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
166594 #define RBU_REPLACE 3 /* Delete and then insert a row */
166595 #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
166596 #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
166597 
166598 #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
166599 
166600 /*
166601 ** A single step of an incremental checkpoint - frame iWalFrame of the wal
166602 ** file should be copied to page iDbPage of the database file.
166603 */
166604 struct RbuFrame {
166605  u32 iDbPage;
166606  u32 iWalFrame;
166607 };
166608 
166609 /*
166610 ** RBU handle.
166611 **
166612 ** nPhaseOneStep:
166613 ** If the RBU database contains an rbu_count table, this value is set to
166614 ** a running estimate of the number of b-tree operations required to
166615 ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
166616 ** API to calculate the permyriadage progress of populating the *-oal file
166617 ** using the formula:
166618 **
166619 ** permyriadage = (10000 * nProgress) / nPhaseOneStep
166620 **
166621 ** nPhaseOneStep is initialized to the sum of:
166622 **
166623 ** nRow * (nIndex + 1)
166624 **
166625 ** for all source tables in the RBU database, where nRow is the number
166626 ** of rows in the source table and nIndex the number of indexes on the
166627 ** corresponding target database table.
166628 **
166629 ** This estimate is accurate if the RBU update consists entirely of
166630 ** INSERT operations. However, it is inaccurate if:
166631 **
166632 ** * the RBU update contains any UPDATE operations. If the PK specified
166633 ** for an UPDATE operation does not exist in the target table, then
166634 ** no b-tree operations are required on index b-trees. Or if the
166635 ** specified PK does exist, then (nIndex*2) such operations are
166636 ** required (one delete and one insert on each index b-tree).
166637 **
166638 ** * the RBU update contains any DELETE operations for which the specified
166639 ** PK does not exist. In this case no operations are required on index
166640 ** b-trees.
166641 **
166642 ** * the RBU update contains REPLACE operations. These are similar to
166643 ** UPDATE operations.
166644 **
166645 ** nPhaseOneStep is updated to account for the conditions above during the
166646 ** first pass of each source table. The updated nPhaseOneStep value is
166647 ** stored in the rbu_state table if the RBU update is suspended.
166648 */
166649 struct sqlite3rbu {
166650  int eStage; /* Value of RBU_STATE_STAGE field */
166651  sqlite3 *dbMain; /* target database handle */
166652  sqlite3 *dbRbu; /* rbu database handle */
166653  char *zTarget; /* Path to target db */
166654  char *zRbu; /* Path to rbu db */
166655  char *zState; /* Path to state db (or NULL if zRbu) */
166656  char zStateDb[5]; /* Db name for state ("stat" or "main") */
166657  int rc; /* Value returned by last rbu_step() call */
166658  char *zErrmsg; /* Error message if rc!=SQLITE_OK */
166659  int nStep; /* Rows processed for current object */
166660  int nProgress; /* Rows processed for all objects */
166661  RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
166662  const char *zVfsName; /* Name of automatically created rbu vfs */
166663  rbu_file *pTargetFd; /* File handle open on target db */
166664  i64 iOalSz;
166665  i64 nPhaseOneStep;
166666 
166667  /* The following state variables are used as part of the incremental
166668  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
166669  ** function rbuSetupCheckpoint() for details. */
166670  u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
166671  u32 mLock;
166672  int nFrame; /* Entries in aFrame[] array */
166673  int nFrameAlloc; /* Allocated size of aFrame[] array */
166674  RbuFrame *aFrame;
166675  int pgsz;
166676  u8 *aBuf;
166677  i64 iWalCksum;
166678 
166679  /* Used in RBU vacuum mode only */
166680  int nRbu; /* Number of RBU VFS in the stack */
166681  rbu_file *pRbuFd; /* Fd for main db of dbRbu */
166682 };
166683 
166684 /*
166685 ** An rbu VFS is implemented using an instance of this structure.
166686 */
166687 struct rbu_vfs {
166688  sqlite3_vfs base; /* rbu VFS shim methods */
166689  sqlite3_vfs *pRealVfs; /* Underlying VFS */
166690  sqlite3_mutex *mutex; /* Mutex to protect pMain */
166691  rbu_file *pMain; /* Linked list of main db files */
166692 };
166693 
166694 /*
166695 ** Each file opened by an rbu VFS is represented by an instance of
166696 ** the following structure.
166697 */
166698 struct rbu_file {
166699  sqlite3_file base; /* sqlite3_file methods */
166700  sqlite3_file *pReal; /* Underlying file handle */
166701  rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
166702  sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
166703 
166704  int openFlags; /* Flags this file was opened with */
166705  u32 iCookie; /* Cookie value for main db files */
166706  u8 iWriteVer; /* "write-version" value for main db files */
166707  u8 bNolock; /* True to fail EXCLUSIVE locks */
166708 
166709  int nShm; /* Number of entries in apShm[] array */
166710  char **apShm; /* Array of mmap'd *-shm regions */
166711  char *zDel; /* Delete this when closing file */
166712 
166713  const char *zWal; /* Wal filename for this main db file */
166714  rbu_file *pWalFd; /* Wal file descriptor for this main db */
166715  rbu_file *pMainNext; /* Next MAIN_DB file */
166716 };
166717 
166718 /*
166719 ** True for an RBU vacuum handle, or false otherwise.
166720 */
166721 #define rbuIsVacuum(p) ((p)->zTarget==0)
166722 
166723 
166724 /*************************************************************************
166725 ** The following three functions, found below:
166726 **
166727 ** rbuDeltaGetInt()
166728 ** rbuDeltaChecksum()
166729 ** rbuDeltaApply()
166730 **
166731 ** are lifted from the fossil source code (http://fossil-scm.org). They
166732 ** are used to implement the scalar SQL function rbu_fossil_delta().
166733 */
166734 
166735 /*
166736 ** Read bytes from *pz and convert them into a positive integer. When
166737 ** finished, leave *pz pointing to the first character past the end of
166738 ** the integer. The *pLen parameter holds the length of the string
166739 ** in *pz and is decremented once for each character in the integer.
166740 */
166741 static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
166742  static const signed char zValue[] = {
166743  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
166744  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
166745  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
166746  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
166747  -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
166748  25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
166749  -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
166750  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
166751  };
166752  unsigned int v = 0;
166753  int c;
166754  unsigned char *z = (unsigned char*)*pz;
166755  unsigned char *zStart = z;
166756  while( (c = zValue[0x7f&*(z++)])>=0 ){
166757  v = (v<<6) + c;
166758  }
166759  z--;
166760  *pLen -= z - zStart;
166761  *pz = (char*)z;
166762  return v;
166763 }
166764 
166765 /*
166766 ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
166767 */
166768 static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
166769  const unsigned char *z = (const unsigned char *)zIn;
166770  unsigned sum0 = 0;
166771  unsigned sum1 = 0;
166772  unsigned sum2 = 0;
166773  unsigned sum3 = 0;
166774  while(N >= 16){
166775  sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
166776  sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
166777  sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
166778  sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
166779  z += 16;
166780  N -= 16;
166781  }
166782  while(N >= 4){
166783  sum0 += z[0];
166784  sum1 += z[1];
166785  sum2 += z[2];
166786  sum3 += z[3];
166787  z += 4;
166788  N -= 4;
166789  }
166790  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
166791  switch(N){
166792  case 3: sum3 += (z[2] << 8);
166793  case 2: sum3 += (z[1] << 16);
166794  case 1: sum3 += (z[0] << 24);
166795  default: ;
166796  }
166797  return sum3;
166798 }
166799 
166800 /*
166801 ** Apply a delta.
166802 **
166803 ** The output buffer should be big enough to hold the whole output
166804 ** file and a NUL terminator at the end. The delta_output_size()
166805 ** routine will determine this size for you.
166806 **
166807 ** The delta string should be null-terminated. But the delta string
166808 ** may contain embedded NUL characters (if the input and output are
166809 ** binary files) so we also have to pass in the length of the delta in
166810 ** the lenDelta parameter.
166811 **
166812 ** This function returns the size of the output file in bytes (excluding
166813 ** the final NUL terminator character). Except, if the delta string is
166814 ** malformed or intended for use with a source file other than zSrc,
166815 ** then this routine returns -1.
166816 **
166817 ** Refer to the delta_create() documentation above for a description
166818 ** of the delta file format.
166819 */
166820 static int rbuDeltaApply(
166821  const char *zSrc, /* The source or pattern file */
166822  int lenSrc, /* Length of the source file */
166823  const char *zDelta, /* Delta to apply to the pattern */
166824  int lenDelta, /* Length of the delta */
166825  char *zOut /* Write the output into this preallocated buffer */
166826 ){
166827  unsigned int limit;
166828  unsigned int total = 0;
166829 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
166830  char *zOrigOut = zOut;
166831 #endif
166832 
166833  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
166834  if( *zDelta!='\n' ){
166835  /* ERROR: size integer not terminated by "\n" */
166836  return -1;
166837  }
166838  zDelta++; lenDelta--;
166839  while( *zDelta && lenDelta>0 ){
166840  unsigned int cnt, ofst;
166841  cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
166842  switch( zDelta[0] ){
166843  case '@': {
166844  zDelta++; lenDelta--;
166845  ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
166846  if( lenDelta>0 && zDelta[0]!=',' ){
166847  /* ERROR: copy command not terminated by ',' */
166848  return -1;
166849  }
166850  zDelta++; lenDelta--;
166851  total += cnt;
166852  if( total>limit ){
166853  /* ERROR: copy exceeds output file size */
166854  return -1;
166855  }
166856  if( (int)(ofst+cnt) > lenSrc ){
166857  /* ERROR: copy extends past end of input */
166858  return -1;
166859  }
166860  memcpy(zOut, &zSrc[ofst], cnt);
166861  zOut += cnt;
166862  break;
166863  }
166864  case ':': {
166865  zDelta++; lenDelta--;
166866  total += cnt;
166867  if( total>limit ){
166868  /* ERROR: insert command gives an output larger than predicted */
166869  return -1;
166870  }
166871  if( (int)cnt>lenDelta ){
166872  /* ERROR: insert count exceeds size of delta */
166873  return -1;
166874  }
166875  memcpy(zOut, zDelta, cnt);
166876  zOut += cnt;
166877  zDelta += cnt;
166878  lenDelta -= cnt;
166879  break;
166880  }
166881  case ';': {
166882  zDelta++; lenDelta--;
166883  zOut[0] = 0;
166884 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
166885  if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
166886  /* ERROR: bad checksum */
166887  return -1;
166888  }
166889 #endif
166890  if( total!=limit ){
166891  /* ERROR: generated size does not match predicted size */
166892  return -1;
166893  }
166894  return total;
166895  }
166896  default: {
166897  /* ERROR: unknown delta operator */
166898  return -1;
166899  }
166900  }
166901  }
166902  /* ERROR: unterminated delta */
166903  return -1;
166904 }
166905 
166906 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
166907  int size;
166908  size = rbuDeltaGetInt(&zDelta, &lenDelta);
166909  if( *zDelta!='\n' ){
166910  /* ERROR: size integer not terminated by "\n" */
166911  return -1;
166912  }
166913  return size;
166914 }
166915 
166916 /*
166917 ** End of code taken from fossil.
166918 *************************************************************************/
166919 
166920 /*
166921 ** Implementation of SQL scalar function rbu_fossil_delta().
166922 **
166923 ** This function applies a fossil delta patch to a blob. Exactly two
166924 ** arguments must be passed to this function. The first is the blob to
166925 ** patch and the second the patch to apply. If no error occurs, this
166926 ** function returns the patched blob.
166927 */
166928 static void rbuFossilDeltaFunc(
166929  sqlite3_context *context,
166930  int argc,
166931  sqlite3_value **argv
166932 ){
166933  const char *aDelta;
166934  int nDelta;
166935  const char *aOrig;
166936  int nOrig;
166937 
166938  int nOut;
166939  int nOut2;
166940  char *aOut;
166941 
166942  assert( argc==2 );
166943 
166944  nOrig = sqlite3_value_bytes(argv[0]);
166945  aOrig = (const char*)sqlite3_value_blob(argv[0]);
166946  nDelta = sqlite3_value_bytes(argv[1]);
166947  aDelta = (const char*)sqlite3_value_blob(argv[1]);
166948 
166949  /* Figure out the size of the output */
166950  nOut = rbuDeltaOutputSize(aDelta, nDelta);
166951  if( nOut<0 ){
166952  sqlite3_result_error(context, "corrupt fossil delta", -1);
166953  return;
166954  }
166955 
166956  aOut = sqlite3_malloc(nOut+1);
166957  if( aOut==0 ){
166958  sqlite3_result_error_nomem(context);
166959  }else{
166960  nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
166961  if( nOut2!=nOut ){
166962  sqlite3_result_error(context, "corrupt fossil delta", -1);
166963  }else{
166964  sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
166965  }
166966  }
166967 }
166968 
166969 
166970 /*
166971 ** Prepare the SQL statement in buffer zSql against database handle db.
166972 ** If successful, set *ppStmt to point to the new statement and return
166973 ** SQLITE_OK.
166974 **
166975 ** Otherwise, if an error does occur, set *ppStmt to NULL and return
166976 ** an SQLite error code. Additionally, set output variable *pzErrmsg to
166977 ** point to a buffer containing an error message. It is the responsibility
166978 ** of the caller to (eventually) free this buffer using sqlite3_free().
166979 */
166980 static int prepareAndCollectError(
166981  sqlite3 *db,
166982  sqlite3_stmt **ppStmt,
166983  char **pzErrmsg,
166984  const char *zSql
166985 ){
166986  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
166987  if( rc!=SQLITE_OK ){
166988  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166989  *ppStmt = 0;
166990  }
166991  return rc;
166992 }
166993 
166994 /*
166995 ** Reset the SQL statement passed as the first argument. Return a copy
166996 ** of the value returned by sqlite3_reset().
166997 **
166998 ** If an error has occurred, then set *pzErrmsg to point to a buffer
166999 ** containing an error message. It is the responsibility of the caller
167000 ** to eventually free this buffer using sqlite3_free().
167001 */
167002 static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
167003  int rc = sqlite3_reset(pStmt);
167004  if( rc!=SQLITE_OK ){
167005  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
167006  }
167007  return rc;
167008 }
167009 
167010 /*
167011 ** Unless it is NULL, argument zSql points to a buffer allocated using
167012 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
167013 ** statement against database db and frees the buffer. If statement
167014 ** compilation is successful, *ppStmt is set to point to the new statement
167015 ** handle and SQLITE_OK is returned.
167016 **
167017 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
167018 ** returned. In this case, *pzErrmsg may also be set to point to an error
167019 ** message. It is the responsibility of the caller to free this error message
167020 ** buffer using sqlite3_free().
167021 **
167022 ** If argument zSql is NULL, this function assumes that an OOM has occurred.
167023 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
167024 */
167025 static int prepareFreeAndCollectError(
167026  sqlite3 *db,
167027  sqlite3_stmt **ppStmt,
167028  char **pzErrmsg,
167029  char *zSql
167030 ){
167031  int rc;
167032  assert( *pzErrmsg==0 );
167033  if( zSql==0 ){
167034  rc = SQLITE_NOMEM;
167035  *ppStmt = 0;
167036  }else{
167037  rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
167038  sqlite3_free(zSql);
167039  }
167040  return rc;
167041 }
167042 
167043 /*
167044 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
167045 ** by an earlier call to rbuObjIterCacheTableInfo().
167046 */
167047 static void rbuObjIterFreeCols(RbuObjIter *pIter){
167048  int i;
167049  for(i=0; i<pIter->nTblCol; i++){
167050  sqlite3_free(pIter->azTblCol[i]);
167051  sqlite3_free(pIter->azTblType[i]);
167052  }
167053  sqlite3_free(pIter->azTblCol);
167054  pIter->azTblCol = 0;
167055  pIter->azTblType = 0;
167056  pIter->aiSrcOrder = 0;
167057  pIter->abTblPk = 0;
167058  pIter->abNotNull = 0;
167059  pIter->nTblCol = 0;
167060  pIter->eType = 0; /* Invalid value */
167061 }
167062 
167063 /*
167064 ** Finalize all statements and free all allocations that are specific to
167065 ** the current object (table/index pair).
167066 */
167067 static void rbuObjIterClearStatements(RbuObjIter *pIter){
167068  RbuUpdateStmt *pUp;
167069 
167070  sqlite3_finalize(pIter->pSelect);
167071  sqlite3_finalize(pIter->pInsert);
167072  sqlite3_finalize(pIter->pDelete);
167073  sqlite3_finalize(pIter->pTmpInsert);
167074  pUp = pIter->pRbuUpdate;
167075  while( pUp ){
167076  RbuUpdateStmt *pTmp = pUp->pNext;
167077  sqlite3_finalize(pUp->pUpdate);
167078  sqlite3_free(pUp);
167079  pUp = pTmp;
167080  }
167081 
167082  pIter->pSelect = 0;
167083  pIter->pInsert = 0;
167084  pIter->pDelete = 0;
167085  pIter->pRbuUpdate = 0;
167086  pIter->pTmpInsert = 0;
167087  pIter->nCol = 0;
167088 }
167089 
167090 /*
167091 ** Clean up any resources allocated as part of the iterator object passed
167092 ** as the only argument.
167093 */
167094 static void rbuObjIterFinalize(RbuObjIter *pIter){
167095  rbuObjIterClearStatements(pIter);
167096  sqlite3_finalize(pIter->pTblIter);
167097  sqlite3_finalize(pIter->pIdxIter);
167098  rbuObjIterFreeCols(pIter);
167099  memset(pIter, 0, sizeof(RbuObjIter));
167100 }
167101 
167102 /*
167103 ** Advance the iterator to the next position.
167104 **
167105 ** If no error occurs, SQLITE_OK is returned and the iterator is left
167106 ** pointing to the next entry. Otherwise, an error code and message is
167107 ** left in the RBU handle passed as the first argument. A copy of the
167108 ** error code is returned.
167109 */
167110 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
167111  int rc = p->rc;
167112  if( rc==SQLITE_OK ){
167113 
167114  /* Free any SQLite statements used while processing the previous object */
167115  rbuObjIterClearStatements(pIter);
167116  if( pIter->zIdx==0 ){
167117  rc = sqlite3_exec(p->dbMain,
167118  "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
167119  "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
167120  "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
167121  "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
167122  , 0, 0, &p->zErrmsg
167123  );
167124  }
167125 
167126  if( rc==SQLITE_OK ){
167127  if( pIter->bCleanup ){
167128  rbuObjIterFreeCols(pIter);
167129  pIter->bCleanup = 0;
167130  rc = sqlite3_step(pIter->pTblIter);
167131  if( rc!=SQLITE_ROW ){
167132  rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
167133  pIter->zTbl = 0;
167134  }else{
167135  pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
167136  pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
167137  rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
167138  }
167139  }else{
167140  if( pIter->zIdx==0 ){
167141  sqlite3_stmt *pIdx = pIter->pIdxIter;
167142  rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
167143  }
167144  if( rc==SQLITE_OK ){
167145  rc = sqlite3_step(pIter->pIdxIter);
167146  if( rc!=SQLITE_ROW ){
167147  rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
167148  pIter->bCleanup = 1;
167149  pIter->zIdx = 0;
167150  }else{
167151  pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
167152  pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
167153  pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
167154  rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
167155  }
167156  }
167157  }
167158  }
167159  }
167160 
167161  if( rc!=SQLITE_OK ){
167162  rbuObjIterFinalize(pIter);
167163  p->rc = rc;
167164  }
167165  return rc;
167166 }
167167 
167168 
167169 /*
167170 ** The implementation of the rbu_target_name() SQL function. This function
167171 ** accepts one or two arguments. The first argument is the name of a table -
167172 ** the name of a table in the RBU database. The second, if it is present, is 1
167173 ** for a view or 0 for a table.
167174 **
167175 ** For a non-vacuum RBU handle, if the table name matches the pattern:
167176 **
167177 ** data[0-9]_<name>
167178 **
167179 ** where <name> is any sequence of 1 or more characters, <name> is returned.
167180 ** Otherwise, if the only argument does not match the above pattern, an SQL
167181 ** NULL is returned.
167182 **
167183 ** "data_t1" -> "t1"
167184 ** "data0123_t2" -> "t2"
167185 ** "dataAB_t3" -> NULL
167186 **
167187 ** For an rbu vacuum handle, a copy of the first argument is returned if
167188 ** the second argument is either missing or 0 (not a view).
167189 */
167190 static void rbuTargetNameFunc(
167191  sqlite3_context *pCtx,
167192  int argc,
167193  sqlite3_value **argv
167194 ){
167195  sqlite3rbu *p = sqlite3_user_data(pCtx);
167196  const char *zIn;
167197  assert( argc==1 || argc==2 );
167198 
167199  zIn = (const char*)sqlite3_value_text(argv[0]);
167200  if( zIn ){
167201  if( rbuIsVacuum(p) ){
167202  if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
167203  sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
167204  }
167205  }else{
167206  if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
167207  int i;
167208  for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
167209  if( zIn[i]=='_' && zIn[i+1] ){
167210  sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
167211  }
167212  }
167213  }
167214  }
167215 }
167216 
167217 /*
167218 ** Initialize the iterator structure passed as the second argument.
167219 **
167220 ** If no error occurs, SQLITE_OK is returned and the iterator is left
167221 ** pointing to the first entry. Otherwise, an error code and message is
167222 ** left in the RBU handle passed as the first argument. A copy of the
167223 ** error code is returned.
167224 */
167225 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
167226  int rc;
167227  memset(pIter, 0, sizeof(RbuObjIter));
167228 
167229  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
167230  sqlite3_mprintf(
167231  "SELECT rbu_target_name(name, type='view') AS target, name "
167232  "FROM sqlite_master "
167233  "WHERE type IN ('table', 'view') AND target IS NOT NULL "
167234  " %s "
167235  "ORDER BY name"
167236  , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
167237 
167238  if( rc==SQLITE_OK ){
167239  rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
167240  "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
167241  " FROM main.sqlite_master "
167242  " WHERE type='index' AND tbl_name = ?"
167243  );
167244  }
167245 
167246  pIter->bCleanup = 1;
167247  p->rc = rc;
167248  return rbuObjIterNext(p, pIter);
167249 }
167250 
167251 /*
167252 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
167253 ** an error code is stored in the RBU handle passed as the first argument.
167254 **
167255 ** If an error has already occurred (p->rc is already set to something other
167256 ** than SQLITE_OK), then this function returns NULL without modifying the
167257 ** stored error code. In this case it still calls sqlite3_free() on any
167258 ** printf() parameters associated with %z conversions.
167259 */
167260 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
167261  char *zSql = 0;
167262  va_list ap;
167263  va_start(ap, zFmt);
167264  zSql = sqlite3_vmprintf(zFmt, ap);
167265  if( p->rc==SQLITE_OK ){
167266  if( zSql==0 ) p->rc = SQLITE_NOMEM;
167267  }else{
167268  sqlite3_free(zSql);
167269  zSql = 0;
167270  }
167271  va_end(ap);
167272  return zSql;
167273 }
167274 
167275 /*
167276 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
167277 ** arguments are the usual subsitution values. This function performs
167278 ** the printf() style substitutions and executes the result as an SQL
167279 ** statement on the RBU handles database.
167280 **
167281 ** If an error occurs, an error code and error message is stored in the
167282 ** RBU handle. If an error has already occurred when this function is
167283 ** called, it is a no-op.
167284 */
167285 static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
167286  va_list ap;
167287  char *zSql;
167288  va_start(ap, zFmt);
167289  zSql = sqlite3_vmprintf(zFmt, ap);
167290  if( p->rc==SQLITE_OK ){
167291  if( zSql==0 ){
167292  p->rc = SQLITE_NOMEM;
167293  }else{
167294  p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
167295  }
167296  }
167297  sqlite3_free(zSql);
167298  va_end(ap);
167299  return p->rc;
167300 }
167301 
167302 /*
167303 ** Attempt to allocate and return a pointer to a zeroed block of nByte
167304 ** bytes.
167305 **
167306 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
167307 ** error code in the rbu handle passed as the first argument. Or, if an
167308 ** error has already occurred when this function is called, return NULL
167309 ** immediately without attempting the allocation or modifying the stored
167310 ** error code.
167311 */
167312 static void *rbuMalloc(sqlite3rbu *p, int nByte){
167313  void *pRet = 0;
167314  if( p->rc==SQLITE_OK ){
167315  assert( nByte>0 );
167316  pRet = sqlite3_malloc64(nByte);
167317  if( pRet==0 ){
167318  p->rc = SQLITE_NOMEM;
167319  }else{
167320  memset(pRet, 0, nByte);
167321  }
167322  }
167323  return pRet;
167324 }
167325 
167326 
167327 /*
167328 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
167329 ** there is room for at least nCol elements. If an OOM occurs, store an
167330 ** error code in the RBU handle passed as the first argument.
167331 */
167332 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
167333  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
167334  char **azNew;
167335 
167336  azNew = (char**)rbuMalloc(p, nByte);
167337  if( azNew ){
167338  pIter->azTblCol = azNew;
167339  pIter->azTblType = &azNew[nCol];
167340  pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
167341  pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
167342  pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
167343  pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
167344  }
167345 }
167346 
167347 /*
167348 ** The first argument must be a nul-terminated string. This function
167349 ** returns a copy of the string in memory obtained from sqlite3_malloc().
167350 ** It is the responsibility of the caller to eventually free this memory
167351 ** using sqlite3_free().
167352 **
167353 ** If an OOM condition is encountered when attempting to allocate memory,
167354 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
167355 ** if the allocation succeeds, (*pRc) is left unchanged.
167356 */
167357 static char *rbuStrndup(const char *zStr, int *pRc){
167358  char *zRet = 0;
167359 
167360  assert( *pRc==SQLITE_OK );
167361  if( zStr ){
167362  size_t nCopy = strlen(zStr) + 1;
167363  zRet = (char*)sqlite3_malloc64(nCopy);
167364  if( zRet ){
167365  memcpy(zRet, zStr, nCopy);
167366  }else{
167367  *pRc = SQLITE_NOMEM;
167368  }
167369  }
167370 
167371  return zRet;
167372 }
167373 
167374 /*
167375 ** Finalize the statement passed as the second argument.
167376 **
167377 ** If the sqlite3_finalize() call indicates that an error occurs, and the
167378 ** rbu handle error code is not already set, set the error code and error
167379 ** message accordingly.
167380 */
167381 static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
167382  sqlite3 *db = sqlite3_db_handle(pStmt);
167383  int rc = sqlite3_finalize(pStmt);
167384  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
167385  p->rc = rc;
167386  p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
167387  }
167388 }
167389 
167390 /* Determine the type of a table.
167391 **
167392 ** peType is of type (int*), a pointer to an output parameter of type
167393 ** (int). This call sets the output parameter as follows, depending
167394 ** on the type of the table specified by parameters dbName and zTbl.
167395 **
167396 ** RBU_PK_NOTABLE: No such table.
167397 ** RBU_PK_NONE: Table has an implicit rowid.
167398 ** RBU_PK_IPK: Table has an explicit IPK column.
167399 ** RBU_PK_EXTERNAL: Table has an external PK index.
167400 ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
167401 ** RBU_PK_VTAB: Table is a virtual table.
167402 **
167403 ** Argument *piPk is also of type (int*), and also points to an output
167404 ** parameter. Unless the table has an external primary key index
167405 ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
167406 ** if the table does have an external primary key index, then *piPk
167407 ** is set to the root page number of the primary key index before
167408 ** returning.
167409 **
167410 ** ALGORITHM:
167411 **
167412 ** if( no entry exists in sqlite_master ){
167413 ** return RBU_PK_NOTABLE
167414 ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
167415 ** return RBU_PK_VTAB
167416 ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
167417 ** if( the index that is the pk exists in sqlite_master ){
167418 ** *piPK = rootpage of that index.
167419 ** return RBU_PK_EXTERNAL
167420 ** }else{
167421 ** return RBU_PK_WITHOUT_ROWID
167422 ** }
167423 ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
167424 ** return RBU_PK_IPK
167425 ** }else{
167426 ** return RBU_PK_NONE
167427 ** }
167428 */
167429 static void rbuTableType(
167430  sqlite3rbu *p,
167431  const char *zTab,
167432  int *peType,
167433  int *piTnum,
167434  int *piPk
167435 ){
167436  /*
167437  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
167438  ** 1) PRAGMA index_list = ?
167439  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
167440  ** 3) PRAGMA table_info = ?
167441  */
167442  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
167443 
167444  *peType = RBU_PK_NOTABLE;
167445  *piPk = 0;
167446 
167447  assert( p->rc==SQLITE_OK );
167448  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
167449  sqlite3_mprintf(
167450  "SELECT (sql LIKE 'create virtual%%'), rootpage"
167451  " FROM sqlite_master"
167452  " WHERE name=%Q", zTab
167453  ));
167454  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
167455  /* Either an error, or no such table. */
167456  goto rbuTableType_end;
167457  }
167458  if( sqlite3_column_int(aStmt[0], 0) ){
167459  *peType = RBU_PK_VTAB; /* virtual table */
167460  goto rbuTableType_end;
167461  }
167462  *piTnum = sqlite3_column_int(aStmt[0], 1);
167463 
167464  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
167465  sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
167466  );
167467  if( p->rc ) goto rbuTableType_end;
167468  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
167469  const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
167470  const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
167471  if( zOrig && zIdx && zOrig[0]=='p' ){
167472  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
167473  sqlite3_mprintf(
167474  "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
167475  ));
167476  if( p->rc==SQLITE_OK ){
167477  if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
167478  *piPk = sqlite3_column_int(aStmt[2], 0);
167479  *peType = RBU_PK_EXTERNAL;
167480  }else{
167481  *peType = RBU_PK_WITHOUT_ROWID;
167482  }
167483  }
167484  goto rbuTableType_end;
167485  }
167486  }
167487 
167488  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
167489  sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
167490  );
167491  if( p->rc==SQLITE_OK ){
167492  while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
167493  if( sqlite3_column_int(aStmt[3],5)>0 ){
167494  *peType = RBU_PK_IPK; /* explicit IPK column */
167495  goto rbuTableType_end;
167496  }
167497  }
167498  *peType = RBU_PK_NONE;
167499  }
167500 
167501 rbuTableType_end: {
167502  unsigned int i;
167503  for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
167504  rbuFinalize(p, aStmt[i]);
167505  }
167506  }
167507 }
167508 
167509 /*
167510 ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
167511 ** the pIter->abIndexed[] array.
167512 */
167513 static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
167514  sqlite3_stmt *pList = 0;
167515  int bIndex = 0;
167516 
167517  if( p->rc==SQLITE_OK ){
167518  memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
167519  p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
167520  sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
167521  );
167522  }
167523 
167524  pIter->nIndex = 0;
167525  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
167526  const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
167527  sqlite3_stmt *pXInfo = 0;
167528  if( zIdx==0 ) break;
167529  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
167530  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
167531  );
167532  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
167533  int iCid = sqlite3_column_int(pXInfo, 1);
167534  if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
167535  }
167536  rbuFinalize(p, pXInfo);
167537  bIndex = 1;
167538  pIter->nIndex++;
167539  }
167540 
167541  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
167542  /* "PRAGMA index_list" includes the main PK b-tree */
167543  pIter->nIndex--;
167544  }
167545 
167546  rbuFinalize(p, pList);
167547  if( bIndex==0 ) pIter->abIndexed = 0;
167548 }
167549 
167550 
167551 /*
167552 ** If they are not already populated, populate the pIter->azTblCol[],
167553 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
167554 ** the table (not index) that the iterator currently points to.
167555 **
167556 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
167557 ** an error does occur, an error code and error message are also left in
167558 ** the RBU handle.
167559 */
167560 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
167561  if( pIter->azTblCol==0 ){
167562  sqlite3_stmt *pStmt = 0;
167563  int nCol = 0;
167564  int i; /* for() loop iterator variable */
167565  int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
167566  int iOrder = 0;
167567  int iTnum = 0;
167568 
167569  /* Figure out the type of table this step will deal with. */
167570  assert( pIter->eType==0 );
167571  rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
167572  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
167573  p->rc = SQLITE_ERROR;
167574  p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
167575  }
167576  if( p->rc ) return p->rc;
167577  if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
167578 
167579  assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
167580  || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
167581  || pIter->eType==RBU_PK_VTAB
167582  );
167583 
167584  /* Populate the azTblCol[] and nTblCol variables based on the columns
167585  ** of the input table. Ignore any input table columns that begin with
167586  ** "rbu_". */
167587  p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
167588  sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
167589  );
167590  if( p->rc==SQLITE_OK ){
167591  nCol = sqlite3_column_count(pStmt);
167592  rbuAllocateIterArrays(p, pIter, nCol);
167593  }
167594  for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
167595  const char *zName = (const char*)sqlite3_column_name(pStmt, i);
167596  if( sqlite3_strnicmp("rbu_", zName, 4) ){
167597  char *zCopy = rbuStrndup(zName, &p->rc);
167598  pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
167599  pIter->azTblCol[pIter->nTblCol++] = zCopy;
167600  }
167601  else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
167602  bRbuRowid = 1;
167603  }
167604  }
167605  sqlite3_finalize(pStmt);
167606  pStmt = 0;
167607 
167608  if( p->rc==SQLITE_OK
167609  && rbuIsVacuum(p)==0
167610  && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
167611  ){
167612  p->rc = SQLITE_ERROR;
167613  p->zErrmsg = sqlite3_mprintf(
167614  "table %q %s rbu_rowid column", pIter->zDataTbl,
167615  (bRbuRowid ? "may not have" : "requires")
167616  );
167617  }
167618 
167619  /* Check that all non-HIDDEN columns in the destination table are also
167620  ** present in the input table. Populate the abTblPk[], azTblType[] and
167621  ** aiTblOrder[] arrays at the same time. */
167622  if( p->rc==SQLITE_OK ){
167623  p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
167624  sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
167625  );
167626  }
167627  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
167628  const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
167629  if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
167630  for(i=iOrder; i<pIter->nTblCol; i++){
167631  if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
167632  }
167633  if( i==pIter->nTblCol ){
167634  p->rc = SQLITE_ERROR;
167635  p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
167636  pIter->zDataTbl, zName
167637  );
167638  }else{
167639  int iPk = sqlite3_column_int(pStmt, 5);
167640  int bNotNull = sqlite3_column_int(pStmt, 3);
167641  const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
167642 
167643  if( i!=iOrder ){
167644  SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
167645  SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
167646  }
167647 
167648  pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
167649  pIter->abTblPk[iOrder] = (iPk!=0);
167650  pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
167651  iOrder++;
167652  }
167653  }
167654 
167655  rbuFinalize(p, pStmt);
167656  rbuObjIterCacheIndexedCols(p, pIter);
167657  assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
167658  assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
167659  }
167660 
167661  return p->rc;
167662 }
167663 
167664 /*
167665 ** This function constructs and returns a pointer to a nul-terminated
167666 ** string containing some SQL clause or list based on one or more of the
167667 ** column names currently stored in the pIter->azTblCol[] array.
167668 */
167669 static char *rbuObjIterGetCollist(
167670  sqlite3rbu *p, /* RBU object */
167671  RbuObjIter *pIter /* Object iterator for column names */
167672 ){
167673  char *zList = 0;
167674  const char *zSep = "";
167675  int i;
167676  for(i=0; i<pIter->nTblCol; i++){
167677  const char *z = pIter->azTblCol[i];
167678  zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
167679  zSep = ", ";
167680  }
167681  return zList;
167682 }
167683 
167684 /*
167685 ** This function is used to create a SELECT list (the list of SQL
167686 ** expressions that follows a SELECT keyword) for a SELECT statement
167687 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
167688 ** index object currently indicated by the iterator object passed as the
167689 ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
167690 ** to obtain the required information.
167691 **
167692 ** If the index is of the following form:
167693 **
167694 ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
167695 **
167696 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
167697 ** "ipk", the returned string is:
167698 **
167699 ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
167700 **
167701 ** As well as the returned string, three other malloc'd strings are
167702 ** returned via output parameters. As follows:
167703 **
167704 ** pzImposterCols: ...
167705 ** pzImposterPk: ...
167706 ** pzWhere: ...
167707 */
167708 static char *rbuObjIterGetIndexCols(
167709  sqlite3rbu *p, /* RBU object */
167710  RbuObjIter *pIter, /* Object iterator for column names */
167711  char **pzImposterCols, /* OUT: Columns for imposter table */
167712  char **pzImposterPk, /* OUT: Imposter PK clause */
167713  char **pzWhere, /* OUT: WHERE clause */
167714  int *pnBind /* OUT: Trbul number of columns */
167715 ){
167716  int rc = p->rc; /* Error code */
167717  int rc2; /* sqlite3_finalize() return code */
167718  char *zRet = 0; /* String to return */
167719  char *zImpCols = 0; /* String to return via *pzImposterCols */
167720  char *zImpPK = 0; /* String to return via *pzImposterPK */
167721  char *zWhere = 0; /* String to return via *pzWhere */
167722  int nBind = 0; /* Value to return via *pnBind */
167723  const char *zCom = ""; /* Set to ", " later on */
167724  const char *zAnd = ""; /* Set to " AND " later on */
167725  sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
167726 
167727  if( rc==SQLITE_OK ){
167728  assert( p->zErrmsg==0 );
167729  rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
167730  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
167731  );
167732  }
167733 
167734  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
167735  int iCid = sqlite3_column_int(pXInfo, 1);
167736  int bDesc = sqlite3_column_int(pXInfo, 3);
167737  const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
167738  const char *zCol;
167739  const char *zType;
167740 
167741  if( iCid<0 ){
167742  /* An integer primary key. If the table has an explicit IPK, use
167743  ** its name. Otherwise, use "rbu_rowid". */
167744  if( pIter->eType==RBU_PK_IPK ){
167745  int i;
167746  for(i=0; pIter->abTblPk[i]==0; i++);
167747  assert( i<pIter->nTblCol );
167748  zCol = pIter->azTblCol[i];
167749  }else if( rbuIsVacuum(p) ){
167750  zCol = "_rowid_";
167751  }else{
167752  zCol = "rbu_rowid";
167753  }
167754  zType = "INTEGER";
167755  }else{
167756  zCol = pIter->azTblCol[iCid];
167757  zType = pIter->azTblType[iCid];
167758  }
167759 
167760  zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
167761  if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
167762  const char *zOrder = (bDesc ? " DESC" : "");
167763  zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
167764  zImpPK, zCom, nBind, zCol, zOrder
167765  );
167766  }
167767  zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
167768  zImpCols, zCom, nBind, zCol, zType, zCollate
167769  );
167770  zWhere = sqlite3_mprintf(
167771  "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
167772  );
167773  if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
167774  zCom = ", ";
167775  zAnd = " AND ";
167776  nBind++;
167777  }
167778 
167779  rc2 = sqlite3_finalize(pXInfo);
167780  if( rc==SQLITE_OK ) rc = rc2;
167781 
167782  if( rc!=SQLITE_OK ){
167783  sqlite3_free(zRet);
167784  sqlite3_free(zImpCols);
167785  sqlite3_free(zImpPK);
167786  sqlite3_free(zWhere);
167787  zRet = 0;
167788  zImpCols = 0;
167789  zImpPK = 0;
167790  zWhere = 0;
167791  p->rc = rc;
167792  }
167793 
167794  *pzImposterCols = zImpCols;
167795  *pzImposterPk = zImpPK;
167796  *pzWhere = zWhere;
167797  *pnBind = nBind;
167798  return zRet;
167799 }
167800 
167801 /*
167802 ** Assuming the current table columns are "a", "b" and "c", and the zObj
167803 ** paramter is passed "old", return a string of the form:
167804 **
167805 ** "old.a, old.b, old.b"
167806 **
167807 ** With the column names escaped.
167808 **
167809 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
167810 ** the text ", old._rowid_" to the returned value.
167811 */
167812 static char *rbuObjIterGetOldlist(
167813  sqlite3rbu *p,
167814  RbuObjIter *pIter,
167815  const char *zObj
167816 ){
167817  char *zList = 0;
167818  if( p->rc==SQLITE_OK && pIter->abIndexed ){
167819  const char *zS = "";
167820  int i;
167821  for(i=0; i<pIter->nTblCol; i++){
167822  if( pIter->abIndexed[i] ){
167823  const char *zCol = pIter->azTblCol[i];
167824  zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
167825  }else{
167826  zList = sqlite3_mprintf("%z%sNULL", zList, zS);
167827  }
167828  zS = ", ";
167829  if( zList==0 ){
167830  p->rc = SQLITE_NOMEM;
167831  break;
167832  }
167833  }
167834 
167835  /* For a table with implicit rowids, append "old._rowid_" to the list. */
167836  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
167837  zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
167838  }
167839  }
167840  return zList;
167841 }
167842 
167843 /*
167844 ** Return an expression that can be used in a WHERE clause to match the
167845 ** primary key of the current table. For example, if the table is:
167846 **
167847 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
167848 **
167849 ** Return the string:
167850 **
167851 ** "b = ?1 AND c = ?2"
167852 */
167853 static char *rbuObjIterGetWhere(
167854  sqlite3rbu *p,
167855  RbuObjIter *pIter
167856 ){
167857  char *zList = 0;
167858  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
167859  zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
167860  }else if( pIter->eType==RBU_PK_EXTERNAL ){
167861  const char *zSep = "";
167862  int i;
167863  for(i=0; i<pIter->nTblCol; i++){
167864  if( pIter->abTblPk[i] ){
167865  zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
167866  zSep = " AND ";
167867  }
167868  }
167869  zList = rbuMPrintf(p,
167870  "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
167871  );
167872 
167873  }else{
167874  const char *zSep = "";
167875  int i;
167876  for(i=0; i<pIter->nTblCol; i++){
167877  if( pIter->abTblPk[i] ){
167878  const char *zCol = pIter->azTblCol[i];
167879  zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
167880  zSep = " AND ";
167881  }
167882  }
167883  }
167884  return zList;
167885 }
167886 
167887 /*
167888 ** The SELECT statement iterating through the keys for the current object
167889 ** (p->objiter.pSelect) currently points to a valid row. However, there
167890 ** is something wrong with the rbu_control value in the rbu_control value
167891 ** stored in the (p->nCol+1)'th column. Set the error code and error message
167892 ** of the RBU handle to something reflecting this.
167893 */
167894 static void rbuBadControlError(sqlite3rbu *p){
167895  p->rc = SQLITE_ERROR;
167896  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
167897 }
167898 
167899 
167900 /*
167901 ** Return a nul-terminated string containing the comma separated list of
167902 ** assignments that should be included following the "SET" keyword of
167903 ** an UPDATE statement used to update the table object that the iterator
167904 ** passed as the second argument currently points to if the rbu_control
167905 ** column of the data_xxx table entry is set to zMask.
167906 **
167907 ** The memory for the returned string is obtained from sqlite3_malloc().
167908 ** It is the responsibility of the caller to eventually free it using
167909 ** sqlite3_free().
167910 **
167911 ** If an OOM error is encountered when allocating space for the new
167912 ** string, an error code is left in the rbu handle passed as the first
167913 ** argument and NULL is returned. Or, if an error has already occurred
167914 ** when this function is called, NULL is returned immediately, without
167915 ** attempting the allocation or modifying the stored error code.
167916 */
167917 static char *rbuObjIterGetSetlist(
167918  sqlite3rbu *p,
167919  RbuObjIter *pIter,
167920  const char *zMask
167921 ){
167922  char *zList = 0;
167923  if( p->rc==SQLITE_OK ){
167924  int i;
167925 
167926  if( (int)strlen(zMask)!=pIter->nTblCol ){
167927  rbuBadControlError(p);
167928  }else{
167929  const char *zSep = "";
167930  for(i=0; i<pIter->nTblCol; i++){
167931  char c = zMask[pIter->aiSrcOrder[i]];
167932  if( c=='x' ){
167933  zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
167934  zList, zSep, pIter->azTblCol[i], i+1
167935  );
167936  zSep = ", ";
167937  }
167938  else if( c=='d' ){
167939  zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
167940  zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
167941  );
167942  zSep = ", ";
167943  }
167944  else if( c=='f' ){
167945  zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
167946  zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
167947  );
167948  zSep = ", ";
167949  }
167950  }
167951  }
167952  }
167953  return zList;
167954 }
167955 
167956 /*
167957 ** Return a nul-terminated string consisting of nByte comma separated
167958 ** "?" expressions. For example, if nByte is 3, return a pointer to
167959 ** a buffer containing the string "?,?,?".
167960 **
167961 ** The memory for the returned string is obtained from sqlite3_malloc().
167962 ** It is the responsibility of the caller to eventually free it using
167963 ** sqlite3_free().
167964 **
167965 ** If an OOM error is encountered when allocating space for the new
167966 ** string, an error code is left in the rbu handle passed as the first
167967 ** argument and NULL is returned. Or, if an error has already occurred
167968 ** when this function is called, NULL is returned immediately, without
167969 ** attempting the allocation or modifying the stored error code.
167970 */
167971 static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
167972  char *zRet = 0;
167973  int nByte = nBind*2 + 1;
167974 
167975  zRet = (char*)rbuMalloc(p, nByte);
167976  if( zRet ){
167977  int i;
167978  for(i=0; i<nBind; i++){
167979  zRet[i*2] = '?';
167980  zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
167981  }
167982  }
167983  return zRet;
167984 }
167985 
167986 /*
167987 ** The iterator currently points to a table (not index) of type
167988 ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
167989 ** declaration for the corresponding imposter table. For example,
167990 ** if the iterator points to a table created as:
167991 **
167992 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
167993 **
167994 ** this function returns:
167995 **
167996 ** PRIMARY KEY("b", "a" DESC)
167997 */
167998 static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
167999  char *z = 0;
168000  assert( pIter->zIdx==0 );
168001  if( p->rc==SQLITE_OK ){
168002  const char *zSep = "PRIMARY KEY(";
168003  sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
168004  sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
168005 
168006  p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
168007  sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
168008  );
168009  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
168010  const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
168011  if( zOrig && strcmp(zOrig, "pk")==0 ){
168012  const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
168013  if( zIdx ){
168014  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
168015  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
168016  );
168017  }
168018  break;
168019  }
168020  }
168021  rbuFinalize(p, pXList);
168022 
168023  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
168024  if( sqlite3_column_int(pXInfo, 5) ){
168025  /* int iCid = sqlite3_column_int(pXInfo, 0); */
168026  const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
168027  const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
168028  z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
168029  zSep = ", ";
168030  }
168031  }
168032  z = rbuMPrintf(p, "%z)", z);
168033  rbuFinalize(p, pXInfo);
168034  }
168035  return z;
168036 }
168037 
168038 /*
168039 ** This function creates the second imposter table used when writing to
168040 ** a table b-tree where the table has an external primary key. If the
168041 ** iterator passed as the second argument does not currently point to
168042 ** a table (not index) with an external primary key, this function is a
168043 ** no-op.
168044 **
168045 ** Assuming the iterator does point to a table with an external PK, this
168046 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
168047 ** used to access that PK index. For example, if the target table is
168048 ** declared as follows:
168049 **
168050 ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
168051 **
168052 ** then the imposter table schema is:
168053 **
168054 ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
168055 **
168056 */
168057 static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
168058  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
168059  int tnum = pIter->iPkTnum; /* Root page of PK index */
168060  sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
168061  const char *zIdx = 0; /* Name of PK index */
168062  sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
168063  const char *zComma = "";
168064  char *zCols = 0; /* Used to build up list of table cols */
168065  char *zPk = 0; /* Used to build up table PK declaration */
168066 
168067  /* Figure out the name of the primary key index for the current table.
168068  ** This is needed for the argument to "PRAGMA index_xinfo". Set
168069  ** zIdx to point to a nul-terminated string containing this name. */
168070  p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
168071  "SELECT name FROM sqlite_master WHERE rootpage = ?"
168072  );
168073  if( p->rc==SQLITE_OK ){
168074  sqlite3_bind_int(pQuery, 1, tnum);
168075  if( SQLITE_ROW==sqlite3_step(pQuery) ){
168076  zIdx = (const char*)sqlite3_column_text(pQuery, 0);
168077  }
168078  }
168079  if( zIdx ){
168080  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
168081  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
168082  );
168083  }
168084  rbuFinalize(p, pQuery);
168085 
168086  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
168087  int bKey = sqlite3_column_int(pXInfo, 5);
168088  if( bKey ){
168089  int iCid = sqlite3_column_int(pXInfo, 1);
168090  int bDesc = sqlite3_column_int(pXInfo, 3);
168091  const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
168092  zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
168093  iCid, pIter->azTblType[iCid], zCollate
168094  );
168095  zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
168096  zComma = ", ";
168097  }
168098  }
168099  zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
168100  rbuFinalize(p, pXInfo);
168101 
168102  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
168103  rbuMPrintfExec(p, p->dbMain,
168104  "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
168105  zCols, zPk
168106  );
168107  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
168108  }
168109 }
168110 
168111 /*
168112 ** If an error has already occurred when this function is called, it
168113 ** immediately returns zero (without doing any work). Or, if an error
168114 ** occurs during the execution of this function, it sets the error code
168115 ** in the sqlite3rbu object indicated by the first argument and returns
168116 ** zero.
168117 **
168118 ** The iterator passed as the second argument is guaranteed to point to
168119 ** a table (not an index) when this function is called. This function
168120 ** attempts to create any imposter table required to write to the main
168121 ** table b-tree of the table before returning. Non-zero is returned if
168122 ** an imposter table are created, or zero otherwise.
168123 **
168124 ** An imposter table is required in all cases except RBU_PK_VTAB. Only
168125 ** virtual tables are written to directly. The imposter table has the
168126 ** same schema as the actual target table (less any UNIQUE constraints).
168127 ** More precisely, the "same schema" means the same columns, types,
168128 ** collation sequences. For tables that do not have an external PRIMARY
168129 ** KEY, it also means the same PRIMARY KEY declaration.
168130 */
168131 static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
168132  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
168133  int tnum = pIter->iTnum;
168134  const char *zComma = "";
168135  char *zSql = 0;
168136  int iCol;
168137  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
168138 
168139  for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
168140  const char *zPk = "";
168141  const char *zCol = pIter->azTblCol[iCol];
168142  const char *zColl = 0;
168143 
168145  p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
168146  );
168147 
168148  if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
168149  /* If the target table column is an "INTEGER PRIMARY KEY", add
168150  ** "PRIMARY KEY" to the imposter table column declaration. */
168151  zPk = "PRIMARY KEY ";
168152  }
168153  zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
168154  zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
168155  (pIter->abNotNull[iCol] ? " NOT NULL" : "")
168156  );
168157  zComma = ", ";
168158  }
168159 
168160  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
168161  char *zPk = rbuWithoutRowidPK(p, pIter);
168162  if( zPk ){
168163  zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
168164  }
168165  }
168166 
168167  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
168168  rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
168169  pIter->zTbl, zSql,
168170  (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
168171  );
168172  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
168173  }
168174 }
168175 
168176 /*
168177 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
168178 ** Specifically a statement of the form:
168179 **
168180 ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
168181 **
168182 ** The number of bound variables is equal to the number of columns in
168183 ** the target table, plus one (for the rbu_control column), plus one more
168184 ** (for the rbu_rowid column) if the target table is an implicit IPK or
168185 ** virtual table.
168186 */
168187 static void rbuObjIterPrepareTmpInsert(
168188  sqlite3rbu *p,
168189  RbuObjIter *pIter,
168190  const char *zCollist,
168191  const char *zRbuRowid
168192 ){
168193  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
168194  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
168195  if( zBind ){
168196  assert( pIter->pTmpInsert==0 );
168197  p->rc = prepareFreeAndCollectError(
168198  p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
168199  "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
168200  p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
168201  ));
168202  }
168203 }
168204 
168205 static void rbuTmpInsertFunc(
168206  sqlite3_context *pCtx,
168207  int nVal,
168208  sqlite3_value **apVal
168209 ){
168210  sqlite3rbu *p = sqlite3_user_data(pCtx);
168211  int rc = SQLITE_OK;
168212  int i;
168213 
168214  assert( sqlite3_value_int(apVal[0])!=0
168215  || p->objiter.eType==RBU_PK_EXTERNAL
168216  || p->objiter.eType==RBU_PK_NONE
168217  );
168218  if( sqlite3_value_int(apVal[0])!=0 ){
168219  p->nPhaseOneStep += p->objiter.nIndex;
168220  }
168221 
168222  for(i=0; rc==SQLITE_OK && i<nVal; i++){
168223  rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
168224  }
168225  if( rc==SQLITE_OK ){
168226  sqlite3_step(p->objiter.pTmpInsert);
168227  rc = sqlite3_reset(p->objiter.pTmpInsert);
168228  }
168229 
168230  if( rc!=SQLITE_OK ){
168231  sqlite3_result_error_code(pCtx, rc);
168232  }
168233 }
168234 
168235 /*
168236 ** Ensure that the SQLite statement handles required to update the
168237 ** target database object currently indicated by the iterator passed
168238 ** as the second argument are available.
168239 */
168240 static int rbuObjIterPrepareAll(
168241  sqlite3rbu *p,
168242  RbuObjIter *pIter,
168243  int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
168244 ){
168245  assert( pIter->bCleanup==0 );
168246  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
168247  const int tnum = pIter->iTnum;
168248  char *zCollist = 0; /* List of indexed columns */
168249  char **pz = &p->zErrmsg;
168250  const char *zIdx = pIter->zIdx;
168251  char *zLimit = 0;
168252 
168253  if( nOffset ){
168254  zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
168255  if( !zLimit ) p->rc = SQLITE_NOMEM;
168256  }
168257 
168258  if( zIdx ){
168259  const char *zTbl = pIter->zTbl;
168260  char *zImposterCols = 0; /* Columns for imposter table */
168261  char *zImposterPK = 0; /* Primary key declaration for imposter */
168262  char *zWhere = 0; /* WHERE clause on PK columns */
168263  char *zBind = 0;
168264  int nBind = 0;
168265 
168266  assert( pIter->eType!=RBU_PK_VTAB );
168267  zCollist = rbuObjIterGetIndexCols(
168268  p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
168269  );
168270  zBind = rbuObjIterGetBindlist(p, nBind);
168271 
168272  /* Create the imposter table used to write to this index. */
168273  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
168274  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
168275  rbuMPrintfExec(p, p->dbMain,
168276  "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
168277  zTbl, zImposterCols, zImposterPK
168278  );
168279  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
168280 
168281  /* Create the statement to insert index entries */
168282  pIter->nCol = nBind;
168283  if( p->rc==SQLITE_OK ){
168284  p->rc = prepareFreeAndCollectError(
168285  p->dbMain, &pIter->pInsert, &p->zErrmsg,
168286  sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
168287  );
168288  }
168289 
168290  /* And to delete index entries */
168291  if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
168292  p->rc = prepareFreeAndCollectError(
168293  p->dbMain, &pIter->pDelete, &p->zErrmsg,
168294  sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
168295  );
168296  }
168297 
168298  /* Create the SELECT statement to read keys in sorted order */
168299  if( p->rc==SQLITE_OK ){
168300  char *zSql;
168301  if( rbuIsVacuum(p) ){
168302  zSql = sqlite3_mprintf(
168303  "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
168304  zCollist,
168305  pIter->zDataTbl,
168306  zCollist, zLimit
168307  );
168308  }else
168309 
168310  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
168311  zSql = sqlite3_mprintf(
168312  "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
168313  zCollist, p->zStateDb, pIter->zDataTbl,
168314  zCollist, zLimit
168315  );
168316  }else{
168317  zSql = sqlite3_mprintf(
168318  "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
168319  "UNION ALL "
168320  "SELECT %s, rbu_control FROM '%q' "
168321  "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
168322  "ORDER BY %s%s",
168323  zCollist, p->zStateDb, pIter->zDataTbl,
168324  zCollist, pIter->zDataTbl,
168325  zCollist, zLimit
168326  );
168327  }
168328  p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
168329  }
168330 
168331  sqlite3_free(zImposterCols);
168332  sqlite3_free(zImposterPK);
168333  sqlite3_free(zWhere);
168334  sqlite3_free(zBind);
168335  }else{
168336  int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
168337  ||(pIter->eType==RBU_PK_NONE)
168338  ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
168339  const char *zTbl = pIter->zTbl; /* Table this step applies to */
168340  const char *zWrite; /* Imposter table name */
168341 
168342  char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
168343  char *zWhere = rbuObjIterGetWhere(p, pIter);
168344  char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
168345  char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
168346 
168347  zCollist = rbuObjIterGetCollist(p, pIter);
168348  pIter->nCol = pIter->nTblCol;
168349 
168350  /* Create the imposter table or tables (if required). */
168351  rbuCreateImposterTable(p, pIter);
168352  rbuCreateImposterTable2(p, pIter);
168353  zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
168354 
168355  /* Create the INSERT statement to write to the target PK b-tree */
168356  if( p->rc==SQLITE_OK ){
168357  p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
168358  sqlite3_mprintf(
168359  "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
168360  zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
168361  )
168362  );
168363  }
168364 
168365  /* Create the DELETE statement to write to the target PK b-tree.
168366  ** Because it only performs INSERT operations, this is not required for
168367  ** an rbu vacuum handle. */
168368  if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
168369  p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
168370  sqlite3_mprintf(
168371  "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
168372  )
168373  );
168374  }
168375 
168376  if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
168377  const char *zRbuRowid = "";
168378  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
168379  zRbuRowid = ", rbu_rowid";
168380  }
168381 
168382  /* Create the rbu_tmp_xxx table and the triggers to populate it. */
168383  rbuMPrintfExec(p, p->dbRbu,
168384  "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
168385  "SELECT *%s FROM '%q' WHERE 0;"
168386  , p->zStateDb, pIter->zDataTbl
168387  , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
168388  , pIter->zDataTbl
168389  );
168390 
168391  rbuMPrintfExec(p, p->dbMain,
168392  "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
168393  "BEGIN "
168394  " SELECT rbu_tmp_insert(3, %s);"
168395  "END;"
168396 
168397  "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
168398  "BEGIN "
168399  " SELECT rbu_tmp_insert(3, %s);"
168400  "END;"
168401 
168402  "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
168403  "BEGIN "
168404  " SELECT rbu_tmp_insert(4, %s);"
168405  "END;",
168406  zWrite, zTbl, zOldlist,
168407  zWrite, zTbl, zOldlist,
168408  zWrite, zTbl, zNewlist
168409  );
168410 
168411  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
168412  rbuMPrintfExec(p, p->dbMain,
168413  "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
168414  "BEGIN "
168415  " SELECT rbu_tmp_insert(0, %s);"
168416  "END;",
168417  zWrite, zTbl, zNewlist
168418  );
168419  }
168420 
168421  rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
168422  }
168423 
168424  /* Create the SELECT statement to read keys from data_xxx */
168425  if( p->rc==SQLITE_OK ){
168426  const char *zRbuRowid = "";
168427  if( bRbuRowid ){
168428  zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
168429  }
168430  p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
168431  sqlite3_mprintf(
168432  "SELECT %s,%s rbu_control%s FROM '%q'%s",
168433  zCollist,
168434  (rbuIsVacuum(p) ? "0 AS " : ""),
168435  zRbuRowid,
168436  pIter->zDataTbl, zLimit
168437  )
168438  );
168439  }
168440 
168441  sqlite3_free(zWhere);
168442  sqlite3_free(zOldlist);
168443  sqlite3_free(zNewlist);
168444  sqlite3_free(zBindings);
168445  }
168446  sqlite3_free(zCollist);
168447  sqlite3_free(zLimit);
168448  }
168449 
168450  return p->rc;
168451 }
168452 
168453 /*
168454 ** Set output variable *ppStmt to point to an UPDATE statement that may
168455 ** be used to update the imposter table for the main table b-tree of the
168456 ** table object that pIter currently points to, assuming that the
168457 ** rbu_control column of the data_xyz table contains zMask.
168458 **
168459 ** If the zMask string does not specify any columns to update, then this
168460 ** is not an error. Output variable *ppStmt is set to NULL in this case.
168461 */
168462 static int rbuGetUpdateStmt(
168463  sqlite3rbu *p, /* RBU handle */
168464  RbuObjIter *pIter, /* Object iterator */
168465  const char *zMask, /* rbu_control value ('x.x.') */
168466  sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
168467 ){
168468  RbuUpdateStmt **pp;
168469  RbuUpdateStmt *pUp = 0;
168470  int nUp = 0;
168471 
168472  /* In case an error occurs */
168473  *ppStmt = 0;
168474 
168475  /* Search for an existing statement. If one is found, shift it to the front
168476  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
168477  ** to the number of statements currently in the cache and pUp to the
168478  ** last object in the list. */
168479  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
168480  pUp = *pp;
168481  if( strcmp(pUp->zMask, zMask)==0 ){
168482  *pp = pUp->pNext;
168483  pUp->pNext = pIter->pRbuUpdate;
168484  pIter->pRbuUpdate = pUp;
168485  *ppStmt = pUp->pUpdate;
168486  return SQLITE_OK;
168487  }
168488  nUp++;
168489  }
168490  assert( pUp==0 || pUp->pNext==0 );
168491 
168492  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
168493  for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
168494  *pp = 0;
168495  sqlite3_finalize(pUp->pUpdate);
168496  pUp->pUpdate = 0;
168497  }else{
168498  pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
168499  }
168500 
168501  if( pUp ){
168502  char *zWhere = rbuObjIterGetWhere(p, pIter);
168503  char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
168504  char *zUpdate = 0;
168505 
168506  pUp->zMask = (char*)&pUp[1];
168507  memcpy(pUp->zMask, zMask, pIter->nTblCol);
168508  pUp->pNext = pIter->pRbuUpdate;
168509  pIter->pRbuUpdate = pUp;
168510 
168511  if( zSet ){
168512  const char *zPrefix = "";
168513 
168514  if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
168515  zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
168516  zPrefix, pIter->zTbl, zSet, zWhere
168517  );
168518  p->rc = prepareFreeAndCollectError(
168519  p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
168520  );
168521  *ppStmt = pUp->pUpdate;
168522  }
168523  sqlite3_free(zWhere);
168524  sqlite3_free(zSet);
168525  }
168526 
168527  return p->rc;
168528 }
168529 
168530 static sqlite3 *rbuOpenDbhandle(
168531  sqlite3rbu *p,
168532  const char *zName,
168533  int bUseVfs
168534 ){
168535  sqlite3 *db = 0;
168536  if( p->rc==SQLITE_OK ){
168538  p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
168539  if( p->rc ){
168540  p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
168541  sqlite3_close(db);
168542  db = 0;
168543  }
168544  }
168545  return db;
168546 }
168547 
168548 /*
168549 ** Free an RbuState object allocated by rbuLoadState().
168550 */
168551 static void rbuFreeState(RbuState *p){
168552  if( p ){
168553  sqlite3_free(p->zTbl);
168554  sqlite3_free(p->zIdx);
168555  sqlite3_free(p);
168556  }
168557 }
168558 
168559 /*
168560 ** Allocate an RbuState object and load the contents of the rbu_state
168561 ** table into it. Return a pointer to the new object. It is the
168562 ** responsibility of the caller to eventually free the object using
168563 ** sqlite3_free().
168564 **
168565 ** If an error occurs, leave an error code and message in the rbu handle
168566 ** and return NULL.
168567 */
168568 static RbuState *rbuLoadState(sqlite3rbu *p){
168569  RbuState *pRet = 0;
168570  sqlite3_stmt *pStmt = 0;
168571  int rc;
168572  int rc2;
168573 
168574  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
168575  if( pRet==0 ) return 0;
168576 
168577  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168578  sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
168579  );
168580  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
168581  switch( sqlite3_column_int(pStmt, 0) ){
168582  case RBU_STATE_STAGE:
168583  pRet->eStage = sqlite3_column_int(pStmt, 1);
168584  if( pRet->eStage!=RBU_STAGE_OAL
168585  && pRet->eStage!=RBU_STAGE_MOVE
168586  && pRet->eStage!=RBU_STAGE_CKPT
168587  ){
168588  p->rc = SQLITE_CORRUPT;
168589  }
168590  break;
168591 
168592  case RBU_STATE_TBL:
168593  pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
168594  break;
168595 
168596  case RBU_STATE_IDX:
168597  pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
168598  break;
168599 
168600  case RBU_STATE_ROW:
168601  pRet->nRow = sqlite3_column_int(pStmt, 1);
168602  break;
168603 
168604  case RBU_STATE_PROGRESS:
168605  pRet->nProgress = sqlite3_column_int64(pStmt, 1);
168606  break;
168607 
168608  case RBU_STATE_CKPT:
168609  pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
168610  break;
168611 
168612  case RBU_STATE_COOKIE:
168613  pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
168614  break;
168615 
168616  case RBU_STATE_OALSZ:
168617  pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
168618  break;
168619 
168620  case RBU_STATE_PHASEONESTEP:
168621  pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
168622  break;
168623 
168624  default:
168625  rc = SQLITE_CORRUPT;
168626  break;
168627  }
168628  }
168629  rc2 = sqlite3_finalize(pStmt);
168630  if( rc==SQLITE_OK ) rc = rc2;
168631 
168632  p->rc = rc;
168633  return pRet;
168634 }
168635 
168636 
168637 /*
168638 ** Open the database handle and attach the RBU database as "rbu". If an
168639 ** error occurs, leave an error code and message in the RBU handle.
168640 */
168641 static void rbuOpenDatabase(sqlite3rbu *p){
168642  assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
168643  assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
168644 
168645  /* Open the RBU database */
168646  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
168647 
168648  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
168649  sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
168650  if( p->zState==0 ){
168651  const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
168652  p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
168653  }
168654  }
168655 
168656  /* If using separate RBU and state databases, attach the state database to
168657  ** the RBU db handle now. */
168658  if( p->zState ){
168659  rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
168660  memcpy(p->zStateDb, "stat", 4);
168661  }else{
168662  memcpy(p->zStateDb, "main", 4);
168663  }
168664 
168665 #if 0
168666  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
168667  p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
168668  }
168669 #endif
168670 
168671  /* If it has not already been created, create the rbu_state table */
168672  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
168673 
168674 #if 0
168675  if( rbuIsVacuum(p) ){
168676  if( p->rc==SQLITE_OK ){
168677  int rc2;
168678  int bOk = 0;
168679  sqlite3_stmt *pCnt = 0;
168680  p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
168681  "SELECT count(*) FROM stat.sqlite_master"
168682  );
168683  if( p->rc==SQLITE_OK
168684  && sqlite3_step(pCnt)==SQLITE_ROW
168685  && 1==sqlite3_column_int(pCnt, 0)
168686  ){
168687  bOk = 1;
168688  }
168689  rc2 = sqlite3_finalize(pCnt);
168690  if( p->rc==SQLITE_OK ) p->rc = rc2;
168691 
168692  if( p->rc==SQLITE_OK && bOk==0 ){
168693  p->rc = SQLITE_ERROR;
168694  p->zErrmsg = sqlite3_mprintf("invalid state database");
168695  }
168696 
168697  if( p->rc==SQLITE_OK ){
168698  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
168699  }
168700  }
168701  }
168702 #endif
168703 
168704  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
168705  int bOpen = 0;
168706  int rc;
168707  p->nRbu = 0;
168708  p->pRbuFd = 0;
168709  rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
168710  if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
168711  if( p->eStage>=RBU_STAGE_MOVE ){
168712  bOpen = 1;
168713  }else{
168714  RbuState *pState = rbuLoadState(p);
168715  if( pState ){
168716  bOpen = (pState->eStage>RBU_STAGE_MOVE);
168717  rbuFreeState(pState);
168718  }
168719  }
168720  if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
168721  }
168722 
168723  p->eStage = 0;
168724  if( p->rc==SQLITE_OK && p->dbMain==0 ){
168725  if( !rbuIsVacuum(p) ){
168726  p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
168727  }else if( p->pRbuFd->pWalFd ){
168728  p->rc = SQLITE_ERROR;
168729  p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
168730  }else{
168731  char *zTarget;
168732  char *zExtra = 0;
168733  if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
168734  zExtra = &p->zRbu[5];
168735  while( *zExtra ){
168736  if( *zExtra++=='?' ) break;
168737  }
168738  if( *zExtra=='\0' ) zExtra = 0;
168739  }
168740 
168741  zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
168742  sqlite3_db_filename(p->dbRbu, "main"),
168743  (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
168744  );
168745 
168746  if( zTarget==0 ){
168747  p->rc = SQLITE_NOMEM;
168748  return;
168749  }
168750  p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
168751  sqlite3_free(zTarget);
168752  }
168753  }
168754 
168755  if( p->rc==SQLITE_OK ){
168756  p->rc = sqlite3_create_function(p->dbMain,
168757  "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
168758  );
168759  }
168760 
168761  if( p->rc==SQLITE_OK ){
168762  p->rc = sqlite3_create_function(p->dbMain,
168763  "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
168764  );
168765  }
168766 
168767  if( p->rc==SQLITE_OK ){
168768  p->rc = sqlite3_create_function(p->dbRbu,
168769  "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
168770  );
168771  }
168772 
168773  if( p->rc==SQLITE_OK ){
168774  p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
168775  }
168776  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
168777 
168778  /* Mark the database file just opened as an RBU target database. If
168779  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
168780  ** This is an error. */
168781  if( p->rc==SQLITE_OK ){
168782  p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
168783  }
168784 
168785  if( p->rc==SQLITE_NOTFOUND ){
168786  p->rc = SQLITE_ERROR;
168787  p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
168788  }
168789 }
168790 
168791 /*
168792 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
168793 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
168794 **
168795 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
168796 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
168797 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
168798 ** three characters, then shorten the suffix on z[] to be the last three
168799 ** characters of the original suffix.
168800 **
168801 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
168802 ** do the suffix shortening regardless of URI parameter.
168803 **
168804 ** Examples:
168805 **
168806 ** test.db-journal => test.nal
168807 ** test.db-wal => test.wal
168808 ** test.db-shm => test.shm
168809 ** test.db-mj7f3319fa => test.9fa
168810 */
168811 static void rbuFileSuffix3(const char *zBase, char *z){
168812 #ifdef SQLITE_ENABLE_8_3_NAMES
168813 #if SQLITE_ENABLE_8_3_NAMES<2
168814  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
168815 #endif
168816  {
168817  int i, sz;
168818  sz = (int)strlen(z)&0xffffff;
168819  for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
168820  if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
168821  }
168822 #endif
168823 }
168824 
168825 /*
168826 ** Return the current wal-index header checksum for the target database
168827 ** as a 64-bit integer.
168828 **
168829 ** The checksum is store in the first page of xShmMap memory as an 8-byte
168830 ** blob starting at byte offset 40.
168831 */
168832 static i64 rbuShmChecksum(sqlite3rbu *p){
168833  i64 iRet = 0;
168834  if( p->rc==SQLITE_OK ){
168835  sqlite3_file *pDb = p->pTargetFd->pReal;
168836  u32 volatile *ptr;
168837  p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
168838  if( p->rc==SQLITE_OK ){
168839  iRet = ((i64)ptr[10] << 32) + ptr[11];
168840  }
168841  }
168842  return iRet;
168843 }
168844 
168845 /*
168846 ** This function is called as part of initializing or reinitializing an
168847 ** incremental checkpoint.
168848 **
168849 ** It populates the sqlite3rbu.aFrame[] array with the set of
168850 ** (wal frame -> db page) copy operations required to checkpoint the
168851 ** current wal file, and obtains the set of shm locks required to safely
168852 ** perform the copy operations directly on the file-system.
168853 **
168854 ** If argument pState is not NULL, then the incremental checkpoint is
168855 ** being resumed. In this case, if the checksum of the wal-index-header
168856 ** following recovery is not the same as the checksum saved in the RbuState
168857 ** object, then the rbu handle is set to DONE state. This occurs if some
168858 ** other client appends a transaction to the wal file in the middle of
168859 ** an incremental checkpoint.
168860 */
168861 static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
168862 
168863  /* If pState is NULL, then the wal file may not have been opened and
168864  ** recovered. Running a read-statement here to ensure that doing so
168865  ** does not interfere with the "capture" process below. */
168866  if( pState==0 ){
168867  p->eStage = 0;
168868  if( p->rc==SQLITE_OK ){
168869  p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
168870  }
168871  }
168872 
168873  /* Assuming no error has occurred, run a "restart" checkpoint with the
168874  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
168875  ** special behaviour in the rbu VFS:
168876  **
168877  ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
168878  ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
168879  ** proceed with running a passive checkpoint instead of failing).
168880  **
168881  ** * Attempts to read from the *-wal file or write to the database file
168882  ** do not perform any IO. Instead, the frame/page combinations that
168883  ** would be read/written are recorded in the sqlite3rbu.aFrame[]
168884  ** array.
168885  **
168886  ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
168887  ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
168888  ** no-ops. These locks will not be released until the connection
168889  ** is closed.
168890  **
168891  ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
168892  ** error.
168893  **
168894  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
168895  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
168896  ** array populated with a set of (frame -> page) mappings. Because the
168897  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
168898  ** data from the wal file into the database file according to the
168899  ** contents of aFrame[].
168900  */
168901  if( p->rc==SQLITE_OK ){
168902  int rc2;
168903  p->eStage = RBU_STAGE_CAPTURE;
168904  rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
168905  if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
168906  }
168907 
168908  if( p->rc==SQLITE_OK ){
168909  p->eStage = RBU_STAGE_CKPT;
168910  p->nStep = (pState ? pState->nRow : 0);
168911  p->aBuf = rbuMalloc(p, p->pgsz);
168912  p->iWalCksum = rbuShmChecksum(p);
168913  }
168914 
168915  if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
168916  p->rc = SQLITE_DONE;
168917  p->eStage = RBU_STAGE_DONE;
168918  }
168919 }
168920 
168921 /*
168922 ** Called when iAmt bytes are read from offset iOff of the wal file while
168923 ** the rbu object is in capture mode. Record the frame number of the frame
168924 ** being read in the aFrame[] array.
168925 */
168926 static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
168927  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
168928  u32 iFrame;
168929 
168930  if( pRbu->mLock!=mReq ){
168931  pRbu->rc = SQLITE_BUSY;
168932  return SQLITE_INTERNAL;
168933  }
168934 
168935  pRbu->pgsz = iAmt;
168936  if( pRbu->nFrame==pRbu->nFrameAlloc ){
168937  int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
168938  RbuFrame *aNew;
168939  aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
168940  if( aNew==0 ) return SQLITE_NOMEM;
168941  pRbu->aFrame = aNew;
168942  pRbu->nFrameAlloc = nNew;
168943  }
168944 
168945  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
168946  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
168947  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
168948  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
168949  pRbu->nFrame++;
168950  return SQLITE_OK;
168951 }
168952 
168953 /*
168954 ** Called when a page of data is written to offset iOff of the database
168955 ** file while the rbu handle is in capture mode. Record the page number
168956 ** of the page being written in the aFrame[] array.
168957 */
168958 static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
168959  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
168960  return SQLITE_OK;
168961 }
168962 
168963 /*
168964 ** This is called as part of an incremental checkpoint operation. Copy
168965 ** a single frame of data from the wal file into the database file, as
168966 ** indicated by the RbuFrame object.
168967 */
168968 static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
168969  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
168970  sqlite3_file *pDb = p->pTargetFd->pReal;
168971  i64 iOff;
168972 
168973  assert( p->rc==SQLITE_OK );
168974  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
168975  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
168976  if( p->rc ) return;
168977 
168978  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
168979  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
168980 }
168981 
168982 
168983 /*
168984 ** Take an EXCLUSIVE lock on the database file.
168985 */
168986 static void rbuLockDatabase(sqlite3rbu *p){
168987  sqlite3_file *pReal = p->pTargetFd->pReal;
168988  assert( p->rc==SQLITE_OK );
168989  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
168990  if( p->rc==SQLITE_OK ){
168991  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
168992  }
168993 }
168994 
168995 #if defined(_WIN32_WCE)
168996 static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
168997  int nChar;
168998  LPWSTR zWideFilename;
168999 
169000  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
169001  if( nChar==0 ){
169002  return 0;
169003  }
169004  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
169005  if( zWideFilename==0 ){
169006  return 0;
169007  }
169008  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
169009  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
169010  nChar);
169011  if( nChar==0 ){
169012  sqlite3_free(zWideFilename);
169013  zWideFilename = 0;
169014  }
169015  return zWideFilename;
169016 }
169017 #endif
169018 
169019 /*
169020 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
169021 ** on the database file. This proc moves the *-oal file to the *-wal path,
169022 ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
169023 ** If an error occurs, leave an error code and error message in the rbu
169024 ** handle.
169025 */
169026 static void rbuMoveOalFile(sqlite3rbu *p){
169027  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
169028  const char *zMove = zBase;
169029  char *zOal;
169030  char *zWal;
169031 
169032  if( rbuIsVacuum(p) ){
169033  zMove = sqlite3_db_filename(p->dbRbu, "main");
169034  }
169035  zOal = sqlite3_mprintf("%s-oal", zMove);
169036  zWal = sqlite3_mprintf("%s-wal", zMove);
169037 
169038  assert( p->eStage==RBU_STAGE_MOVE );
169039  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
169040  if( zWal==0 || zOal==0 ){
169041  p->rc = SQLITE_NOMEM;
169042  }else{
169043  /* Move the *-oal file to *-wal. At this point connection p->db is
169044  ** holding a SHARED lock on the target database file (because it is
169045  ** in WAL mode). So no other connection may be writing the db.
169046  **
169047  ** In order to ensure that there are no database readers, an EXCLUSIVE
169048  ** lock is obtained here before the *-oal is moved to *-wal.
169049  */
169050  rbuLockDatabase(p);
169051  if( p->rc==SQLITE_OK ){
169052  rbuFileSuffix3(zBase, zWal);
169053  rbuFileSuffix3(zBase, zOal);
169054 
169055  /* Re-open the databases. */
169056  rbuObjIterFinalize(&p->objiter);
169057  sqlite3_close(p->dbRbu);
169058  sqlite3_close(p->dbMain);
169059  p->dbMain = 0;
169060  p->dbRbu = 0;
169061 
169062 #if defined(_WIN32_WCE)
169063  {
169064  LPWSTR zWideOal;
169065  LPWSTR zWideWal;
169066 
169067  zWideOal = rbuWinUtf8ToUnicode(zOal);
169068  if( zWideOal ){
169069  zWideWal = rbuWinUtf8ToUnicode(zWal);
169070  if( zWideWal ){
169071  if( MoveFileW(zWideOal, zWideWal) ){
169072  p->rc = SQLITE_OK;
169073  }else{
169074  p->rc = SQLITE_IOERR;
169075  }
169076  sqlite3_free(zWideWal);
169077  }else{
169078  p->rc = SQLITE_IOERR_NOMEM;
169079  }
169080  sqlite3_free(zWideOal);
169081  }else{
169082  p->rc = SQLITE_IOERR_NOMEM;
169083  }
169084  }
169085 #else
169086  p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
169087 #endif
169088 
169089  if( p->rc==SQLITE_OK ){
169090  rbuOpenDatabase(p);
169091  rbuSetupCheckpoint(p, 0);
169092  }
169093  }
169094  }
169095 
169096  sqlite3_free(zWal);
169097  sqlite3_free(zOal);
169098 }
169099 
169100 /*
169101 ** The SELECT statement iterating through the keys for the current object
169102 ** (p->objiter.pSelect) currently points to a valid row. This function
169103 ** determines the type of operation requested by this row and returns
169104 ** one of the following values to indicate the result:
169105 **
169106 ** * RBU_INSERT
169107 ** * RBU_DELETE
169108 ** * RBU_IDX_DELETE
169109 ** * RBU_UPDATE
169110 **
169111 ** If RBU_UPDATE is returned, then output variable *pzMask is set to
169112 ** point to the text value indicating the columns to update.
169113 **
169114 ** If the rbu_control field contains an invalid value, an error code and
169115 ** message are left in the RBU handle and zero returned.
169116 */
169117 static int rbuStepType(sqlite3rbu *p, const char **pzMask){
169118  int iCol = p->objiter.nCol; /* Index of rbu_control column */
169119  int res = 0; /* Return value */
169120 
169121  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
169122  case SQLITE_INTEGER: {
169123  int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
169124  switch( iVal ){
169125  case 0: res = RBU_INSERT; break;
169126  case 1: res = RBU_DELETE; break;
169127  case 2: res = RBU_REPLACE; break;
169128  case 3: res = RBU_IDX_DELETE; break;
169129  case 4: res = RBU_IDX_INSERT; break;
169130  }
169131  break;
169132  }
169133 
169134  case SQLITE_TEXT: {
169135  const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
169136  if( z==0 ){
169137  p->rc = SQLITE_NOMEM;
169138  }else{
169139  *pzMask = (const char*)z;
169140  }
169141  res = RBU_UPDATE;
169142 
169143  break;
169144  }
169145 
169146  default:
169147  break;
169148  }
169149 
169150  if( res==0 ){
169151  rbuBadControlError(p);
169152  }
169153  return res;
169154 }
169155 
169156 #ifdef SQLITE_DEBUG
169157 /*
169158 ** Assert that column iCol of statement pStmt is named zName.
169159 */
169160 static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
169161  const char *zCol = sqlite3_column_name(pStmt, iCol);
169162  assert( 0==sqlite3_stricmp(zName, zCol) );
169163 }
169164 #else
169165 # define assertColumnName(x,y,z)
169166 #endif
169167 
169168 /*
169169 ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
169170 ** RBU_IDX_DELETE. This function performs the work of a single
169171 ** sqlite3rbu_step() call for the type of operation specified by eType.
169172 */
169173 static void rbuStepOneOp(sqlite3rbu *p, int eType){
169174  RbuObjIter *pIter = &p->objiter;
169175  sqlite3_value *pVal;
169176  sqlite3_stmt *pWriter;
169177  int i;
169178 
169179  assert( p->rc==SQLITE_OK );
169180  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
169181  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
169182  || eType==RBU_INSERT || eType==RBU_IDX_INSERT
169183  );
169184 
169185  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
169186  ** statement below does actually delete a row, nPhaseOneStep will be
169187  ** incremented by the same amount when SQL function rbu_tmp_insert()
169188  ** is invoked by the trigger. */
169189  if( eType==RBU_DELETE ){
169190  p->nPhaseOneStep -= p->objiter.nIndex;
169191  }
169192 
169193  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
169194  pWriter = pIter->pDelete;
169195  }else{
169196  pWriter = pIter->pInsert;
169197  }
169198 
169199  for(i=0; i<pIter->nCol; i++){
169200  /* If this is an INSERT into a table b-tree and the table has an
169201  ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
169202  ** to write a NULL into the IPK column. That is not permitted. */
169203  if( eType==RBU_INSERT
169204  && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
169205  && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
169206  ){
169207  p->rc = SQLITE_MISMATCH;
169208  p->zErrmsg = sqlite3_mprintf("datatype mismatch");
169209  return;
169210  }
169211 
169212  if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
169213  continue;
169214  }
169215 
169216  pVal = sqlite3_column_value(pIter->pSelect, i);
169217  p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
169218  if( p->rc ) return;
169219  }
169220  if( pIter->zIdx==0 ){
169221  if( pIter->eType==RBU_PK_VTAB
169222  || pIter->eType==RBU_PK_NONE
169223  || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
169224  ){
169225  /* For a virtual table, or a table with no primary key, the
169226  ** SELECT statement is:
169227  **
169228  ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
169229  **
169230  ** Hence column_value(pIter->nCol+1).
169231  */
169232  assertColumnName(pIter->pSelect, pIter->nCol+1,
169233  rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
169234  );
169235  pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
169236  p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
169237  }
169238  }
169239  if( p->rc==SQLITE_OK ){
169240  sqlite3_step(pWriter);
169241  p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
169242  }
169243 }
169244 
169245 /*
169246 ** This function does the work for an sqlite3rbu_step() call.
169247 **
169248 ** The object-iterator (p->objiter) currently points to a valid object,
169249 ** and the input cursor (p->objiter.pSelect) currently points to a valid
169250 ** input row. Perform whatever processing is required and return.
169251 **
169252 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
169253 ** and message is left in the RBU handle and a copy of the error code
169254 ** returned.
169255 */
169256 static int rbuStep(sqlite3rbu *p){
169257  RbuObjIter *pIter = &p->objiter;
169258  const char *zMask = 0;
169259  int eType = rbuStepType(p, &zMask);
169260 
169261  if( eType ){
169262  assert( eType==RBU_INSERT || eType==RBU_DELETE
169263  || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
169264  || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
169265  );
169266  assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
169267 
169268  if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
169269  rbuBadControlError(p);
169270  }
169271  else if( eType==RBU_REPLACE ){
169272  if( pIter->zIdx==0 ){
169273  p->nPhaseOneStep += p->objiter.nIndex;
169274  rbuStepOneOp(p, RBU_DELETE);
169275  }
169276  if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
169277  }
169278  else if( eType!=RBU_UPDATE ){
169279  rbuStepOneOp(p, eType);
169280  }
169281  else{
169282  sqlite3_value *pVal;
169283  sqlite3_stmt *pUpdate = 0;
169284  assert( eType==RBU_UPDATE );
169285  p->nPhaseOneStep -= p->objiter.nIndex;
169286  rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
169287  if( pUpdate ){
169288  int i;
169289  for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
169290  char c = zMask[pIter->aiSrcOrder[i]];
169291  pVal = sqlite3_column_value(pIter->pSelect, i);
169292  if( pIter->abTblPk[i] || c!='.' ){
169293  p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
169294  }
169295  }
169296  if( p->rc==SQLITE_OK
169297  && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
169298  ){
169299  /* Bind the rbu_rowid value to column _rowid_ */
169300  assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
169301  pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
169302  p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
169303  }
169304  if( p->rc==SQLITE_OK ){
169305  sqlite3_step(pUpdate);
169306  p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
169307  }
169308  }
169309  }
169310  }
169311  return p->rc;
169312 }
169313 
169314 /*
169315 ** Increment the schema cookie of the main database opened by p->dbMain.
169316 **
169317 ** Or, if this is an RBU vacuum, set the schema cookie of the main db
169318 ** opened by p->dbMain to one more than the schema cookie of the main
169319 ** db opened by p->dbRbu.
169320 */
169321 static void rbuIncrSchemaCookie(sqlite3rbu *p){
169322  if( p->rc==SQLITE_OK ){
169323  sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
169324  int iCookie = 1000000;
169325  sqlite3_stmt *pStmt;
169326 
169327  p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
169328  "PRAGMA schema_version"
169329  );
169330  if( p->rc==SQLITE_OK ){
169331  /* Coverage: it may be that this sqlite3_step() cannot fail. There
169332  ** is already a transaction open, so the prepared statement cannot
169333  ** throw an SQLITE_SCHEMA exception. The only database page the
169334  ** statement reads is page 1, which is guaranteed to be in the cache.
169335  ** And no memory allocations are required. */
169336  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169337  iCookie = sqlite3_column_int(pStmt, 0);
169338  }
169339  rbuFinalize(p, pStmt);
169340  }
169341  if( p->rc==SQLITE_OK ){
169342  rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
169343  }
169344  }
169345 }
169346 
169347 /*
169348 ** Update the contents of the rbu_state table within the rbu database. The
169349 ** value stored in the RBU_STATE_STAGE column is eStage. All other values
169350 ** are determined by inspecting the rbu handle passed as the first argument.
169351 */
169352 static void rbuSaveState(sqlite3rbu *p, int eStage){
169353  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
169354  sqlite3_stmt *pInsert = 0;
169355  rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
169356  int rc;
169357 
169358  assert( p->zErrmsg==0 );
169359  rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
169360  sqlite3_mprintf(
169361  "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
169362  "(%d, %d), "
169363  "(%d, %Q), "
169364  "(%d, %Q), "
169365  "(%d, %d), "
169366  "(%d, %d), "
169367  "(%d, %lld), "
169368  "(%d, %lld), "
169369  "(%d, %lld), "
169370  "(%d, %lld) ",
169371  p->zStateDb,
169372  RBU_STATE_STAGE, eStage,
169373  RBU_STATE_TBL, p->objiter.zTbl,
169374  RBU_STATE_IDX, p->objiter.zIdx,
169375  RBU_STATE_ROW, p->nStep,
169376  RBU_STATE_PROGRESS, p->nProgress,
169377  RBU_STATE_CKPT, p->iWalCksum,
169378  RBU_STATE_COOKIE, (i64)pFd->iCookie,
169379  RBU_STATE_OALSZ, p->iOalSz,
169380  RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
169381  )
169382  );
169383  assert( pInsert==0 || rc==SQLITE_OK );
169384 
169385  if( rc==SQLITE_OK ){
169386  sqlite3_step(pInsert);
169387  rc = sqlite3_finalize(pInsert);
169388  }
169389  if( rc!=SQLITE_OK ) p->rc = rc;
169390  }
169391 }
169392 
169393 
169394 /*
169395 ** The second argument passed to this function is the name of a PRAGMA
169396 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
169397 ** This function executes the following on sqlite3rbu.dbRbu:
169398 **
169399 ** "PRAGMA main.$zPragma"
169400 **
169401 ** where $zPragma is the string passed as the second argument, then
169402 ** on sqlite3rbu.dbMain:
169403 **
169404 ** "PRAGMA main.$zPragma = $val"
169405 **
169406 ** where $val is the value returned by the first PRAGMA invocation.
169407 **
169408 ** In short, it copies the value of the specified PRAGMA setting from
169409 ** dbRbu to dbMain.
169410 */
169411 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
169412  if( p->rc==SQLITE_OK ){
169413  sqlite3_stmt *pPragma = 0;
169414  p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
169415  sqlite3_mprintf("PRAGMA main.%s", zPragma)
169416  );
169417  if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
169418  p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
169419  zPragma, sqlite3_column_int(pPragma, 0)
169420  );
169421  }
169422  rbuFinalize(p, pPragma);
169423  }
169424 }
169425 
169426 /*
169427 ** The RBU handle passed as the only argument has just been opened and
169428 ** the state database is empty. If this RBU handle was opened for an
169429 ** RBU vacuum operation, create the schema in the target db.
169430 */
169431 static void rbuCreateTargetSchema(sqlite3rbu *p){
169432  sqlite3_stmt *pSql = 0;
169433  sqlite3_stmt *pInsert = 0;
169434 
169435  assert( rbuIsVacuum(p) );
169436  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
169437  if( p->rc==SQLITE_OK ){
169438  p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
169439  "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
169440  " AND name!='sqlite_sequence' "
169441  " ORDER BY type DESC"
169442  );
169443  }
169444 
169445  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
169446  const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
169447  p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
169448  }
169449  rbuFinalize(p, pSql);
169450  if( p->rc!=SQLITE_OK ) return;
169451 
169452  if( p->rc==SQLITE_OK ){
169453  p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
169454  "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
169455  );
169456  }
169457 
169458  if( p->rc==SQLITE_OK ){
169459  p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
169460  "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
169461  );
169462  }
169463 
169464  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
169465  int i;
169466  for(i=0; i<5; i++){
169467  sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
169468  }
169469  sqlite3_step(pInsert);
169470  p->rc = sqlite3_reset(pInsert);
169471  }
169472  if( p->rc==SQLITE_OK ){
169473  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
169474  }
169475 
169476  rbuFinalize(p, pSql);
169477  rbuFinalize(p, pInsert);
169478 }
169479 
169480 /*
169481 ** Step the RBU object.
169482 */
169483 SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
169484  if( p ){
169485  switch( p->eStage ){
169486  case RBU_STAGE_OAL: {
169487  RbuObjIter *pIter = &p->objiter;
169488 
169489  /* If this is an RBU vacuum operation and the state table was empty
169490  ** when this handle was opened, create the target database schema. */
169491  if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
169492  rbuCreateTargetSchema(p);
169493  rbuCopyPragma(p, "user_version");
169494  rbuCopyPragma(p, "application_id");
169495  }
169496 
169497  while( p->rc==SQLITE_OK && pIter->zTbl ){
169498 
169499  if( pIter->bCleanup ){
169500  /* Clean up the rbu_tmp_xxx table for the previous table. It
169501  ** cannot be dropped as there are currently active SQL statements.
169502  ** But the contents can be deleted. */
169503  if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
169504  rbuMPrintfExec(p, p->dbRbu,
169505  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
169506  );
169507  }
169508  }else{
169509  rbuObjIterPrepareAll(p, pIter, 0);
169510 
169511  /* Advance to the next row to process. */
169512  if( p->rc==SQLITE_OK ){
169513  int rc = sqlite3_step(pIter->pSelect);
169514  if( rc==SQLITE_ROW ){
169515  p->nProgress++;
169516  p->nStep++;
169517  return rbuStep(p);
169518  }
169519  p->rc = sqlite3_reset(pIter->pSelect);
169520  p->nStep = 0;
169521  }
169522  }
169523 
169524  rbuObjIterNext(p, pIter);
169525  }
169526 
169527  if( p->rc==SQLITE_OK ){
169528  assert( pIter->zTbl==0 );
169529  rbuSaveState(p, RBU_STAGE_MOVE);
169530  rbuIncrSchemaCookie(p);
169531  if( p->rc==SQLITE_OK ){
169532  p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
169533  }
169534  if( p->rc==SQLITE_OK ){
169535  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
169536  }
169537  p->eStage = RBU_STAGE_MOVE;
169538  }
169539  break;
169540  }
169541 
169542  case RBU_STAGE_MOVE: {
169543  if( p->rc==SQLITE_OK ){
169544  rbuMoveOalFile(p);
169545  p->nProgress++;
169546  }
169547  break;
169548  }
169549 
169550  case RBU_STAGE_CKPT: {
169551  if( p->rc==SQLITE_OK ){
169552  if( p->nStep>=p->nFrame ){
169553  sqlite3_file *pDb = p->pTargetFd->pReal;
169554 
169555  /* Sync the db file */
169556  p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
169557 
169558  /* Update nBackfill */
169559  if( p->rc==SQLITE_OK ){
169560  void volatile *ptr;
169561  p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
169562  if( p->rc==SQLITE_OK ){
169563  ((u32 volatile*)ptr)[24] = p->iMaxFrame;
169564  }
169565  }
169566 
169567  if( p->rc==SQLITE_OK ){
169568  p->eStage = RBU_STAGE_DONE;
169569  p->rc = SQLITE_DONE;
169570  }
169571  }else{
169572  RbuFrame *pFrame = &p->aFrame[p->nStep];
169573  rbuCheckpointFrame(p, pFrame);
169574  p->nStep++;
169575  }
169576  p->nProgress++;
169577  }
169578  break;
169579  }
169580 
169581  default:
169582  break;
169583  }
169584  return p->rc;
169585  }else{
169586  return SQLITE_NOMEM;
169587  }
169588 }
169589 
169590 /*
169591 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
169592 ** otherwise. Either or both argument may be NULL. Two NULL values are
169593 ** considered equal, and NULL is considered distinct from all other values.
169594 */
169595 static int rbuStrCompare(const char *z1, const char *z2){
169596  if( z1==0 && z2==0 ) return 0;
169597  if( z1==0 || z2==0 ) return 1;
169598  return (sqlite3_stricmp(z1, z2)!=0);
169599 }
169600 
169601 /*
169602 ** This function is called as part of sqlite3rbu_open() when initializing
169603 ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
169604 ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
169605 ** things so that the next call to sqlite3rbu_step() continues on from
169606 ** where the previous rbu handle left off.
169607 **
169608 ** If an error occurs, an error code and error message are left in the
169609 ** rbu handle passed as the first argument.
169610 */
169611 static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
169612  assert( p->rc==SQLITE_OK );
169613  if( pState->zTbl ){
169614  RbuObjIter *pIter = &p->objiter;
169615  int rc = SQLITE_OK;
169616 
169617  while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
169618  || rbuStrCompare(pIter->zIdx, pState->zIdx)
169619  || rbuStrCompare(pIter->zTbl, pState->zTbl)
169620  )){
169621  rc = rbuObjIterNext(p, pIter);
169622  }
169623 
169624  if( rc==SQLITE_OK && !pIter->zTbl ){
169625  rc = SQLITE_ERROR;
169626  p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
169627  }
169628 
169629  if( rc==SQLITE_OK ){
169630  p->nStep = pState->nRow;
169631  rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
169632  }
169633 
169634  p->rc = rc;
169635  }
169636 }
169637 
169638 /*
169639 ** If there is a "*-oal" file in the file-system corresponding to the
169640 ** target database in the file-system, delete it. If an error occurs,
169641 ** leave an error code and error message in the rbu handle.
169642 */
169643 static void rbuDeleteOalFile(sqlite3rbu *p){
169644  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
169645  if( zOal ){
169646  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
169647  assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
169648  pVfs->xDelete(pVfs, zOal, 0);
169649  sqlite3_free(zOal);
169650  }
169651 }
169652 
169653 /*
169654 ** Allocate a private rbu VFS for the rbu handle passed as the only
169655 ** argument. This VFS will be used unless the call to sqlite3rbu_open()
169656 ** specified a URI with a vfs=? option in place of a target database
169657 ** file name.
169658 */
169659 static void rbuCreateVfs(sqlite3rbu *p){
169660  int rnd;
169661  char zRnd[64];
169662 
169663  assert( p->rc==SQLITE_OK );
169664  sqlite3_randomness(sizeof(int), (void*)&rnd);
169665  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
169666  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
169667  if( p->rc==SQLITE_OK ){
169668  sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
169669  assert( pVfs );
169670  p->zVfsName = pVfs->zName;
169671  }
169672 }
169673 
169674 /*
169675 ** Destroy the private VFS created for the rbu handle passed as the only
169676 ** argument by an earlier call to rbuCreateVfs().
169677 */
169678 static void rbuDeleteVfs(sqlite3rbu *p){
169679  if( p->zVfsName ){
169680  sqlite3rbu_destroy_vfs(p->zVfsName);
169681  p->zVfsName = 0;
169682  }
169683 }
169684 
169685 /*
169686 ** This user-defined SQL function is invoked with a single argument - the
169687 ** name of a table expected to appear in the target database. It returns
169688 ** the number of auxilliary indexes on the table.
169689 */
169690 static void rbuIndexCntFunc(
169691  sqlite3_context *pCtx,
169692  int nVal,
169693  sqlite3_value **apVal
169694 ){
169695  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
169696  sqlite3_stmt *pStmt = 0;
169697  char *zErrmsg = 0;
169698  int rc;
169699 
169700  assert( nVal==1 );
169701 
169702  rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
169703  sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
169704  "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
169705  );
169706  if( rc!=SQLITE_OK ){
169707  sqlite3_result_error(pCtx, zErrmsg, -1);
169708  }else{
169709  int nIndex = 0;
169710  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169711  nIndex = sqlite3_column_int(pStmt, 0);
169712  }
169713  rc = sqlite3_finalize(pStmt);
169714  if( rc==SQLITE_OK ){
169715  sqlite3_result_int(pCtx, nIndex);
169716  }else{
169717  sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
169718  }
169719  }
169720 
169721  sqlite3_free(zErrmsg);
169722 }
169723 
169724 /*
169725 ** If the RBU database contains the rbu_count table, use it to initialize
169726 ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
169727 ** is assumed to contain the same columns as:
169728 **
169729 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
169730 **
169731 ** There should be one row in the table for each data_xxx table in the
169732 ** database. The 'tbl' column should contain the name of a data_xxx table,
169733 ** and the cnt column the number of rows it contains.
169734 **
169735 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
169736 ** for all rows in the rbu_count table, where nIndex is the number of
169737 ** indexes on the corresponding target database table.
169738 */
169739 static void rbuInitPhaseOneSteps(sqlite3rbu *p){
169740  if( p->rc==SQLITE_OK ){
169741  sqlite3_stmt *pStmt = 0;
169742  int bExists = 0; /* True if rbu_count exists */
169743 
169744  p->nPhaseOneStep = -1;
169745 
169746  p->rc = sqlite3_create_function(p->dbRbu,
169747  "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
169748  );
169749 
169750  /* Check for the rbu_count table. If it does not exist, or if an error
169751  ** occurs, nPhaseOneStep will be left set to -1. */
169752  if( p->rc==SQLITE_OK ){
169753  p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
169754  "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
169755  );
169756  }
169757  if( p->rc==SQLITE_OK ){
169758  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169759  bExists = 1;
169760  }
169761  p->rc = sqlite3_finalize(pStmt);
169762  }
169763 
169764  if( p->rc==SQLITE_OK && bExists ){
169765  p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
169766  "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
169767  "FROM rbu_count"
169768  );
169769  if( p->rc==SQLITE_OK ){
169770  if( SQLITE_ROW==sqlite3_step(pStmt) ){
169771  p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
169772  }
169773  p->rc = sqlite3_finalize(pStmt);
169774  }
169775  }
169776  }
169777 }
169778 
169779 
169780 static sqlite3rbu *openRbuHandle(
169781  const char *zTarget,
169782  const char *zRbu,
169783  const char *zState
169784 ){
169785  sqlite3rbu *p;
169786  size_t nTarget = zTarget ? strlen(zTarget) : 0;
169787  size_t nRbu = strlen(zRbu);
169788  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
169789 
169790  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
169791  if( p ){
169792  RbuState *pState = 0;
169793 
169794  /* Create the custom VFS. */
169795  memset(p, 0, sizeof(sqlite3rbu));
169796  rbuCreateVfs(p);
169797 
169798  /* Open the target, RBU and state databases */
169799  if( p->rc==SQLITE_OK ){
169800  char *pCsr = (char*)&p[1];
169801  if( zTarget ){
169802  p->zTarget = pCsr;
169803  memcpy(p->zTarget, zTarget, nTarget+1);
169804  pCsr += nTarget+1;
169805  }
169806  p->zRbu = pCsr;
169807  memcpy(p->zRbu, zRbu, nRbu+1);
169808  pCsr += nRbu+1;
169809  if( zState ){
169810  p->zState = rbuMPrintf(p, "%s", zState);
169811  }
169812  rbuOpenDatabase(p);
169813  }
169814 
169815  if( p->rc==SQLITE_OK ){
169816  pState = rbuLoadState(p);
169817  assert( pState || p->rc!=SQLITE_OK );
169818  if( p->rc==SQLITE_OK ){
169819 
169820  if( pState->eStage==0 ){
169821  rbuDeleteOalFile(p);
169822  rbuInitPhaseOneSteps(p);
169823  p->eStage = RBU_STAGE_OAL;
169824  }else{
169825  p->eStage = pState->eStage;
169826  p->nPhaseOneStep = pState->nPhaseOneStep;
169827  }
169828  p->nProgress = pState->nProgress;
169829  p->iOalSz = pState->iOalSz;
169830  }
169831  }
169832  assert( p->rc!=SQLITE_OK || p->eStage!=0 );
169833 
169834  if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
169835  if( p->eStage==RBU_STAGE_OAL ){
169836  p->rc = SQLITE_ERROR;
169837  p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
169838  }else if( p->eStage==RBU_STAGE_MOVE ){
169839  p->eStage = RBU_STAGE_CKPT;
169840  p->nStep = 0;
169841  }
169842  }
169843 
169844  if( p->rc==SQLITE_OK
169845  && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
169846  && pState->eStage!=0
169847  ){
169848  rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
169849  if( pFd->iCookie!=pState->iCookie ){
169850  /* At this point (pTargetFd->iCookie) contains the value of the
169851  ** change-counter cookie (the thing that gets incremented when a
169852  ** transaction is committed in rollback mode) currently stored on
169853  ** page 1 of the database file. */
169854  p->rc = SQLITE_BUSY;
169855  p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
169856  (rbuIsVacuum(p) ? "vacuum" : "update")
169857  );
169858  }
169859  }
169860 
169861  if( p->rc==SQLITE_OK ){
169862  if( p->eStage==RBU_STAGE_OAL ){
169863  sqlite3 *db = p->dbMain;
169864  p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
169865 
169866  /* Point the object iterator at the first object */
169867  if( p->rc==SQLITE_OK ){
169868  p->rc = rbuObjIterFirst(p, &p->objiter);
169869  }
169870 
169871  /* If the RBU database contains no data_xxx tables, declare the RBU
169872  ** update finished. */
169873  if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
169874  p->rc = SQLITE_DONE;
169875  p->eStage = RBU_STAGE_DONE;
169876  }else{
169877  if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
169878  rbuCopyPragma(p, "page_size");
169879  rbuCopyPragma(p, "auto_vacuum");
169880  }
169881 
169882  /* Open transactions both databases. The *-oal file is opened or
169883  ** created at this point. */
169884  if( p->rc==SQLITE_OK ){
169885  p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
169886  }
169887 
169888  /* Check if the main database is a zipvfs db. If it is, set the upper
169889  ** level pager to use "journal_mode=off". This prevents it from
169890  ** generating a large journal using a temp file. */
169891  if( p->rc==SQLITE_OK ){
169892  int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
169893  if( frc==SQLITE_OK ){
169894  p->rc = sqlite3_exec(
169895  db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
169896  }
169897  }
169898 
169899  if( p->rc==SQLITE_OK ){
169900  rbuSetupOal(p, pState);
169901  }
169902  }
169903  }else if( p->eStage==RBU_STAGE_MOVE ){
169904  /* no-op */
169905  }else if( p->eStage==RBU_STAGE_CKPT ){
169906  rbuSetupCheckpoint(p, pState);
169907  }else if( p->eStage==RBU_STAGE_DONE ){
169908  p->rc = SQLITE_DONE;
169909  }else{
169910  p->rc = SQLITE_CORRUPT;
169911  }
169912  }
169913 
169914  rbuFreeState(pState);
169915  }
169916 
169917  return p;
169918 }
169919 
169920 /*
169921 ** Allocate and return an RBU handle with all fields zeroed except for the
169922 ** error code, which is set to SQLITE_MISUSE.
169923 */
169924 static sqlite3rbu *rbuMisuseError(void){
169925  sqlite3rbu *pRet;
169926  pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
169927  if( pRet ){
169928  memset(pRet, 0, sizeof(sqlite3rbu));
169929  pRet->rc = SQLITE_MISUSE;
169930  }
169931  return pRet;
169932 }
169933 
169934 /*
169935 ** Open and return a new RBU handle.
169936 */
169937 SQLITE_API sqlite3rbu *sqlite3rbu_open(
169938  const char *zTarget,
169939  const char *zRbu,
169940  const char *zState
169941 ){
169942  if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
169943  /* TODO: Check that zTarget and zRbu are non-NULL */
169944  return openRbuHandle(zTarget, zRbu, zState);
169945 }
169946 
169947 /*
169948 ** Open a handle to begin or resume an RBU VACUUM operation.
169949 */
169950 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
169951  const char *zTarget,
169952  const char *zState
169953 ){
169954  if( zTarget==0 ){ return rbuMisuseError(); }
169955  /* TODO: Check that both arguments are non-NULL */
169956  return openRbuHandle(0, zTarget, zState);
169957 }
169958 
169959 /*
169960 ** Return the database handle used by pRbu.
169961 */
169962 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
169963  sqlite3 *db = 0;
169964  if( pRbu ){
169965  db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
169966  }
169967  return db;
169968 }
169969 
169970 
169971 /*
169972 ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
169973 ** then edit any error message string so as to remove all occurrences of
169974 ** the pattern "rbu_imp_[0-9]*".
169975 */
169976 static void rbuEditErrmsg(sqlite3rbu *p){
169977  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
169978  unsigned int i;
169979  size_t nErrmsg = strlen(p->zErrmsg);
169980  for(i=0; i<(nErrmsg-8); i++){
169981  if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
169982  int nDel = 8;
169983  while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
169984  memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
169985  nErrmsg -= nDel;
169986  }
169987  }
169988  }
169989 }
169990 
169991 /*
169992 ** Close the RBU handle.
169993 */
169994 SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
169995  int rc;
169996  if( p ){
169997 
169998  /* Commit the transaction to the *-oal file. */
169999  if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
170000  p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
170001  }
170002 
170003  rbuSaveState(p, p->eStage);
170004 
170005  if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
170006  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
170007  }
170008 
170009  /* Close any open statement handles. */
170010  rbuObjIterFinalize(&p->objiter);
170011 
170012  /* If this is an RBU vacuum handle and the vacuum has either finished
170013  ** successfully or encountered an error, delete the contents of the
170014  ** state table. This causes the next call to sqlite3rbu_vacuum()
170015  ** specifying the current target and state databases to start a new
170016  ** vacuum from scratch. */
170017  if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
170018  int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
170019  if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
170020  }
170021 
170022  /* Close the open database handle and VFS object. */
170023  sqlite3_close(p->dbRbu);
170024  sqlite3_close(p->dbMain);
170025  rbuDeleteVfs(p);
170026  sqlite3_free(p->aBuf);
170027  sqlite3_free(p->aFrame);
170028 
170029  rbuEditErrmsg(p);
170030  rc = p->rc;
170031  *pzErrmsg = p->zErrmsg;
170032  sqlite3_free(p->zState);
170033  sqlite3_free(p);
170034  }else{
170035  rc = SQLITE_NOMEM;
170036  *pzErrmsg = 0;
170037  }
170038  return rc;
170039 }
170040 
170041 /*
170042 ** Return the total number of key-value operations (inserts, deletes or
170043 ** updates) that have been performed on the target database since the
170044 ** current RBU update was started.
170045 */
170046 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
170047  return pRbu->nProgress;
170048 }
170049 
170050 /*
170051 ** Return permyriadage progress indications for the two main stages of
170052 ** an RBU update.
170053 */
170054 SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
170055  const int MAX_PROGRESS = 10000;
170056  switch( p->eStage ){
170057  case RBU_STAGE_OAL:
170058  if( p->nPhaseOneStep>0 ){
170059  *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
170060  }else{
170061  *pnOne = -1;
170062  }
170063  *pnTwo = 0;
170064  break;
170065 
170066  case RBU_STAGE_MOVE:
170067  *pnOne = MAX_PROGRESS;
170068  *pnTwo = 0;
170069  break;
170070 
170071  case RBU_STAGE_CKPT:
170072  *pnOne = MAX_PROGRESS;
170073  *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
170074  break;
170075 
170076  case RBU_STAGE_DONE:
170077  *pnOne = MAX_PROGRESS;
170078  *pnTwo = MAX_PROGRESS;
170079  break;
170080 
170081  default:
170082  assert( 0 );
170083  }
170084 }
170085 
170086 /*
170087 ** Return the current state of the RBU vacuum or update operation.
170088 */
170089 SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
170090  int aRes[] = {
170091  0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
170092  0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
170093  };
170094 
170095  assert( RBU_STAGE_OAL==1 );
170096  assert( RBU_STAGE_MOVE==2 );
170097  assert( RBU_STAGE_CKPT==4 );
170098  assert( RBU_STAGE_DONE==5 );
170099  assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
170100  assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
170101  assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
170102  assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
170103 
170104  if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
170105  return SQLITE_RBU_STATE_ERROR;
170106  }else{
170107  assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
170108  assert( p->eStage==RBU_STAGE_OAL
170109  || p->eStage==RBU_STAGE_MOVE
170110  || p->eStage==RBU_STAGE_CKPT
170111  || p->eStage==RBU_STAGE_DONE
170112  );
170113  return aRes[p->eStage];
170114  }
170115 }
170116 
170117 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
170118  int rc = p->rc;
170119  if( rc==SQLITE_DONE ) return SQLITE_OK;
170120 
170121  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
170122  if( p->eStage==RBU_STAGE_OAL ){
170123  assert( rc!=SQLITE_DONE );
170124  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
170125  }
170126 
170127  p->rc = rc;
170128  rbuSaveState(p, p->eStage);
170129  rc = p->rc;
170130 
170131  if( p->eStage==RBU_STAGE_OAL ){
170132  assert( rc!=SQLITE_DONE );
170133  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
170134  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
170135  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
170136  }
170137 
170138  p->rc = rc;
170139  return rc;
170140 }
170141 
170142 /**************************************************************************
170143 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
170144 ** of a standard VFS in the following ways:
170145 **
170146 ** 1. Whenever the first page of a main database file is read or
170147 ** written, the value of the change-counter cookie is stored in
170148 ** rbu_file.iCookie. Similarly, the value of the "write-version"
170149 ** database header field is stored in rbu_file.iWriteVer. This ensures
170150 ** that the values are always trustworthy within an open transaction.
170151 **
170152 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
170153 ** member variable of the associated database file descriptor is set
170154 ** to point to the new file. A mutex protected linked list of all main
170155 ** db fds opened using a particular RBU VFS is maintained at
170156 ** rbu_vfs.pMain to facilitate this.
170157 **
170158 ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
170159 ** object can be marked as the target database of an RBU update. This
170160 ** turns on the following extra special behaviour:
170161 **
170162 ** 3a. If xAccess() is called to check if there exists a *-wal file
170163 ** associated with an RBU target database currently in RBU_STAGE_OAL
170164 ** stage (preparing the *-oal file), the following special handling
170165 ** applies:
170166 **
170167 ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
170168 ** target database may not be in wal mode already.
170169 **
170170 ** * if the *-wal file does not exist, set the output parameter to
170171 ** non-zero (to tell SQLite that it does exist) anyway.
170172 **
170173 ** Then, when xOpen() is called to open the *-wal file associated with
170174 ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
170175 ** file, the rbu vfs opens the corresponding *-oal file instead.
170176 **
170177 ** 3b. The *-shm pages returned by xShmMap() for a target db file in
170178 ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
170179 ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
170180 ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
170181 ** because assert() statements in some VFS implementations fail if
170182 ** xShmLock() is called before xShmMap().
170183 **
170184 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
170185 ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
170186 ** fails with an SQLITE_BUSY error. This is to stop RBU connections
170187 ** from automatically checkpointing a *-wal (or *-oal) file from within
170188 ** sqlite3_close().
170189 **
170190 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
170191 ** all xWrite() calls on the target database file perform no IO.
170192 ** Instead the frame and page numbers that would be read and written
170193 ** are recorded. Additionally, successful attempts to obtain exclusive
170194 ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
170195 ** database file are recorded. xShmLock() calls to unlock the same
170196 ** locks are no-ops (so that once obtained, these locks are never
170197 ** relinquished). Finally, calls to xSync() on the target database
170198 ** file fail with SQLITE_INTERNAL errors.
170199 */
170200 
170201 static void rbuUnlockShm(rbu_file *p){
170202  if( p->pRbu ){
170203  int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
170204  int i;
170205  for(i=0; i<SQLITE_SHM_NLOCK;i++){
170206  if( (1<<i) & p->pRbu->mLock ){
170207  xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
170208  }
170209  }
170210  p->pRbu->mLock = 0;
170211  }
170212 }
170213 
170214 /*
170215 ** Close an rbu file.
170216 */
170217 static int rbuVfsClose(sqlite3_file *pFile){
170218  rbu_file *p = (rbu_file*)pFile;
170219  int rc;
170220  int i;
170221 
170222  /* Free the contents of the apShm[] array. And the array itself. */
170223  for(i=0; i<p->nShm; i++){
170224  sqlite3_free(p->apShm[i]);
170225  }
170226  sqlite3_free(p->apShm);
170227  p->apShm = 0;
170228  sqlite3_free(p->zDel);
170229 
170230  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
170231  rbu_file **pp;
170232  sqlite3_mutex_enter(p->pRbuVfs->mutex);
170233  for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
170234  *pp = p->pMainNext;
170235  sqlite3_mutex_leave(p->pRbuVfs->mutex);
170236  rbuUnlockShm(p);
170237  p->pReal->pMethods->xShmUnmap(p->pReal, 0);
170238  }
170239 
170240  /* Close the underlying file handle */
170241  rc = p->pReal->pMethods->xClose(p->pReal);
170242  return rc;
170243 }
170244 
170245 
170246 /*
170247 ** Read and return an unsigned 32-bit big-endian integer from the buffer
170248 ** passed as the only argument.
170249 */
170250 static u32 rbuGetU32(u8 *aBuf){
170251  return ((u32)aBuf[0] << 24)
170252  + ((u32)aBuf[1] << 16)
170253  + ((u32)aBuf[2] << 8)
170254  + ((u32)aBuf[3]);
170255 }
170256 
170257 /*
170258 ** Write an unsigned 32-bit value in big-endian format to the supplied
170259 ** buffer.
170260 */
170261 static void rbuPutU32(u8 *aBuf, u32 iVal){
170262  aBuf[0] = (iVal >> 24) & 0xFF;
170263  aBuf[1] = (iVal >> 16) & 0xFF;
170264  aBuf[2] = (iVal >> 8) & 0xFF;
170265  aBuf[3] = (iVal >> 0) & 0xFF;
170266 }
170267 
170268 static void rbuPutU16(u8 *aBuf, u16 iVal){
170269  aBuf[0] = (iVal >> 8) & 0xFF;
170270  aBuf[1] = (iVal >> 0) & 0xFF;
170271 }
170272 
170273 /*
170274 ** Read data from an rbuVfs-file.
170275 */
170276 static int rbuVfsRead(
170277  sqlite3_file *pFile,
170278  void *zBuf,
170279  int iAmt,
170280  sqlite_int64 iOfst
170281 ){
170282  rbu_file *p = (rbu_file*)pFile;
170283  sqlite3rbu *pRbu = p->pRbu;
170284  int rc;
170285 
170286  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
170287  assert( p->openFlags & SQLITE_OPEN_WAL );
170288  rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
170289  }else{
170290  if( pRbu && pRbu->eStage==RBU_STAGE_OAL
170291  && (p->openFlags & SQLITE_OPEN_WAL)
170292  && iOfst>=pRbu->iOalSz
170293  ){
170294  rc = SQLITE_OK;
170295  memset(zBuf, 0, iAmt);
170296  }else{
170297  rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
170298 #if 1
170299  /* If this is being called to read the first page of the target
170300  ** database as part of an rbu vacuum operation, synthesize the
170301  ** contents of the first page if it does not yet exist. Otherwise,
170302  ** SQLite will not check for a *-wal file. */
170303  if( pRbu && rbuIsVacuum(pRbu)
170304  && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
170305  && (p->openFlags & SQLITE_OPEN_MAIN_DB)
170306  && pRbu->rc==SQLITE_OK
170307  ){
170308  sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
170309  rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
170310  if( rc==SQLITE_OK ){
170311  u8 *aBuf = (u8*)zBuf;
170312  u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
170313  rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
170314  rbuPutU32(&aBuf[36], 0); /* number of free pages */
170315  rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
170316  rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
170317  rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
170318 
170319  if( iAmt>100 ){
170320  memset(&aBuf[100], 0, iAmt-100);
170321  rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
170322  aBuf[100] = 0x0D;
170323  }
170324  }
170325  }
170326 #endif
170327  }
170328  if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
170329  /* These look like magic numbers. But they are stable, as they are part
170330  ** of the definition of the SQLite file format, which may not change. */
170331  u8 *pBuf = (u8*)zBuf;
170332  p->iCookie = rbuGetU32(&pBuf[24]);
170333  p->iWriteVer = pBuf[19];
170334  }
170335  }
170336  return rc;
170337 }
170338 
170339 /*
170340 ** Write data to an rbuVfs-file.
170341 */
170342 static int rbuVfsWrite(
170343  sqlite3_file *pFile,
170344  const void *zBuf,
170345  int iAmt,
170346  sqlite_int64 iOfst
170347 ){
170348  rbu_file *p = (rbu_file*)pFile;
170349  sqlite3rbu *pRbu = p->pRbu;
170350  int rc;
170351 
170352  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
170353  assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
170354  rc = rbuCaptureDbWrite(p->pRbu, iOfst);
170355  }else{
170356  if( pRbu && pRbu->eStage==RBU_STAGE_OAL
170357  && (p->openFlags & SQLITE_OPEN_WAL)
170358  && iOfst>=pRbu->iOalSz
170359  ){
170360  pRbu->iOalSz = iAmt + iOfst;
170361  }
170362  rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
170363  if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
170364  /* These look like magic numbers. But they are stable, as they are part
170365  ** of the definition of the SQLite file format, which may not change. */
170366  u8 *pBuf = (u8*)zBuf;
170367  p->iCookie = rbuGetU32(&pBuf[24]);
170368  p->iWriteVer = pBuf[19];
170369  }
170370  }
170371  return rc;
170372 }
170373 
170374 /*
170375 ** Truncate an rbuVfs-file.
170376 */
170377 static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
170378  rbu_file *p = (rbu_file*)pFile;
170379  return p->pReal->pMethods->xTruncate(p->pReal, size);
170380 }
170381 
170382 /*
170383 ** Sync an rbuVfs-file.
170384 */
170385 static int rbuVfsSync(sqlite3_file *pFile, int flags){
170386  rbu_file *p = (rbu_file *)pFile;
170387  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
170388  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
170389  return SQLITE_INTERNAL;
170390  }
170391  return SQLITE_OK;
170392  }
170393  return p->pReal->pMethods->xSync(p->pReal, flags);
170394 }
170395 
170396 /*
170397 ** Return the current file-size of an rbuVfs-file.
170398 */
170399 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
170400  rbu_file *p = (rbu_file *)pFile;
170401  int rc;
170402  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
170403 
170404  /* If this is an RBU vacuum operation and this is the target database,
170405  ** pretend that it has at least one page. Otherwise, SQLite will not
170406  ** check for the existance of a *-wal file. rbuVfsRead() contains
170407  ** similar logic. */
170408  if( rc==SQLITE_OK && *pSize==0
170409  && p->pRbu && rbuIsVacuum(p->pRbu)
170410  && (p->openFlags & SQLITE_OPEN_MAIN_DB)
170411  ){
170412  *pSize = 1024;
170413  }
170414  return rc;
170415 }
170416 
170417 /*
170418 ** Lock an rbuVfs-file.
170419 */
170420 static int rbuVfsLock(sqlite3_file *pFile, int eLock){
170421  rbu_file *p = (rbu_file*)pFile;
170422  sqlite3rbu *pRbu = p->pRbu;
170423  int rc = SQLITE_OK;
170424 
170425  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170426  if( eLock==SQLITE_LOCK_EXCLUSIVE
170427  && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
170428  ){
170429  /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
170430  ** prevents it from checkpointing the database from sqlite3_close(). */
170431  rc = SQLITE_BUSY;
170432  }else{
170433  rc = p->pReal->pMethods->xLock(p->pReal, eLock);
170434  }
170435 
170436  return rc;
170437 }
170438 
170439 /*
170440 ** Unlock an rbuVfs-file.
170441 */
170442 static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
170443  rbu_file *p = (rbu_file *)pFile;
170444  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
170445 }
170446 
170447 /*
170448 ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
170449 */
170450 static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
170451  rbu_file *p = (rbu_file *)pFile;
170452  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
170453 }
170454 
170455 /*
170456 ** File control method. For custom operations on an rbuVfs-file.
170457 */
170458 static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
170459  rbu_file *p = (rbu_file *)pFile;
170460  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
170461  int rc;
170462 
170463  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
170465  );
170466  if( op==SQLITE_FCNTL_RBU ){
170467  sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
170468 
170469  /* First try to find another RBU vfs lower down in the vfs stack. If
170470  ** one is found, this vfs will operate in pass-through mode. The lower
170471  ** level vfs will do the special RBU handling. */
170472  rc = xControl(p->pReal, op, pArg);
170473 
170474  if( rc==SQLITE_NOTFOUND ){
170475  /* Now search for a zipvfs instance lower down in the VFS stack. If
170476  ** one is found, this is an error. */
170477  void *dummy = 0;
170478  rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
170479  if( rc==SQLITE_OK ){
170480  rc = SQLITE_ERROR;
170481  pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
170482  }else if( rc==SQLITE_NOTFOUND ){
170483  pRbu->pTargetFd = p;
170484  p->pRbu = pRbu;
170485  if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
170486  rc = SQLITE_OK;
170487  }
170488  }
170489  return rc;
170490  }
170491  else if( op==SQLITE_FCNTL_RBUCNT ){
170492  sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
170493  pRbu->nRbu++;
170494  pRbu->pRbuFd = p;
170495  p->bNolock = 1;
170496  }
170497 
170498  rc = xControl(p->pReal, op, pArg);
170499  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
170500  rbu_vfs *pRbuVfs = p->pRbuVfs;
170501  char *zIn = *(char**)pArg;
170502  char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
170503  *(char**)pArg = zOut;
170504  if( zOut==0 ) rc = SQLITE_NOMEM;
170505  }
170506 
170507  return rc;
170508 }
170509 
170510 /*
170511 ** Return the sector-size in bytes for an rbuVfs-file.
170512 */
170513 static int rbuVfsSectorSize(sqlite3_file *pFile){
170514  rbu_file *p = (rbu_file *)pFile;
170515  return p->pReal->pMethods->xSectorSize(p->pReal);
170516 }
170517 
170518 /*
170519 ** Return the device characteristic flags supported by an rbuVfs-file.
170520 */
170521 static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
170522  rbu_file *p = (rbu_file *)pFile;
170523  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
170524 }
170525 
170526 /*
170527 ** Take or release a shared-memory lock.
170528 */
170529 static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
170530  rbu_file *p = (rbu_file*)pFile;
170531  sqlite3rbu *pRbu = p->pRbu;
170532  int rc = SQLITE_OK;
170533 
170534 #ifdef SQLITE_AMALGAMATION
170535  assert( WAL_CKPT_LOCK==1 );
170536 #endif
170537 
170538  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170539  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
170540  /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
170541  ** taking this lock also prevents any checkpoints from occurring.
170542  ** todo: really, it's not clear why this might occur, as
170543  ** wal_autocheckpoint ought to be turned off. */
170544  if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
170545  }else{
170546  int bCapture = 0;
170547  if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
170548  && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
170549  && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
170550  ){
170551  bCapture = 1;
170552  }
170553 
170554  if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
170555  rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
170556  if( bCapture && rc==SQLITE_OK ){
170557  pRbu->mLock |= (1 << ofst);
170558  }
170559  }
170560  }
170561 
170562  return rc;
170563 }
170564 
170565 /*
170566 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
170567 */
170568 static int rbuVfsShmMap(
170569  sqlite3_file *pFile,
170570  int iRegion,
170571  int szRegion,
170572  int isWrite,
170573  void volatile **pp
170574 ){
170575  rbu_file *p = (rbu_file*)pFile;
170576  int rc = SQLITE_OK;
170577  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
170578 
170579  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
170580  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
170581  ** instead of a file on disk. */
170582  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170583  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
170584  if( iRegion<=p->nShm ){
170585  int nByte = (iRegion+1) * sizeof(char*);
170586  char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
170587  if( apNew==0 ){
170588  rc = SQLITE_NOMEM;
170589  }else{
170590  memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
170591  p->apShm = apNew;
170592  p->nShm = iRegion+1;
170593  }
170594  }
170595 
170596  if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
170597  char *pNew = (char*)sqlite3_malloc64(szRegion);
170598  if( pNew==0 ){
170599  rc = SQLITE_NOMEM;
170600  }else{
170601  memset(pNew, 0, szRegion);
170602  p->apShm[iRegion] = pNew;
170603  }
170604  }
170605 
170606  if( rc==SQLITE_OK ){
170607  *pp = p->apShm[iRegion];
170608  }else{
170609  *pp = 0;
170610  }
170611  }else{
170612  assert( p->apShm==0 );
170613  rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
170614  }
170615 
170616  return rc;
170617 }
170618 
170619 /*
170620 ** Memory barrier.
170621 */
170622 static void rbuVfsShmBarrier(sqlite3_file *pFile){
170623  rbu_file *p = (rbu_file *)pFile;
170624  p->pReal->pMethods->xShmBarrier(p->pReal);
170625 }
170626 
170627 /*
170628 ** The xShmUnmap method.
170629 */
170630 static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
170631  rbu_file *p = (rbu_file*)pFile;
170632  int rc = SQLITE_OK;
170633  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
170634 
170635  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
170636  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
170637  /* no-op */
170638  }else{
170639  /* Release the checkpointer and writer locks */
170640  rbuUnlockShm(p);
170641  rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
170642  }
170643  return rc;
170644 }
170645 
170646 /*
170647 ** Given that zWal points to a buffer containing a wal file name passed to
170648 ** either the xOpen() or xAccess() VFS method, return a pointer to the
170649 ** file-handle opened by the same database connection on the corresponding
170650 ** database file.
170651 */
170652 static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
170653  rbu_file *pDb;
170654  sqlite3_mutex_enter(pRbuVfs->mutex);
170655  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
170656  sqlite3_mutex_leave(pRbuVfs->mutex);
170657  return pDb;
170658 }
170659 
170660 /*
170661 ** A main database named zName has just been opened. The following
170662 ** function returns a pointer to a buffer owned by SQLite that contains
170663 ** the name of the *-wal file this db connection will use. SQLite
170664 ** happens to pass a pointer to this buffer when using xAccess()
170665 ** or xOpen() to operate on the *-wal file.
170666 */
170667 static const char *rbuMainToWal(const char *zName, int flags){
170668  int n = (int)strlen(zName);
170669  const char *z = &zName[n];
170670  if( flags & SQLITE_OPEN_URI ){
170671  int odd = 0;
170672  while( 1 ){
170673  if( z[0]==0 ){
170674  odd = 1 - odd;
170675  if( odd && z[1]==0 ) break;
170676  }
170677  z++;
170678  }
170679  z += 2;
170680  }else{
170681  while( *z==0 ) z++;
170682  }
170683  z += (n + 8 + 1);
170684  return z;
170685 }
170686 
170687 /*
170688 ** Open an rbu file handle.
170689 */
170690 static int rbuVfsOpen(
170691  sqlite3_vfs *pVfs,
170692  const char *zName,
170693  sqlite3_file *pFile,
170694  int flags,
170695  int *pOutFlags
170696 ){
170697  static sqlite3_io_methods rbuvfs_io_methods = {
170698  2, /* iVersion */
170699  rbuVfsClose, /* xClose */
170700  rbuVfsRead, /* xRead */
170701  rbuVfsWrite, /* xWrite */
170702  rbuVfsTruncate, /* xTruncate */
170703  rbuVfsSync, /* xSync */
170704  rbuVfsFileSize, /* xFileSize */
170705  rbuVfsLock, /* xLock */
170706  rbuVfsUnlock, /* xUnlock */
170707  rbuVfsCheckReservedLock, /* xCheckReservedLock */
170708  rbuVfsFileControl, /* xFileControl */
170709  rbuVfsSectorSize, /* xSectorSize */
170710  rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
170711  rbuVfsShmMap, /* xShmMap */
170712  rbuVfsShmLock, /* xShmLock */
170713  rbuVfsShmBarrier, /* xShmBarrier */
170714  rbuVfsShmUnmap, /* xShmUnmap */
170715  0, 0 /* xFetch, xUnfetch */
170716  };
170717  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
170718  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
170719  rbu_file *pFd = (rbu_file *)pFile;
170720  int rc = SQLITE_OK;
170721  const char *zOpen = zName;
170722  int oflags = flags;
170723 
170724  memset(pFd, 0, sizeof(rbu_file));
170725  pFd->pReal = (sqlite3_file*)&pFd[1];
170726  pFd->pRbuVfs = pRbuVfs;
170727  pFd->openFlags = flags;
170728  if( zName ){
170729  if( flags & SQLITE_OPEN_MAIN_DB ){
170730  /* A main database has just been opened. The following block sets
170731  ** (pFd->zWal) to point to a buffer owned by SQLite that contains
170732  ** the name of the *-wal file this db connection will use. SQLite
170733  ** happens to pass a pointer to this buffer when using xAccess()
170734  ** or xOpen() to operate on the *-wal file. */
170735  pFd->zWal = rbuMainToWal(zName, flags);
170736  }
170737  else if( flags & SQLITE_OPEN_WAL ){
170738  rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
170739  if( pDb ){
170740  if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
170741  /* This call is to open a *-wal file. Intead, open the *-oal. This
170742  ** code ensures that the string passed to xOpen() is terminated by a
170743  ** pair of '\0' bytes in case the VFS attempts to extract a URI
170744  ** parameter from it. */
170745  const char *zBase = zName;
170746  size_t nCopy;
170747  char *zCopy;
170748  if( rbuIsVacuum(pDb->pRbu) ){
170749  zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
170750  zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
170751  }
170752  nCopy = strlen(zBase);
170753  zCopy = sqlite3_malloc64(nCopy+2);
170754  if( zCopy ){
170755  memcpy(zCopy, zBase, nCopy);
170756  zCopy[nCopy-3] = 'o';
170757  zCopy[nCopy] = '\0';
170758  zCopy[nCopy+1] = '\0';
170759  zOpen = (const char*)(pFd->zDel = zCopy);
170760  }else{
170761  rc = SQLITE_NOMEM;
170762  }
170763  pFd->pRbu = pDb->pRbu;
170764  }
170765  pDb->pWalFd = pFd;
170766  }
170767  }
170768  }
170769 
170770  if( oflags & SQLITE_OPEN_MAIN_DB
170771  && sqlite3_uri_boolean(zName, "rbu_memory", 0)
170772  ){
170773  assert( oflags & SQLITE_OPEN_MAIN_DB );
170776  zOpen = 0;
170777  }
170778 
170779  if( rc==SQLITE_OK ){
170780  rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
170781  }
170782  if( pFd->pReal->pMethods ){
170783  /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
170784  ** pointer and, if the file is a main database file, link it into the
170785  ** mutex protected linked list of all such files. */
170786  pFile->pMethods = &rbuvfs_io_methods;
170787  if( flags & SQLITE_OPEN_MAIN_DB ){
170788  sqlite3_mutex_enter(pRbuVfs->mutex);
170789  pFd->pMainNext = pRbuVfs->pMain;
170790  pRbuVfs->pMain = pFd;
170791  sqlite3_mutex_leave(pRbuVfs->mutex);
170792  }
170793  }else{
170794  sqlite3_free(pFd->zDel);
170795  }
170796 
170797  return rc;
170798 }
170799 
170800 /*
170801 ** Delete the file located at zPath.
170802 */
170803 static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
170804  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170805  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
170806 }
170807 
170808 /*
170809 ** Test for access permissions. Return true if the requested permission
170810 ** is available, or false otherwise.
170811 */
170812 static int rbuVfsAccess(
170813  sqlite3_vfs *pVfs,
170814  const char *zPath,
170815  int flags,
170816  int *pResOut
170817 ){
170818  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
170819  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
170820  int rc;
170821 
170822  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
170823 
170824  /* If this call is to check if a *-wal file associated with an RBU target
170825  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
170826  ** the following special handling is activated:
170827  **
170828  ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
170829  ** ensures that the RBU extension never tries to update a database
170830  ** in wal mode, even if the first page of the database file has
170831  ** been damaged.
170832  **
170833  ** b) if the *-wal file does not exist, claim that it does anyway,
170834  ** causing SQLite to call xOpen() to open it. This call will also
170835  ** be intercepted (see the rbuVfsOpen() function) and the *-oal
170836  ** file opened instead.
170837  */
170838  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
170839  rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
170840  if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
170841  if( *pResOut ){
170842  rc = SQLITE_CANTOPEN;
170843  }else{
170844  *pResOut = 1;
170845  }
170846  }
170847  }
170848 
170849  return rc;
170850 }
170851 
170852 /*
170853 ** Populate buffer zOut with the full canonical pathname corresponding
170854 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
170855 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
170856 */
170857 static int rbuVfsFullPathname(
170858  sqlite3_vfs *pVfs,
170859  const char *zPath,
170860  int nOut,
170861  char *zOut
170862 ){
170863  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170864  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
170865 }
170866 
170867 #ifndef SQLITE_OMIT_LOAD_EXTENSION
170868 /*
170869 ** Open the dynamic library located at zPath and return a handle.
170870 */
170871 static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
170872  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170873  return pRealVfs->xDlOpen(pRealVfs, zPath);
170874 }
170875 
170876 /*
170877 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
170878 ** utf-8 string describing the most recent error encountered associated
170879 ** with dynamic libraries.
170880 */
170881 static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
170882  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170883  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
170884 }
170885 
170886 /*
170887 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
170888 */
170889 static void (*rbuVfsDlSym(
170890  sqlite3_vfs *pVfs,
170891  void *pArg,
170892  const char *zSym
170893 ))(void){
170894  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170895  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
170896 }
170897 
170898 /*
170899 ** Close the dynamic library handle pHandle.
170900 */
170901 static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
170902  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170903  pRealVfs->xDlClose(pRealVfs, pHandle);
170904 }
170905 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
170906 
170907 /*
170908 ** Populate the buffer pointed to by zBufOut with nByte bytes of
170909 ** random data.
170910 */
170911 static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
170912  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170913  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
170914 }
170915 
170916 /*
170917 ** Sleep for nMicro microseconds. Return the number of microseconds
170918 ** actually slept.
170919 */
170920 static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
170921  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170922  return pRealVfs->xSleep(pRealVfs, nMicro);
170923 }
170924 
170925 /*
170926 ** Return the current time as a Julian Day number in *pTimeOut.
170927 */
170928 static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
170929  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
170930  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
170931 }
170932 
170933 /*
170934 ** No-op.
170935 */
170936 static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
170937  return 0;
170938 }
170939 
170940 /*
170941 ** Deregister and destroy an RBU vfs created by an earlier call to
170942 ** sqlite3rbu_create_vfs().
170943 */
170944 SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
170945  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
170946  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
170947  sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
170948  sqlite3_vfs_unregister(pVfs);
170949  sqlite3_free(pVfs);
170950  }
170951 }
170952 
170953 /*
170954 ** Create an RBU VFS named zName that accesses the underlying file-system
170955 ** via existing VFS zParent. The new object is registered as a non-default
170956 ** VFS with SQLite before returning.
170957 */
170958 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
170959 
170960  /* Template for VFS */
170961  static sqlite3_vfs vfs_template = {
170962  1, /* iVersion */
170963  0, /* szOsFile */
170964  0, /* mxPathname */
170965  0, /* pNext */
170966  0, /* zName */
170967  0, /* pAppData */
170968  rbuVfsOpen, /* xOpen */
170969  rbuVfsDelete, /* xDelete */
170970  rbuVfsAccess, /* xAccess */
170971  rbuVfsFullPathname, /* xFullPathname */
170972 
170973 #ifndef SQLITE_OMIT_LOAD_EXTENSION
170974  rbuVfsDlOpen, /* xDlOpen */
170975  rbuVfsDlError, /* xDlError */
170976  rbuVfsDlSym, /* xDlSym */
170977  rbuVfsDlClose, /* xDlClose */
170978 #else
170979  0, 0, 0, 0,
170980 #endif
170981 
170982  rbuVfsRandomness, /* xRandomness */
170983  rbuVfsSleep, /* xSleep */
170984  rbuVfsCurrentTime, /* xCurrentTime */
170985  rbuVfsGetLastError, /* xGetLastError */
170986  0, /* xCurrentTimeInt64 (version 2) */
170987  0, 0, 0 /* Unimplemented version 3 methods */
170988  };
170989 
170990  rbu_vfs *pNew = 0; /* Newly allocated VFS */
170991  int rc = SQLITE_OK;
170992  size_t nName;
170993  size_t nByte;
170994 
170995  nName = strlen(zName);
170996  nByte = sizeof(rbu_vfs) + nName + 1;
170997  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
170998  if( pNew==0 ){
170999  rc = SQLITE_NOMEM;
171000  }else{
171001  sqlite3_vfs *pParent; /* Parent VFS */
171002  memset(pNew, 0, nByte);
171003  pParent = sqlite3_vfs_find(zParent);
171004  if( pParent==0 ){
171005  rc = SQLITE_NOTFOUND;
171006  }else{
171007  char *zSpace;
171008  memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
171009  pNew->base.mxPathname = pParent->mxPathname;
171010  pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
171011  pNew->pRealVfs = pParent;
171012  pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
171013  memcpy(zSpace, zName, nName);
171014 
171015  /* Allocate the mutex and register the new VFS (not as the default) */
171017  if( pNew->mutex==0 ){
171018  rc = SQLITE_NOMEM;
171019  }else{
171020  rc = sqlite3_vfs_register(&pNew->base, 0);
171021  }
171022  }
171023 
171024  if( rc!=SQLITE_OK ){
171025  sqlite3_mutex_free(pNew->mutex);
171026  sqlite3_free(pNew);
171027  }
171028  }
171029 
171030  return rc;
171031 }
171032 
171033 
171034 /**************************************************************************/
171035 
171036 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
171037 
171038 /************** End of sqlite3rbu.c ******************************************/
171039 /************** Begin file dbstat.c ******************************************/
171040 /*
171041 ** 2010 July 12
171042 **
171043 ** The author disclaims copyright to this source code. In place of
171044 ** a legal notice, here is a blessing:
171045 **
171046 ** May you do good and not evil.
171047 ** May you find forgiveness for yourself and forgive others.
171048 ** May you share freely, never taking more than you give.
171049 **
171050 ******************************************************************************
171051 **
171052 ** This file contains an implementation of the "dbstat" virtual table.
171053 **
171054 ** The dbstat virtual table is used to extract low-level formatting
171055 ** information from an SQLite database in order to implement the
171056 ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
171057 ** for an example implementation.
171058 **
171059 ** Additional information is available on the "dbstat.html" page of the
171060 ** official SQLite documentation.
171061 */
171062 
171063 /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
171064 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
171065  && !defined(SQLITE_OMIT_VIRTUALTABLE)
171066 
171067 /*
171068 ** Page paths:
171069 **
171070 ** The value of the 'path' column describes the path taken from the
171071 ** root-node of the b-tree structure to each page. The value of the
171072 ** root-node path is '/'.
171073 **
171074 ** The value of the path for the left-most child page of the root of
171075 ** a b-tree is '/000/'. (Btrees store content ordered from left to right
171076 ** so the pages to the left have smaller keys than the pages to the right.)
171077 ** The next to left-most child of the root page is
171078 ** '/001', and so on, each sibling page identified by a 3-digit hex
171079 ** value. The children of the 451st left-most sibling have paths such
171080 ** as '/1c2/000/, '/1c2/001/' etc.
171081 **
171082 ** Overflow pages are specified by appending a '+' character and a
171083 ** six-digit hexadecimal value to the path to the cell they are linked
171084 ** from. For example, the three overflow pages in a chain linked from
171085 ** the left-most cell of the 450th child of the root page are identified
171086 ** by the paths:
171087 **
171088 ** '/1c2/000+000000' // First page in overflow chain
171089 ** '/1c2/000+000001' // Second page in overflow chain
171090 ** '/1c2/000+000002' // Third page in overflow chain
171091 **
171092 ** If the paths are sorted using the BINARY collation sequence, then
171093 ** the overflow pages associated with a cell will appear earlier in the
171094 ** sort-order than its child page:
171095 **
171096 ** '/1c2/000/' // Left-most child of 451st child of root
171097 */
171098 #define VTAB_SCHEMA \
171099  "CREATE TABLE xx( " \
171100  " name TEXT, /* Name of table or index */" \
171101  " path TEXT, /* Path to page from root */" \
171102  " pageno INTEGER, /* Page number */" \
171103  " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
171104  " ncell INTEGER, /* Cells on page (0 for overflow) */" \
171105  " payload INTEGER, /* Bytes of payload on this page */" \
171106  " unused INTEGER, /* Bytes of unused space on this page */" \
171107  " mx_payload INTEGER, /* Largest payload size of all cells */" \
171108  " pgoffset INTEGER, /* Offset of page in file */" \
171109  " pgsize INTEGER, /* Size of the page */" \
171110  " schema TEXT HIDDEN /* Database schema being analyzed */" \
171111  ");"
171112 
171113 
171114 typedef struct StatTable StatTable;
171115 typedef struct StatCursor StatCursor;
171116 typedef struct StatPage StatPage;
171117 typedef struct StatCell StatCell;
171118 
171119 struct StatCell {
171120  int nLocal; /* Bytes of local payload */
171121  u32 iChildPg; /* Child node (or 0 if this is a leaf) */
171122  int nOvfl; /* Entries in aOvfl[] */
171123  u32 *aOvfl; /* Array of overflow page numbers */
171124  int nLastOvfl; /* Bytes of payload on final overflow page */
171125  int iOvfl; /* Iterates through aOvfl[] */
171126 };
171127 
171128 struct StatPage {
171129  u32 iPgno;
171130  DbPage *pPg;
171131  int iCell;
171132 
171133  char *zPath; /* Path to this page */
171134 
171135  /* Variables populated by statDecodePage(): */
171136  u8 flags; /* Copy of flags byte */
171137  int nCell; /* Number of cells on page */
171138  int nUnused; /* Number of unused bytes on page */
171139  StatCell *aCell; /* Array of parsed cells */
171140  u32 iRightChildPg; /* Right-child page number (or 0) */
171141  int nMxPayload; /* Largest payload of any cell on this page */
171142 };
171143 
171144 struct StatCursor {
171145  sqlite3_vtab_cursor base;
171146  sqlite3_stmt *pStmt; /* Iterates through set of root pages */
171147  int isEof; /* After pStmt has returned SQLITE_DONE */
171148  int iDb; /* Schema used for this query */
171149 
171150  StatPage aPage[32];
171151  int iPage; /* Current entry in aPage[] */
171152 
171153  /* Values to return. */
171154  char *zName; /* Value of 'name' column */
171155  char *zPath; /* Value of 'path' column */
171156  u32 iPageno; /* Value of 'pageno' column */
171157  char *zPagetype; /* Value of 'pagetype' column */
171158  int nCell; /* Value of 'ncell' column */
171159  int nPayload; /* Value of 'payload' column */
171160  int nUnused; /* Value of 'unused' column */
171161  int nMxPayload; /* Value of 'mx_payload' column */
171162  i64 iOffset; /* Value of 'pgOffset' column */
171163  int szPage; /* Value of 'pgSize' column */
171164 };
171165 
171166 struct StatTable {
171167  sqlite3_vtab base;
171168  sqlite3 *db;
171169  int iDb; /* Index of database to analyze */
171170 };
171171 
171172 #ifndef get2byte
171173 # define get2byte(x) ((x)[0]<<8 | (x)[1])
171174 #endif
171175 
171176 /*
171177 ** Connect to or create a statvfs virtual table.
171178 */
171179 static int statConnect(
171180  sqlite3 *db,
171181  void *pAux,
171182  int argc, const char *const*argv,
171183  sqlite3_vtab **ppVtab,
171184  char **pzErr
171185 ){
171186  StatTable *pTab = 0;
171187  int rc = SQLITE_OK;
171188  int iDb;
171189 
171190  if( argc>=4 ){
171191  Token nm;
171192  sqlite3TokenInit(&nm, (char*)argv[3]);
171193  iDb = sqlite3FindDb(db, &nm);
171194  if( iDb<0 ){
171195  *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
171196  return SQLITE_ERROR;
171197  }
171198  }else{
171199  iDb = 0;
171200  }
171201  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
171202  if( rc==SQLITE_OK ){
171203  pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
171204  if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
171205  }
171206 
171207  assert( rc==SQLITE_OK || pTab==0 );
171208  if( rc==SQLITE_OK ){
171209  memset(pTab, 0, sizeof(StatTable));
171210  pTab->db = db;
171211  pTab->iDb = iDb;
171212  }
171213 
171214  *ppVtab = (sqlite3_vtab*)pTab;
171215  return rc;
171216 }
171217 
171218 /*
171219 ** Disconnect from or destroy a statvfs virtual table.
171220 */
171221 static int statDisconnect(sqlite3_vtab *pVtab){
171222  sqlite3_free(pVtab);
171223  return SQLITE_OK;
171224 }
171225 
171226 /*
171227 ** There is no "best-index". This virtual table always does a linear
171228 ** scan. However, a schema=? constraint should cause this table to
171229 ** operate on a different database schema, so check for it.
171230 **
171231 ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
171232 */
171233 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
171234  int i;
171235 
171236  pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
171237 
171238  /* Look for a valid schema=? constraint. If found, change the idxNum to
171239  ** 1 and request the value of that constraint be sent to xFilter. And
171240  ** lower the cost estimate to encourage the constrained version to be
171241  ** used.
171242  */
171243  for(i=0; i<pIdxInfo->nConstraint; i++){
171244  if( pIdxInfo->aConstraint[i].usable==0 ) continue;
171245  if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
171246  if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
171247  pIdxInfo->idxNum = 1;
171248  pIdxInfo->estimatedCost = 1.0;
171249  pIdxInfo->aConstraintUsage[i].argvIndex = 1;
171250  pIdxInfo->aConstraintUsage[i].omit = 1;
171251  break;
171252  }
171253 
171254 
171255  /* Records are always returned in ascending order of (name, path).
171256  ** If this will satisfy the client, set the orderByConsumed flag so that
171257  ** SQLite does not do an external sort.
171258  */
171259  if( ( pIdxInfo->nOrderBy==1
171260  && pIdxInfo->aOrderBy[0].iColumn==0
171261  && pIdxInfo->aOrderBy[0].desc==0
171262  ) ||
171263  ( pIdxInfo->nOrderBy==2
171264  && pIdxInfo->aOrderBy[0].iColumn==0
171265  && pIdxInfo->aOrderBy[0].desc==0
171266  && pIdxInfo->aOrderBy[1].iColumn==1
171267  && pIdxInfo->aOrderBy[1].desc==0
171268  )
171269  ){
171270  pIdxInfo->orderByConsumed = 1;
171271  }
171272 
171273  return SQLITE_OK;
171274 }
171275 
171276 /*
171277 ** Open a new statvfs cursor.
171278 */
171279 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
171280  StatTable *pTab = (StatTable *)pVTab;
171281  StatCursor *pCsr;
171282 
171283  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
171284  if( pCsr==0 ){
171285  return SQLITE_NOMEM_BKPT;
171286  }else{
171287  memset(pCsr, 0, sizeof(StatCursor));
171288  pCsr->base.pVtab = pVTab;
171289  pCsr->iDb = pTab->iDb;
171290  }
171291 
171292  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
171293  return SQLITE_OK;
171294 }
171295 
171296 static void statClearPage(StatPage *p){
171297  int i;
171298  if( p->aCell ){
171299  for(i=0; i<p->nCell; i++){
171300  sqlite3_free(p->aCell[i].aOvfl);
171301  }
171302  sqlite3_free(p->aCell);
171303  }
171304  sqlite3PagerUnref(p->pPg);
171305  sqlite3_free(p->zPath);
171306  memset(p, 0, sizeof(StatPage));
171307 }
171308 
171309 static void statResetCsr(StatCursor *pCsr){
171310  int i;
171311  sqlite3_reset(pCsr->pStmt);
171312  for(i=0; i<ArraySize(pCsr->aPage); i++){
171313  statClearPage(&pCsr->aPage[i]);
171314  }
171315  pCsr->iPage = 0;
171316  sqlite3_free(pCsr->zPath);
171317  pCsr->zPath = 0;
171318  pCsr->isEof = 0;
171319 }
171320 
171321 /*
171322 ** Close a statvfs cursor.
171323 */
171324 static int statClose(sqlite3_vtab_cursor *pCursor){
171325  StatCursor *pCsr = (StatCursor *)pCursor;
171326  statResetCsr(pCsr);
171327  sqlite3_finalize(pCsr->pStmt);
171328  sqlite3_free(pCsr);
171329  return SQLITE_OK;
171330 }
171331 
171332 static void getLocalPayload(
171333  int nUsable, /* Usable bytes per page */
171334  u8 flags, /* Page flags */
171335  int nTotal, /* Total record (payload) size */
171336  int *pnLocal /* OUT: Bytes stored locally */
171337 ){
171338  int nLocal;
171339  int nMinLocal;
171340  int nMaxLocal;
171341 
171342  if( flags==0x0D ){ /* Table leaf node */
171343  nMinLocal = (nUsable - 12) * 32 / 255 - 23;
171344  nMaxLocal = nUsable - 35;
171345  }else{ /* Index interior and leaf nodes */
171346  nMinLocal = (nUsable - 12) * 32 / 255 - 23;
171347  nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
171348  }
171349 
171350  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
171351  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
171352  *pnLocal = nLocal;
171353 }
171354 
171355 static int statDecodePage(Btree *pBt, StatPage *p){
171356  int nUnused;
171357  int iOff;
171358  int nHdr;
171359  int isLeaf;
171360  int szPage;
171361 
171362  u8 *aData = sqlite3PagerGetData(p->pPg);
171363  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
171364 
171365  p->flags = aHdr[0];
171366  p->nCell = get2byte(&aHdr[3]);
171367  p->nMxPayload = 0;
171368 
171369  isLeaf = (p->flags==0x0A || p->flags==0x0D);
171370  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
171371 
171372  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
171373  nUnused += (int)aHdr[7];
171374  iOff = get2byte(&aHdr[1]);
171375  while( iOff ){
171376  nUnused += get2byte(&aData[iOff+2]);
171377  iOff = get2byte(&aData[iOff]);
171378  }
171379  p->nUnused = nUnused;
171380  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
171381  szPage = sqlite3BtreeGetPageSize(pBt);
171382 
171383  if( p->nCell ){
171384  int i; /* Used to iterate through cells */
171385  int nUsable; /* Usable bytes per page */
171386 
171387  sqlite3BtreeEnter(pBt);
171388  nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
171389  sqlite3BtreeLeave(pBt);
171390  p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
171391  if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
171392  memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
171393 
171394  for(i=0; i<p->nCell; i++){
171395  StatCell *pCell = &p->aCell[i];
171396 
171397  iOff = get2byte(&aData[nHdr+i*2]);
171398  if( !isLeaf ){
171399  pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
171400  iOff += 4;
171401  }
171402  if( p->flags==0x05 ){
171403  /* A table interior node. nPayload==0. */
171404  }else{
171405  u32 nPayload; /* Bytes of payload total (local+overflow) */
171406  int nLocal; /* Bytes of payload stored locally */
171407  iOff += getVarint32(&aData[iOff], nPayload);
171408  if( p->flags==0x0D ){
171409  u64 dummy;
171410  iOff += sqlite3GetVarint(&aData[iOff], &dummy);
171411  }
171412  if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
171413  getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
171414  pCell->nLocal = nLocal;
171415  assert( nLocal>=0 );
171416  assert( nPayload>=(u32)nLocal );
171417  assert( nLocal<=(nUsable-35) );
171418  if( nPayload>(u32)nLocal ){
171419  int j;
171420  int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
171421  pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
171422  pCell->nOvfl = nOvfl;
171423  pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
171424  if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
171425  pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
171426  for(j=1; j<nOvfl; j++){
171427  int rc;
171428  u32 iPrev = pCell->aOvfl[j-1];
171429  DbPage *pPg = 0;
171430  rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
171431  if( rc!=SQLITE_OK ){
171432  assert( pPg==0 );
171433  return rc;
171434  }
171435  pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
171436  sqlite3PagerUnref(pPg);
171437  }
171438  }
171439  }
171440  }
171441  }
171442 
171443  return SQLITE_OK;
171444 }
171445 
171446 /*
171447 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
171448 ** the current value of pCsr->iPageno.
171449 */
171450 static void statSizeAndOffset(StatCursor *pCsr){
171451  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
171452  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
171453  Pager *pPager = sqlite3BtreePager(pBt);
171454  sqlite3_file *fd;
171455  sqlite3_int64 x[2];
171456 
171457  /* The default page size and offset */
171458  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
171459  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
171460 
171461  /* If connected to a ZIPVFS backend, override the page size and
171462  ** offset with actual values obtained from ZIPVFS.
171463  */
171464  fd = sqlite3PagerFile(pPager);
171465  x[0] = pCsr->iPageno;
171466  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
171467  pCsr->iOffset = x[0];
171468  pCsr->szPage = (int)x[1];
171469  }
171470 }
171471 
171472 /*
171473 ** Move a statvfs cursor to the next entry in the file.
171474 */
171475 static int statNext(sqlite3_vtab_cursor *pCursor){
171476  int rc;
171477  int nPayload;
171478  char *z;
171479  StatCursor *pCsr = (StatCursor *)pCursor;
171480  StatTable *pTab = (StatTable *)pCursor->pVtab;
171481  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
171482  Pager *pPager = sqlite3BtreePager(pBt);
171483 
171484  sqlite3_free(pCsr->zPath);
171485  pCsr->zPath = 0;
171486 
171487 statNextRestart:
171488  if( pCsr->aPage[0].pPg==0 ){
171489  rc = sqlite3_step(pCsr->pStmt);
171490  if( rc==SQLITE_ROW ){
171491  int nPage;
171492  u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
171493  sqlite3PagerPagecount(pPager, &nPage);
171494  if( nPage==0 ){
171495  pCsr->isEof = 1;
171496  return sqlite3_reset(pCsr->pStmt);
171497  }
171498  rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
171499  pCsr->aPage[0].iPgno = iRoot;
171500  pCsr->aPage[0].iCell = 0;
171501  pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
171502  pCsr->iPage = 0;
171503  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
171504  }else{
171505  pCsr->isEof = 1;
171506  return sqlite3_reset(pCsr->pStmt);
171507  }
171508  }else{
171509 
171510  /* Page p itself has already been visited. */
171511  StatPage *p = &pCsr->aPage[pCsr->iPage];
171512 
171513  while( p->iCell<p->nCell ){
171514  StatCell *pCell = &p->aCell[p->iCell];
171515  if( pCell->iOvfl<pCell->nOvfl ){
171516  int nUsable;
171517  sqlite3BtreeEnter(pBt);
171518  nUsable = sqlite3BtreeGetPageSize(pBt) -
171520  sqlite3BtreeLeave(pBt);
171521  pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
171522  pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
171523  pCsr->zPagetype = "overflow";
171524  pCsr->nCell = 0;
171525  pCsr->nMxPayload = 0;
171526  pCsr->zPath = z = sqlite3_mprintf(
171527  "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
171528  );
171529  if( pCell->iOvfl<pCell->nOvfl-1 ){
171530  pCsr->nUnused = 0;
171531  pCsr->nPayload = nUsable - 4;
171532  }else{
171533  pCsr->nPayload = pCell->nLastOvfl;
171534  pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
171535  }
171536  pCell->iOvfl++;
171537  statSizeAndOffset(pCsr);
171538  return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
171539  }
171540  if( p->iRightChildPg ) break;
171541  p->iCell++;
171542  }
171543 
171544  if( !p->iRightChildPg || p->iCell>p->nCell ){
171545  statClearPage(p);
171546  if( pCsr->iPage==0 ) return statNext(pCursor);
171547  pCsr->iPage--;
171548  goto statNextRestart; /* Tail recursion */
171549  }
171550  pCsr->iPage++;
171551  assert( p==&pCsr->aPage[pCsr->iPage-1] );
171552 
171553  if( p->iCell==p->nCell ){
171554  p[1].iPgno = p->iRightChildPg;
171555  }else{
171556  p[1].iPgno = p->aCell[p->iCell].iChildPg;
171557  }
171558  rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
171559  p[1].iCell = 0;
171560  p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
171561  p->iCell++;
171562  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
171563  }
171564 
171565 
171566  /* Populate the StatCursor fields with the values to be returned
171567  ** by the xColumn() and xRowid() methods.
171568  */
171569  if( rc==SQLITE_OK ){
171570  int i;
171571  StatPage *p = &pCsr->aPage[pCsr->iPage];
171572  pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
171573  pCsr->iPageno = p->iPgno;
171574 
171575  rc = statDecodePage(pBt, p);
171576  if( rc==SQLITE_OK ){
171577  statSizeAndOffset(pCsr);
171578 
171579  switch( p->flags ){
171580  case 0x05: /* table internal */
171581  case 0x02: /* index internal */
171582  pCsr->zPagetype = "internal";
171583  break;
171584  case 0x0D: /* table leaf */
171585  case 0x0A: /* index leaf */
171586  pCsr->zPagetype = "leaf";
171587  break;
171588  default:
171589  pCsr->zPagetype = "corrupted";
171590  break;
171591  }
171592  pCsr->nCell = p->nCell;
171593  pCsr->nUnused = p->nUnused;
171594  pCsr->nMxPayload = p->nMxPayload;
171595  pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
171596  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
171597  nPayload = 0;
171598  for(i=0; i<p->nCell; i++){
171599  nPayload += p->aCell[i].nLocal;
171600  }
171601  pCsr->nPayload = nPayload;
171602  }
171603  }
171604 
171605  return rc;
171606 }
171607 
171608 static int statEof(sqlite3_vtab_cursor *pCursor){
171609  StatCursor *pCsr = (StatCursor *)pCursor;
171610  return pCsr->isEof;
171611 }
171612 
171613 static int statFilter(
171614  sqlite3_vtab_cursor *pCursor,
171615  int idxNum, const char *idxStr,
171616  int argc, sqlite3_value **argv
171617 ){
171618  StatCursor *pCsr = (StatCursor *)pCursor;
171619  StatTable *pTab = (StatTable*)(pCursor->pVtab);
171620  char *zSql;
171621  int rc = SQLITE_OK;
171622  char *zMaster;
171623 
171624  if( idxNum==1 ){
171625  const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
171626  pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
171627  if( pCsr->iDb<0 ){
171628  sqlite3_free(pCursor->pVtab->zErrMsg);
171629  pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
171630  return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
171631  }
171632  }else{
171633  pCsr->iDb = pTab->iDb;
171634  }
171635  statResetCsr(pCsr);
171636  sqlite3_finalize(pCsr->pStmt);
171637  pCsr->pStmt = 0;
171638  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
171639  zSql = sqlite3_mprintf(
171640  "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
171641  " UNION ALL "
171642  "SELECT name, rootpage, type"
171643  " FROM \"%w\".%s WHERE rootpage!=0"
171644  " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
171645  if( zSql==0 ){
171646  return SQLITE_NOMEM_BKPT;
171647  }else{
171648  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
171649  sqlite3_free(zSql);
171650  }
171651 
171652  if( rc==SQLITE_OK ){
171653  rc = statNext(pCursor);
171654  }
171655  return rc;
171656 }
171657 
171658 static int statColumn(
171659  sqlite3_vtab_cursor *pCursor,
171660  sqlite3_context *ctx,
171661  int i
171662 ){
171663  StatCursor *pCsr = (StatCursor *)pCursor;
171664  switch( i ){
171665  case 0: /* name */
171666  sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
171667  break;
171668  case 1: /* path */
171669  sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
171670  break;
171671  case 2: /* pageno */
171672  sqlite3_result_int64(ctx, pCsr->iPageno);
171673  break;
171674  case 3: /* pagetype */
171675  sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
171676  break;
171677  case 4: /* ncell */
171678  sqlite3_result_int(ctx, pCsr->nCell);
171679  break;
171680  case 5: /* payload */
171681  sqlite3_result_int(ctx, pCsr->nPayload);
171682  break;
171683  case 6: /* unused */
171684  sqlite3_result_int(ctx, pCsr->nUnused);
171685  break;
171686  case 7: /* mx_payload */
171687  sqlite3_result_int(ctx, pCsr->nMxPayload);
171688  break;
171689  case 8: /* pgoffset */
171690  sqlite3_result_int64(ctx, pCsr->iOffset);
171691  break;
171692  case 9: /* pgsize */
171693  sqlite3_result_int(ctx, pCsr->szPage);
171694  break;
171695  default: { /* schema */
171696  sqlite3 *db = sqlite3_context_db_handle(ctx);
171697  int iDb = pCsr->iDb;
171698  sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
171699  break;
171700  }
171701  }
171702  return SQLITE_OK;
171703 }
171704 
171705 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
171706  StatCursor *pCsr = (StatCursor *)pCursor;
171707  *pRowid = pCsr->iPageno;
171708  return SQLITE_OK;
171709 }
171710 
171711 /*
171712 ** Invoke this routine to register the "dbstat" virtual table module
171713 */
171714 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
171715  static sqlite3_module dbstat_module = {
171716  0, /* iVersion */
171717  statConnect, /* xCreate */
171718  statConnect, /* xConnect */
171719  statBestIndex, /* xBestIndex */
171720  statDisconnect, /* xDisconnect */
171721  statDisconnect, /* xDestroy */
171722  statOpen, /* xOpen - open a cursor */
171723  statClose, /* xClose - close a cursor */
171724  statFilter, /* xFilter - configure scan constraints */
171725  statNext, /* xNext - advance a cursor */
171726  statEof, /* xEof - check for end of scan */
171727  statColumn, /* xColumn - read data */
171728  statRowid, /* xRowid - read data */
171729  0, /* xUpdate */
171730  0, /* xBegin */
171731  0, /* xSync */
171732  0, /* xCommit */
171733  0, /* xRollback */
171734  0, /* xFindMethod */
171735  0, /* xRename */
171736  };
171737  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
171738 }
171739 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
171740 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
171741 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
171742 
171743 /************** End of dbstat.c **********************************************/
171744 /************** Begin file sqlite3session.c **********************************/
171745 
171746 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
171747 /* #include "sqlite3session.h" */
171748 /* #include <assert.h> */
171749 /* #include <string.h> */
171750 
171751 #ifndef SQLITE_AMALGAMATION
171752 /* # include "sqliteInt.h" */
171753 /* # include "vdbeInt.h" */
171754 #endif
171755 
171756 typedef struct SessionTable SessionTable;
171757 typedef struct SessionChange SessionChange;
171758 typedef struct SessionBuffer SessionBuffer;
171759 typedef struct SessionInput SessionInput;
171760 
171761 /*
171762 ** Minimum chunk size used by streaming versions of functions.
171763 */
171764 #ifndef SESSIONS_STRM_CHUNK_SIZE
171765 # ifdef SQLITE_TEST
171766 # define SESSIONS_STRM_CHUNK_SIZE 64
171767 # else
171768 # define SESSIONS_STRM_CHUNK_SIZE 1024
171769 # endif
171770 #endif
171771 
171772 typedef struct SessionHook SessionHook;
171773 struct SessionHook {
171774  void *pCtx;
171775  int (*xOld)(void*,int,sqlite3_value**);
171776  int (*xNew)(void*,int,sqlite3_value**);
171777  int (*xCount)(void*);
171778  int (*xDepth)(void*);
171779 };
171780 
171781 /*
171782 ** Session handle structure.
171783 */
171784 struct sqlite3_session {
171785  sqlite3 *db; /* Database handle session is attached to */
171786  char *zDb; /* Name of database session is attached to */
171787  int bEnable; /* True if currently recording */
171788  int bIndirect; /* True if all changes are indirect */
171789  int bAutoAttach; /* True to auto-attach tables */
171790  int rc; /* Non-zero if an error has occurred */
171791  void *pFilterCtx; /* First argument to pass to xTableFilter */
171792  int (*xTableFilter)(void *pCtx, const char *zTab);
171793  sqlite3_session *pNext; /* Next session object on same db. */
171794  SessionTable *pTable; /* List of attached tables */
171795  SessionHook hook; /* APIs to grab new and old data with */
171796 };
171797 
171798 /*
171799 ** Instances of this structure are used to build strings or binary records.
171800 */
171801 struct SessionBuffer {
171802  u8 *aBuf; /* Pointer to changeset buffer */
171803  int nBuf; /* Size of buffer aBuf */
171804  int nAlloc; /* Size of allocation containing aBuf */
171805 };
171806 
171807 /*
171808 ** An object of this type is used internally as an abstraction for
171809 ** input data. Input data may be supplied either as a single large buffer
171810 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
171811 ** sqlite3changeset_start_strm()).
171812 */
171813 struct SessionInput {
171814  int bNoDiscard; /* If true, discard no data */
171815  int iCurrent; /* Offset in aData[] of current change */
171816  int iNext; /* Offset in aData[] of next change */
171817  u8 *aData; /* Pointer to buffer containing changeset */
171818  int nData; /* Number of bytes in aData */
171819 
171820  SessionBuffer buf; /* Current read buffer */
171821  int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
171822  void *pIn; /* First argument to xInput */
171823  int bEof; /* Set to true after xInput finished */
171824 };
171825 
171826 /*
171827 ** Structure for changeset iterators.
171828 */
171829 struct sqlite3_changeset_iter {
171830  SessionInput in; /* Input buffer or stream */
171831  SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
171832  int bPatchset; /* True if this is a patchset */
171833  int rc; /* Iterator error code */
171834  sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
171835  char *zTab; /* Current table */
171836  int nCol; /* Number of columns in zTab */
171837  int op; /* Current operation */
171838  int bIndirect; /* True if current change was indirect */
171839  u8 *abPK; /* Primary key array */
171840  sqlite3_value **apValue; /* old.* and new.* values */
171841 };
171842 
171843 /*
171844 ** Each session object maintains a set of the following structures, one
171845 ** for each table the session object is monitoring. The structures are
171846 ** stored in a linked list starting at sqlite3_session.pTable.
171847 **
171848 ** The keys of the SessionTable.aChange[] hash table are all rows that have
171849 ** been modified in any way since the session object was attached to the
171850 ** table.
171851 **
171852 ** The data associated with each hash-table entry is a structure containing
171853 ** a subset of the initial values that the modified row contained at the
171854 ** start of the session. Or no initial values if the row was inserted.
171855 */
171856 struct SessionTable {
171857  SessionTable *pNext;
171858  char *zName; /* Local name of table */
171859  int nCol; /* Number of columns in table zName */
171860  const char **azCol; /* Column names */
171861  u8 *abPK; /* Array of primary key flags */
171862  int nEntry; /* Total number of entries in hash table */
171863  int nChange; /* Size of apChange[] array */
171864  SessionChange **apChange; /* Hash table buckets */
171865 };
171866 
171867 /*
171868 ** RECORD FORMAT:
171869 **
171870 ** The following record format is similar to (but not compatible with) that
171871 ** used in SQLite database files. This format is used as part of the
171872 ** change-set binary format, and so must be architecture independent.
171873 **
171874 ** Unlike the SQLite database record format, each field is self-contained -
171875 ** there is no separation of header and data. Each field begins with a
171876 ** single byte describing its type, as follows:
171877 **
171878 ** 0x00: Undefined value.
171879 ** 0x01: Integer value.
171880 ** 0x02: Real value.
171881 ** 0x03: Text value.
171882 ** 0x04: Blob value.
171883 ** 0x05: SQL NULL value.
171884 **
171885 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
171886 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
171887 ** only of the single type byte. For other types of values, the type byte
171888 ** is followed by:
171889 **
171890 ** Text values:
171891 ** A varint containing the number of bytes in the value (encoded using
171892 ** UTF-8). Followed by a buffer containing the UTF-8 representation
171893 ** of the text value. There is no nul terminator.
171894 **
171895 ** Blob values:
171896 ** A varint containing the number of bytes in the value, followed by
171897 ** a buffer containing the value itself.
171898 **
171899 ** Integer values:
171900 ** An 8-byte big-endian integer value.
171901 **
171902 ** Real values:
171903 ** An 8-byte big-endian IEEE 754-2008 real value.
171904 **
171905 ** Varint values are encoded in the same way as varints in the SQLite
171906 ** record format.
171907 **
171908 ** CHANGESET FORMAT:
171909 **
171910 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
171911 ** one or more tables. Operations on a single table are grouped together,
171912 ** but may occur in any order (i.e. deletes, updates and inserts are all
171913 ** mixed together).
171914 **
171915 ** Each group of changes begins with a table header:
171916 **
171917 ** 1 byte: Constant 0x54 (capital 'T')
171918 ** Varint: Number of columns in the table.
171919 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
171920 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
171921 **
171922 ** Followed by one or more changes to the table.
171923 **
171924 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
171925 ** 1 byte: The "indirect-change" flag.
171926 ** old.* record: (delete and update only)
171927 ** new.* record: (insert and update only)
171928 **
171929 ** The "old.*" and "new.*" records, if present, are N field records in the
171930 ** format described above under "RECORD FORMAT", where N is the number of
171931 ** columns in the table. The i'th field of each record is associated with
171932 ** the i'th column of the table, counting from left to right in the order
171933 ** in which columns were declared in the CREATE TABLE statement.
171934 **
171935 ** The new.* record that is part of each INSERT change contains the values
171936 ** that make up the new row. Similarly, the old.* record that is part of each
171937 ** DELETE change contains the values that made up the row that was deleted
171938 ** from the database. In the changeset format, the records that are part
171939 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
171940 ** fields.
171941 **
171942 ** Within the old.* record associated with an UPDATE change, all fields
171943 ** associated with table columns that are not PRIMARY KEY columns and are
171944 ** not modified by the UPDATE change are set to "undefined". Other fields
171945 ** are set to the values that made up the row before the UPDATE that the
171946 ** change records took place. Within the new.* record, fields associated
171947 ** with table columns modified by the UPDATE change contain the new
171948 ** values. Fields associated with table columns that are not modified
171949 ** are set to "undefined".
171950 **
171951 ** PATCHSET FORMAT:
171952 **
171953 ** A patchset is also a collection of changes. It is similar to a changeset,
171954 ** but leaves undefined those fields that are not useful if no conflict
171955 ** resolution is required when applying the changeset.
171956 **
171957 ** Each group of changes begins with a table header:
171958 **
171959 ** 1 byte: Constant 0x50 (capital 'P')
171960 ** Varint: Number of columns in the table.
171961 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
171962 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
171963 **
171964 ** Followed by one or more changes to the table.
171965 **
171966 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
171967 ** 1 byte: The "indirect-change" flag.
171968 ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
171969 ** full record for INSERT).
171970 **
171971 ** As in the changeset format, each field of the single record that is part
171972 ** of a patchset change is associated with the correspondingly positioned
171973 ** table column, counting from left to right within the CREATE TABLE
171974 ** statement.
171975 **
171976 ** For a DELETE change, all fields within the record except those associated
171977 ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
171978 ** contain the values identifying the row to delete.
171979 **
171980 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
171981 ** columns and columns that are modified by the UPDATE are set to "undefined".
171982 ** PRIMARY KEY fields contain the values identifying the table row to update,
171983 ** and fields associated with modified columns contain the new column values.
171984 **
171985 ** The records associated with INSERT changes are in the same format as for
171986 ** changesets. It is not possible for a record associated with an INSERT
171987 ** change to contain a field set to "undefined".
171988 */
171989 
171990 /*
171991 ** For each row modified during a session, there exists a single instance of
171992 ** this structure stored in a SessionTable.aChange[] hash table.
171993 */
171994 struct SessionChange {
171995  int op; /* One of UPDATE, DELETE, INSERT */
171996  int bIndirect; /* True if this change is "indirect" */
171997  int nRecord; /* Number of bytes in buffer aRecord[] */
171998  u8 *aRecord; /* Buffer containing old.* record */
171999  SessionChange *pNext; /* For hash-table collisions */
172000 };
172001 
172002 /*
172003 ** Write a varint with value iVal into the buffer at aBuf. Return the
172004 ** number of bytes written.
172005 */
172006 static int sessionVarintPut(u8 *aBuf, int iVal){
172007  return putVarint32(aBuf, iVal);
172008 }
172009 
172010 /*
172011 ** Return the number of bytes required to store value iVal as a varint.
172012 */
172013 static int sessionVarintLen(int iVal){
172014  return sqlite3VarintLen(iVal);
172015 }
172016 
172017 /*
172018 ** Read a varint value from aBuf[] into *piVal. Return the number of
172019 ** bytes read.
172020 */
172021 static int sessionVarintGet(u8 *aBuf, int *piVal){
172022  return getVarint32(aBuf, *piVal);
172023 }
172024 
172025 /* Load an unaligned and unsigned 32-bit integer */
172026 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
172027 
172028 /*
172029 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
172030 ** the value read.
172031 */
172032 static sqlite3_int64 sessionGetI64(u8 *aRec){
172033  u64 x = SESSION_UINT32(aRec);
172034  u32 y = SESSION_UINT32(aRec+4);
172035  x = (x<<32) + y;
172036  return (sqlite3_int64)x;
172037 }
172038 
172039 /*
172040 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
172041 */
172042 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
172043  aBuf[0] = (i>>56) & 0xFF;
172044  aBuf[1] = (i>>48) & 0xFF;
172045  aBuf[2] = (i>>40) & 0xFF;
172046  aBuf[3] = (i>>32) & 0xFF;
172047  aBuf[4] = (i>>24) & 0xFF;
172048  aBuf[5] = (i>>16) & 0xFF;
172049  aBuf[6] = (i>> 8) & 0xFF;
172050  aBuf[7] = (i>> 0) & 0xFF;
172051 }
172052 
172053 /*
172054 ** This function is used to serialize the contents of value pValue (see
172055 ** comment titled "RECORD FORMAT" above).
172056 **
172057 ** If it is non-NULL, the serialized form of the value is written to
172058 ** buffer aBuf. *pnWrite is set to the number of bytes written before
172059 ** returning. Or, if aBuf is NULL, the only thing this function does is
172060 ** set *pnWrite.
172061 **
172062 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
172063 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
172064 ** SQLITE_NOMEM is returned.
172065 */
172066 static int sessionSerializeValue(
172067  u8 *aBuf, /* If non-NULL, write serialized value here */
172068  sqlite3_value *pValue, /* Value to serialize */
172069  int *pnWrite /* IN/OUT: Increment by bytes written */
172070 ){
172071  int nByte; /* Size of serialized value in bytes */
172072 
172073  if( pValue ){
172074  int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
172075 
172076  eType = sqlite3_value_type(pValue);
172077  if( aBuf ) aBuf[0] = eType;
172078 
172079  switch( eType ){
172080  case SQLITE_NULL:
172081  nByte = 1;
172082  break;
172083 
172084  case SQLITE_INTEGER:
172085  case SQLITE_FLOAT:
172086  if( aBuf ){
172087  /* TODO: SQLite does something special to deal with mixed-endian
172088  ** floating point values (e.g. ARM7). This code probably should
172089  ** too. */
172090  u64 i;
172091  if( eType==SQLITE_INTEGER ){
172092  i = (u64)sqlite3_value_int64(pValue);
172093  }else{
172094  double r;
172095  assert( sizeof(double)==8 && sizeof(u64)==8 );
172096  r = sqlite3_value_double(pValue);
172097  memcpy(&i, &r, 8);
172098  }
172099  sessionPutI64(&aBuf[1], i);
172100  }
172101  nByte = 9;
172102  break;
172103 
172104  default: {
172105  u8 *z;
172106  int n;
172107  int nVarint;
172108 
172109  assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
172110  if( eType==SQLITE_TEXT ){
172111  z = (u8 *)sqlite3_value_text(pValue);
172112  }else{
172113  z = (u8 *)sqlite3_value_blob(pValue);
172114  }
172115  n = sqlite3_value_bytes(pValue);
172116  if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
172117  nVarint = sessionVarintLen(n);
172118 
172119  if( aBuf ){
172120  sessionVarintPut(&aBuf[1], n);
172121  memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ?
172122  sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
172123  );
172124  }
172125 
172126  nByte = 1 + nVarint + n;
172127  break;
172128  }
172129  }
172130  }else{
172131  nByte = 1;
172132  if( aBuf ) aBuf[0] = '\0';
172133  }
172134 
172135  if( pnWrite ) *pnWrite += nByte;
172136  return SQLITE_OK;
172137 }
172138 
172139 
172140 /*
172141 ** This macro is used to calculate hash key values for data structures. In
172142 ** order to use this macro, the entire data structure must be represented
172143 ** as a series of unsigned integers. In order to calculate a hash-key value
172144 ** for a data structure represented as three such integers, the macro may
172145 ** then be used as follows:
172146 **
172147 ** int hash_key_value;
172148 ** hash_key_value = HASH_APPEND(0, <value 1>);
172149 ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
172150 ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
172151 **
172152 ** In practice, the data structures this macro is used for are the primary
172153 ** key values of modified rows.
172154 */
172155 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
172156 
172157 /*
172158 ** Append the hash of the 64-bit integer passed as the second argument to the
172159 ** hash-key value passed as the first. Return the new hash-key value.
172160 */
172161 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
172162  h = HASH_APPEND(h, i & 0xFFFFFFFF);
172163  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
172164 }
172165 
172166 /*
172167 ** Append the hash of the blob passed via the second and third arguments to
172168 ** the hash-key value passed as the first. Return the new hash-key value.
172169 */
172170 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
172171  int i;
172172  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
172173  return h;
172174 }
172175 
172176 /*
172177 ** Append the hash of the data type passed as the second argument to the
172178 ** hash-key value passed as the first. Return the new hash-key value.
172179 */
172180 static unsigned int sessionHashAppendType(unsigned int h, int eType){
172181  return HASH_APPEND(h, eType);
172182 }
172183 
172184 /*
172185 ** This function may only be called from within a pre-update callback.
172186 ** It calculates a hash based on the primary key values of the old.* or
172187 ** new.* row currently available and, assuming no error occurs, writes it to
172188 ** *piHash before returning. If the primary key contains one or more NULL
172189 ** values, *pbNullPK is set to true before returning.
172190 **
172191 ** If an error occurs, an SQLite error code is returned and the final values
172192 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
172193 ** and the output variables are set as described above.
172194 */
172195 static int sessionPreupdateHash(
172196  sqlite3_session *pSession, /* Session object that owns pTab */
172197  SessionTable *pTab, /* Session table handle */
172198  int bNew, /* True to hash the new.* PK */
172199  int *piHash, /* OUT: Hash value */
172200  int *pbNullPK /* OUT: True if there are NULL values in PK */
172201 ){
172202  unsigned int h = 0; /* Hash value to return */
172203  int i; /* Used to iterate through columns */
172204 
172205  assert( *pbNullPK==0 );
172206  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
172207  for(i=0; i<pTab->nCol; i++){
172208  if( pTab->abPK[i] ){
172209  int rc;
172210  int eType;
172211  sqlite3_value *pVal;
172212 
172213  if( bNew ){
172214  rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
172215  }else{
172216  rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
172217  }
172218  if( rc!=SQLITE_OK ) return rc;
172219 
172220  eType = sqlite3_value_type(pVal);
172221  h = sessionHashAppendType(h, eType);
172222  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172223  i64 iVal;
172224  if( eType==SQLITE_INTEGER ){
172225  iVal = sqlite3_value_int64(pVal);
172226  }else{
172227  double rVal = sqlite3_value_double(pVal);
172228  assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
172229  memcpy(&iVal, &rVal, 8);
172230  }
172231  h = sessionHashAppendI64(h, iVal);
172232  }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172233  const u8 *z;
172234  int n;
172235  if( eType==SQLITE_TEXT ){
172236  z = (const u8 *)sqlite3_value_text(pVal);
172237  }else{
172238  z = (const u8 *)sqlite3_value_blob(pVal);
172239  }
172240  n = sqlite3_value_bytes(pVal);
172241  if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
172242  h = sessionHashAppendBlob(h, n, z);
172243  }else{
172244  assert( eType==SQLITE_NULL );
172245  *pbNullPK = 1;
172246  }
172247  }
172248  }
172249 
172250  *piHash = (h % pTab->nChange);
172251  return SQLITE_OK;
172252 }
172253 
172254 /*
172255 ** The buffer that the argument points to contains a serialized SQL value.
172256 ** Return the number of bytes of space occupied by the value (including
172257 ** the type byte).
172258 */
172259 static int sessionSerialLen(u8 *a){
172260  int e = *a;
172261  int n;
172262  if( e==0 ) return 1;
172263  if( e==SQLITE_NULL ) return 1;
172264  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
172265  return sessionVarintGet(&a[1], &n) + 1 + n;
172266 }
172267 
172268 /*
172269 ** Based on the primary key values stored in change aRecord, calculate a
172270 ** hash key. Assume the has table has nBucket buckets. The hash keys
172271 ** calculated by this function are compatible with those calculated by
172272 ** sessionPreupdateHash().
172273 **
172274 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
172275 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
172276 */
172277 static unsigned int sessionChangeHash(
172278  SessionTable *pTab, /* Table handle */
172279  int bPkOnly, /* Record consists of PK fields only */
172280  u8 *aRecord, /* Change record */
172281  int nBucket /* Assume this many buckets in hash table */
172282 ){
172283  unsigned int h = 0; /* Value to return */
172284  int i; /* Used to iterate through columns */
172285  u8 *a = aRecord; /* Used to iterate through change record */
172286 
172287  for(i=0; i<pTab->nCol; i++){
172288  int eType = *a;
172289  int isPK = pTab->abPK[i];
172290  if( bPkOnly && isPK==0 ) continue;
172291 
172292  /* It is not possible for eType to be SQLITE_NULL here. The session
172293  ** module does not record changes for rows with NULL values stored in
172294  ** primary key columns. */
172295  assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
172296  || eType==SQLITE_TEXT || eType==SQLITE_BLOB
172297  || eType==SQLITE_NULL || eType==0
172298  );
172299  assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
172300 
172301  if( isPK ){
172302  a++;
172303  h = sessionHashAppendType(h, eType);
172304  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172305  h = sessionHashAppendI64(h, sessionGetI64(a));
172306  a += 8;
172307  }else{
172308  int n;
172309  a += sessionVarintGet(a, &n);
172310  h = sessionHashAppendBlob(h, n, a);
172311  a += n;
172312  }
172313  }else{
172314  a += sessionSerialLen(a);
172315  }
172316  }
172317  return (h % nBucket);
172318 }
172319 
172320 /*
172321 ** Arguments aLeft and aRight are pointers to change records for table pTab.
172322 ** This function returns true if the two records apply to the same row (i.e.
172323 ** have the same values stored in the primary key columns), or false
172324 ** otherwise.
172325 */
172326 static int sessionChangeEqual(
172327  SessionTable *pTab, /* Table used for PK definition */
172328  int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
172329  u8 *aLeft, /* Change record */
172330  int bRightPkOnly, /* True if aRight[] contains PK fields only */
172331  u8 *aRight /* Change record */
172332 ){
172333  u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
172334  u8 *a2 = aRight; /* Cursor to iterate through aRight */
172335  int iCol; /* Used to iterate through table columns */
172336 
172337  for(iCol=0; iCol<pTab->nCol; iCol++){
172338  if( pTab->abPK[iCol] ){
172339  int n1 = sessionSerialLen(a1);
172340  int n2 = sessionSerialLen(a2);
172341 
172342  if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
172343  return 0;
172344  }
172345  a1 += n1;
172346  a2 += n2;
172347  }else{
172348  if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
172349  if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
172350  }
172351  }
172352 
172353  return 1;
172354 }
172355 
172356 /*
172357 ** Arguments aLeft and aRight both point to buffers containing change
172358 ** records with nCol columns. This function "merges" the two records into
172359 ** a single records which is written to the buffer at *paOut. *paOut is
172360 ** then set to point to one byte after the last byte written before
172361 ** returning.
172362 **
172363 ** The merging of records is done as follows: For each column, if the
172364 ** aRight record contains a value for the column, copy the value from
172365 ** their. Otherwise, if aLeft contains a value, copy it. If neither
172366 ** record contains a value for a given column, then neither does the
172367 ** output record.
172368 */
172369 static void sessionMergeRecord(
172370  u8 **paOut,
172371  int nCol,
172372  u8 *aLeft,
172373  u8 *aRight
172374 ){
172375  u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
172376  u8 *a2 = aRight; /* Cursor used to iterate through aRight */
172377  u8 *aOut = *paOut; /* Output cursor */
172378  int iCol; /* Used to iterate from 0 to nCol */
172379 
172380  for(iCol=0; iCol<nCol; iCol++){
172381  int n1 = sessionSerialLen(a1);
172382  int n2 = sessionSerialLen(a2);
172383  if( *a2 ){
172384  memcpy(aOut, a2, n2);
172385  aOut += n2;
172386  }else{
172387  memcpy(aOut, a1, n1);
172388  aOut += n1;
172389  }
172390  a1 += n1;
172391  a2 += n2;
172392  }
172393 
172394  *paOut = aOut;
172395 }
172396 
172397 /*
172398 ** This is a helper function used by sessionMergeUpdate().
172399 **
172400 ** When this function is called, both *paOne and *paTwo point to a value
172401 ** within a change record. Before it returns, both have been advanced so
172402 ** as to point to the next value in the record.
172403 **
172404 ** If, when this function is called, *paTwo points to a valid value (i.e.
172405 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
172406 ** pointer is returned and *pnVal is set to the number of bytes in the
172407 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
172408 ** set to the number of bytes in the value at *paOne. If *paOne points
172409 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
172410 **
172411 ** if( *paTwo is valid ) return *paTwo;
172412 ** return *paOne;
172413 **
172414 */
172415 static u8 *sessionMergeValue(
172416  u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
172417  u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
172418  int *pnVal /* OUT: Bytes in returned value */
172419 ){
172420  u8 *a1 = *paOne;
172421  u8 *a2 = *paTwo;
172422  u8 *pRet = 0;
172423  int n1;
172424 
172425  assert( a1 );
172426  if( a2 ){
172427  int n2 = sessionSerialLen(a2);
172428  if( *a2 ){
172429  *pnVal = n2;
172430  pRet = a2;
172431  }
172432  *paTwo = &a2[n2];
172433  }
172434 
172435  n1 = sessionSerialLen(a1);
172436  if( pRet==0 ){
172437  *pnVal = n1;
172438  pRet = a1;
172439  }
172440  *paOne = &a1[n1];
172441 
172442  return pRet;
172443 }
172444 
172445 /*
172446 ** This function is used by changeset_concat() to merge two UPDATE changes
172447 ** on the same row.
172448 */
172449 static int sessionMergeUpdate(
172450  u8 **paOut, /* IN/OUT: Pointer to output buffer */
172451  SessionTable *pTab, /* Table change pertains to */
172452  int bPatchset, /* True if records are patchset records */
172453  u8 *aOldRecord1, /* old.* record for first change */
172454  u8 *aOldRecord2, /* old.* record for second change */
172455  u8 *aNewRecord1, /* new.* record for first change */
172456  u8 *aNewRecord2 /* new.* record for second change */
172457 ){
172458  u8 *aOld1 = aOldRecord1;
172459  u8 *aOld2 = aOldRecord2;
172460  u8 *aNew1 = aNewRecord1;
172461  u8 *aNew2 = aNewRecord2;
172462 
172463  u8 *aOut = *paOut;
172464  int i;
172465 
172466  if( bPatchset==0 ){
172467  int bRequired = 0;
172468 
172469  assert( aOldRecord1 && aNewRecord1 );
172470 
172471  /* Write the old.* vector first. */
172472  for(i=0; i<pTab->nCol; i++){
172473  int nOld;
172474  u8 *aOld;
172475  int nNew;
172476  u8 *aNew;
172477 
172478  aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
172479  aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
172480  if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
172481  if( pTab->abPK[i]==0 ) bRequired = 1;
172482  memcpy(aOut, aOld, nOld);
172483  aOut += nOld;
172484  }else{
172485  *(aOut++) = '\0';
172486  }
172487  }
172488 
172489  if( !bRequired ) return 0;
172490  }
172491 
172492  /* Write the new.* vector */
172493  aOld1 = aOldRecord1;
172494  aOld2 = aOldRecord2;
172495  aNew1 = aNewRecord1;
172496  aNew2 = aNewRecord2;
172497  for(i=0; i<pTab->nCol; i++){
172498  int nOld;
172499  u8 *aOld;
172500  int nNew;
172501  u8 *aNew;
172502 
172503  aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
172504  aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
172505  if( bPatchset==0
172506  && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
172507  ){
172508  *(aOut++) = '\0';
172509  }else{
172510  memcpy(aOut, aNew, nNew);
172511  aOut += nNew;
172512  }
172513  }
172514 
172515  *paOut = aOut;
172516  return 1;
172517 }
172518 
172519 /*
172520 ** This function is only called from within a pre-update-hook callback.
172521 ** It determines if the current pre-update-hook change affects the same row
172522 ** as the change stored in argument pChange. If so, it returns true. Otherwise
172523 ** if the pre-update-hook does not affect the same row as pChange, it returns
172524 ** false.
172525 */
172526 static int sessionPreupdateEqual(
172527  sqlite3_session *pSession, /* Session object that owns SessionTable */
172528  SessionTable *pTab, /* Table associated with change */
172529  SessionChange *pChange, /* Change to compare to */
172530  int op /* Current pre-update operation */
172531 ){
172532  int iCol; /* Used to iterate through columns */
172533  u8 *a = pChange->aRecord; /* Cursor used to scan change record */
172534 
172535  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
172536  for(iCol=0; iCol<pTab->nCol; iCol++){
172537  if( !pTab->abPK[iCol] ){
172538  a += sessionSerialLen(a);
172539  }else{
172540  sqlite3_value *pVal; /* Value returned by preupdate_new/old */
172541  int rc; /* Error code from preupdate_new/old */
172542  int eType = *a++; /* Type of value from change record */
172543 
172544  /* The following calls to preupdate_new() and preupdate_old() can not
172545  ** fail. This is because they cache their return values, and by the
172546  ** time control flows to here they have already been called once from
172547  ** within sessionPreupdateHash(). The first two asserts below verify
172548  ** this (that the method has already been called). */
172549  if( op==SQLITE_INSERT ){
172550  /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
172551  rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
172552  }else{
172553  /* assert( db->pPreUpdate->pUnpacked ); */
172554  rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
172555  }
172556  assert( rc==SQLITE_OK );
172557  if( sqlite3_value_type(pVal)!=eType ) return 0;
172558 
172559  /* A SessionChange object never has a NULL value in a PK column */
172560  assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
172561  || eType==SQLITE_BLOB || eType==SQLITE_TEXT
172562  );
172563 
172564  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172565  i64 iVal = sessionGetI64(a);
172566  a += 8;
172567  if( eType==SQLITE_INTEGER ){
172568  if( sqlite3_value_int64(pVal)!=iVal ) return 0;
172569  }else{
172570  double rVal;
172571  assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
172572  memcpy(&rVal, &iVal, 8);
172573  if( sqlite3_value_double(pVal)!=rVal ) return 0;
172574  }
172575  }else{
172576  int n;
172577  const u8 *z;
172578  a += sessionVarintGet(a, &n);
172579  if( sqlite3_value_bytes(pVal)!=n ) return 0;
172580  if( eType==SQLITE_TEXT ){
172581  z = sqlite3_value_text(pVal);
172582  }else{
172583  z = sqlite3_value_blob(pVal);
172584  }
172585  if( memcmp(a, z, n) ) return 0;
172586  a += n;
172587  break;
172588  }
172589  }
172590  }
172591 
172592  return 1;
172593 }
172594 
172595 /*
172596 ** If required, grow the hash table used to store changes on table pTab
172597 ** (part of the session pSession). If a fatal OOM error occurs, set the
172598 ** session object to failed and return SQLITE_ERROR. Otherwise, return
172599 ** SQLITE_OK.
172600 **
172601 ** It is possible that a non-fatal OOM error occurs in this function. In
172602 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
172603 ** Growing the hash table in this case is a performance optimization only,
172604 ** it is not required for correct operation.
172605 */
172606 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
172607  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
172608  int i;
172609  SessionChange **apNew;
172610  int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
172611 
172612  apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
172613  if( apNew==0 ){
172614  if( pTab->nChange==0 ){
172615  return SQLITE_ERROR;
172616  }
172617  return SQLITE_OK;
172618  }
172619  memset(apNew, 0, sizeof(SessionChange *) * nNew);
172620 
172621  for(i=0; i<pTab->nChange; i++){
172622  SessionChange *p;
172623  SessionChange *pNext;
172624  for(p=pTab->apChange[i]; p; p=pNext){
172625  int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
172626  int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
172627  pNext = p->pNext;
172628  p->pNext = apNew[iHash];
172629  apNew[iHash] = p;
172630  }
172631  }
172632 
172633  sqlite3_free(pTab->apChange);
172634  pTab->nChange = nNew;
172635  pTab->apChange = apNew;
172636  }
172637 
172638  return SQLITE_OK;
172639 }
172640 
172641 /*
172642 ** This function queries the database for the names of the columns of table
172643 ** zThis, in schema zDb. It is expected that the table has nCol columns. If
172644 ** not, SQLITE_SCHEMA is returned and none of the output variables are
172645 ** populated.
172646 **
172647 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
172648 ** of columns in the database table and variable *pzTab is set to point to a
172649 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
172650 ** point to an array of pointers to column names. And *pabPK (again, if not
172651 ** NULL) is set to point to an array of booleans - true if the corresponding
172652 ** column is part of the primary key.
172653 **
172654 ** For example, if the table is declared as:
172655 **
172656 ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
172657 **
172658 ** Then the four output variables are populated as follows:
172659 **
172660 ** *pnCol = 4
172661 ** *pzTab = "tbl1"
172662 ** *pazCol = {"w", "x", "y", "z"}
172663 ** *pabPK = {1, 0, 0, 1}
172664 **
172665 ** All returned buffers are part of the same single allocation, which must
172666 ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
172667 ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
172668 ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
172669 */
172670 static int sessionTableInfo(
172671  sqlite3 *db, /* Database connection */
172672  const char *zDb, /* Name of attached database (e.g. "main") */
172673  const char *zThis, /* Table name */
172674  int *pnCol, /* OUT: number of columns */
172675  const char **pzTab, /* OUT: Copy of zThis */
172676  const char ***pazCol, /* OUT: Array of column names for table */
172677  u8 **pabPK /* OUT: Array of booleans - true for PK col */
172678 ){
172679  char *zPragma;
172680  sqlite3_stmt *pStmt;
172681  int rc;
172682  int nByte;
172683  int nDbCol = 0;
172684  int nThis;
172685  int i;
172686  u8 *pAlloc = 0;
172687  char **azCol = 0;
172688  u8 *abPK = 0;
172689 
172690  assert( pazCol && pabPK );
172691 
172692  nThis = sqlite3Strlen30(zThis);
172693  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
172694  if( !zPragma ) return SQLITE_NOMEM;
172695 
172696  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
172697  sqlite3_free(zPragma);
172698  if( rc!=SQLITE_OK ) return rc;
172699 
172700  nByte = nThis + 1;
172701  while( SQLITE_ROW==sqlite3_step(pStmt) ){
172702  nByte += sqlite3_column_bytes(pStmt, 1);
172703  nDbCol++;
172704  }
172705  rc = sqlite3_reset(pStmt);
172706 
172707  if( rc==SQLITE_OK ){
172708  nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
172709  pAlloc = sqlite3_malloc(nByte);
172710  if( pAlloc==0 ){
172711  rc = SQLITE_NOMEM;
172712  }
172713  }
172714  if( rc==SQLITE_OK ){
172715  azCol = (char **)pAlloc;
172716  pAlloc = (u8 *)&azCol[nDbCol];
172717  abPK = (u8 *)pAlloc;
172718  pAlloc = &abPK[nDbCol];
172719  if( pzTab ){
172720  memcpy(pAlloc, zThis, nThis+1);
172721  *pzTab = (char *)pAlloc;
172722  pAlloc += nThis+1;
172723  }
172724 
172725  i = 0;
172726  while( SQLITE_ROW==sqlite3_step(pStmt) ){
172727  int nName = sqlite3_column_bytes(pStmt, 1);
172728  const unsigned char *zName = sqlite3_column_text(pStmt, 1);
172729  if( zName==0 ) break;
172730  memcpy(pAlloc, zName, nName+1);
172731  azCol[i] = (char *)pAlloc;
172732  pAlloc += nName+1;
172733  abPK[i] = sqlite3_column_int(pStmt, 5);
172734  i++;
172735  }
172736  rc = sqlite3_reset(pStmt);
172737 
172738  }
172739 
172740  /* If successful, populate the output variables. Otherwise, zero them and
172741  ** free any allocation made. An error code will be returned in this case.
172742  */
172743  if( rc==SQLITE_OK ){
172744  *pazCol = (const char **)azCol;
172745  *pabPK = abPK;
172746  *pnCol = nDbCol;
172747  }else{
172748  *pazCol = 0;
172749  *pabPK = 0;
172750  *pnCol = 0;
172751  if( pzTab ) *pzTab = 0;
172752  sqlite3_free(azCol);
172753  }
172754  sqlite3_finalize(pStmt);
172755  return rc;
172756 }
172757 
172758 /*
172759 ** This function is only called from within a pre-update handler for a
172760 ** write to table pTab, part of session pSession. If this is the first
172761 ** write to this table, initalize the SessionTable.nCol, azCol[] and
172762 ** abPK[] arrays accordingly.
172763 **
172764 ** If an error occurs, an error code is stored in sqlite3_session.rc and
172765 ** non-zero returned. Or, if no error occurs but the table has no primary
172766 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
172767 ** indicate that updates on this table should be ignored. SessionTable.abPK
172768 ** is set to NULL in this case.
172769 */
172770 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
172771  if( pTab->nCol==0 ){
172772  u8 *abPK;
172773  assert( pTab->azCol==0 || pTab->abPK==0 );
172774  pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
172775  pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
172776  );
172777  if( pSession->rc==SQLITE_OK ){
172778  int i;
172779  for(i=0; i<pTab->nCol; i++){
172780  if( abPK[i] ){
172781  pTab->abPK = abPK;
172782  break;
172783  }
172784  }
172785  }
172786  }
172787  return (pSession->rc || pTab->abPK==0);
172788 }
172789 
172790 /*
172791 ** This function is only called from with a pre-update-hook reporting a
172792 ** change on table pTab (attached to session pSession). The type of change
172793 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
172794 **
172795 ** Unless one is already present or an error occurs, an entry is added
172796 ** to the changed-rows hash table associated with table pTab.
172797 */
172798 static void sessionPreupdateOneChange(
172799  int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
172800  sqlite3_session *pSession, /* Session object pTab is attached to */
172801  SessionTable *pTab /* Table that change applies to */
172802 ){
172803  int iHash;
172804  int bNull = 0;
172805  int rc = SQLITE_OK;
172806 
172807  if( pSession->rc ) return;
172808 
172809  /* Load table details if required */
172810  if( sessionInitTable(pSession, pTab) ) return;
172811 
172812  /* Check the number of columns in this xPreUpdate call matches the
172813  ** number of columns in the table. */
172814  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
172815  pSession->rc = SQLITE_SCHEMA;
172816  return;
172817  }
172818 
172819  /* Grow the hash table if required */
172820  if( sessionGrowHash(0, pTab) ){
172821  pSession->rc = SQLITE_NOMEM;
172822  return;
172823  }
172824 
172825  /* Calculate the hash-key for this change. If the primary key of the row
172826  ** includes a NULL value, exit early. Such changes are ignored by the
172827  ** session module. */
172828  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
172829  if( rc!=SQLITE_OK ) goto error_out;
172830 
172831  if( bNull==0 ){
172832  /* Search the hash table for an existing record for this row. */
172833  SessionChange *pC;
172834  for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
172835  if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
172836  }
172837 
172838  if( pC==0 ){
172839  /* Create a new change object containing all the old values (if
172840  ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
172841  ** values (if this is an INSERT). */
172842  SessionChange *pChange; /* New change object */
172843  int nByte; /* Number of bytes to allocate */
172844  int i; /* Used to iterate through columns */
172845 
172846  assert( rc==SQLITE_OK );
172847  pTab->nEntry++;
172848 
172849  /* Figure out how large an allocation is required */
172850  nByte = sizeof(SessionChange);
172851  for(i=0; i<pTab->nCol; i++){
172852  sqlite3_value *p = 0;
172853  if( op!=SQLITE_INSERT ){
172854  TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
172855  assert( trc==SQLITE_OK );
172856  }else if( pTab->abPK[i] ){
172857  TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
172858  assert( trc==SQLITE_OK );
172859  }
172860 
172861  /* This may fail if SQLite value p contains a utf-16 string that must
172862  ** be converted to utf-8 and an OOM error occurs while doing so. */
172863  rc = sessionSerializeValue(0, p, &nByte);
172864  if( rc!=SQLITE_OK ) goto error_out;
172865  }
172866 
172867  /* Allocate the change object */
172868  pChange = (SessionChange *)sqlite3_malloc(nByte);
172869  if( !pChange ){
172870  rc = SQLITE_NOMEM;
172871  goto error_out;
172872  }else{
172873  memset(pChange, 0, sizeof(SessionChange));
172874  pChange->aRecord = (u8 *)&pChange[1];
172875  }
172876 
172877  /* Populate the change object. None of the preupdate_old(),
172878  ** preupdate_new() or SerializeValue() calls below may fail as all
172879  ** required values and encodings have already been cached in memory.
172880  ** It is not possible for an OOM to occur in this block. */
172881  nByte = 0;
172882  for(i=0; i<pTab->nCol; i++){
172883  sqlite3_value *p = 0;
172884  if( op!=SQLITE_INSERT ){
172885  pSession->hook.xOld(pSession->hook.pCtx, i, &p);
172886  }else if( pTab->abPK[i] ){
172887  pSession->hook.xNew(pSession->hook.pCtx, i, &p);
172888  }
172889  sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
172890  }
172891 
172892  /* Add the change to the hash-table */
172893  if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
172894  pChange->bIndirect = 1;
172895  }
172896  pChange->nRecord = nByte;
172897  pChange->op = op;
172898  pChange->pNext = pTab->apChange[iHash];
172899  pTab->apChange[iHash] = pChange;
172900 
172901  }else if( pC->bIndirect ){
172902  /* If the existing change is considered "indirect", but this current
172903  ** change is "direct", mark the change object as direct. */
172904  if( pSession->hook.xDepth(pSession->hook.pCtx)==0
172905  && pSession->bIndirect==0
172906  ){
172907  pC->bIndirect = 0;
172908  }
172909  }
172910  }
172911 
172912  /* If an error has occurred, mark the session object as failed. */
172913  error_out:
172914  if( rc!=SQLITE_OK ){
172915  pSession->rc = rc;
172916  }
172917 }
172918 
172919 static int sessionFindTable(
172920  sqlite3_session *pSession,
172921  const char *zName,
172922  SessionTable **ppTab
172923 ){
172924  int rc = SQLITE_OK;
172925  int nName = sqlite3Strlen30(zName);
172926  SessionTable *pRet;
172927 
172928  /* Search for an existing table */
172929  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
172930  if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
172931  }
172932 
172933  if( pRet==0 && pSession->bAutoAttach ){
172934  /* If there is a table-filter configured, invoke it. If it returns 0,
172935  ** do not automatically add the new table. */
172936  if( pSession->xTableFilter==0
172937  || pSession->xTableFilter(pSession->pFilterCtx, zName)
172938  ){
172939  rc = sqlite3session_attach(pSession, zName);
172940  if( rc==SQLITE_OK ){
172941  for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
172942  assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
172943  }
172944  }
172945  }
172946 
172947  assert( rc==SQLITE_OK || pRet==0 );
172948  *ppTab = pRet;
172949  return rc;
172950 }
172951 
172952 /*
172953 ** The 'pre-update' hook registered by this module with SQLite databases.
172954 */
172955 static void xPreUpdate(
172956  void *pCtx, /* Copy of third arg to preupdate_hook() */
172957  sqlite3 *db, /* Database handle */
172958  int op, /* SQLITE_UPDATE, DELETE or INSERT */
172959  char const *zDb, /* Database name */
172960  char const *zName, /* Table name */
172961  sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
172962  sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
172963 ){
172964  sqlite3_session *pSession;
172965  int nDb = sqlite3Strlen30(zDb);
172966 
172967  assert( sqlite3_mutex_held(db->mutex) );
172968 
172969  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
172970  SessionTable *pTab;
172971 
172972  /* If this session is attached to a different database ("main", "temp"
172973  ** etc.), or if it is not currently enabled, there is nothing to do. Skip
172974  ** to the next session object attached to this database. */
172975  if( pSession->bEnable==0 ) continue;
172976  if( pSession->rc ) continue;
172977  if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
172978 
172979  pSession->rc = sessionFindTable(pSession, zName, &pTab);
172980  if( pTab ){
172981  assert( pSession->rc==SQLITE_OK );
172982  sessionPreupdateOneChange(op, pSession, pTab);
172983  if( op==SQLITE_UPDATE ){
172984  sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
172985  }
172986  }
172987  }
172988 }
172989 
172990 /*
172991 ** The pre-update hook implementations.
172992 */
172993 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
172994  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
172995 }
172996 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
172997  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
172998 }
172999 static int sessionPreupdateCount(void *pCtx){
173000  return sqlite3_preupdate_count((sqlite3*)pCtx);
173001 }
173002 static int sessionPreupdateDepth(void *pCtx){
173003  return sqlite3_preupdate_depth((sqlite3*)pCtx);
173004 }
173005 
173006 /*
173007 ** Install the pre-update hooks on the session object passed as the only
173008 ** argument.
173009 */
173010 static void sessionPreupdateHooks(
173011  sqlite3_session *pSession
173012 ){
173013  pSession->hook.pCtx = (void*)pSession->db;
173014  pSession->hook.xOld = sessionPreupdateOld;
173015  pSession->hook.xNew = sessionPreupdateNew;
173016  pSession->hook.xCount = sessionPreupdateCount;
173017  pSession->hook.xDepth = sessionPreupdateDepth;
173018 }
173019 
173020 typedef struct SessionDiffCtx SessionDiffCtx;
173021 struct SessionDiffCtx {
173022  sqlite3_stmt *pStmt;
173023  int nOldOff;
173024 };
173025 
173026 /*
173027 ** The diff hook implementations.
173028 */
173029 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
173030  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
173031  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
173032  return SQLITE_OK;
173033 }
173034 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
173035  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
173036  *ppVal = sqlite3_column_value(p->pStmt, iVal);
173037  return SQLITE_OK;
173038 }
173039 static int sessionDiffCount(void *pCtx){
173040  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
173041  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
173042 }
173043 static int sessionDiffDepth(void *pCtx){
173044  return 0;
173045 }
173046 
173047 /*
173048 ** Install the diff hooks on the session object passed as the only
173049 ** argument.
173050 */
173051 static void sessionDiffHooks(
173052  sqlite3_session *pSession,
173053  SessionDiffCtx *pDiffCtx
173054 ){
173055  pSession->hook.pCtx = (void*)pDiffCtx;
173056  pSession->hook.xOld = sessionDiffOld;
173057  pSession->hook.xNew = sessionDiffNew;
173058  pSession->hook.xCount = sessionDiffCount;
173059  pSession->hook.xDepth = sessionDiffDepth;
173060 }
173061 
173062 static char *sessionExprComparePK(
173063  int nCol,
173064  const char *zDb1, const char *zDb2,
173065  const char *zTab,
173066  const char **azCol, u8 *abPK
173067 ){
173068  int i;
173069  const char *zSep = "";
173070  char *zRet = 0;
173071 
173072  for(i=0; i<nCol; i++){
173073  if( abPK[i] ){
173074  zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
173075  zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
173076  );
173077  zSep = " AND ";
173078  if( zRet==0 ) break;
173079  }
173080  }
173081 
173082  return zRet;
173083 }
173084 
173085 static char *sessionExprCompareOther(
173086  int nCol,
173087  const char *zDb1, const char *zDb2,
173088  const char *zTab,
173089  const char **azCol, u8 *abPK
173090 ){
173091  int i;
173092  const char *zSep = "";
173093  char *zRet = 0;
173094  int bHave = 0;
173095 
173096  for(i=0; i<nCol; i++){
173097  if( abPK[i]==0 ){
173098  bHave = 1;
173099  zRet = sqlite3_mprintf(
173100  "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
173101  zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
173102  );
173103  zSep = " OR ";
173104  if( zRet==0 ) break;
173105  }
173106  }
173107 
173108  if( bHave==0 ){
173109  assert( zRet==0 );
173110  zRet = sqlite3_mprintf("0");
173111  }
173112 
173113  return zRet;
173114 }
173115 
173116 static char *sessionSelectFindNew(
173117  int nCol,
173118  const char *zDb1, /* Pick rows in this db only */
173119  const char *zDb2, /* But not in this one */
173120  const char *zTbl, /* Table name */
173121  const char *zExpr
173122 ){
173123  char *zRet = sqlite3_mprintf(
173124  "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
173125  " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
173126  ")",
173127  zDb1, zTbl, zDb2, zTbl, zExpr
173128  );
173129  return zRet;
173130 }
173131 
173132 static int sessionDiffFindNew(
173133  int op,
173134  sqlite3_session *pSession,
173135  SessionTable *pTab,
173136  const char *zDb1,
173137  const char *zDb2,
173138  char *zExpr
173139 ){
173140  int rc = SQLITE_OK;
173141  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
173142 
173143  if( zStmt==0 ){
173144  rc = SQLITE_NOMEM;
173145  }else{
173146  sqlite3_stmt *pStmt;
173147  rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
173148  if( rc==SQLITE_OK ){
173149  SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
173150  pDiffCtx->pStmt = pStmt;
173151  pDiffCtx->nOldOff = 0;
173152  while( SQLITE_ROW==sqlite3_step(pStmt) ){
173153  sessionPreupdateOneChange(op, pSession, pTab);
173154  }
173155  rc = sqlite3_finalize(pStmt);
173156  }
173157  sqlite3_free(zStmt);
173158  }
173159 
173160  return rc;
173161 }
173162 
173163 static int sessionDiffFindModified(
173164  sqlite3_session *pSession,
173165  SessionTable *pTab,
173166  const char *zFrom,
173167  const char *zExpr
173168 ){
173169  int rc = SQLITE_OK;
173170 
173171  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
173172  pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
173173  );
173174  if( zExpr2==0 ){
173175  rc = SQLITE_NOMEM;
173176  }else{
173177  char *zStmt = sqlite3_mprintf(
173178  "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
173179  pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
173180  );
173181  if( zStmt==0 ){
173182  rc = SQLITE_NOMEM;
173183  }else{
173184  sqlite3_stmt *pStmt;
173185  rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
173186 
173187  if( rc==SQLITE_OK ){
173188  SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
173189  pDiffCtx->pStmt = pStmt;
173190  pDiffCtx->nOldOff = pTab->nCol;
173191  while( SQLITE_ROW==sqlite3_step(pStmt) ){
173192  sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
173193  }
173194  rc = sqlite3_finalize(pStmt);
173195  }
173196  sqlite3_free(zStmt);
173197  }
173198  }
173199 
173200  return rc;
173201 }
173202 
173203 SQLITE_API int sqlite3session_diff(
173204  sqlite3_session *pSession,
173205  const char *zFrom,
173206  const char *zTbl,
173207  char **pzErrMsg
173208 ){
173209  const char *zDb = pSession->zDb;
173210  int rc = pSession->rc;
173211  SessionDiffCtx d;
173212 
173213  memset(&d, 0, sizeof(d));
173214  sessionDiffHooks(pSession, &d);
173215 
173216  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
173217  if( pzErrMsg ) *pzErrMsg = 0;
173218  if( rc==SQLITE_OK ){
173219  char *zExpr = 0;
173220  sqlite3 *db = pSession->db;
173221  SessionTable *pTo; /* Table zTbl */
173222 
173223  /* Locate and if necessary initialize the target table object */
173224  rc = sessionFindTable(pSession, zTbl, &pTo);
173225  if( pTo==0 ) goto diff_out;
173226  if( sessionInitTable(pSession, pTo) ){
173227  rc = pSession->rc;
173228  goto diff_out;
173229  }
173230 
173231  /* Check the table schemas match */
173232  if( rc==SQLITE_OK ){
173233  int bHasPk = 0;
173234  int bMismatch = 0;
173235  int nCol; /* Columns in zFrom.zTbl */
173236  u8 *abPK;
173237  const char **azCol = 0;
173238  rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
173239  if( rc==SQLITE_OK ){
173240  if( pTo->nCol!=nCol ){
173241  bMismatch = 1;
173242  }else{
173243  int i;
173244  for(i=0; i<nCol; i++){
173245  if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
173246  if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
173247  if( abPK[i] ) bHasPk = 1;
173248  }
173249  }
173250 
173251  }
173252  sqlite3_free((char*)azCol);
173253  if( bMismatch ){
173254  *pzErrMsg = sqlite3_mprintf("table schemas do not match");
173255  rc = SQLITE_SCHEMA;
173256  }
173257  if( bHasPk==0 ){
173258  /* Ignore tables with no primary keys */
173259  goto diff_out;
173260  }
173261  }
173262 
173263  if( rc==SQLITE_OK ){
173264  zExpr = sessionExprComparePK(pTo->nCol,
173265  zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
173266  );
173267  }
173268 
173269  /* Find new rows */
173270  if( rc==SQLITE_OK ){
173271  rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
173272  }
173273 
173274  /* Find old rows */
173275  if( rc==SQLITE_OK ){
173276  rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
173277  }
173278 
173279  /* Find modified rows */
173280  if( rc==SQLITE_OK ){
173281  rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
173282  }
173283 
173284  sqlite3_free(zExpr);
173285  }
173286 
173287  diff_out:
173288  sessionPreupdateHooks(pSession);
173289  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
173290  return rc;
173291 }
173292 
173293 /*
173294 ** Create a session object. This session object will record changes to
173295 ** database zDb attached to connection db.
173296 */
173297 SQLITE_API int sqlite3session_create(
173298  sqlite3 *db, /* Database handle */
173299  const char *zDb, /* Name of db (e.g. "main") */
173300  sqlite3_session **ppSession /* OUT: New session object */
173301 ){
173302  sqlite3_session *pNew; /* Newly allocated session object */
173303  sqlite3_session *pOld; /* Session object already attached to db */
173304  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
173305 
173306  /* Zero the output value in case an error occurs. */
173307  *ppSession = 0;
173308 
173309  /* Allocate and populate the new session object. */
173310  pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
173311  if( !pNew ) return SQLITE_NOMEM;
173312  memset(pNew, 0, sizeof(sqlite3_session));
173313  pNew->db = db;
173314  pNew->zDb = (char *)&pNew[1];
173315  pNew->bEnable = 1;
173316  memcpy(pNew->zDb, zDb, nDb+1);
173317  sessionPreupdateHooks(pNew);
173318 
173319  /* Add the new session object to the linked list of session objects
173320  ** attached to database handle $db. Do this under the cover of the db
173321  ** handle mutex. */
173323  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
173324  pNew->pNext = pOld;
173326 
173327  *ppSession = pNew;
173328  return SQLITE_OK;
173329 }
173330 
173331 /*
173332 ** Free the list of table objects passed as the first argument. The contents
173333 ** of the changed-rows hash tables are also deleted.
173334 */
173335 static void sessionDeleteTable(SessionTable *pList){
173336  SessionTable *pNext;
173337  SessionTable *pTab;
173338 
173339  for(pTab=pList; pTab; pTab=pNext){
173340  int i;
173341  pNext = pTab->pNext;
173342  for(i=0; i<pTab->nChange; i++){
173343  SessionChange *p;
173344  SessionChange *pNextChange;
173345  for(p=pTab->apChange[i]; p; p=pNextChange){
173346  pNextChange = p->pNext;
173347  sqlite3_free(p);
173348  }
173349  }
173350  sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
173351  sqlite3_free(pTab->apChange);
173352  sqlite3_free(pTab);
173353  }
173354 }
173355 
173356 /*
173357 ** Delete a session object previously allocated using sqlite3session_create().
173358 */
173359 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
173360  sqlite3 *db = pSession->db;
173361  sqlite3_session *pHead;
173362  sqlite3_session **pp;
173363 
173364  /* Unlink the session from the linked list of sessions attached to the
173365  ** database handle. Hold the db mutex while doing so. */
173367  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
173368  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
173369  if( (*pp)==pSession ){
173370  *pp = (*pp)->pNext;
173371  if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
173372  break;
173373  }
173374  }
173376 
173377  /* Delete all attached table objects. And the contents of their
173378  ** associated hash-tables. */
173379  sessionDeleteTable(pSession->pTable);
173380 
173381  /* Free the session object itself. */
173382  sqlite3_free(pSession);
173383 }
173384 
173385 /*
173386 ** Set a table filter on a Session Object.
173387 */
173388 SQLITE_API void sqlite3session_table_filter(
173389  sqlite3_session *pSession,
173390  int(*xFilter)(void*, const char*),
173391  void *pCtx /* First argument passed to xFilter */
173392 ){
173393  pSession->bAutoAttach = 1;
173394  pSession->pFilterCtx = pCtx;
173395  pSession->xTableFilter = xFilter;
173396 }
173397 
173398 /*
173399 ** Attach a table to a session. All subsequent changes made to the table
173400 ** while the session object is enabled will be recorded.
173401 **
173402 ** Only tables that have a PRIMARY KEY defined may be attached. It does
173403 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
173404 ** or not.
173405 */
173406 SQLITE_API int sqlite3session_attach(
173407  sqlite3_session *pSession, /* Session object */
173408  const char *zName /* Table name */
173409 ){
173410  int rc = SQLITE_OK;
173411  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
173412 
173413  if( !zName ){
173414  pSession->bAutoAttach = 1;
173415  }else{
173416  SessionTable *pTab; /* New table object (if required) */
173417  int nName; /* Number of bytes in string zName */
173418 
173419  /* First search for an existing entry. If one is found, this call is
173420  ** a no-op. Return early. */
173421  nName = sqlite3Strlen30(zName);
173422  for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
173423  if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
173424  }
173425 
173426  if( !pTab ){
173427  /* Allocate new SessionTable object. */
173428  pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
173429  if( !pTab ){
173430  rc = SQLITE_NOMEM;
173431  }else{
173432  /* Populate the new SessionTable object and link it into the list.
173433  ** The new object must be linked onto the end of the list, not
173434  ** simply added to the start of it in order to ensure that tables
173435  ** appear in the correct order when a changeset or patchset is
173436  ** eventually generated. */
173437  SessionTable **ppTab;
173438  memset(pTab, 0, sizeof(SessionTable));
173439  pTab->zName = (char *)&pTab[1];
173440  memcpy(pTab->zName, zName, nName+1);
173441  for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
173442  *ppTab = pTab;
173443  }
173444  }
173445  }
173446 
173447  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
173448  return rc;
173449 }
173450 
173451 /*
173452 ** Ensure that there is room in the buffer to append nByte bytes of data.
173453 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
173454 **
173455 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
173456 ** set *pRc to SQLITE_NOMEM and return non-zero.
173457 */
173458 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
173459  if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
173460  u8 *aNew;
173461  int nNew = p->nAlloc ? p->nAlloc : 128;
173462  do {
173463  nNew = nNew*2;
173464  }while( nNew<(p->nBuf+nByte) );
173465 
173466  aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
173467  if( 0==aNew ){
173468  *pRc = SQLITE_NOMEM;
173469  }else{
173470  p->aBuf = aNew;
173471  p->nAlloc = nNew;
173472  }
173473  }
173474  return (*pRc!=SQLITE_OK);
173475 }
173476 
173477 /*
173478 ** Append the value passed as the second argument to the buffer passed
173479 ** as the first.
173480 **
173481 ** This function is a no-op if *pRc is non-zero when it is called.
173482 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
173483 ** before returning.
173484 */
173485 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
173486  int rc = *pRc;
173487  if( rc==SQLITE_OK ){
173488  int nByte = 0;
173489  rc = sessionSerializeValue(0, pVal, &nByte);
173490  sessionBufferGrow(p, nByte, &rc);
173491  if( rc==SQLITE_OK ){
173492  rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
173493  p->nBuf += nByte;
173494  }else{
173495  *pRc = rc;
173496  }
173497  }
173498 }
173499 
173500 /*
173501 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173502 ** called. Otherwise, append a single byte to the buffer.
173503 **
173504 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173505 ** returning.
173506 */
173507 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
173508  if( 0==sessionBufferGrow(p, 1, pRc) ){
173509  p->aBuf[p->nBuf++] = v;
173510  }
173511 }
173512 
173513 /*
173514 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173515 ** called. Otherwise, append a single varint to the buffer.
173516 **
173517 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173518 ** returning.
173519 */
173520 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
173521  if( 0==sessionBufferGrow(p, 9, pRc) ){
173522  p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
173523  }
173524 }
173525 
173526 /*
173527 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173528 ** called. Otherwise, append a blob of data to the buffer.
173529 **
173530 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173531 ** returning.
173532 */
173533 static void sessionAppendBlob(
173534  SessionBuffer *p,
173535  const u8 *aBlob,
173536  int nBlob,
173537  int *pRc
173538 ){
173539  if( 0==sessionBufferGrow(p, nBlob, pRc) ){
173540  memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
173541  p->nBuf += nBlob;
173542  }
173543 }
173544 
173545 /*
173546 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173547 ** called. Otherwise, append a string to the buffer. All bytes in the string
173548 ** up to (but not including) the nul-terminator are written to the buffer.
173549 **
173550 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173551 ** returning.
173552 */
173553 static void sessionAppendStr(
173554  SessionBuffer *p,
173555  const char *zStr,
173556  int *pRc
173557 ){
173558  int nStr = sqlite3Strlen30(zStr);
173559  if( 0==sessionBufferGrow(p, nStr, pRc) ){
173560  memcpy(&p->aBuf[p->nBuf], zStr, nStr);
173561  p->nBuf += nStr;
173562  }
173563 }
173564 
173565 /*
173566 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173567 ** called. Otherwise, append the string representation of integer iVal
173568 ** to the buffer. No nul-terminator is written.
173569 **
173570 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173571 ** returning.
173572 */
173573 static void sessionAppendInteger(
173574  SessionBuffer *p, /* Buffer to append to */
173575  int iVal, /* Value to write the string rep. of */
173576  int *pRc /* IN/OUT: Error code */
173577 ){
173578  char aBuf[24];
173579  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
173580  sessionAppendStr(p, aBuf, pRc);
173581 }
173582 
173583 /*
173584 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173585 ** called. Otherwise, append the string zStr enclosed in quotes (") and
173586 ** with any embedded quote characters escaped to the buffer. No
173587 ** nul-terminator byte is written.
173588 **
173589 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
173590 ** returning.
173591 */
173592 static void sessionAppendIdent(
173593  SessionBuffer *p, /* Buffer to a append to */
173594  const char *zStr, /* String to quote, escape and append */
173595  int *pRc /* IN/OUT: Error code */
173596 ){
173597  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
173598  if( 0==sessionBufferGrow(p, nStr, pRc) ){
173599  char *zOut = (char *)&p->aBuf[p->nBuf];
173600  const char *zIn = zStr;
173601  *zOut++ = '"';
173602  while( *zIn ){
173603  if( *zIn=='"' ) *zOut++ = '"';
173604  *zOut++ = *(zIn++);
173605  }
173606  *zOut++ = '"';
173607  p->nBuf = (int)((u8 *)zOut - p->aBuf);
173608  }
173609 }
173610 
173611 /*
173612 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
173613 ** called. Otherwse, it appends the serialized version of the value stored
173614 ** in column iCol of the row that SQL statement pStmt currently points
173615 ** to to the buffer.
173616 */
173617 static void sessionAppendCol(
173618  SessionBuffer *p, /* Buffer to append to */
173619  sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
173620  int iCol, /* Column to read value from */
173621  int *pRc /* IN/OUT: Error code */
173622 ){
173623  if( *pRc==SQLITE_OK ){
173624  int eType = sqlite3_column_type(pStmt, iCol);
173625  sessionAppendByte(p, (u8)eType, pRc);
173626  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
173627  sqlite3_int64 i;
173628  u8 aBuf[8];
173629  if( eType==SQLITE_INTEGER ){
173630  i = sqlite3_column_int64(pStmt, iCol);
173631  }else{
173632  double r = sqlite3_column_double(pStmt, iCol);
173633  memcpy(&i, &r, 8);
173634  }
173635  sessionPutI64(aBuf, i);
173636  sessionAppendBlob(p, aBuf, 8, pRc);
173637  }
173638  if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
173639  u8 *z;
173640  int nByte;
173641  if( eType==SQLITE_BLOB ){
173642  z = (u8 *)sqlite3_column_blob(pStmt, iCol);
173643  }else{
173644  z = (u8 *)sqlite3_column_text(pStmt, iCol);
173645  }
173646  nByte = sqlite3_column_bytes(pStmt, iCol);
173647  if( z || (eType==SQLITE_BLOB && nByte==0) ){
173648  sessionAppendVarint(p, nByte, pRc);
173649  sessionAppendBlob(p, z, nByte, pRc);
173650  }else{
173651  *pRc = SQLITE_NOMEM;
173652  }
173653  }
173654  }
173655 }
173656 
173657 /*
173658 **
173659 ** This function appends an update change to the buffer (see the comments
173660 ** under "CHANGESET FORMAT" at the top of the file). An update change
173661 ** consists of:
173662 **
173663 ** 1 byte: SQLITE_UPDATE (0x17)
173664 ** n bytes: old.* record (see RECORD FORMAT)
173665 ** m bytes: new.* record (see RECORD FORMAT)
173666 **
173667 ** The SessionChange object passed as the third argument contains the
173668 ** values that were stored in the row when the session began (the old.*
173669 ** values). The statement handle passed as the second argument points
173670 ** at the current version of the row (the new.* values).
173671 **
173672 ** If all of the old.* values are equal to their corresponding new.* value
173673 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
173674 **
173675 ** Otherwise, the old.* record contains all primary key values and the
173676 ** original values of any fields that have been modified. The new.* record
173677 ** contains the new values of only those fields that have been modified.
173678 */
173679 static int sessionAppendUpdate(
173680  SessionBuffer *pBuf, /* Buffer to append to */
173681  int bPatchset, /* True for "patchset", 0 for "changeset" */
173682  sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
173683  SessionChange *p, /* Object containing old values */
173684  u8 *abPK /* Boolean array - true for PK columns */
173685 ){
173686  int rc = SQLITE_OK;
173687  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
173688  int bNoop = 1; /* Set to zero if any values are modified */
173689  int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
173690  int i; /* Used to iterate through columns */
173691  u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
173692 
173693  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
173694  sessionAppendByte(pBuf, p->bIndirect, &rc);
173695  for(i=0; i<sqlite3_column_count(pStmt); i++){
173696  int bChanged = 0;
173697  int nAdvance;
173698  int eType = *pCsr;
173699  switch( eType ){
173700  case SQLITE_NULL:
173701  nAdvance = 1;
173702  if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
173703  bChanged = 1;
173704  }
173705  break;
173706 
173707  case SQLITE_FLOAT:
173708  case SQLITE_INTEGER: {
173709  nAdvance = 9;
173710  if( eType==sqlite3_column_type(pStmt, i) ){
173711  sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
173712  if( eType==SQLITE_INTEGER ){
173713  if( iVal==sqlite3_column_int64(pStmt, i) ) break;
173714  }else{
173715  double dVal;
173716  memcpy(&dVal, &iVal, 8);
173717  if( dVal==sqlite3_column_double(pStmt, i) ) break;
173718  }
173719  }
173720  bChanged = 1;
173721  break;
173722  }
173723 
173724  default: {
173725  int nByte;
173726  int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
173727  assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
173728  nAdvance = nHdr + nByte;
173729  if( eType==sqlite3_column_type(pStmt, i)
173730  && nByte==sqlite3_column_bytes(pStmt, i)
173731  && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
173732  ){
173733  break;
173734  }
173735  bChanged = 1;
173736  }
173737  }
173738 
173739  /* If at least one field has been modified, this is not a no-op. */
173740  if( bChanged ) bNoop = 0;
173741 
173742  /* Add a field to the old.* record. This is omitted if this modules is
173743  ** currently generating a patchset. */
173744  if( bPatchset==0 ){
173745  if( bChanged || abPK[i] ){
173746  sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
173747  }else{
173748  sessionAppendByte(pBuf, 0, &rc);
173749  }
173750  }
173751 
173752  /* Add a field to the new.* record. Or the only record if currently
173753  ** generating a patchset. */
173754  if( bChanged || (bPatchset && abPK[i]) ){
173755  sessionAppendCol(&buf2, pStmt, i, &rc);
173756  }else{
173757  sessionAppendByte(&buf2, 0, &rc);
173758  }
173759 
173760  pCsr += nAdvance;
173761  }
173762 
173763  if( bNoop ){
173764  pBuf->nBuf = nRewind;
173765  }else{
173766  sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
173767  }
173768  sqlite3_free(buf2.aBuf);
173769 
173770  return rc;
173771 }
173772 
173773 /*
173774 ** Append a DELETE change to the buffer passed as the first argument. Use
173775 ** the changeset format if argument bPatchset is zero, or the patchset
173776 ** format otherwise.
173777 */
173778 static int sessionAppendDelete(
173779  SessionBuffer *pBuf, /* Buffer to append to */
173780  int bPatchset, /* True for "patchset", 0 for "changeset" */
173781  SessionChange *p, /* Object containing old values */
173782  int nCol, /* Number of columns in table */
173783  u8 *abPK /* Boolean array - true for PK columns */
173784 ){
173785  int rc = SQLITE_OK;
173786 
173787  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
173788  sessionAppendByte(pBuf, p->bIndirect, &rc);
173789 
173790  if( bPatchset==0 ){
173791  sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
173792  }else{
173793  int i;
173794  u8 *a = p->aRecord;
173795  for(i=0; i<nCol; i++){
173796  u8 *pStart = a;
173797  int eType = *a++;
173798 
173799  switch( eType ){
173800  case 0:
173801  case SQLITE_NULL:
173802  assert( abPK[i]==0 );
173803  break;
173804 
173805  case SQLITE_FLOAT:
173806  case SQLITE_INTEGER:
173807  a += 8;
173808  break;
173809 
173810  default: {
173811  int n;
173812  a += sessionVarintGet(a, &n);
173813  a += n;
173814  break;
173815  }
173816  }
173817  if( abPK[i] ){
173818  sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
173819  }
173820  }
173821  assert( (a - p->aRecord)==p->nRecord );
173822  }
173823 
173824  return rc;
173825 }
173826 
173827 /*
173828 ** Formulate and prepare a SELECT statement to retrieve a row from table
173829 ** zTab in database zDb based on its primary key. i.e.
173830 **
173831 ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
173832 */
173833 static int sessionSelectStmt(
173834  sqlite3 *db, /* Database handle */
173835  const char *zDb, /* Database name */
173836  const char *zTab, /* Table name */
173837  int nCol, /* Number of columns in table */
173838  const char **azCol, /* Names of table columns */
173839  u8 *abPK, /* PRIMARY KEY array */
173840  sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
173841 ){
173842  int rc = SQLITE_OK;
173843  int i;
173844  const char *zSep = "";
173845  SessionBuffer buf = {0, 0, 0};
173846 
173847  sessionAppendStr(&buf, "SELECT * FROM ", &rc);
173848  sessionAppendIdent(&buf, zDb, &rc);
173849  sessionAppendStr(&buf, ".", &rc);
173850  sessionAppendIdent(&buf, zTab, &rc);
173851  sessionAppendStr(&buf, " WHERE ", &rc);
173852  for(i=0; i<nCol; i++){
173853  if( abPK[i] ){
173854  sessionAppendStr(&buf, zSep, &rc);
173855  sessionAppendIdent(&buf, azCol[i], &rc);
173856  sessionAppendStr(&buf, " = ?", &rc);
173857  sessionAppendInteger(&buf, i+1, &rc);
173858  zSep = " AND ";
173859  }
173860  }
173861  if( rc==SQLITE_OK ){
173862  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
173863  }
173864  sqlite3_free(buf.aBuf);
173865  return rc;
173866 }
173867 
173868 /*
173869 ** Bind the PRIMARY KEY values from the change passed in argument pChange
173870 ** to the SELECT statement passed as the first argument. The SELECT statement
173871 ** is as prepared by function sessionSelectStmt().
173872 **
173873 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
173874 ** error code (e.g. SQLITE_NOMEM) otherwise.
173875 */
173876 static int sessionSelectBind(
173877  sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
173878  int nCol, /* Number of columns in table */
173879  u8 *abPK, /* PRIMARY KEY array */
173880  SessionChange *pChange /* Change structure */
173881 ){
173882  int i;
173883  int rc = SQLITE_OK;
173884  u8 *a = pChange->aRecord;
173885 
173886  for(i=0; i<nCol && rc==SQLITE_OK; i++){
173887  int eType = *a++;
173888 
173889  switch( eType ){
173890  case 0:
173891  case SQLITE_NULL:
173892  assert( abPK[i]==0 );
173893  break;
173894 
173895  case SQLITE_INTEGER: {
173896  if( abPK[i] ){
173897  i64 iVal = sessionGetI64(a);
173898  rc = sqlite3_bind_int64(pSelect, i+1, iVal);
173899  }
173900  a += 8;
173901  break;
173902  }
173903 
173904  case SQLITE_FLOAT: {
173905  if( abPK[i] ){
173906  double rVal;
173907  i64 iVal = sessionGetI64(a);
173908  memcpy(&rVal, &iVal, 8);
173909  rc = sqlite3_bind_double(pSelect, i+1, rVal);
173910  }
173911  a += 8;
173912  break;
173913  }
173914 
173915  case SQLITE_TEXT: {
173916  int n;
173917  a += sessionVarintGet(a, &n);
173918  if( abPK[i] ){
173919  rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
173920  }
173921  a += n;
173922  break;
173923  }
173924 
173925  default: {
173926  int n;
173927  assert( eType==SQLITE_BLOB );
173928  a += sessionVarintGet(a, &n);
173929  if( abPK[i] ){
173930  rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
173931  }
173932  a += n;
173933  break;
173934  }
173935  }
173936  }
173937 
173938  return rc;
173939 }
173940 
173941 /*
173942 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
173943 ** is called. Otherwise, append a serialized table header (part of the binary
173944 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
173945 ** SQLite error code before returning.
173946 */
173947 static void sessionAppendTableHdr(
173948  SessionBuffer *pBuf, /* Append header to this buffer */
173949  int bPatchset, /* Use the patchset format if true */
173950  SessionTable *pTab, /* Table object to append header for */
173951  int *pRc /* IN/OUT: Error code */
173952 ){
173953  /* Write a table header */
173954  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
173955  sessionAppendVarint(pBuf, pTab->nCol, pRc);
173956  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
173957  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
173958 }
173959 
173960 /*
173961 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
173962 ** (if it is non-zero) based on the current contents of the session object
173963 ** passed as the first argument.
173964 **
173965 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
173966 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
173967 ** occurs, an SQLite error code is returned and both output variables set
173968 ** to 0.
173969 */
173970 static int sessionGenerateChangeset(
173971  sqlite3_session *pSession, /* Session object */
173972  int bPatchset, /* True for patchset, false for changeset */
173973  int (*xOutput)(void *pOut, const void *pData, int nData),
173974  void *pOut, /* First argument for xOutput */
173975  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
173976  void **ppChangeset /* OUT: Buffer containing changeset */
173977 ){
173978  sqlite3 *db = pSession->db; /* Source database handle */
173979  SessionTable *pTab; /* Used to iterate through attached tables */
173980  SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
173981  int rc; /* Return code */
173982 
173983  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
173984 
173985  /* Zero the output variables in case an error occurs. If this session
173986  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
173987  ** this call will be a no-op. */
173988  if( xOutput==0 ){
173989  *pnChangeset = 0;
173990  *ppChangeset = 0;
173991  }
173992 
173993  if( pSession->rc ) return pSession->rc;
173994  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
173995  if( rc!=SQLITE_OK ) return rc;
173996 
173998 
173999  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
174000  if( pTab->nEntry ){
174001  const char *zName = pTab->zName;
174002  int nCol; /* Number of columns in table */
174003  u8 *abPK; /* Primary key array */
174004  const char **azCol = 0; /* Table columns */
174005  int i; /* Used to iterate through hash buckets */
174006  sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
174007  int nRewind = buf.nBuf; /* Initial size of write buffer */
174008  int nNoop; /* Size of buffer after writing tbl header */
174009 
174010  /* Check the table schema is still Ok. */
174011  rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
174012  if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
174013  rc = SQLITE_SCHEMA;
174014  }
174015 
174016  /* Write a table header */
174017  sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
174018 
174019  /* Build and compile a statement to execute: */
174020  if( rc==SQLITE_OK ){
174021  rc = sessionSelectStmt(
174022  db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
174023  }
174024 
174025  nNoop = buf.nBuf;
174026  for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
174027  SessionChange *p; /* Used to iterate through changes */
174028 
174029  for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
174030  rc = sessionSelectBind(pSel, nCol, abPK, p);
174031  if( rc!=SQLITE_OK ) continue;
174032  if( sqlite3_step(pSel)==SQLITE_ROW ){
174033  if( p->op==SQLITE_INSERT ){
174034  int iCol;
174035  sessionAppendByte(&buf, SQLITE_INSERT, &rc);
174036  sessionAppendByte(&buf, p->bIndirect, &rc);
174037  for(iCol=0; iCol<nCol; iCol++){
174038  sessionAppendCol(&buf, pSel, iCol, &rc);
174039  }
174040  }else{
174041  rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
174042  }
174043  }else if( p->op!=SQLITE_INSERT ){
174044  rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
174045  }
174046  if( rc==SQLITE_OK ){
174047  rc = sqlite3_reset(pSel);
174048  }
174049 
174050  /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
174051  ** its contents to the xOutput() callback. */
174052  if( xOutput
174053  && rc==SQLITE_OK
174054  && buf.nBuf>nNoop
174055  && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
174056  ){
174057  rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
174058  nNoop = -1;
174059  buf.nBuf = 0;
174060  }
174061 
174062  }
174063  }
174064 
174065  sqlite3_finalize(pSel);
174066  if( buf.nBuf==nNoop ){
174067  buf.nBuf = nRewind;
174068  }
174069  sqlite3_free((char*)azCol); /* cast works around VC++ bug */
174070  }
174071  }
174072 
174073  if( rc==SQLITE_OK ){
174074  if( xOutput==0 ){
174075  *pnChangeset = buf.nBuf;
174076  *ppChangeset = buf.aBuf;
174077  buf.aBuf = 0;
174078  }else if( buf.nBuf>0 ){
174079  rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
174080  }
174081  }
174082 
174083  sqlite3_free(buf.aBuf);
174084  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
174086  return rc;
174087 }
174088 
174089 /*
174090 ** Obtain a changeset object containing all changes recorded by the
174091 ** session object passed as the first argument.
174092 **
174093 ** It is the responsibility of the caller to eventually free the buffer
174094 ** using sqlite3_free().
174095 */
174096 SQLITE_API int sqlite3session_changeset(
174097  sqlite3_session *pSession, /* Session object */
174098  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
174099  void **ppChangeset /* OUT: Buffer containing changeset */
174100 ){
174101  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
174102 }
174103 
174104 /*
174105 ** Streaming version of sqlite3session_changeset().
174106 */
174107 SQLITE_API int sqlite3session_changeset_strm(
174108  sqlite3_session *pSession,
174109  int (*xOutput)(void *pOut, const void *pData, int nData),
174110  void *pOut
174111 ){
174112  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
174113 }
174114 
174115 /*
174116 ** Streaming version of sqlite3session_patchset().
174117 */
174118 SQLITE_API int sqlite3session_patchset_strm(
174119  sqlite3_session *pSession,
174120  int (*xOutput)(void *pOut, const void *pData, int nData),
174121  void *pOut
174122 ){
174123  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
174124 }
174125 
174126 /*
174127 ** Obtain a patchset object containing all changes recorded by the
174128 ** session object passed as the first argument.
174129 **
174130 ** It is the responsibility of the caller to eventually free the buffer
174131 ** using sqlite3_free().
174132 */
174133 SQLITE_API int sqlite3session_patchset(
174134  sqlite3_session *pSession, /* Session object */
174135  int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
174136  void **ppPatchset /* OUT: Buffer containing changeset */
174137 ){
174138  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
174139 }
174140 
174141 /*
174142 ** Enable or disable the session object passed as the first argument.
174143 */
174144 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
174145  int ret;
174146  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
174147  if( bEnable>=0 ){
174148  pSession->bEnable = bEnable;
174149  }
174150  ret = pSession->bEnable;
174151  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
174152  return ret;
174153 }
174154 
174155 /*
174156 ** Enable or disable the session object passed as the first argument.
174157 */
174158 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
174159  int ret;
174160  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
174161  if( bIndirect>=0 ){
174162  pSession->bIndirect = bIndirect;
174163  }
174164  ret = pSession->bIndirect;
174165  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
174166  return ret;
174167 }
174168 
174169 /*
174170 ** Return true if there have been no changes to monitored tables recorded
174171 ** by the session object passed as the only argument.
174172 */
174173 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
174174  int ret = 0;
174175  SessionTable *pTab;
174176 
174177  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
174178  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
174179  ret = (pTab->nEntry>0);
174180  }
174181  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
174182 
174183  return (ret==0);
174184 }
174185 
174186 /*
174187 ** Do the work for either sqlite3changeset_start() or start_strm().
174188 */
174189 static int sessionChangesetStart(
174190  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
174191  int (*xInput)(void *pIn, void *pData, int *pnData),
174192  void *pIn,
174193  int nChangeset, /* Size of buffer pChangeset in bytes */
174194  void *pChangeset /* Pointer to buffer containing changeset */
174195 ){
174196  sqlite3_changeset_iter *pRet; /* Iterator to return */
174197  int nByte; /* Number of bytes to allocate for iterator */
174198 
174199  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
174200 
174201  /* Zero the output variable in case an error occurs. */
174202  *pp = 0;
174203 
174204  /* Allocate and initialize the iterator structure. */
174205  nByte = sizeof(sqlite3_changeset_iter);
174206  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
174207  if( !pRet ) return SQLITE_NOMEM;
174208  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
174209  pRet->in.aData = (u8 *)pChangeset;
174210  pRet->in.nData = nChangeset;
174211  pRet->in.xInput = xInput;
174212  pRet->in.pIn = pIn;
174213  pRet->in.bEof = (xInput ? 0 : 1);
174214 
174215  /* Populate the output variable and return success. */
174216  *pp = pRet;
174217  return SQLITE_OK;
174218 }
174219 
174220 /*
174221 ** Create an iterator used to iterate through the contents of a changeset.
174222 */
174223 SQLITE_API int sqlite3changeset_start(
174224  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
174225  int nChangeset, /* Size of buffer pChangeset in bytes */
174226  void *pChangeset /* Pointer to buffer containing changeset */
174227 ){
174228  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
174229 }
174230 
174231 /*
174232 ** Streaming version of sqlite3changeset_start().
174233 */
174234 SQLITE_API int sqlite3changeset_start_strm(
174235  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
174236  int (*xInput)(void *pIn, void *pData, int *pnData),
174237  void *pIn
174238 ){
174239  return sessionChangesetStart(pp, xInput, pIn, 0, 0);
174240 }
174241 
174242 /*
174243 ** If the SessionInput object passed as the only argument is a streaming
174244 ** object and the buffer is full, discard some data to free up space.
174245 */
174246 static void sessionDiscardData(SessionInput *pIn){
174247  if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
174248  int nMove = pIn->buf.nBuf - pIn->iNext;
174249  assert( nMove>=0 );
174250  if( nMove>0 ){
174251  memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
174252  }
174253  pIn->buf.nBuf -= pIn->iNext;
174254  pIn->iNext = 0;
174255  pIn->nData = pIn->buf.nBuf;
174256  }
174257 }
174258 
174259 /*
174260 ** Ensure that there are at least nByte bytes available in the buffer. Or,
174261 ** if there are not nByte bytes remaining in the input, that all available
174262 ** data is in the buffer.
174263 **
174264 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
174265 */
174266 static int sessionInputBuffer(SessionInput *pIn, int nByte){
174267  int rc = SQLITE_OK;
174268  if( pIn->xInput ){
174269  while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
174270  int nNew = SESSIONS_STRM_CHUNK_SIZE;
174271 
174272  if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
174273  if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
174274  rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
174275  if( nNew==0 ){
174276  pIn->bEof = 1;
174277  }else{
174278  pIn->buf.nBuf += nNew;
174279  }
174280  }
174281 
174282  pIn->aData = pIn->buf.aBuf;
174283  pIn->nData = pIn->buf.nBuf;
174284  }
174285  }
174286  return rc;
174287 }
174288 
174289 /*
174290 ** When this function is called, *ppRec points to the start of a record
174291 ** that contains nCol values. This function advances the pointer *ppRec
174292 ** until it points to the byte immediately following that record.
174293 */
174294 static void sessionSkipRecord(
174295  u8 **ppRec, /* IN/OUT: Record pointer */
174296  int nCol /* Number of values in record */
174297 ){
174298  u8 *aRec = *ppRec;
174299  int i;
174300  for(i=0; i<nCol; i++){
174301  int eType = *aRec++;
174302  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
174303  int nByte;
174304  aRec += sessionVarintGet((u8*)aRec, &nByte);
174305  aRec += nByte;
174306  }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174307  aRec += 8;
174308  }
174309  }
174310 
174311  *ppRec = aRec;
174312 }
174313 
174314 /*
174315 ** This function sets the value of the sqlite3_value object passed as the
174316 ** first argument to a copy of the string or blob held in the aData[]
174317 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
174318 ** error occurs.
174319 */
174320 static int sessionValueSetStr(
174321  sqlite3_value *pVal, /* Set the value of this object */
174322  u8 *aData, /* Buffer containing string or blob data */
174323  int nData, /* Size of buffer aData[] in bytes */
174324  u8 enc /* String encoding (0 for blobs) */
174325 ){
174326  /* In theory this code could just pass SQLITE_TRANSIENT as the final
174327  ** argument to sqlite3ValueSetStr() and have the copy created
174328  ** automatically. But doing so makes it difficult to detect any OOM
174329  ** error. Hence the code to create the copy externally. */
174330  u8 *aCopy = sqlite3_malloc(nData+1);
174331  if( aCopy==0 ) return SQLITE_NOMEM;
174332  memcpy(aCopy, aData, nData);
174333  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
174334  return SQLITE_OK;
174335 }
174336 
174337 /*
174338 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
174339 ** for details.
174340 **
174341 ** When this function is called, *paChange points to the start of the record
174342 ** to deserialize. Assuming no error occurs, *paChange is set to point to
174343 ** one byte after the end of the same record before this function returns.
174344 ** If the argument abPK is NULL, then the record contains nCol values. Or,
174345 ** if abPK is other than NULL, then the record contains only the PK fields
174346 ** (in other words, it is a patchset DELETE record).
174347 **
174348 ** If successful, each element of the apOut[] array (allocated by the caller)
174349 ** is set to point to an sqlite3_value object containing the value read
174350 ** from the corresponding position in the record. If that value is not
174351 ** included in the record (i.e. because the record is part of an UPDATE change
174352 ** and the field was not modified), the corresponding element of apOut[] is
174353 ** set to NULL.
174354 **
174355 ** It is the responsibility of the caller to free all sqlite_value structures
174356 ** using sqlite3_free().
174357 **
174358 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
174359 ** The apOut[] array may have been partially populated in this case.
174360 */
174361 static int sessionReadRecord(
174362  SessionInput *pIn, /* Input data */
174363  int nCol, /* Number of values in record */
174364  u8 *abPK, /* Array of primary key flags, or NULL */
174365  sqlite3_value **apOut /* Write values to this array */
174366 ){
174367  int i; /* Used to iterate through columns */
174368  int rc = SQLITE_OK;
174369 
174370  for(i=0; i<nCol && rc==SQLITE_OK; i++){
174371  int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
174372  if( abPK && abPK[i]==0 ) continue;
174373  rc = sessionInputBuffer(pIn, 9);
174374  if( rc==SQLITE_OK ){
174375  eType = pIn->aData[pIn->iNext++];
174376  }
174377 
174378  assert( apOut[i]==0 );
174379  if( eType ){
174380  apOut[i] = sqlite3ValueNew(0);
174381  if( !apOut[i] ) rc = SQLITE_NOMEM;
174382  }
174383 
174384  if( rc==SQLITE_OK ){
174385  u8 *aVal = &pIn->aData[pIn->iNext];
174386  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
174387  int nByte;
174388  pIn->iNext += sessionVarintGet(aVal, &nByte);
174389  rc = sessionInputBuffer(pIn, nByte);
174390  if( rc==SQLITE_OK ){
174391  u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
174392  rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
174393  }
174394  pIn->iNext += nByte;
174395  }
174396  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174397  sqlite3_int64 v = sessionGetI64(aVal);
174398  if( eType==SQLITE_INTEGER ){
174399  sqlite3VdbeMemSetInt64(apOut[i], v);
174400  }else{
174401  double d;
174402  memcpy(&d, &v, 8);
174403  sqlite3VdbeMemSetDouble(apOut[i], d);
174404  }
174405  pIn->iNext += 8;
174406  }
174407  }
174408  }
174409 
174410  return rc;
174411 }
174412 
174413 /*
174414 ** The input pointer currently points to the second byte of a table-header.
174415 ** Specifically, to the following:
174416 **
174417 ** + number of columns in table (varint)
174418 ** + array of PK flags (1 byte per column),
174419 ** + table name (nul terminated).
174420 **
174421 ** This function ensures that all of the above is present in the input
174422 ** buffer (i.e. that it can be accessed without any calls to xInput()).
174423 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
174424 ** The input pointer is not moved.
174425 */
174426 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
174427  int rc = SQLITE_OK;
174428  int nCol = 0;
174429  int nRead = 0;
174430 
174431  rc = sessionInputBuffer(pIn, 9);
174432  if( rc==SQLITE_OK ){
174433  nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
174434  rc = sessionInputBuffer(pIn, nRead+nCol+100);
174435  nRead += nCol;
174436  }
174437 
174438  while( rc==SQLITE_OK ){
174439  while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
174440  nRead++;
174441  }
174442  if( (pIn->iNext + nRead)<pIn->nData ) break;
174443  rc = sessionInputBuffer(pIn, nRead + 100);
174444  }
174445  *pnByte = nRead+1;
174446  return rc;
174447 }
174448 
174449 /*
174450 ** The input pointer currently points to the first byte of the first field
174451 ** of a record consisting of nCol columns. This function ensures the entire
174452 ** record is buffered. It does not move the input pointer.
174453 **
174454 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
174455 ** the record in bytes. Otherwise, an SQLite error code is returned. The
174456 ** final value of *pnByte is undefined in this case.
174457 */
174458 static int sessionChangesetBufferRecord(
174459  SessionInput *pIn, /* Input data */
174460  int nCol, /* Number of columns in record */
174461  int *pnByte /* OUT: Size of record in bytes */
174462 ){
174463  int rc = SQLITE_OK;
174464  int nByte = 0;
174465  int i;
174466  for(i=0; rc==SQLITE_OK && i<nCol; i++){
174467  int eType;
174468  rc = sessionInputBuffer(pIn, nByte + 10);
174469  if( rc==SQLITE_OK ){
174470  eType = pIn->aData[pIn->iNext + nByte++];
174471  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
174472  int n;
174473  nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
174474  nByte += n;
174475  rc = sessionInputBuffer(pIn, nByte);
174476  }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
174477  nByte += 8;
174478  }
174479  }
174480  }
174481  *pnByte = nByte;
174482  return rc;
174483 }
174484 
174485 /*
174486 ** The input pointer currently points to the second byte of a table-header.
174487 ** Specifically, to the following:
174488 **
174489 ** + number of columns in table (varint)
174490 ** + array of PK flags (1 byte per column),
174491 ** + table name (nul terminated).
174492 **
174493 ** This function decodes the table-header and populates the p->nCol,
174494 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
174495 ** also allocated or resized according to the new value of p->nCol. The
174496 ** input pointer is left pointing to the byte following the table header.
174497 **
174498 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
174499 ** is returned and the final values of the various fields enumerated above
174500 ** are undefined.
174501 */
174502 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
174503  int rc;
174504  int nCopy;
174505  assert( p->rc==SQLITE_OK );
174506 
174507  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
174508  if( rc==SQLITE_OK ){
174509  int nByte;
174510  int nVarint;
174511  nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
174512  nCopy -= nVarint;
174513  p->in.iNext += nVarint;
174514  nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
174515  p->tblhdr.nBuf = 0;
174516  sessionBufferGrow(&p->tblhdr, nByte, &rc);
174517  }
174518 
174519  if( rc==SQLITE_OK ){
174520  int iPK = sizeof(sqlite3_value*)*p->nCol*2;
174521  memset(p->tblhdr.aBuf, 0, iPK);
174522  memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
174523  p->in.iNext += nCopy;
174524  }
174525 
174526  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
174527  p->abPK = (u8*)&p->apValue[p->nCol*2];
174528  p->zTab = (char*)&p->abPK[p->nCol];
174529  return (p->rc = rc);
174530 }
174531 
174532 /*
174533 ** Advance the changeset iterator to the next change.
174534 **
174535 ** If both paRec and pnRec are NULL, then this function works like the public
174536 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
174537 ** sqlite3changeset_new() and old() APIs may be used to query for values.
174538 **
174539 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
174540 ** record is written to *paRec before returning and the number of bytes in
174541 ** the record to *pnRec.
174542 **
174543 ** Either way, this function returns SQLITE_ROW if the iterator is
174544 ** successfully advanced to the next change in the changeset, an SQLite
174545 ** error code if an error occurs, or SQLITE_DONE if there are no further
174546 ** changes in the changeset.
174547 */
174548 static int sessionChangesetNext(
174549  sqlite3_changeset_iter *p, /* Changeset iterator */
174550  u8 **paRec, /* If non-NULL, store record pointer here */
174551  int *pnRec /* If non-NULL, store size of record here */
174552 ){
174553  int i;
174554  u8 op;
174555 
174556  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
174557 
174558  /* If the iterator is in the error-state, return immediately. */
174559  if( p->rc!=SQLITE_OK ) return p->rc;
174560 
174561  /* Free the current contents of p->apValue[], if any. */
174562  if( p->apValue ){
174563  for(i=0; i<p->nCol*2; i++){
174564  sqlite3ValueFree(p->apValue[i]);
174565  }
174566  memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
174567  }
174568 
174569  /* Make sure the buffer contains at least 10 bytes of input data, or all
174570  ** remaining data if there are less than 10 bytes available. This is
174571  ** sufficient either for the 'T' or 'P' byte and the varint that follows
174572  ** it, or for the two single byte values otherwise. */
174573  p->rc = sessionInputBuffer(&p->in, 2);
174574  if( p->rc!=SQLITE_OK ) return p->rc;
174575 
174576  /* If the iterator is already at the end of the changeset, return DONE. */
174577  if( p->in.iNext>=p->in.nData ){
174578  return SQLITE_DONE;
174579  }
174580 
174581  sessionDiscardData(&p->in);
174582  p->in.iCurrent = p->in.iNext;
174583 
174584  op = p->in.aData[p->in.iNext++];
174585  if( op=='T' || op=='P' ){
174586  p->bPatchset = (op=='P');
174587  if( sessionChangesetReadTblhdr(p) ) return p->rc;
174588  if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
174589  p->in.iCurrent = p->in.iNext;
174590  op = p->in.aData[p->in.iNext++];
174591  }
174592 
174593  p->op = op;
174594  p->bIndirect = p->in.aData[p->in.iNext++];
174595  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
174596  return (p->rc = SQLITE_CORRUPT_BKPT);
174597  }
174598 
174599  if( paRec ){
174600  int nVal; /* Number of values to buffer */
174601  if( p->bPatchset==0 && op==SQLITE_UPDATE ){
174602  nVal = p->nCol * 2;
174603  }else if( p->bPatchset && op==SQLITE_DELETE ){
174604  nVal = 0;
174605  for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
174606  }else{
174607  nVal = p->nCol;
174608  }
174609  p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
174610  if( p->rc!=SQLITE_OK ) return p->rc;
174611  *paRec = &p->in.aData[p->in.iNext];
174612  p->in.iNext += *pnRec;
174613  }else{
174614 
174615  /* If this is an UPDATE or DELETE, read the old.* record. */
174616  if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
174617  u8 *abPK = p->bPatchset ? p->abPK : 0;
174618  p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
174619  if( p->rc!=SQLITE_OK ) return p->rc;
174620  }
174621 
174622  /* If this is an INSERT or UPDATE, read the new.* record. */
174623  if( p->op!=SQLITE_DELETE ){
174624  p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
174625  if( p->rc!=SQLITE_OK ) return p->rc;
174626  }
174627 
174628  if( p->bPatchset && p->op==SQLITE_UPDATE ){
174629  /* If this is an UPDATE that is part of a patchset, then all PK and
174630  ** modified fields are present in the new.* record. The old.* record
174631  ** is currently completely empty. This block shifts the PK fields from
174632  ** new.* to old.*, to accommodate the code that reads these arrays. */
174633  for(i=0; i<p->nCol; i++){
174634  assert( p->apValue[i]==0 );
174635  assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
174636  if( p->abPK[i] ){
174637  p->apValue[i] = p->apValue[i+p->nCol];
174638  p->apValue[i+p->nCol] = 0;
174639  }
174640  }
174641  }
174642  }
174643 
174644  return SQLITE_ROW;
174645 }
174646 
174647 /*
174648 ** Advance an iterator created by sqlite3changeset_start() to the next
174649 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
174650 ** or SQLITE_CORRUPT.
174651 **
174652 ** This function may not be called on iterators passed to a conflict handler
174653 ** callback by changeset_apply().
174654 */
174655 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
174656  return sessionChangesetNext(p, 0, 0);
174657 }
174658 
174659 /*
174660 ** The following function extracts information on the current change
174661 ** from a changeset iterator. It may only be called after changeset_next()
174662 ** has returned SQLITE_ROW.
174663 */
174664 SQLITE_API int sqlite3changeset_op(
174665  sqlite3_changeset_iter *pIter, /* Iterator handle */
174666  const char **pzTab, /* OUT: Pointer to table name */
174667  int *pnCol, /* OUT: Number of columns in table */
174668  int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
174669  int *pbIndirect /* OUT: True if change is indirect */
174670 ){
174671  *pOp = pIter->op;
174672  *pnCol = pIter->nCol;
174673  *pzTab = pIter->zTab;
174674  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
174675  return SQLITE_OK;
174676 }
174677 
174678 /*
174679 ** Return information regarding the PRIMARY KEY and number of columns in
174680 ** the database table affected by the change that pIter currently points
174681 ** to. This function may only be called after changeset_next() returns
174682 ** SQLITE_ROW.
174683 */
174684 SQLITE_API int sqlite3changeset_pk(
174685  sqlite3_changeset_iter *pIter, /* Iterator object */
174686  unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
174687  int *pnCol /* OUT: Number of entries in output array */
174688 ){
174689  *pabPK = pIter->abPK;
174690  if( pnCol ) *pnCol = pIter->nCol;
174691  return SQLITE_OK;
174692 }
174693 
174694 /*
174695 ** This function may only be called while the iterator is pointing to an
174696 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
174697 ** Otherwise, SQLITE_MISUSE is returned.
174698 **
174699 ** It sets *ppValue to point to an sqlite3_value structure containing the
174700 ** iVal'th value in the old.* record. Or, if that particular value is not
174701 ** included in the record (because the change is an UPDATE and the field
174702 ** was not modified and is not a PK column), set *ppValue to NULL.
174703 **
174704 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
174705 ** not modified. Otherwise, SQLITE_OK.
174706 */
174707 SQLITE_API int sqlite3changeset_old(
174708  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174709  int iVal, /* Index of old.* value to retrieve */
174710  sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
174711 ){
174712  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
174713  return SQLITE_MISUSE;
174714  }
174715  if( iVal<0 || iVal>=pIter->nCol ){
174716  return SQLITE_RANGE;
174717  }
174718  *ppValue = pIter->apValue[iVal];
174719  return SQLITE_OK;
174720 }
174721 
174722 /*
174723 ** This function may only be called while the iterator is pointing to an
174724 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
174725 ** Otherwise, SQLITE_MISUSE is returned.
174726 **
174727 ** It sets *ppValue to point to an sqlite3_value structure containing the
174728 ** iVal'th value in the new.* record. Or, if that particular value is not
174729 ** included in the record (because the change is an UPDATE and the field
174730 ** was not modified), set *ppValue to NULL.
174731 **
174732 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
174733 ** not modified. Otherwise, SQLITE_OK.
174734 */
174735 SQLITE_API int sqlite3changeset_new(
174736  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174737  int iVal, /* Index of new.* value to retrieve */
174738  sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
174739 ){
174740  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
174741  return SQLITE_MISUSE;
174742  }
174743  if( iVal<0 || iVal>=pIter->nCol ){
174744  return SQLITE_RANGE;
174745  }
174746  *ppValue = pIter->apValue[pIter->nCol+iVal];
174747  return SQLITE_OK;
174748 }
174749 
174750 /*
174751 ** The following two macros are used internally. They are similar to the
174752 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
174753 ** they omit all error checking and return a pointer to the requested value.
174754 */
174755 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
174756 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
174757 
174758 /*
174759 ** This function may only be called with a changeset iterator that has been
174760 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
174761 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
174762 **
174763 ** If successful, *ppValue is set to point to an sqlite3_value structure
174764 ** containing the iVal'th value of the conflicting record.
174765 **
174766 ** If value iVal is out-of-range or some other error occurs, an SQLite error
174767 ** code is returned. Otherwise, SQLITE_OK.
174768 */
174769 SQLITE_API int sqlite3changeset_conflict(
174770  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174771  int iVal, /* Index of conflict record value to fetch */
174772  sqlite3_value **ppValue /* OUT: Value from conflicting row */
174773 ){
174774  if( !pIter->pConflict ){
174775  return SQLITE_MISUSE;
174776  }
174777  if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
174778  return SQLITE_RANGE;
174779  }
174780  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
174781  return SQLITE_OK;
174782 }
174783 
174784 /*
174785 ** This function may only be called with an iterator passed to an
174786 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
174787 ** it sets the output variable to the total number of known foreign key
174788 ** violations in the destination database and returns SQLITE_OK.
174789 **
174790 ** In all other cases this function returns SQLITE_MISUSE.
174791 */
174792 SQLITE_API int sqlite3changeset_fk_conflicts(
174793  sqlite3_changeset_iter *pIter, /* Changeset iterator */
174794  int *pnOut /* OUT: Number of FK violations */
174795 ){
174796  if( pIter->pConflict || pIter->apValue ){
174797  return SQLITE_MISUSE;
174798  }
174799  *pnOut = pIter->nCol;
174800  return SQLITE_OK;
174801 }
174802 
174803 
174804 /*
174805 ** Finalize an iterator allocated with sqlite3changeset_start().
174806 **
174807 ** This function may not be called on iterators passed to a conflict handler
174808 ** callback by changeset_apply().
174809 */
174810 SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
174811  int rc = SQLITE_OK;
174812  if( p ){
174813  int i; /* Used to iterate through p->apValue[] */
174814  rc = p->rc;
174815  if( p->apValue ){
174816  for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
174817  }
174818  sqlite3_free(p->tblhdr.aBuf);
174819  sqlite3_free(p->in.buf.aBuf);
174820  sqlite3_free(p);
174821  }
174822  return rc;
174823 }
174824 
174825 static int sessionChangesetInvert(
174826  SessionInput *pInput, /* Input changeset */
174827  int (*xOutput)(void *pOut, const void *pData, int nData),
174828  void *pOut,
174829  int *pnInverted, /* OUT: Number of bytes in output changeset */
174830  void **ppInverted /* OUT: Inverse of pChangeset */
174831 ){
174832  int rc = SQLITE_OK; /* Return value */
174833  SessionBuffer sOut; /* Output buffer */
174834  int nCol = 0; /* Number of cols in current table */
174835  u8 *abPK = 0; /* PK array for current table */
174836  sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
174837  SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
174838 
174839  /* Initialize the output buffer */
174840  memset(&sOut, 0, sizeof(SessionBuffer));
174841 
174842  /* Zero the output variables in case an error occurs. */
174843  if( ppInverted ){
174844  *ppInverted = 0;
174845  *pnInverted = 0;
174846  }
174847 
174848  while( 1 ){
174849  u8 eType;
174850 
174851  /* Test for EOF. */
174852  if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
174853  if( pInput->iNext>=pInput->nData ) break;
174854  eType = pInput->aData[pInput->iNext];
174855 
174856  switch( eType ){
174857  case 'T': {
174858  /* A 'table' record consists of:
174859  **
174860  ** * A constant 'T' character,
174861  ** * Number of columns in said table (a varint),
174862  ** * An array of nCol bytes (sPK),
174863  ** * A nul-terminated table name.
174864  */
174865  int nByte;
174866  int nVar;
174867  pInput->iNext++;
174868  if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
174869  goto finished_invert;
174870  }
174871  nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
174872  sPK.nBuf = 0;
174873  sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
174874  sessionAppendByte(&sOut, eType, &rc);
174875  sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
174876  if( rc ) goto finished_invert;
174877 
174878  pInput->iNext += nByte;
174879  sqlite3_free(apVal);
174880  apVal = 0;
174881  abPK = sPK.aBuf;
174882  break;
174883  }
174884 
174885  case SQLITE_INSERT:
174886  case SQLITE_DELETE: {
174887  int nByte;
174888  int bIndirect = pInput->aData[pInput->iNext+1];
174889  int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
174890  pInput->iNext += 2;
174891  assert( rc==SQLITE_OK );
174892  rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
174893  sessionAppendByte(&sOut, eType2, &rc);
174894  sessionAppendByte(&sOut, bIndirect, &rc);
174895  sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
174896  pInput->iNext += nByte;
174897  if( rc ) goto finished_invert;
174898  break;
174899  }
174900 
174901  case SQLITE_UPDATE: {
174902  int iCol;
174903 
174904  if( 0==apVal ){
174905  apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
174906  if( 0==apVal ){
174907  rc = SQLITE_NOMEM;
174908  goto finished_invert;
174909  }
174910  memset(apVal, 0, sizeof(apVal[0])*nCol*2);
174911  }
174912 
174913  /* Write the header for the new UPDATE change. Same as the original. */
174914  sessionAppendByte(&sOut, eType, &rc);
174915  sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
174916 
174917  /* Read the old.* and new.* records for the update change. */
174918  pInput->iNext += 2;
174919  rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
174920  if( rc==SQLITE_OK ){
174921  rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
174922  }
174923 
174924  /* Write the new old.* record. Consists of the PK columns from the
174925  ** original old.* record, and the other values from the original
174926  ** new.* record. */
174927  for(iCol=0; iCol<nCol; iCol++){
174928  sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
174929  sessionAppendValue(&sOut, pVal, &rc);
174930  }
174931 
174932  /* Write the new new.* record. Consists of a copy of all values
174933  ** from the original old.* record, except for the PK columns, which
174934  ** are set to "undefined". */
174935  for(iCol=0; iCol<nCol; iCol++){
174936  sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
174937  sessionAppendValue(&sOut, pVal, &rc);
174938  }
174939 
174940  for(iCol=0; iCol<nCol*2; iCol++){
174941  sqlite3ValueFree(apVal[iCol]);
174942  }
174943  memset(apVal, 0, sizeof(apVal[0])*nCol*2);
174944  if( rc!=SQLITE_OK ){
174945  goto finished_invert;
174946  }
174947 
174948  break;
174949  }
174950 
174951  default:
174952  rc = SQLITE_CORRUPT_BKPT;
174953  goto finished_invert;
174954  }
174955 
174956  assert( rc==SQLITE_OK );
174957  if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
174958  rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
174959  sOut.nBuf = 0;
174960  if( rc!=SQLITE_OK ) goto finished_invert;
174961  }
174962  }
174963 
174964  assert( rc==SQLITE_OK );
174965  if( pnInverted ){
174966  *pnInverted = sOut.nBuf;
174967  *ppInverted = sOut.aBuf;
174968  sOut.aBuf = 0;
174969  }else if( sOut.nBuf>0 ){
174970  rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
174971  }
174972 
174973  finished_invert:
174974  sqlite3_free(sOut.aBuf);
174975  sqlite3_free(apVal);
174976  sqlite3_free(sPK.aBuf);
174977  return rc;
174978 }
174979 
174980 
174981 /*
174982 ** Invert a changeset object.
174983 */
174984 SQLITE_API int sqlite3changeset_invert(
174985  int nChangeset, /* Number of bytes in input */
174986  const void *pChangeset, /* Input changeset */
174987  int *pnInverted, /* OUT: Number of bytes in output changeset */
174988  void **ppInverted /* OUT: Inverse of pChangeset */
174989 ){
174990  SessionInput sInput;
174991 
174992  /* Set up the input stream */
174993  memset(&sInput, 0, sizeof(SessionInput));
174994  sInput.nData = nChangeset;
174995  sInput.aData = (u8*)pChangeset;
174996 
174997  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
174998 }
174999 
175000 /*
175001 ** Streaming version of sqlite3changeset_invert().
175002 */
175003 SQLITE_API int sqlite3changeset_invert_strm(
175004  int (*xInput)(void *pIn, void *pData, int *pnData),
175005  void *pIn,
175006  int (*xOutput)(void *pOut, const void *pData, int nData),
175007  void *pOut
175008 ){
175009  SessionInput sInput;
175010  int rc;
175011 
175012  /* Set up the input stream */
175013  memset(&sInput, 0, sizeof(SessionInput));
175014  sInput.xInput = xInput;
175015  sInput.pIn = pIn;
175016 
175017  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
175018  sqlite3_free(sInput.buf.aBuf);
175019  return rc;
175020 }
175021 
175022 typedef struct SessionApplyCtx SessionApplyCtx;
175023 struct SessionApplyCtx {
175024  sqlite3 *db;
175025  sqlite3_stmt *pDelete; /* DELETE statement */
175026  sqlite3_stmt *pUpdate; /* UPDATE statement */
175027  sqlite3_stmt *pInsert; /* INSERT statement */
175028  sqlite3_stmt *pSelect; /* SELECT statement */
175029  int nCol; /* Size of azCol[] and abPK[] arrays */
175030  const char **azCol; /* Array of column names */
175031  u8 *abPK; /* Boolean array - true if column is in PK */
175032 
175033  int bDeferConstraints; /* True to defer constraints */
175034  SessionBuffer constraints; /* Deferred constraints are stored here */
175035 };
175036 
175037 /*
175038 ** Formulate a statement to DELETE a row from database db. Assuming a table
175039 ** structure like this:
175040 **
175041 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
175042 **
175043 ** The DELETE statement looks like this:
175044 **
175045 ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
175046 **
175047 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
175048 ** matching b and d values, or 1 otherwise. The second case comes up if the
175049 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
175050 **
175051 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
175052 ** pointing to the prepared version of the SQL statement.
175053 */
175054 static int sessionDeleteRow(
175055  sqlite3 *db, /* Database handle */
175056  const char *zTab, /* Table name */
175057  SessionApplyCtx *p /* Session changeset-apply context */
175058 ){
175059  int i;
175060  const char *zSep = "";
175061  int rc = SQLITE_OK;
175062  SessionBuffer buf = {0, 0, 0};
175063  int nPk = 0;
175064 
175065  sessionAppendStr(&buf, "DELETE FROM ", &rc);
175066  sessionAppendIdent(&buf, zTab, &rc);
175067  sessionAppendStr(&buf, " WHERE ", &rc);
175068 
175069  for(i=0; i<p->nCol; i++){
175070  if( p->abPK[i] ){
175071  nPk++;
175072  sessionAppendStr(&buf, zSep, &rc);
175073  sessionAppendIdent(&buf, p->azCol[i], &rc);
175074  sessionAppendStr(&buf, " = ?", &rc);
175075  sessionAppendInteger(&buf, i+1, &rc);
175076  zSep = " AND ";
175077  }
175078  }
175079 
175080  if( nPk<p->nCol ){
175081  sessionAppendStr(&buf, " AND (?", &rc);
175082  sessionAppendInteger(&buf, p->nCol+1, &rc);
175083  sessionAppendStr(&buf, " OR ", &rc);
175084 
175085  zSep = "";
175086  for(i=0; i<p->nCol; i++){
175087  if( !p->abPK[i] ){
175088  sessionAppendStr(&buf, zSep, &rc);
175089  sessionAppendIdent(&buf, p->azCol[i], &rc);
175090  sessionAppendStr(&buf, " IS ?", &rc);
175091  sessionAppendInteger(&buf, i+1, &rc);
175092  zSep = "AND ";
175093  }
175094  }
175095  sessionAppendStr(&buf, ")", &rc);
175096  }
175097 
175098  if( rc==SQLITE_OK ){
175099  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
175100  }
175101  sqlite3_free(buf.aBuf);
175102 
175103  return rc;
175104 }
175105 
175106 /*
175107 ** Formulate and prepare a statement to UPDATE a row from database db.
175108 ** Assuming a table structure like this:
175109 **
175110 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
175111 **
175112 ** The UPDATE statement looks like this:
175113 **
175114 ** UPDATE x SET
175115 ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
175116 ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
175117 ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
175118 ** d = CASE WHEN ?11 THEN ?12 ELSE d END
175119 ** WHERE a = ?1 AND c = ?7 AND (?13 OR
175120 ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
175121 ** )
175122 **
175123 ** For each column in the table, there are three variables to bind:
175124 **
175125 ** ?(i*3+1) The old.* value of the column, if any.
175126 ** ?(i*3+2) A boolean flag indicating that the value is being modified.
175127 ** ?(i*3+3) The new.* value of the column, if any.
175128 **
175129 ** Also, a boolean flag that, if set to true, causes the statement to update
175130 ** a row even if the non-PK values do not match. This is required if the
175131 ** conflict-handler is invoked with CHANGESET_DATA and returns
175132 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
175133 **
175134 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
175135 ** pointing to the prepared version of the SQL statement.
175136 */
175137 static int sessionUpdateRow(
175138  sqlite3 *db, /* Database handle */
175139  const char *zTab, /* Table name */
175140  SessionApplyCtx *p /* Session changeset-apply context */
175141 ){
175142  int rc = SQLITE_OK;
175143  int i;
175144  const char *zSep = "";
175145  SessionBuffer buf = {0, 0, 0};
175146 
175147  /* Append "UPDATE tbl SET " */
175148  sessionAppendStr(&buf, "UPDATE ", &rc);
175149  sessionAppendIdent(&buf, zTab, &rc);
175150  sessionAppendStr(&buf, " SET ", &rc);
175151 
175152  /* Append the assignments */
175153  for(i=0; i<p->nCol; i++){
175154  sessionAppendStr(&buf, zSep, &rc);
175155  sessionAppendIdent(&buf, p->azCol[i], &rc);
175156  sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
175157  sessionAppendInteger(&buf, i*3+2, &rc);
175158  sessionAppendStr(&buf, " THEN ?", &rc);
175159  sessionAppendInteger(&buf, i*3+3, &rc);
175160  sessionAppendStr(&buf, " ELSE ", &rc);
175161  sessionAppendIdent(&buf, p->azCol[i], &rc);
175162  sessionAppendStr(&buf, " END", &rc);
175163  zSep = ", ";
175164  }
175165 
175166  /* Append the PK part of the WHERE clause */
175167  sessionAppendStr(&buf, " WHERE ", &rc);
175168  for(i=0; i<p->nCol; i++){
175169  if( p->abPK[i] ){
175170  sessionAppendIdent(&buf, p->azCol[i], &rc);
175171  sessionAppendStr(&buf, " = ?", &rc);
175172  sessionAppendInteger(&buf, i*3+1, &rc);
175173  sessionAppendStr(&buf, " AND ", &rc);
175174  }
175175  }
175176 
175177  /* Append the non-PK part of the WHERE clause */
175178  sessionAppendStr(&buf, " (?", &rc);
175179  sessionAppendInteger(&buf, p->nCol*3+1, &rc);
175180  sessionAppendStr(&buf, " OR 1", &rc);
175181  for(i=0; i<p->nCol; i++){
175182  if( !p->abPK[i] ){
175183  sessionAppendStr(&buf, " AND (?", &rc);
175184  sessionAppendInteger(&buf, i*3+2, &rc);
175185  sessionAppendStr(&buf, "=0 OR ", &rc);
175186  sessionAppendIdent(&buf, p->azCol[i], &rc);
175187  sessionAppendStr(&buf, " IS ?", &rc);
175188  sessionAppendInteger(&buf, i*3+1, &rc);
175189  sessionAppendStr(&buf, ")", &rc);
175190  }
175191  }
175192  sessionAppendStr(&buf, ")", &rc);
175193 
175194  if( rc==SQLITE_OK ){
175195  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
175196  }
175197  sqlite3_free(buf.aBuf);
175198 
175199  return rc;
175200 }
175201 
175202 /*
175203 ** Formulate and prepare an SQL statement to query table zTab by primary
175204 ** key. Assuming the following table structure:
175205 **
175206 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
175207 **
175208 ** The SELECT statement looks like this:
175209 **
175210 ** SELECT * FROM x WHERE a = ?1 AND c = ?3
175211 **
175212 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
175213 ** pointing to the prepared version of the SQL statement.
175214 */
175215 static int sessionSelectRow(
175216  sqlite3 *db, /* Database handle */
175217  const char *zTab, /* Table name */
175218  SessionApplyCtx *p /* Session changeset-apply context */
175219 ){
175220  return sessionSelectStmt(
175221  db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
175222 }
175223 
175224 /*
175225 ** Formulate and prepare an INSERT statement to add a record to table zTab.
175226 ** For example:
175227 **
175228 ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
175229 **
175230 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
175231 ** pointing to the prepared version of the SQL statement.
175232 */
175233 static int sessionInsertRow(
175234  sqlite3 *db, /* Database handle */
175235  const char *zTab, /* Table name */
175236  SessionApplyCtx *p /* Session changeset-apply context */
175237 ){
175238  int rc = SQLITE_OK;
175239  int i;
175240  SessionBuffer buf = {0, 0, 0};
175241 
175242  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
175243  sessionAppendIdent(&buf, zTab, &rc);
175244  sessionAppendStr(&buf, " VALUES(?", &rc);
175245  for(i=1; i<p->nCol; i++){
175246  sessionAppendStr(&buf, ", ?", &rc);
175247  }
175248  sessionAppendStr(&buf, ")", &rc);
175249 
175250  if( rc==SQLITE_OK ){
175251  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
175252  }
175253  sqlite3_free(buf.aBuf);
175254  return rc;
175255 }
175256 
175257 /*
175258 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
175259 ** See comments in the body of this function for details.
175260 */
175261 static int sessionBindValue(
175262  sqlite3_stmt *pStmt, /* Statement to bind value to */
175263  int i, /* Parameter number to bind to */
175264  sqlite3_value *pVal /* Value to bind */
175265 ){
175266  int eType = sqlite3_value_type(pVal);
175267  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
175268  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
175269  ** the (pVal->z) variable remains as it was or the type of the value is
175270  ** set to SQLITE_NULL. */
175271  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
175272  /* This condition occurs when an earlier OOM in a call to
175273  ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
175274  ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
175275  return SQLITE_NOMEM;
175276  }
175277  return sqlite3_bind_value(pStmt, i, pVal);
175278 }
175279 
175280 /*
175281 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
175282 ** transfers new.* values from the current iterator entry to statement
175283 ** pStmt. The table being inserted into has nCol columns.
175284 **
175285 ** New.* value $i from the iterator is bound to variable ($i+1) of
175286 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
175287 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
175288 ** to an array nCol elements in size. In this case only those values for
175289 ** which abPK[$i] is true are read from the iterator and bound to the
175290 ** statement.
175291 **
175292 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
175293 */
175294 static int sessionBindRow(
175295  sqlite3_changeset_iter *pIter, /* Iterator to read values from */
175296  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
175297  int nCol, /* Number of columns */
175298  u8 *abPK, /* If not NULL, bind only if true */
175299  sqlite3_stmt *pStmt /* Bind values to this statement */
175300 ){
175301  int i;
175302  int rc = SQLITE_OK;
175303 
175304  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
175305  ** argument iterator points to a suitable entry. Make sure that xValue
175306  ** is one of these to guarantee that it is safe to ignore the return
175307  ** in the code below. */
175308  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
175309 
175310  for(i=0; rc==SQLITE_OK && i<nCol; i++){
175311  if( !abPK || abPK[i] ){
175312  sqlite3_value *pVal;
175313  (void)xValue(pIter, i, &pVal);
175314  rc = sessionBindValue(pStmt, i+1, pVal);
175315  }
175316  }
175317  return rc;
175318 }
175319 
175320 /*
175321 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
175322 ** This function binds the primary key values from the change that changeset
175323 ** iterator pIter points to to the SELECT and attempts to seek to the table
175324 ** entry. If a row is found, the SELECT statement left pointing at the row
175325 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
175326 ** has occured, the statement is reset and SQLITE_OK is returned. If an
175327 ** error occurs, the statement is reset and an SQLite error code is returned.
175328 **
175329 ** If this function returns SQLITE_ROW, the caller must eventually reset()
175330 ** statement pSelect. If any other value is returned, the statement does
175331 ** not require a reset().
175332 **
175333 ** If the iterator currently points to an INSERT record, bind values from the
175334 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
175335 ** UPDATE, bind values from the old.* record.
175336 */
175337 static int sessionSeekToRow(
175338  sqlite3 *db, /* Database handle */
175339  sqlite3_changeset_iter *pIter, /* Changeset iterator */
175340  u8 *abPK, /* Primary key flags array */
175341  sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
175342 ){
175343  int rc; /* Return code */
175344  int nCol; /* Number of columns in table */
175345  int op; /* Changset operation (SQLITE_UPDATE etc.) */
175346  const char *zDummy; /* Unused */
175347 
175348  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
175349  rc = sessionBindRow(pIter,
175350  op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
175351  nCol, abPK, pSelect
175352  );
175353 
175354  if( rc==SQLITE_OK ){
175355  rc = sqlite3_step(pSelect);
175356  if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
175357  }
175358 
175359  return rc;
175360 }
175361 
175362 /*
175363 ** Invoke the conflict handler for the change that the changeset iterator
175364 ** currently points to.
175365 **
175366 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
175367 ** If argument pbReplace is NULL, then the type of conflict handler invoked
175368 ** depends solely on eType, as follows:
175369 **
175370 ** eType value Value passed to xConflict
175371 ** -------------------------------------------------
175372 ** CHANGESET_DATA CHANGESET_NOTFOUND
175373 ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
175374 **
175375 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
175376 ** record with the same primary key as the record about to be deleted, updated
175377 ** or inserted. If such a record can be found, it is available to the conflict
175378 ** handler as the "conflicting" record. In this case the type of conflict
175379 ** handler invoked is as follows:
175380 **
175381 ** eType value PK Record found? Value passed to xConflict
175382 ** ----------------------------------------------------------------
175383 ** CHANGESET_DATA Yes CHANGESET_DATA
175384 ** CHANGESET_DATA No CHANGESET_NOTFOUND
175385 ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
175386 ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
175387 **
175388 ** If pbReplace is not NULL, and a record with a matching PK is found, and
175389 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
175390 ** is set to non-zero before returning SQLITE_OK.
175391 **
175392 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
175393 ** returned. Or, if the conflict handler returns an invalid value,
175394 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
175395 ** this function returns SQLITE_OK.
175396 */
175397 static int sessionConflictHandler(
175398  int eType, /* Either CHANGESET_DATA or CONFLICT */
175399  SessionApplyCtx *p, /* changeset_apply() context */
175400  sqlite3_changeset_iter *pIter, /* Changeset iterator */
175401  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
175402  void *pCtx, /* First argument for conflict handler */
175403  int *pbReplace /* OUT: Set to true if PK row is found */
175404 ){
175405  int res = 0; /* Value returned by conflict handler */
175406  int rc;
175407  int nCol;
175408  int op;
175409  const char *zDummy;
175410 
175411  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
175412 
175413  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
175414  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
175415  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
175416 
175417  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
175418  if( pbReplace ){
175419  rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
175420  }else{
175421  rc = SQLITE_OK;
175422  }
175423 
175424  if( rc==SQLITE_ROW ){
175425  /* There exists another row with the new.* primary key. */
175426  pIter->pConflict = p->pSelect;
175427  res = xConflict(pCtx, eType, pIter);
175428  pIter->pConflict = 0;
175429  rc = sqlite3_reset(p->pSelect);
175430  }else if( rc==SQLITE_OK ){
175431  if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
175432  /* Instead of invoking the conflict handler, append the change blob
175433  ** to the SessionApplyCtx.constraints buffer. */
175434  u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
175435  int nBlob = pIter->in.iNext - pIter->in.iCurrent;
175436  sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
175437  res = SQLITE_CHANGESET_OMIT;
175438  }else{
175439  /* No other row with the new.* primary key. */
175440  res = xConflict(pCtx, eType+1, pIter);
175441  if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
175442  }
175443  }
175444 
175445  if( rc==SQLITE_OK ){
175446  switch( res ){
175447  case SQLITE_CHANGESET_REPLACE:
175448  assert( pbReplace );
175449  *pbReplace = 1;
175450  break;
175451 
175452  case SQLITE_CHANGESET_OMIT:
175453  break;
175454 
175455  case SQLITE_CHANGESET_ABORT:
175456  rc = SQLITE_ABORT;
175457  break;
175458 
175459  default:
175460  rc = SQLITE_MISUSE;
175461  break;
175462  }
175463  }
175464 
175465  return rc;
175466 }
175467 
175468 /*
175469 ** Attempt to apply the change that the iterator passed as the first argument
175470 ** currently points to to the database. If a conflict is encountered, invoke
175471 ** the conflict handler callback.
175472 **
175473 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
175474 ** one is encountered, update or delete the row with the matching primary key
175475 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
175476 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
175477 ** to true before returning. In this case the caller will invoke this function
175478 ** again, this time with pbRetry set to NULL.
175479 **
175480 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
175481 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
175482 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
175483 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
175484 ** before retrying. In this case the caller attempts to remove the conflicting
175485 ** row before invoking this function again, this time with pbReplace set
175486 ** to NULL.
175487 **
175488 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
175489 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
175490 ** returned.
175491 */
175492 static int sessionApplyOneOp(
175493  sqlite3_changeset_iter *pIter, /* Changeset iterator */
175494  SessionApplyCtx *p, /* changeset_apply() context */
175495  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
175496  void *pCtx, /* First argument for the conflict handler */
175497  int *pbReplace, /* OUT: True to remove PK row and retry */
175498  int *pbRetry /* OUT: True to retry. */
175499 ){
175500  const char *zDummy;
175501  int op;
175502  int nCol;
175503  int rc = SQLITE_OK;
175504 
175505  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
175506  assert( p->azCol && p->abPK );
175507  assert( !pbReplace || *pbReplace==0 );
175508 
175509  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
175510 
175511  if( op==SQLITE_DELETE ){
175512 
175513  /* Bind values to the DELETE statement. If conflict handling is required,
175514  ** bind values for all columns and set bound variable (nCol+1) to true.
175515  ** Or, if conflict handling is not required, bind just the PK column
175516  ** values and, if it exists, set (nCol+1) to false. Conflict handling
175517  ** is not required if:
175518  **
175519  ** * this is a patchset, or
175520  ** * (pbRetry==0), or
175521  ** * all columns of the table are PK columns (in this case there is
175522  ** no (nCol+1) variable to bind to).
175523  */
175524  u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
175525  rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
175526  if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
175527  rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
175528  }
175529  if( rc!=SQLITE_OK ) return rc;
175530 
175531  sqlite3_step(p->pDelete);
175532  rc = sqlite3_reset(p->pDelete);
175533  if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
175534  rc = sessionConflictHandler(
175535  SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
175536  );
175537  }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
175538  rc = sessionConflictHandler(
175539  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
175540  );
175541  }
175542 
175543  }else if( op==SQLITE_UPDATE ){
175544  int i;
175545 
175546  /* Bind values to the UPDATE statement. */
175547  for(i=0; rc==SQLITE_OK && i<nCol; i++){
175548  sqlite3_value *pOld = sessionChangesetOld(pIter, i);
175549  sqlite3_value *pNew = sessionChangesetNew(pIter, i);
175550 
175551  sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
175552  if( pOld ){
175553  rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
175554  }
175555  if( rc==SQLITE_OK && pNew ){
175556  rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
175557  }
175558  }
175559  if( rc==SQLITE_OK ){
175560  sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
175561  }
175562  if( rc!=SQLITE_OK ) return rc;
175563 
175564  /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
175565  ** the result will be SQLITE_OK with 0 rows modified. */
175566  sqlite3_step(p->pUpdate);
175567  rc = sqlite3_reset(p->pUpdate);
175568 
175569  if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
175570  /* A NOTFOUND or DATA error. Search the table to see if it contains
175571  ** a row with a matching primary key. If so, this is a DATA conflict.
175572  ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
175573 
175574  rc = sessionConflictHandler(
175575  SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
175576  );
175577 
175578  }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
175579  /* This is always a CONSTRAINT conflict. */
175580  rc = sessionConflictHandler(
175581  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
175582  );
175583  }
175584 
175585  }else{
175586  assert( op==SQLITE_INSERT );
175587  rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
175588  if( rc!=SQLITE_OK ) return rc;
175589 
175590  sqlite3_step(p->pInsert);
175591  rc = sqlite3_reset(p->pInsert);
175592  if( (rc&0xff)==SQLITE_CONSTRAINT ){
175593  rc = sessionConflictHandler(
175594  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
175595  );
175596  }
175597  }
175598 
175599  return rc;
175600 }
175601 
175602 /*
175603 ** Attempt to apply the change that the iterator passed as the first argument
175604 ** currently points to to the database. If a conflict is encountered, invoke
175605 ** the conflict handler callback.
175606 **
175607 ** The difference between this function and sessionApplyOne() is that this
175608 ** function handles the case where the conflict-handler is invoked and
175609 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
175610 ** retried in some manner.
175611 */
175612 static int sessionApplyOneWithRetry(
175613  sqlite3 *db, /* Apply change to "main" db of this handle */
175614  sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
175615  SessionApplyCtx *pApply, /* Apply context */
175616  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
175617  void *pCtx /* First argument passed to xConflict */
175618 ){
175619  int bReplace = 0;
175620  int bRetry = 0;
175621  int rc;
175622 
175623  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
175624  assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
175625 
175626  /* If the bRetry flag is set, the change has not been applied due to an
175627  ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
175628  ** a row with the correct PK is present in the db, but one or more other
175629  ** fields do not contain the expected values) and the conflict handler
175630  ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
175631  ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
175632  ** the SQLITE_CHANGESET_DATA problem. */
175633  if( bRetry ){
175634  assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
175635  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
175636  }
175637 
175638  /* If the bReplace flag is set, the change is an INSERT that has not
175639  ** been performed because the database already contains a row with the
175640  ** specified primary key and the conflict handler returned
175641  ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
175642  ** before reattempting the INSERT. */
175643  else if( bReplace ){
175644  assert( pIter->op==SQLITE_INSERT );
175645  rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
175646  if( rc==SQLITE_OK ){
175647  rc = sessionBindRow(pIter,
175648  sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
175649  sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
175650  }
175651  if( rc==SQLITE_OK ){
175652  sqlite3_step(pApply->pDelete);
175653  rc = sqlite3_reset(pApply->pDelete);
175654  }
175655  if( rc==SQLITE_OK ){
175656  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
175657  }
175658  if( rc==SQLITE_OK ){
175659  rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
175660  }
175661  }
175662 
175663  return rc;
175664 }
175665 
175666 /*
175667 ** Retry the changes accumulated in the pApply->constraints buffer.
175668 */
175669 static int sessionRetryConstraints(
175670  sqlite3 *db,
175671  int bPatchset,
175672  const char *zTab,
175673  SessionApplyCtx *pApply,
175674  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
175675  void *pCtx /* First argument passed to xConflict */
175676 ){
175677  int rc = SQLITE_OK;
175678 
175679  while( pApply->constraints.nBuf ){
175680  sqlite3_changeset_iter *pIter2 = 0;
175681  SessionBuffer cons = pApply->constraints;
175682  memset(&pApply->constraints, 0, sizeof(SessionBuffer));
175683 
175684  rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
175685  if( rc==SQLITE_OK ){
175686  int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
175687  int rc2;
175688  pIter2->bPatchset = bPatchset;
175689  pIter2->zTab = (char*)zTab;
175690  pIter2->nCol = pApply->nCol;
175691  pIter2->abPK = pApply->abPK;
175692  sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
175693  pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
175694  if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
175695 
175696  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
175697  rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
175698  }
175699 
175700  rc2 = sqlite3changeset_finalize(pIter2);
175701  if( rc==SQLITE_OK ) rc = rc2;
175702  }
175703  assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
175704 
175705  sqlite3_free(cons.aBuf);
175706  if( rc!=SQLITE_OK ) break;
175707  if( pApply->constraints.nBuf>=cons.nBuf ){
175708  /* No progress was made on the last round. */
175709  pApply->bDeferConstraints = 0;
175710  }
175711  }
175712 
175713  return rc;
175714 }
175715 
175716 /*
175717 ** Argument pIter is a changeset iterator that has been initialized, but
175718 ** not yet passed to sqlite3changeset_next(). This function applies the
175719 ** changeset to the main database attached to handle "db". The supplied
175720 ** conflict handler callback is invoked to resolve any conflicts encountered
175721 ** while applying the change.
175722 */
175723 static int sessionChangesetApply(
175724  sqlite3 *db, /* Apply change to "main" db of this handle */
175725  sqlite3_changeset_iter *pIter, /* Changeset to apply */
175726  int(*xFilter)(
175727  void *pCtx, /* Copy of sixth arg to _apply() */
175728  const char *zTab /* Table name */
175729  ),
175730  int(*xConflict)(
175731  void *pCtx, /* Copy of fifth arg to _apply() */
175732  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
175733  sqlite3_changeset_iter *p /* Handle describing change and conflict */
175734  ),
175735  void *pCtx /* First argument passed to xConflict */
175736 ){
175737  int schemaMismatch = 0;
175738  int rc; /* Return code */
175739  const char *zTab = 0; /* Name of current table */
175740  int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
175741  SessionApplyCtx sApply; /* changeset_apply() context object */
175742  int bPatchset;
175743 
175744  assert( xConflict!=0 );
175745 
175746  pIter->in.bNoDiscard = 1;
175747  memset(&sApply, 0, sizeof(sApply));
175749  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
175750  if( rc==SQLITE_OK ){
175751  rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
175752  }
175753  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
175754  int nCol;
175755  int op;
175756  const char *zNew;
175757 
175758  sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
175759 
175760  if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
175761  u8 *abPK;
175762 
175763  rc = sessionRetryConstraints(
175764  db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
175765  );
175766  if( rc!=SQLITE_OK ) break;
175767 
175768  sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
175769  sqlite3_finalize(sApply.pDelete);
175770  sqlite3_finalize(sApply.pUpdate);
175771  sqlite3_finalize(sApply.pInsert);
175772  sqlite3_finalize(sApply.pSelect);
175773  memset(&sApply, 0, sizeof(sApply));
175774  sApply.db = db;
175775  sApply.bDeferConstraints = 1;
175776 
175777  /* If an xFilter() callback was specified, invoke it now. If the
175778  ** xFilter callback returns zero, skip this table. If it returns
175779  ** non-zero, proceed. */
175780  schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
175781  if( schemaMismatch ){
175782  zTab = sqlite3_mprintf("%s", zNew);
175783  if( zTab==0 ){
175784  rc = SQLITE_NOMEM;
175785  break;
175786  }
175787  nTab = (int)strlen(zTab);
175788  sApply.azCol = (const char **)zTab;
175789  }else{
175790  sqlite3changeset_pk(pIter, &abPK, 0);
175791  rc = sessionTableInfo(
175792  db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
175793  );
175794  if( rc!=SQLITE_OK ) break;
175795 
175796  if( sApply.nCol==0 ){
175797  schemaMismatch = 1;
175799  "sqlite3changeset_apply(): no such table: %s", zTab
175800  );
175801  }
175802  else if( sApply.nCol!=nCol ){
175803  schemaMismatch = 1;
175805  "sqlite3changeset_apply(): table %s has %d columns, expected %d",
175806  zTab, sApply.nCol, nCol
175807  );
175808  }
175809  else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
175810  schemaMismatch = 1;
175811  sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
175812  "primary key mismatch for table %s", zTab
175813  );
175814  }
175815  else if(
175816  (rc = sessionSelectRow(db, zTab, &sApply))
175817  || (rc = sessionUpdateRow(db, zTab, &sApply))
175818  || (rc = sessionDeleteRow(db, zTab, &sApply))
175819  || (rc = sessionInsertRow(db, zTab, &sApply))
175820  ){
175821  break;
175822  }
175823  nTab = sqlite3Strlen30(zTab);
175824  }
175825  }
175826 
175827  /* If there is a schema mismatch on the current table, proceed to the
175828  ** next change. A log message has already been issued. */
175829  if( schemaMismatch ) continue;
175830 
175831  rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
175832  }
175833 
175834  bPatchset = pIter->bPatchset;
175835  if( rc==SQLITE_OK ){
175836  rc = sqlite3changeset_finalize(pIter);
175837  }else{
175838  sqlite3changeset_finalize(pIter);
175839  }
175840 
175841  if( rc==SQLITE_OK ){
175842  rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
175843  }
175844 
175845  if( rc==SQLITE_OK ){
175846  int nFk, notUsed;
175847  sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
175848  if( nFk!=0 ){
175849  int res = SQLITE_CHANGESET_ABORT;
175850  sqlite3_changeset_iter sIter;
175851  memset(&sIter, 0, sizeof(sIter));
175852  sIter.nCol = nFk;
175853  res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
175854  if( res!=SQLITE_CHANGESET_OMIT ){
175855  rc = SQLITE_CONSTRAINT;
175856  }
175857  }
175858  }
175859  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
175860 
175861  if( rc==SQLITE_OK ){
175862  rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
175863  }else{
175864  sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
175865  sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
175866  }
175867 
175868  sqlite3_finalize(sApply.pInsert);
175869  sqlite3_finalize(sApply.pDelete);
175870  sqlite3_finalize(sApply.pUpdate);
175871  sqlite3_finalize(sApply.pSelect);
175872  sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
175873  sqlite3_free((char*)sApply.constraints.aBuf);
175875  return rc;
175876 }
175877 
175878 /*
175879 ** Apply the changeset passed via pChangeset/nChangeset to the main database
175880 ** attached to handle "db". Invoke the supplied conflict handler callback
175881 ** to resolve any conflicts encountered while applying the change.
175882 */
175883 SQLITE_API int sqlite3changeset_apply(
175884  sqlite3 *db, /* Apply change to "main" db of this handle */
175885  int nChangeset, /* Size of changeset in bytes */
175886  void *pChangeset, /* Changeset blob */
175887  int(*xFilter)(
175888  void *pCtx, /* Copy of sixth arg to _apply() */
175889  const char *zTab /* Table name */
175890  ),
175891  int(*xConflict)(
175892  void *pCtx, /* Copy of fifth arg to _apply() */
175893  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
175894  sqlite3_changeset_iter *p /* Handle describing change and conflict */
175895  ),
175896  void *pCtx /* First argument passed to xConflict */
175897 ){
175898  sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
175899  int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
175900  if( rc==SQLITE_OK ){
175901  rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
175902  }
175903  return rc;
175904 }
175905 
175906 /*
175907 ** Apply the changeset passed via xInput/pIn to the main database
175908 ** attached to handle "db". Invoke the supplied conflict handler callback
175909 ** to resolve any conflicts encountered while applying the change.
175910 */
175911 SQLITE_API int sqlite3changeset_apply_strm(
175912  sqlite3 *db, /* Apply change to "main" db of this handle */
175913  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
175914  void *pIn, /* First arg for xInput */
175915  int(*xFilter)(
175916  void *pCtx, /* Copy of sixth arg to _apply() */
175917  const char *zTab /* Table name */
175918  ),
175919  int(*xConflict)(
175920  void *pCtx, /* Copy of sixth arg to _apply() */
175921  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
175922  sqlite3_changeset_iter *p /* Handle describing change and conflict */
175923  ),
175924  void *pCtx /* First argument passed to xConflict */
175925 ){
175926  sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
175927  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
175928  if( rc==SQLITE_OK ){
175929  rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
175930  }
175931  return rc;
175932 }
175933 
175934 /*
175935 ** sqlite3_changegroup handle.
175936 */
175937 struct sqlite3_changegroup {
175938  int rc; /* Error code */
175939  int bPatch; /* True to accumulate patchsets */
175940  SessionTable *pList; /* List of tables in current patch */
175941 };
175942 
175943 /*
175944 ** This function is called to merge two changes to the same row together as
175945 ** part of an sqlite3changeset_concat() operation. A new change object is
175946 ** allocated and a pointer to it stored in *ppNew.
175947 */
175948 static int sessionChangeMerge(
175949  SessionTable *pTab, /* Table structure */
175950  int bPatchset, /* True for patchsets */
175951  SessionChange *pExist, /* Existing change */
175952  int op2, /* Second change operation */
175953  int bIndirect, /* True if second change is indirect */
175954  u8 *aRec, /* Second change record */
175955  int nRec, /* Number of bytes in aRec */
175956  SessionChange **ppNew /* OUT: Merged change */
175957 ){
175958  SessionChange *pNew = 0;
175959 
175960  if( !pExist ){
175961  pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
175962  if( !pNew ){
175963  return SQLITE_NOMEM;
175964  }
175965  memset(pNew, 0, sizeof(SessionChange));
175966  pNew->op = op2;
175967  pNew->bIndirect = bIndirect;
175968  pNew->nRecord = nRec;
175969  pNew->aRecord = (u8*)&pNew[1];
175970  memcpy(pNew->aRecord, aRec, nRec);
175971  }else{
175972  int op1 = pExist->op;
175973 
175974  /*
175975  ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
175976  ** op1=INSERT, op2=UPDATE -> INSERT.
175977  ** op1=INSERT, op2=DELETE -> (none)
175978  **
175979  ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
175980  ** op1=UPDATE, op2=UPDATE -> UPDATE.
175981  ** op1=UPDATE, op2=DELETE -> DELETE.
175982  **
175983  ** op1=DELETE, op2=INSERT -> UPDATE.
175984  ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
175985  ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
175986  */
175987  if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
175988  || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
175989  || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
175990  || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
175991  ){
175992  pNew = pExist;
175993  }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
175994  sqlite3_free(pExist);
175995  assert( pNew==0 );
175996  }else{
175997  u8 *aExist = pExist->aRecord;
175998  int nByte;
175999  u8 *aCsr;
176000 
176001  /* Allocate a new SessionChange object. Ensure that the aRecord[]
176002  ** buffer of the new object is large enough to hold any record that
176003  ** may be generated by combining the input records. */
176004  nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
176005  pNew = (SessionChange *)sqlite3_malloc(nByte);
176006  if( !pNew ){
176007  sqlite3_free(pExist);
176008  return SQLITE_NOMEM;
176009  }
176010  memset(pNew, 0, sizeof(SessionChange));
176011  pNew->bIndirect = (bIndirect && pExist->bIndirect);
176012  aCsr = pNew->aRecord = (u8 *)&pNew[1];
176013 
176014  if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
176015  u8 *a1 = aRec;
176016  assert( op2==SQLITE_UPDATE );
176017  pNew->op = SQLITE_INSERT;
176018  if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
176019  sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
176020  }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
176021  assert( op2==SQLITE_INSERT );
176022  pNew->op = SQLITE_UPDATE;
176023  if( bPatchset ){
176024  memcpy(aCsr, aRec, nRec);
176025  aCsr += nRec;
176026  }else{
176027  if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
176028  sqlite3_free(pNew);
176029  pNew = 0;
176030  }
176031  }
176032  }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
176033  u8 *a1 = aExist;
176034  u8 *a2 = aRec;
176035  assert( op1==SQLITE_UPDATE );
176036  if( bPatchset==0 ){
176037  sessionSkipRecord(&a1, pTab->nCol);
176038  sessionSkipRecord(&a2, pTab->nCol);
176039  }
176040  pNew->op = SQLITE_UPDATE;
176041  if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
176042  sqlite3_free(pNew);
176043  pNew = 0;
176044  }
176045  }else{ /* UPDATE + DELETE */
176046  assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
176047  pNew->op = SQLITE_DELETE;
176048  if( bPatchset ){
176049  memcpy(aCsr, aRec, nRec);
176050  aCsr += nRec;
176051  }else{
176052  sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
176053  }
176054  }
176055 
176056  if( pNew ){
176057  pNew->nRecord = (int)(aCsr - pNew->aRecord);
176058  }
176059  sqlite3_free(pExist);
176060  }
176061  }
176062 
176063  *ppNew = pNew;
176064  return SQLITE_OK;
176065 }
176066 
176067 /*
176068 ** Add all changes in the changeset traversed by the iterator passed as
176069 ** the first argument to the changegroup hash tables.
176070 */
176071 static int sessionChangesetToHash(
176072  sqlite3_changeset_iter *pIter, /* Iterator to read from */
176073  sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
176074 ){
176075  u8 *aRec;
176076  int nRec;
176077  int rc = SQLITE_OK;
176078  SessionTable *pTab = 0;
176079 
176080 
176081  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
176082  const char *zNew;
176083  int nCol;
176084  int op;
176085  int iHash;
176086  int bIndirect;
176087  SessionChange *pChange;
176088  SessionChange *pExist = 0;
176089  SessionChange **pp;
176090 
176091  if( pGrp->pList==0 ){
176092  pGrp->bPatch = pIter->bPatchset;
176093  }else if( pIter->bPatchset!=pGrp->bPatch ){
176094  rc = SQLITE_ERROR;
176095  break;
176096  }
176097 
176098  sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
176099  if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
176100  /* Search the list for a matching table */
176101  int nNew = (int)strlen(zNew);
176102  u8 *abPK;
176103 
176104  sqlite3changeset_pk(pIter, &abPK, 0);
176105  for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
176106  if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
176107  }
176108  if( !pTab ){
176109  SessionTable **ppTab;
176110 
176111  pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
176112  if( !pTab ){
176113  rc = SQLITE_NOMEM;
176114  break;
176115  }
176116  memset(pTab, 0, sizeof(SessionTable));
176117  pTab->nCol = nCol;
176118  pTab->abPK = (u8*)&pTab[1];
176119  memcpy(pTab->abPK, abPK, nCol);
176120  pTab->zName = (char*)&pTab->abPK[nCol];
176121  memcpy(pTab->zName, zNew, nNew+1);
176122 
176123  /* The new object must be linked on to the end of the list, not
176124  ** simply added to the start of it. This is to ensure that the
176125  ** tables within the output of sqlite3changegroup_output() are in
176126  ** the right order. */
176127  for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
176128  *ppTab = pTab;
176129  }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
176130  rc = SQLITE_SCHEMA;
176131  break;
176132  }
176133  }
176134 
176135  if( sessionGrowHash(pIter->bPatchset, pTab) ){
176136  rc = SQLITE_NOMEM;
176137  break;
176138  }
176139  iHash = sessionChangeHash(
176140  pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
176141  );
176142 
176143  /* Search for existing entry. If found, remove it from the hash table.
176144  ** Code below may link it back in.
176145  */
176146  for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
176147  int bPkOnly1 = 0;
176148  int bPkOnly2 = 0;
176149  if( pIter->bPatchset ){
176150  bPkOnly1 = (*pp)->op==SQLITE_DELETE;
176151  bPkOnly2 = op==SQLITE_DELETE;
176152  }
176153  if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
176154  pExist = *pp;
176155  *pp = (*pp)->pNext;
176156  pTab->nEntry--;
176157  break;
176158  }
176159  }
176160 
176161  rc = sessionChangeMerge(pTab,
176162  pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
176163  );
176164  if( rc ) break;
176165  if( pChange ){
176166  pChange->pNext = pTab->apChange[iHash];
176167  pTab->apChange[iHash] = pChange;
176168  pTab->nEntry++;
176169  }
176170  }
176171 
176172  if( rc==SQLITE_OK ) rc = pIter->rc;
176173  return rc;
176174 }
176175 
176176 /*
176177 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
176178 ** added to the changegroup object passed as the first argument.
176179 **
176180 ** If xOutput is not NULL, then the changeset/patchset is returned to the
176181 ** user via one or more calls to xOutput, as with the other streaming
176182 ** interfaces.
176183 **
176184 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
176185 ** buffer containing the output changeset before this function returns. In
176186 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
176187 ** is the responsibility of the caller to free the output buffer using
176188 ** sqlite3_free() when it is no longer required.
176189 **
176190 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
176191 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
176192 ** are both set to 0 before returning.
176193 */
176194 static int sessionChangegroupOutput(
176195  sqlite3_changegroup *pGrp,
176196  int (*xOutput)(void *pOut, const void *pData, int nData),
176197  void *pOut,
176198  int *pnOut,
176199  void **ppOut
176200 ){
176201  int rc = SQLITE_OK;
176202  SessionBuffer buf = {0, 0, 0};
176203  SessionTable *pTab;
176204  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
176205 
176206  /* Create the serialized output changeset based on the contents of the
176207  ** hash tables attached to the SessionTable objects in list p->pList.
176208  */
176209  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
176210  int i;
176211  if( pTab->nEntry==0 ) continue;
176212 
176213  sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
176214  for(i=0; i<pTab->nChange; i++){
176215  SessionChange *p;
176216  for(p=pTab->apChange[i]; p; p=p->pNext){
176217  sessionAppendByte(&buf, p->op, &rc);
176218  sessionAppendByte(&buf, p->bIndirect, &rc);
176219  sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
176220  }
176221  }
176222 
176223  if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
176224  rc = xOutput(pOut, buf.aBuf, buf.nBuf);
176225  buf.nBuf = 0;
176226  }
176227  }
176228 
176229  if( rc==SQLITE_OK ){
176230  if( xOutput ){
176231  if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
176232  }else{
176233  *ppOut = buf.aBuf;
176234  *pnOut = buf.nBuf;
176235  buf.aBuf = 0;
176236  }
176237  }
176238  sqlite3_free(buf.aBuf);
176239 
176240  return rc;
176241 }
176242 
176243 /*
176244 ** Allocate a new, empty, sqlite3_changegroup.
176245 */
176246 SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
176247  int rc = SQLITE_OK; /* Return code */
176248  sqlite3_changegroup *p; /* New object */
176249  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
176250  if( p==0 ){
176251  rc = SQLITE_NOMEM;
176252  }else{
176253  memset(p, 0, sizeof(sqlite3_changegroup));
176254  }
176255  *pp = p;
176256  return rc;
176257 }
176258 
176259 /*
176260 ** Add the changeset currently stored in buffer pData, size nData bytes,
176261 ** to changeset-group p.
176262 */
176263 SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
176264  sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
176265  int rc; /* Return code */
176266 
176267  rc = sqlite3changeset_start(&pIter, nData, pData);
176268  if( rc==SQLITE_OK ){
176269  rc = sessionChangesetToHash(pIter, pGrp);
176270  }
176271  sqlite3changeset_finalize(pIter);
176272  return rc;
176273 }
176274 
176275 /*
176276 ** Obtain a buffer containing a changeset representing the concatenation
176277 ** of all changesets added to the group so far.
176278 */
176279 SQLITE_API int sqlite3changegroup_output(
176280  sqlite3_changegroup *pGrp,
176281  int *pnData,
176282  void **ppData
176283 ){
176284  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
176285 }
176286 
176287 /*
176288 ** Streaming versions of changegroup_add().
176289 */
176290 SQLITE_API int sqlite3changegroup_add_strm(
176291  sqlite3_changegroup *pGrp,
176292  int (*xInput)(void *pIn, void *pData, int *pnData),
176293  void *pIn
176294 ){
176295  sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
176296  int rc; /* Return code */
176297 
176298  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
176299  if( rc==SQLITE_OK ){
176300  rc = sessionChangesetToHash(pIter, pGrp);
176301  }
176302  sqlite3changeset_finalize(pIter);
176303  return rc;
176304 }
176305 
176306 /*
176307 ** Streaming versions of changegroup_output().
176308 */
176309 SQLITE_API int sqlite3changegroup_output_strm(
176310  sqlite3_changegroup *pGrp,
176311  int (*xOutput)(void *pOut, const void *pData, int nData),
176312  void *pOut
176313 ){
176314  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
176315 }
176316 
176317 /*
176318 ** Delete a changegroup object.
176319 */
176320 SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
176321  if( pGrp ){
176322  sessionDeleteTable(pGrp->pList);
176323  sqlite3_free(pGrp);
176324  }
176325 }
176326 
176327 /*
176328 ** Combine two changesets together.
176329 */
176330 SQLITE_API int sqlite3changeset_concat(
176331  int nLeft, /* Number of bytes in lhs input */
176332  void *pLeft, /* Lhs input changeset */
176333  int nRight /* Number of bytes in rhs input */,
176334  void *pRight, /* Rhs input changeset */
176335  int *pnOut, /* OUT: Number of bytes in output changeset */
176336  void **ppOut /* OUT: changeset (left <concat> right) */
176337 ){
176338  sqlite3_changegroup *pGrp;
176339  int rc;
176340 
176341  rc = sqlite3changegroup_new(&pGrp);
176342  if( rc==SQLITE_OK ){
176343  rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
176344  }
176345  if( rc==SQLITE_OK ){
176346  rc = sqlite3changegroup_add(pGrp, nRight, pRight);
176347  }
176348  if( rc==SQLITE_OK ){
176349  rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
176350  }
176351  sqlite3changegroup_delete(pGrp);
176352 
176353  return rc;
176354 }
176355 
176356 /*
176357 ** Streaming version of sqlite3changeset_concat().
176358 */
176359 SQLITE_API int sqlite3changeset_concat_strm(
176360  int (*xInputA)(void *pIn, void *pData, int *pnData),
176361  void *pInA,
176362  int (*xInputB)(void *pIn, void *pData, int *pnData),
176363  void *pInB,
176364  int (*xOutput)(void *pOut, const void *pData, int nData),
176365  void *pOut
176366 ){
176367  sqlite3_changegroup *pGrp;
176368  int rc;
176369 
176370  rc = sqlite3changegroup_new(&pGrp);
176371  if( rc==SQLITE_OK ){
176372  rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
176373  }
176374  if( rc==SQLITE_OK ){
176375  rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
176376  }
176377  if( rc==SQLITE_OK ){
176378  rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
176379  }
176380  sqlite3changegroup_delete(pGrp);
176381 
176382  return rc;
176383 }
176384 
176385 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
176386 
176387 /************** End of sqlite3session.c **************************************/
176388 /************** Begin file json1.c *******************************************/
176389 /*
176390 ** 2015-08-12
176391 **
176392 ** The author disclaims copyright to this source code. In place of
176393 ** a legal notice, here is a blessing:
176394 **
176395 ** May you do good and not evil.
176396 ** May you find forgiveness for yourself and forgive others.
176397 ** May you share freely, never taking more than you give.
176398 **
176399 ******************************************************************************
176400 **
176401 ** This SQLite extension implements JSON functions. The interface is
176402 ** modeled after MySQL JSON functions:
176403 **
176404 ** https://dev.mysql.com/doc/refman/5.7/en/json.html
176405 **
176406 ** For the time being, all JSON is stored as pure text. (We might add
176407 ** a JSONB type in the future which stores a binary encoding of JSON in
176408 ** a BLOB, but there is no support for JSONB in the current implementation.
176409 ** This implementation parses JSON text at 250 MB/s, so it is hard to see
176410 ** how JSONB might improve on that.)
176411 */
176412 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
176413 #if !defined(_SQLITEINT_H_)
176414 /* #include "sqlite3ext.h" */
176415 #endif
176417 /* #include <assert.h> */
176418 /* #include <string.h> */
176419 /* #include <stdlib.h> */
176420 /* #include <stdarg.h> */
176421 
176422 /* Mark a function parameter as unused, to suppress nuisance compiler
176423 ** warnings. */
176424 #ifndef UNUSED_PARAM
176425 # define UNUSED_PARAM(X) (void)(X)
176426 #endif
176427 
176428 #ifndef LARGEST_INT64
176429 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
176430 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
176431 #endif
176432 
176433 /*
176434 ** Versions of isspace(), isalnum() and isdigit() to which it is safe
176435 ** to pass signed char values.
176436 */
176437 #ifdef sqlite3Isdigit
176438  /* Use the SQLite core versions if this routine is part of the
176439  ** SQLite amalgamation */
176440 # define safe_isdigit(x) sqlite3Isdigit(x)
176441 # define safe_isalnum(x) sqlite3Isalnum(x)
176442 # define safe_isxdigit(x) sqlite3Isxdigit(x)
176443 #else
176444  /* Use the standard library for separate compilation */
176445 #include <ctype.h> /* amalgamator: keep */
176446 # define safe_isdigit(x) isdigit((unsigned char)(x))
176447 # define safe_isalnum(x) isalnum((unsigned char)(x))
176448 # define safe_isxdigit(x) isxdigit((unsigned char)(x))
176449 #endif
176450 
176451 /*
176452 ** Growing our own isspace() routine this way is twice as fast as
176453 ** the library isspace() function, resulting in a 7% overall performance
176454 ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
176455 */
176456 static const char jsonIsSpace[] = {
176457  0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
176458  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176459  1, 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  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176470  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176471  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176472  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
176473 };
176474 #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
176475 
176476 #ifndef SQLITE_AMALGAMATION
176477  /* Unsigned integer types. These are already defined in the sqliteInt.h,
176478  ** but the definitions need to be repeated for separate compilation. */
176479  typedef sqlite3_uint64 u64;
176480  typedef unsigned int u32;
176481  typedef unsigned char u8;
176482 #endif
176483 
176484 /* Objects */
176485 typedef struct JsonString JsonString;
176486 typedef struct JsonNode JsonNode;
176487 typedef struct JsonParse JsonParse;
176488 
176489 /* An instance of this object represents a JSON string
176490 ** under construction. Really, this is a generic string accumulator
176491 ** that can be and is used to create strings other than JSON.
176492 */
176493 struct JsonString {
176494  sqlite3_context *pCtx; /* Function context - put error messages here */
176495  char *zBuf; /* Append JSON content here */
176496  u64 nAlloc; /* Bytes of storage available in zBuf[] */
176497  u64 nUsed; /* Bytes of zBuf[] currently used */
176498  u8 bStatic; /* True if zBuf is static space */
176499  u8 bErr; /* True if an error has been encountered */
176500  char zSpace[100]; /* Initial static space */
176501 };
176502 
176503 /* JSON type values
176504 */
176505 #define JSON_NULL 0
176506 #define JSON_TRUE 1
176507 #define JSON_FALSE 2
176508 #define JSON_INT 3
176509 #define JSON_REAL 4
176510 #define JSON_STRING 5
176511 #define JSON_ARRAY 6
176512 #define JSON_OBJECT 7
176513 
176514 /* The "subtype" set for JSON values */
176515 #define JSON_SUBTYPE 74 /* Ascii for "J" */
176516 
176517 /*
176518 ** Names of the various JSON types:
176519 */
176520 static const char * const jsonType[] = {
176521  "null", "true", "false", "integer", "real", "text", "array", "object"
176522 };
176523 
176524 /* Bit values for the JsonNode.jnFlag field
176525 */
176526 #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
176527 #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
176528 #define JNODE_REMOVE 0x04 /* Do not output */
176529 #define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
176530 #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
176531 #define JNODE_LABEL 0x20 /* Is a label of an object */
176532 
176533 
176534 /* A single node of parsed JSON
176535 */
176536 struct JsonNode {
176537  u8 eType; /* One of the JSON_ type values */
176538  u8 jnFlags; /* JNODE flags */
176539  u8 iVal; /* Replacement value when JNODE_REPLACE */
176540  u32 n; /* Bytes of content, or number of sub-nodes */
176541  union {
176542  const char *zJContent; /* Content for INT, REAL, and STRING */
176543  u32 iAppend; /* More terms for ARRAY and OBJECT */
176544  u32 iKey; /* Key for ARRAY objects in json_tree() */
176545  } u;
176546 };
176547 
176548 /* A completely parsed JSON string
176549 */
176550 struct JsonParse {
176551  u32 nNode; /* Number of slots of aNode[] used */
176552  u32 nAlloc; /* Number of slots of aNode[] allocated */
176553  JsonNode *aNode; /* Array of nodes containing the parse */
176554  const char *zJson; /* Original JSON string */
176555  u32 *aUp; /* Index of parent of each node */
176556  u8 oom; /* Set to true if out of memory */
176557  u8 nErr; /* Number of errors seen */
176558 };
176559 
176560 /**************************************************************************
176561 ** Utility routines for dealing with JsonString objects
176562 **************************************************************************/
176563 
176564 /* Set the JsonString object to an empty string
176565 */
176566 static void jsonZero(JsonString *p){
176567  p->zBuf = p->zSpace;
176568  p->nAlloc = sizeof(p->zSpace);
176569  p->nUsed = 0;
176570  p->bStatic = 1;
176571 }
176572 
176573 /* Initialize the JsonString object
176574 */
176575 static void jsonInit(JsonString *p, sqlite3_context *pCtx){
176576  p->pCtx = pCtx;
176577  p->bErr = 0;
176578  jsonZero(p);
176579 }
176580 
176581 
176582 /* Free all allocated memory and reset the JsonString object back to its
176583 ** initial state.
176584 */
176585 static void jsonReset(JsonString *p){
176586  if( !p->bStatic ) sqlite3_free(p->zBuf);
176587  jsonZero(p);
176588 }
176589 
176590 
176591 /* Report an out-of-memory (OOM) condition
176592 */
176593 static void jsonOom(JsonString *p){
176594  p->bErr = 1;
176595  sqlite3_result_error_nomem(p->pCtx);
176596  jsonReset(p);
176597 }
176598 
176599 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
176600 ** Return zero on success. Return non-zero on an OOM error
176601 */
176602 static int jsonGrow(JsonString *p, u32 N){
176603  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
176604  char *zNew;
176605  if( p->bStatic ){
176606  if( p->bErr ) return 1;
176607  zNew = sqlite3_malloc64(nTotal);
176608  if( zNew==0 ){
176609  jsonOom(p);
176610  return SQLITE_NOMEM;
176611  }
176612  memcpy(zNew, p->zBuf, (size_t)p->nUsed);
176613  p->zBuf = zNew;
176614  p->bStatic = 0;
176615  }else{
176616  zNew = sqlite3_realloc64(p->zBuf, nTotal);
176617  if( zNew==0 ){
176618  jsonOom(p);
176619  return SQLITE_NOMEM;
176620  }
176621  p->zBuf = zNew;
176622  }
176623  p->nAlloc = nTotal;
176624  return SQLITE_OK;
176625 }
176626 
176627 /* Append N bytes from zIn onto the end of the JsonString string.
176628 */
176629 static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
176630  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
176631  memcpy(p->zBuf+p->nUsed, zIn, N);
176632  p->nUsed += N;
176633 }
176634 
176635 /* Append formatted text (not to exceed N bytes) to the JsonString.
176636 */
176637 static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
176638  va_list ap;
176639  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
176640  va_start(ap, zFormat);
176641  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
176642  va_end(ap);
176643  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
176644 }
176645 
176646 /* Append a single character
176647 */
176648 static void jsonAppendChar(JsonString *p, char c){
176649  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
176650  p->zBuf[p->nUsed++] = c;
176651 }
176652 
176653 /* Append a comma separator to the output buffer, if the previous
176654 ** character is not '[' or '{'.
176655 */
176656 static void jsonAppendSeparator(JsonString *p){
176657  char c;
176658  if( p->nUsed==0 ) return;
176659  c = p->zBuf[p->nUsed-1];
176660  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
176661 }
176662 
176663 /* Append the N-byte string in zIn to the end of the JsonString string
176664 ** under construction. Enclose the string in "..." and escape
176665 ** any double-quotes or backslash characters contained within the
176666 ** string.
176667 */
176668 static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
176669  u32 i;
176670  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
176671  p->zBuf[p->nUsed++] = '"';
176672  for(i=0; i<N; i++){
176673  unsigned char c = ((unsigned const char*)zIn)[i];
176674  if( c=='"' || c=='\\' ){
176675  json_simple_escape:
176676  if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
176677  p->zBuf[p->nUsed++] = '\\';
176678  }else if( c<=0x1f ){
176679  static const char aSpecial[] = {
176680  0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
176681  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
176682  };
176683  assert( sizeof(aSpecial)==32 );
176684  assert( aSpecial['\b']=='b' );
176685  assert( aSpecial['\f']=='f' );
176686  assert( aSpecial['\n']=='n' );
176687  assert( aSpecial['\r']=='r' );
176688  assert( aSpecial['\t']=='t' );
176689  if( aSpecial[c] ){
176690  c = aSpecial[c];
176691  goto json_simple_escape;
176692  }
176693  if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
176694  p->zBuf[p->nUsed++] = '\\';
176695  p->zBuf[p->nUsed++] = 'u';
176696  p->zBuf[p->nUsed++] = '0';
176697  p->zBuf[p->nUsed++] = '0';
176698  p->zBuf[p->nUsed++] = '0' + (c>>4);
176699  c = "0123456789abcdef"[c&0xf];
176700  }
176701  p->zBuf[p->nUsed++] = c;
176702  }
176703  p->zBuf[p->nUsed++] = '"';
176704  assert( p->nUsed<p->nAlloc );
176705 }
176706 
176707 /*
176708 ** Append a function parameter value to the JSON string under
176709 ** construction.
176710 */
176711 static void jsonAppendValue(
176712  JsonString *p, /* Append to this JSON string */
176713  sqlite3_value *pValue /* Value to append */
176714 ){
176715  switch( sqlite3_value_type(pValue) ){
176716  case SQLITE_NULL: {
176717  jsonAppendRaw(p, "null", 4);
176718  break;
176719  }
176720  case SQLITE_INTEGER:
176721  case SQLITE_FLOAT: {
176722  const char *z = (const char*)sqlite3_value_text(pValue);
176723  u32 n = (u32)sqlite3_value_bytes(pValue);
176724  jsonAppendRaw(p, z, n);
176725  break;
176726  }
176727  case SQLITE_TEXT: {
176728  const char *z = (const char*)sqlite3_value_text(pValue);
176729  u32 n = (u32)sqlite3_value_bytes(pValue);
176730  if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
176731  jsonAppendRaw(p, z, n);
176732  }else{
176733  jsonAppendString(p, z, n);
176734  }
176735  break;
176736  }
176737  default: {
176738  if( p->bErr==0 ){
176739  sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
176740  p->bErr = 2;
176741  jsonReset(p);
176742  }
176743  break;
176744  }
176745  }
176746 }
176747 
176748 
176749 /* Make the JSON in p the result of the SQL function.
176750 */
176751 static void jsonResult(JsonString *p){
176752  if( p->bErr==0 ){
176753  sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
176754  p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
176755  SQLITE_UTF8);
176756  jsonZero(p);
176757  }
176758  assert( p->bStatic );
176759 }
176760 
176761 /**************************************************************************
176762 ** Utility routines for dealing with JsonNode and JsonParse objects
176763 **************************************************************************/
176764 
176765 /*
176766 ** Return the number of consecutive JsonNode slots need to represent
176767 ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
176768 ** OBJECT types, the number might be larger.
176769 **
176770 ** Appended elements are not counted. The value returned is the number
176771 ** by which the JsonNode counter should increment in order to go to the
176772 ** next peer value.
176773 */
176774 static u32 jsonNodeSize(JsonNode *pNode){
176775  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
176776 }
176777 
176778 /*
176779 ** Reclaim all memory allocated by a JsonParse object. But do not
176780 ** delete the JsonParse object itself.
176781 */
176782 static void jsonParseReset(JsonParse *pParse){
176783  sqlite3_free(pParse->aNode);
176784  pParse->aNode = 0;
176785  pParse->nNode = 0;
176786  pParse->nAlloc = 0;
176787  sqlite3_free(pParse->aUp);
176788  pParse->aUp = 0;
176789 }
176790 
176791 /*
176792 ** Convert the JsonNode pNode into a pure JSON string and
176793 ** append to pOut. Subsubstructure is also included. Return
176794 ** the number of JsonNode objects that are encoded.
176795 */
176796 static void jsonRenderNode(
176797  JsonNode *pNode, /* The node to render */
176798  JsonString *pOut, /* Write JSON here */
176799  sqlite3_value **aReplace /* Replacement values */
176800 ){
176801  switch( pNode->eType ){
176802  default: {
176803  assert( pNode->eType==JSON_NULL );
176804  jsonAppendRaw(pOut, "null", 4);
176805  break;
176806  }
176807  case JSON_TRUE: {
176808  jsonAppendRaw(pOut, "true", 4);
176809  break;
176810  }
176811  case JSON_FALSE: {
176812  jsonAppendRaw(pOut, "false", 5);
176813  break;
176814  }
176815  case JSON_STRING: {
176816  if( pNode->jnFlags & JNODE_RAW ){
176817  jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
176818  break;
176819  }
176820  /* Fall through into the next case */
176821  }
176822  case JSON_REAL:
176823  case JSON_INT: {
176824  jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
176825  break;
176826  }
176827  case JSON_ARRAY: {
176828  u32 j = 1;
176829  jsonAppendChar(pOut, '[');
176830  for(;;){
176831  while( j<=pNode->n ){
176832  if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
176833  if( pNode[j].jnFlags & JNODE_REPLACE ){
176834  jsonAppendSeparator(pOut);
176835  jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
176836  }
176837  }else{
176838  jsonAppendSeparator(pOut);
176839  jsonRenderNode(&pNode[j], pOut, aReplace);
176840  }
176841  j += jsonNodeSize(&pNode[j]);
176842  }
176843  if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
176844  pNode = &pNode[pNode->u.iAppend];
176845  j = 1;
176846  }
176847  jsonAppendChar(pOut, ']');
176848  break;
176849  }
176850  case JSON_OBJECT: {
176851  u32 j = 1;
176852  jsonAppendChar(pOut, '{');
176853  for(;;){
176854  while( j<=pNode->n ){
176855  if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
176856  jsonAppendSeparator(pOut);
176857  jsonRenderNode(&pNode[j], pOut, aReplace);
176858  jsonAppendChar(pOut, ':');
176859  if( pNode[j+1].jnFlags & JNODE_REPLACE ){
176860  jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
176861  }else{
176862  jsonRenderNode(&pNode[j+1], pOut, aReplace);
176863  }
176864  }
176865  j += 1 + jsonNodeSize(&pNode[j+1]);
176866  }
176867  if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
176868  pNode = &pNode[pNode->u.iAppend];
176869  j = 1;
176870  }
176871  jsonAppendChar(pOut, '}');
176872  break;
176873  }
176874  }
176875 }
176876 
176877 /*
176878 ** Return a JsonNode and all its descendents as a JSON string.
176879 */
176880 static void jsonReturnJson(
176881  JsonNode *pNode, /* Node to return */
176882  sqlite3_context *pCtx, /* Return value for this function */
176883  sqlite3_value **aReplace /* Array of replacement values */
176884 ){
176885  JsonString s;
176886  jsonInit(&s, pCtx);
176887  jsonRenderNode(pNode, &s, aReplace);
176888  jsonResult(&s);
176889  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
176890 }
176891 
176892 /*
176893 ** Make the JsonNode the return value of the function.
176894 */
176895 static void jsonReturn(
176896  JsonNode *pNode, /* Node to return */
176897  sqlite3_context *pCtx, /* Return value for this function */
176898  sqlite3_value **aReplace /* Array of replacement values */
176899 ){
176900  switch( pNode->eType ){
176901  default: {
176902  assert( pNode->eType==JSON_NULL );
176903  sqlite3_result_null(pCtx);
176904  break;
176905  }
176906  case JSON_TRUE: {
176907  sqlite3_result_int(pCtx, 1);
176908  break;
176909  }
176910  case JSON_FALSE: {
176911  sqlite3_result_int(pCtx, 0);
176912  break;
176913  }
176914  case JSON_INT: {
176915  sqlite3_int64 i = 0;
176916  const char *z = pNode->u.zJContent;
176917  if( z[0]=='-' ){ z++; }
176918  while( z[0]>='0' && z[0]<='9' ){
176919  unsigned v = *(z++) - '0';
176920  if( i>=LARGEST_INT64/10 ){
176921  if( i>LARGEST_INT64/10 ) goto int_as_real;
176922  if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
176923  if( v==9 ) goto int_as_real;
176924  if( v==8 ){
176925  if( pNode->u.zJContent[0]=='-' ){
176927  goto int_done;
176928  }else{
176929  goto int_as_real;
176930  }
176931  }
176932  }
176933  i = i*10 + v;
176934  }
176935  if( pNode->u.zJContent[0]=='-' ){ i = -i; }
176936  sqlite3_result_int64(pCtx, i);
176937  int_done:
176938  break;
176939  int_as_real: /* fall through to real */;
176940  }
176941  case JSON_REAL: {
176942  double r;
176943 #ifdef SQLITE_AMALGAMATION
176944  const char *z = pNode->u.zJContent;
176946 #else
176947  r = strtod(pNode->u.zJContent, 0);
176948 #endif
176949  sqlite3_result_double(pCtx, r);
176950  break;
176951  }
176952  case JSON_STRING: {
176953 #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
176954  ** json_insert() and json_replace() and those routines do not
176955  ** call jsonReturn() */
176956  if( pNode->jnFlags & JNODE_RAW ){
176957  sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
176958  SQLITE_TRANSIENT);
176959  }else
176960 #endif
176961  assert( (pNode->jnFlags & JNODE_RAW)==0 );
176962  if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
176963  /* JSON formatted without any backslash-escapes */
176964  sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
176965  SQLITE_TRANSIENT);
176966  }else{
176967  /* Translate JSON formatted string into raw text */
176968  u32 i;
176969  u32 n = pNode->n;
176970  const char *z = pNode->u.zJContent;
176971  char *zOut;
176972  u32 j;
176973  zOut = sqlite3_malloc( n+1 );
176974  if( zOut==0 ){
176976  break;
176977  }
176978  for(i=1, j=0; i<n-1; i++){
176979  char c = z[i];
176980  if( c!='\\' ){
176981  zOut[j++] = c;
176982  }else{
176983  c = z[++i];
176984  if( c=='u' ){
176985  u32 v = 0, k;
176986  for(k=0; k<4 && i<n-2; i++, k++){
176987  c = z[i+1];
176988  if( c>='0' && c<='9' ) v = v*16 + c - '0';
176989  else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
176990  else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
176991  else break;
176992  }
176993  if( v==0 ) break;
176994  if( v<=0x7f ){
176995  zOut[j++] = (char)v;
176996  }else if( v<=0x7ff ){
176997  zOut[j++] = (char)(0xc0 | (v>>6));
176998  zOut[j++] = 0x80 | (v&0x3f);
176999  }else{
177000  zOut[j++] = (char)(0xe0 | (v>>12));
177001  zOut[j++] = 0x80 | ((v>>6)&0x3f);
177002  zOut[j++] = 0x80 | (v&0x3f);
177003  }
177004  }else{
177005  if( c=='b' ){
177006  c = '\b';
177007  }else if( c=='f' ){
177008  c = '\f';
177009  }else if( c=='n' ){
177010  c = '\n';
177011  }else if( c=='r' ){
177012  c = '\r';
177013  }else if( c=='t' ){
177014  c = '\t';
177015  }
177016  zOut[j++] = c;
177017  }
177018  }
177019  }
177020  zOut[j] = 0;
177021  sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
177022  }
177023  break;
177024  }
177025  case JSON_ARRAY:
177026  case JSON_OBJECT: {
177027  jsonReturnJson(pNode, pCtx, aReplace);
177028  break;
177029  }
177030  }
177031 }
177032 
177033 /* Forward reference */
177034 static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
177035 
177036 /*
177037 ** A macro to hint to the compiler that a function should not be
177038 ** inlined.
177039 */
177040 #if defined(__GNUC__)
177041 # define JSON_NOINLINE __attribute__((noinline))
177042 #elif defined(_MSC_VER) && _MSC_VER>=1310
177043 # define JSON_NOINLINE __declspec(noinline)
177044 #else
177045 # define JSON_NOINLINE
177046 #endif
177047 
177048 
177049 static JSON_NOINLINE int jsonParseAddNodeExpand(
177050  JsonParse *pParse, /* Append the node to this object */
177051  u32 eType, /* Node type */
177052  u32 n, /* Content size or sub-node count */
177053  const char *zContent /* Content */
177054 ){
177055  u32 nNew;
177056  JsonNode *pNew;
177057  assert( pParse->nNode>=pParse->nAlloc );
177058  if( pParse->oom ) return -1;
177059  nNew = pParse->nAlloc*2 + 10;
177060  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
177061  if( pNew==0 ){
177062  pParse->oom = 1;
177063  return -1;
177064  }
177065  pParse->nAlloc = nNew;
177066  pParse->aNode = pNew;
177067  assert( pParse->nNode<pParse->nAlloc );
177068  return jsonParseAddNode(pParse, eType, n, zContent);
177069 }
177070 
177071 /*
177072 ** Create a new JsonNode instance based on the arguments and append that
177073 ** instance to the JsonParse. Return the index in pParse->aNode[] of the
177074 ** new node, or -1 if a memory allocation fails.
177075 */
177076 static int jsonParseAddNode(
177077  JsonParse *pParse, /* Append the node to this object */
177078  u32 eType, /* Node type */
177079  u32 n, /* Content size or sub-node count */
177080  const char *zContent /* Content */
177081 ){
177082  JsonNode *p;
177083  if( pParse->nNode>=pParse->nAlloc ){
177084  return jsonParseAddNodeExpand(pParse, eType, n, zContent);
177085  }
177086  p = &pParse->aNode[pParse->nNode];
177087  p->eType = (u8)eType;
177088  p->jnFlags = 0;
177089  p->iVal = 0;
177090  p->n = n;
177091  p->u.zJContent = zContent;
177092  return pParse->nNode++;
177093 }
177094 
177095 /*
177096 ** Return true if z[] begins with 4 (or more) hexadecimal digits
177097 */
177098 static int jsonIs4Hex(const char *z){
177099  int i;
177100  for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
177101  return 1;
177102 }
177103 
177104 /*
177105 ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
177106 ** index of the first character past the end of the value parsed.
177107 **
177108 ** Return negative for a syntax error. Special cases: return -2 if the
177109 ** first non-whitespace character is '}' and return -3 if the first
177110 ** non-whitespace character is ']'.
177111 */
177112 static int jsonParseValue(JsonParse *pParse, u32 i){
177113  char c;
177114  u32 j;
177115  int iThis;
177116  int x;
177117  JsonNode *pNode;
177118  while( safe_isspace(pParse->zJson[i]) ){ i++; }
177119  if( (c = pParse->zJson[i])=='{' ){
177120  /* Parse object */
177121  iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
177122  if( iThis<0 ) return -1;
177123  for(j=i+1;;j++){
177124  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177125  x = jsonParseValue(pParse, j);
177126  if( x<0 ){
177127  if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
177128  return -1;
177129  }
177130  if( pParse->oom ) return -1;
177131  pNode = &pParse->aNode[pParse->nNode-1];
177132  if( pNode->eType!=JSON_STRING ) return -1;
177133  pNode->jnFlags |= JNODE_LABEL;
177134  j = x;
177135  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177136  if( pParse->zJson[j]!=':' ) return -1;
177137  j++;
177138  x = jsonParseValue(pParse, j);
177139  if( x<0 ) return -1;
177140  j = x;
177141  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177142  c = pParse->zJson[j];
177143  if( c==',' ) continue;
177144  if( c!='}' ) return -1;
177145  break;
177146  }
177147  pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
177148  return j+1;
177149  }else if( c=='[' ){
177150  /* Parse array */
177151  iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
177152  if( iThis<0 ) return -1;
177153  for(j=i+1;;j++){
177154  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177155  x = jsonParseValue(pParse, j);
177156  if( x<0 ){
177157  if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
177158  return -1;
177159  }
177160  j = x;
177161  while( safe_isspace(pParse->zJson[j]) ){ j++; }
177162  c = pParse->zJson[j];
177163  if( c==',' ) continue;
177164  if( c!=']' ) return -1;
177165  break;
177166  }
177167  pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
177168  return j+1;
177169  }else if( c=='"' ){
177170  /* Parse string */
177171  u8 jnFlags = 0;
177172  j = i+1;
177173  for(;;){
177174  c = pParse->zJson[j];
177175  if( c==0 ) return -1;
177176  if( c=='\\' ){
177177  c = pParse->zJson[++j];
177178  if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
177179  || c=='n' || c=='r' || c=='t'
177180  || (c=='u' && jsonIs4Hex(pParse->zJson+j+1)) ){
177181  jnFlags = JNODE_ESCAPE;
177182  }else{
177183  return -1;
177184  }
177185  }else if( c=='"' ){
177186  break;
177187  }
177188  j++;
177189  }
177190  jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
177191  if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
177192  return j+1;
177193  }else if( c=='n'
177194  && strncmp(pParse->zJson+i,"null",4)==0
177195  && !safe_isalnum(pParse->zJson[i+4]) ){
177196  jsonParseAddNode(pParse, JSON_NULL, 0, 0);
177197  return i+4;
177198  }else if( c=='t'
177199  && strncmp(pParse->zJson+i,"true",4)==0
177200  && !safe_isalnum(pParse->zJson[i+4]) ){
177201  jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
177202  return i+4;
177203  }else if( c=='f'
177204  && strncmp(pParse->zJson+i,"false",5)==0
177205  && !safe_isalnum(pParse->zJson[i+5]) ){
177206  jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
177207  return i+5;
177208  }else if( c=='-' || (c>='0' && c<='9') ){
177209  /* Parse number */
177210  u8 seenDP = 0;
177211  u8 seenE = 0;
177212  j = i+1;
177213  for(;; j++){
177214  c = pParse->zJson[j];
177215  if( c>='0' && c<='9' ) continue;
177216  if( c=='.' ){
177217  if( pParse->zJson[j-1]=='-' ) return -1;
177218  if( seenDP ) return -1;
177219  seenDP = 1;
177220  continue;
177221  }
177222  if( c=='e' || c=='E' ){
177223  if( pParse->zJson[j-1]<'0' ) return -1;
177224  if( seenE ) return -1;
177225  seenDP = seenE = 1;
177226  c = pParse->zJson[j+1];
177227  if( c=='+' || c=='-' ){
177228  j++;
177229  c = pParse->zJson[j+1];
177230  }
177231  if( c<'0' || c>'9' ) return -1;
177232  continue;
177233  }
177234  break;
177235  }
177236  if( pParse->zJson[j-1]<'0' ) return -1;
177237  jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
177238  j - i, &pParse->zJson[i]);
177239  return j;
177240  }else if( c=='}' ){
177241  return -2; /* End of {...} */
177242  }else if( c==']' ){
177243  return -3; /* End of [...] */
177244  }else if( c==0 ){
177245  return 0; /* End of file */
177246  }else{
177247  return -1; /* Syntax error */
177248  }
177249 }
177250 
177251 /*
177252 ** Parse a complete JSON string. Return 0 on success or non-zero if there
177253 ** are any errors. If an error occurs, free all memory associated with
177254 ** pParse.
177255 **
177256 ** pParse is uninitialized when this routine is called.
177257 */
177258 static int jsonParse(
177259  JsonParse *pParse, /* Initialize and fill this JsonParse object */
177260  sqlite3_context *pCtx, /* Report errors here */
177261  const char *zJson /* Input JSON text to be parsed */
177262 ){
177263  int i;
177264  memset(pParse, 0, sizeof(*pParse));
177265  if( zJson==0 ) return 1;
177266  pParse->zJson = zJson;
177267  i = jsonParseValue(pParse, 0);
177268  if( pParse->oom ) i = -1;
177269  if( i>0 ){
177270  while( safe_isspace(zJson[i]) ) i++;
177271  if( zJson[i] ) i = -1;
177272  }
177273  if( i<=0 ){
177274  if( pCtx!=0 ){
177275  if( pParse->oom ){
177277  }else{
177278  sqlite3_result_error(pCtx, "malformed JSON", -1);
177279  }
177280  }
177281  jsonParseReset(pParse);
177282  return 1;
177283  }
177284  return 0;
177285 }
177286 
177287 /* Mark node i of pParse as being a child of iParent. Call recursively
177288 ** to fill in all the descendants of node i.
177289 */
177290 static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
177291  JsonNode *pNode = &pParse->aNode[i];
177292  u32 j;
177293  pParse->aUp[i] = iParent;
177294  switch( pNode->eType ){
177295  case JSON_ARRAY: {
177296  for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
177297  jsonParseFillInParentage(pParse, i+j, i);
177298  }
177299  break;
177300  }
177301  case JSON_OBJECT: {
177302  for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
177303  pParse->aUp[i+j] = i;
177304  jsonParseFillInParentage(pParse, i+j+1, i);
177305  }
177306  break;
177307  }
177308  default: {
177309  break;
177310  }
177311  }
177312 }
177313 
177314 /*
177315 ** Compute the parentage of all nodes in a completed parse.
177316 */
177317 static int jsonParseFindParents(JsonParse *pParse){
177318  u32 *aUp;
177319  assert( pParse->aUp==0 );
177320  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
177321  if( aUp==0 ){
177322  pParse->oom = 1;
177323  return SQLITE_NOMEM;
177324  }
177325  jsonParseFillInParentage(pParse, 0, 0);
177326  return SQLITE_OK;
177327 }
177328 
177329 /*
177330 ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
177331 ** a match.
177332 */
177333 static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
177334  if( pNode->jnFlags & JNODE_RAW ){
177335  if( pNode->n!=nKey ) return 0;
177336  return strncmp(pNode->u.zJContent, zKey, nKey)==0;
177337  }else{
177338  if( pNode->n!=nKey+2 ) return 0;
177339  return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
177340  }
177341 }
177342 
177343 /* forward declaration */
177344 static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
177345 
177346 /*
177347 ** Search along zPath to find the node specified. Return a pointer
177348 ** to that node, or NULL if zPath is malformed or if there is no such
177349 ** node.
177350 **
177351 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
177352 ** possible to do so and if no existing node corresponds to zPath. If
177353 ** new nodes are appended *pApnd is set to 1.
177354 */
177355 static JsonNode *jsonLookupStep(
177356  JsonParse *pParse, /* The JSON to search */
177357  u32 iRoot, /* Begin the search at this node */
177358  const char *zPath, /* The path to search */
177359  int *pApnd, /* Append nodes to complete path if not NULL */
177360  const char **pzErr /* Make *pzErr point to any syntax error in zPath */
177361 ){
177362  u32 i, j, nKey;
177363  const char *zKey;
177364  JsonNode *pRoot = &pParse->aNode[iRoot];
177365  if( zPath[0]==0 ) return pRoot;
177366  if( zPath[0]=='.' ){
177367  if( pRoot->eType!=JSON_OBJECT ) return 0;
177368  zPath++;
177369  if( zPath[0]=='"' ){
177370  zKey = zPath + 1;
177371  for(i=1; zPath[i] && zPath[i]!='"'; i++){}
177372  nKey = i-1;
177373  if( zPath[i] ){
177374  i++;
177375  }else{
177376  *pzErr = zPath;
177377  return 0;
177378  }
177379  }else{
177380  zKey = zPath;
177381  for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
177382  nKey = i;
177383  }
177384  if( nKey==0 ){
177385  *pzErr = zPath;
177386  return 0;
177387  }
177388  j = 1;
177389  for(;;){
177390  while( j<=pRoot->n ){
177391  if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
177392  return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
177393  }
177394  j++;
177395  j += jsonNodeSize(&pRoot[j]);
177396  }
177397  if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
177398  iRoot += pRoot->u.iAppend;
177399  pRoot = &pParse->aNode[iRoot];
177400  j = 1;
177401  }
177402  if( pApnd ){
177403  u32 iStart, iLabel;
177404  JsonNode *pNode;
177405  iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
177406  iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
177407  zPath += i;
177408  pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
177409  if( pParse->oom ) return 0;
177410  if( pNode ){
177411  pRoot = &pParse->aNode[iRoot];
177412  pRoot->u.iAppend = iStart - iRoot;
177413  pRoot->jnFlags |= JNODE_APPEND;
177414  pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
177415  }
177416  return pNode;
177417  }
177418  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
177419  if( pRoot->eType!=JSON_ARRAY ) return 0;
177420  i = 0;
177421  j = 1;
177422  while( safe_isdigit(zPath[j]) ){
177423  i = i*10 + zPath[j] - '0';
177424  j++;
177425  }
177426  if( zPath[j]!=']' ){
177427  *pzErr = zPath;
177428  return 0;
177429  }
177430  zPath += j + 1;
177431  j = 1;
177432  for(;;){
177433  while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
177434  if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
177435  j += jsonNodeSize(&pRoot[j]);
177436  }
177437  if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
177438  iRoot += pRoot->u.iAppend;
177439  pRoot = &pParse->aNode[iRoot];
177440  j = 1;
177441  }
177442  if( j<=pRoot->n ){
177443  return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
177444  }
177445  if( i==0 && pApnd ){
177446  u32 iStart;
177447  JsonNode *pNode;
177448  iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
177449  pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
177450  if( pParse->oom ) return 0;
177451  if( pNode ){
177452  pRoot = &pParse->aNode[iRoot];
177453  pRoot->u.iAppend = iStart - iRoot;
177454  pRoot->jnFlags |= JNODE_APPEND;
177455  }
177456  return pNode;
177457  }
177458  }else{
177459  *pzErr = zPath;
177460  }
177461  return 0;
177462 }
177463 
177464 /*
177465 ** Append content to pParse that will complete zPath. Return a pointer
177466 ** to the inserted node, or return NULL if the append fails.
177467 */
177468 static JsonNode *jsonLookupAppend(
177469  JsonParse *pParse, /* Append content to the JSON parse */
177470  const char *zPath, /* Description of content to append */
177471  int *pApnd, /* Set this flag to 1 */
177472  const char **pzErr /* Make this point to any syntax error */
177473 ){
177474  *pApnd = 1;
177475  if( zPath[0]==0 ){
177476  jsonParseAddNode(pParse, JSON_NULL, 0, 0);
177477  return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
177478  }
177479  if( zPath[0]=='.' ){
177480  jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
177481  }else if( strncmp(zPath,"[0]",3)==0 ){
177482  jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
177483  }else{
177484  return 0;
177485  }
177486  if( pParse->oom ) return 0;
177487  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
177488 }
177489 
177490 /*
177491 ** Return the text of a syntax error message on a JSON path. Space is
177492 ** obtained from sqlite3_malloc().
177493 */
177494 static char *jsonPathSyntaxError(const char *zErr){
177495  return sqlite3_mprintf("JSON path error near '%q'", zErr);
177496 }
177497 
177498 /*
177499 ** Do a node lookup using zPath. Return a pointer to the node on success.
177500 ** Return NULL if not found or if there is an error.
177501 **
177502 ** On an error, write an error message into pCtx and increment the
177503 ** pParse->nErr counter.
177504 **
177505 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
177506 ** nodes are appended.
177507 */
177508 static JsonNode *jsonLookup(
177509  JsonParse *pParse, /* The JSON to search */
177510  const char *zPath, /* The path to search */
177511  int *pApnd, /* Append nodes to complete path if not NULL */
177512  sqlite3_context *pCtx /* Report errors here, if not NULL */
177513 ){
177514  const char *zErr = 0;
177515  JsonNode *pNode = 0;
177516  char *zMsg;
177517 
177518  if( zPath==0 ) return 0;
177519  if( zPath[0]!='$' ){
177520  zErr = zPath;
177521  goto lookup_err;
177522  }
177523  zPath++;
177524  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
177525  if( zErr==0 ) return pNode;
177526 
177527 lookup_err:
177528  pParse->nErr++;
177529  assert( zErr!=0 && pCtx!=0 );
177530  zMsg = jsonPathSyntaxError(zErr);
177531  if( zMsg ){
177532  sqlite3_result_error(pCtx, zMsg, -1);
177533  sqlite3_free(zMsg);
177534  }else{
177536  }
177537  return 0;
177538 }
177539 
177540 
177541 /*
177542 ** Report the wrong number of arguments for json_insert(), json_replace()
177543 ** or json_set().
177544 */
177545 static void jsonWrongNumArgs(
177546  sqlite3_context *pCtx,
177547  const char *zFuncName
177548 ){
177549  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
177550  zFuncName);
177551  sqlite3_result_error(pCtx, zMsg, -1);
177552  sqlite3_free(zMsg);
177553 }
177554 
177555 
177556 /****************************************************************************
177557 ** SQL functions used for testing and debugging
177558 ****************************************************************************/
177559 
177560 #ifdef SQLITE_DEBUG
177561 /*
177562 ** The json_parse(JSON) function returns a string which describes
177563 ** a parse of the JSON provided. Or it returns NULL if JSON is not
177564 ** well-formed.
177565 */
177566 static void jsonParseFunc(
177567  sqlite3_context *ctx,
177568  int argc,
177569  sqlite3_value **argv
177570 ){
177571  JsonString s; /* Output string - not real JSON */
177572  JsonParse x; /* The parse */
177573  u32 i;
177574 
177575  assert( argc==1 );
177576  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177577  jsonParseFindParents(&x);
177578  jsonInit(&s, ctx);
177579  for(i=0; i<x.nNode; i++){
177580  const char *zType;
177581  if( x.aNode[i].jnFlags & JNODE_LABEL ){
177582  assert( x.aNode[i].eType==JSON_STRING );
177583  zType = "label";
177584  }else{
177585  zType = jsonType[x.aNode[i].eType];
177586  }
177587  jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
177588  i, zType, x.aNode[i].n, x.aUp[i]);
177589  if( x.aNode[i].u.zJContent!=0 ){
177590  jsonAppendRaw(&s, " ", 1);
177591  jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
177592  }
177593  jsonAppendRaw(&s, "\n", 1);
177594  }
177595  jsonParseReset(&x);
177596  jsonResult(&s);
177597 }
177598 
177599 /*
177600 ** The json_test1(JSON) function return true (1) if the input is JSON
177601 ** text generated by another json function. It returns (0) if the input
177602 ** is not known to be JSON.
177603 */
177604 static void jsonTest1Func(
177605  sqlite3_context *ctx,
177606  int argc,
177607  sqlite3_value **argv
177608 ){
177609  UNUSED_PARAM(argc);
177610  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
177611 }
177612 #endif /* SQLITE_DEBUG */
177613 
177614 /****************************************************************************
177615 ** Scalar SQL function implementations
177616 ****************************************************************************/
177617 
177618 /*
177619 ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
177620 ** corresponding to the SQL value input. Mostly this means putting
177621 ** double-quotes around strings and returning the unquoted string "null"
177622 ** when given a NULL input.
177623 */
177624 static void jsonQuoteFunc(
177625  sqlite3_context *ctx,
177626  int argc,
177627  sqlite3_value **argv
177628 ){
177629  JsonString jx;
177630  UNUSED_PARAM(argc);
177631 
177632  jsonInit(&jx, ctx);
177633  jsonAppendValue(&jx, argv[0]);
177634  jsonResult(&jx);
177635  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177636 }
177637 
177638 /*
177639 ** Implementation of the json_array(VALUE,...) function. Return a JSON
177640 ** array that contains all values given in arguments. Or if any argument
177641 ** is a BLOB, throw an error.
177642 */
177643 static void jsonArrayFunc(
177644  sqlite3_context *ctx,
177645  int argc,
177646  sqlite3_value **argv
177647 ){
177648  int i;
177649  JsonString jx;
177650 
177651  jsonInit(&jx, ctx);
177652  jsonAppendChar(&jx, '[');
177653  for(i=0; i<argc; i++){
177654  jsonAppendSeparator(&jx);
177655  jsonAppendValue(&jx, argv[i]);
177656  }
177657  jsonAppendChar(&jx, ']');
177658  jsonResult(&jx);
177659  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177660 }
177661 
177662 
177663 /*
177664 ** json_array_length(JSON)
177665 ** json_array_length(JSON, PATH)
177666 **
177667 ** Return the number of elements in the top-level JSON array.
177668 ** Return 0 if the input is not a well-formed JSON array.
177669 */
177670 static void jsonArrayLengthFunc(
177671  sqlite3_context *ctx,
177672  int argc,
177673  sqlite3_value **argv
177674 ){
177675  JsonParse x; /* The parse */
177676  sqlite3_int64 n = 0;
177677  u32 i;
177678  JsonNode *pNode;
177679 
177680  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177681  assert( x.nNode );
177682  if( argc==2 ){
177683  const char *zPath = (const char*)sqlite3_value_text(argv[1]);
177684  pNode = jsonLookup(&x, zPath, 0, ctx);
177685  }else{
177686  pNode = x.aNode;
177687  }
177688  if( pNode==0 ){
177689  x.nErr = 1;
177690  }else if( pNode->eType==JSON_ARRAY ){
177691  assert( (pNode->jnFlags & JNODE_APPEND)==0 );
177692  for(i=1; i<=pNode->n; n++){
177693  i += jsonNodeSize(&pNode[i]);
177694  }
177695  }
177696  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
177697  jsonParseReset(&x);
177698 }
177699 
177700 /*
177701 ** json_extract(JSON, PATH, ...)
177702 **
177703 ** Return the element described by PATH. Return NULL if there is no
177704 ** PATH element. If there are multiple PATHs, then return a JSON array
177705 ** with the result from each path. Throw an error if the JSON or any PATH
177706 ** is malformed.
177707 */
177708 static void jsonExtractFunc(
177709  sqlite3_context *ctx,
177710  int argc,
177711  sqlite3_value **argv
177712 ){
177713  JsonParse x; /* The parse */
177714  JsonNode *pNode;
177715  const char *zPath;
177716  JsonString jx;
177717  int i;
177718 
177719  if( argc<2 ) return;
177720  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177721  jsonInit(&jx, ctx);
177722  jsonAppendChar(&jx, '[');
177723  for(i=1; i<argc; i++){
177724  zPath = (const char*)sqlite3_value_text(argv[i]);
177725  pNode = jsonLookup(&x, zPath, 0, ctx);
177726  if( x.nErr ) break;
177727  if( argc>2 ){
177728  jsonAppendSeparator(&jx);
177729  if( pNode ){
177730  jsonRenderNode(pNode, &jx, 0);
177731  }else{
177732  jsonAppendRaw(&jx, "null", 4);
177733  }
177734  }else if( pNode ){
177735  jsonReturn(pNode, ctx, 0);
177736  }
177737  }
177738  if( argc>2 && i==argc ){
177739  jsonAppendChar(&jx, ']');
177740  jsonResult(&jx);
177741  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177742  }
177743  jsonReset(&jx);
177744  jsonParseReset(&x);
177745 }
177746 
177747 /*
177748 ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
177749 ** object that contains all name/value given in arguments. Or if any name
177750 ** is not a string or if any value is a BLOB, throw an error.
177751 */
177752 static void jsonObjectFunc(
177753  sqlite3_context *ctx,
177754  int argc,
177755  sqlite3_value **argv
177756 ){
177757  int i;
177758  JsonString jx;
177759  const char *z;
177760  u32 n;
177761 
177762  if( argc&1 ){
177763  sqlite3_result_error(ctx, "json_object() requires an even number "
177764  "of arguments", -1);
177765  return;
177766  }
177767  jsonInit(&jx, ctx);
177768  jsonAppendChar(&jx, '{');
177769  for(i=0; i<argc; i+=2){
177770  if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
177771  sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
177772  jsonReset(&jx);
177773  return;
177774  }
177775  jsonAppendSeparator(&jx);
177776  z = (const char*)sqlite3_value_text(argv[i]);
177777  n = (u32)sqlite3_value_bytes(argv[i]);
177778  jsonAppendString(&jx, z, n);
177779  jsonAppendChar(&jx, ':');
177780  jsonAppendValue(&jx, argv[i+1]);
177781  }
177782  jsonAppendChar(&jx, '}');
177783  jsonResult(&jx);
177784  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
177785 }
177786 
177787 
177788 /*
177789 ** json_remove(JSON, PATH, ...)
177790 **
177791 ** Remove the named elements from JSON and return the result. malformed
177792 ** JSON or PATH arguments result in an error.
177793 */
177794 static void jsonRemoveFunc(
177795  sqlite3_context *ctx,
177796  int argc,
177797  sqlite3_value **argv
177798 ){
177799  JsonParse x; /* The parse */
177800  JsonNode *pNode;
177801  const char *zPath;
177802  u32 i;
177803 
177804  if( argc<1 ) return;
177805  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177806  assert( x.nNode );
177807  for(i=1; i<(u32)argc; i++){
177808  zPath = (const char*)sqlite3_value_text(argv[i]);
177809  if( zPath==0 ) goto remove_done;
177810  pNode = jsonLookup(&x, zPath, 0, ctx);
177811  if( x.nErr ) goto remove_done;
177812  if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
177813  }
177814  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
177815  jsonReturnJson(x.aNode, ctx, 0);
177816  }
177817 remove_done:
177818  jsonParseReset(&x);
177819 }
177820 
177821 /*
177822 ** json_replace(JSON, PATH, VALUE, ...)
177823 **
177824 ** Replace the value at PATH with VALUE. If PATH does not already exist,
177825 ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
177826 */
177827 static void jsonReplaceFunc(
177828  sqlite3_context *ctx,
177829  int argc,
177830  sqlite3_value **argv
177831 ){
177832  JsonParse x; /* The parse */
177833  JsonNode *pNode;
177834  const char *zPath;
177835  u32 i;
177836 
177837  if( argc<1 ) return;
177838  if( (argc&1)==0 ) {
177839  jsonWrongNumArgs(ctx, "replace");
177840  return;
177841  }
177842  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177843  assert( x.nNode );
177844  for(i=1; i<(u32)argc; i+=2){
177845  zPath = (const char*)sqlite3_value_text(argv[i]);
177846  pNode = jsonLookup(&x, zPath, 0, ctx);
177847  if( x.nErr ) goto replace_err;
177848  if( pNode ){
177849  pNode->jnFlags |= (u8)JNODE_REPLACE;
177850  pNode->iVal = (u8)(i+1);
177851  }
177852  }
177853  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
177854  sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
177855  }else{
177856  jsonReturnJson(x.aNode, ctx, argv);
177857  }
177858 replace_err:
177859  jsonParseReset(&x);
177860 }
177861 
177862 /*
177863 ** json_set(JSON, PATH, VALUE, ...)
177864 **
177865 ** Set the value at PATH to VALUE. Create the PATH if it does not already
177866 ** exist. Overwrite existing values that do exist.
177867 ** If JSON or PATH is malformed, throw an error.
177868 **
177869 ** json_insert(JSON, PATH, VALUE, ...)
177870 **
177871 ** Create PATH and initialize it to VALUE. If PATH already exists, this
177872 ** routine is a no-op. If JSON or PATH is malformed, throw an error.
177873 */
177874 static void jsonSetFunc(
177875  sqlite3_context *ctx,
177876  int argc,
177877  sqlite3_value **argv
177878 ){
177879  JsonParse x; /* The parse */
177880  JsonNode *pNode;
177881  const char *zPath;
177882  u32 i;
177883  int bApnd;
177884  int bIsSet = *(int*)sqlite3_user_data(ctx);
177885 
177886  if( argc<1 ) return;
177887  if( (argc&1)==0 ) {
177888  jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
177889  return;
177890  }
177891  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177892  assert( x.nNode );
177893  for(i=1; i<(u32)argc; i+=2){
177894  zPath = (const char*)sqlite3_value_text(argv[i]);
177895  bApnd = 0;
177896  pNode = jsonLookup(&x, zPath, &bApnd, ctx);
177897  if( x.oom ){
177899  goto jsonSetDone;
177900  }else if( x.nErr ){
177901  goto jsonSetDone;
177902  }else if( pNode && (bApnd || bIsSet) ){
177903  pNode->jnFlags |= (u8)JNODE_REPLACE;
177904  pNode->iVal = (u8)(i+1);
177905  }
177906  }
177907  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
177908  sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
177909  }else{
177910  jsonReturnJson(x.aNode, ctx, argv);
177911  }
177912 jsonSetDone:
177913  jsonParseReset(&x);
177914 }
177915 
177916 /*
177917 ** json_type(JSON)
177918 ** json_type(JSON, PATH)
177919 **
177920 ** Return the top-level "type" of a JSON string. Throw an error if
177921 ** either the JSON or PATH inputs are not well-formed.
177922 */
177923 static void jsonTypeFunc(
177924  sqlite3_context *ctx,
177925  int argc,
177926  sqlite3_value **argv
177927 ){
177928  JsonParse x; /* The parse */
177929  const char *zPath;
177930  JsonNode *pNode;
177931 
177932  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
177933  assert( x.nNode );
177934  if( argc==2 ){
177935  zPath = (const char*)sqlite3_value_text(argv[1]);
177936  pNode = jsonLookup(&x, zPath, 0, ctx);
177937  }else{
177938  pNode = x.aNode;
177939  }
177940  if( pNode ){
177941  sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
177942  }
177943  jsonParseReset(&x);
177944 }
177945 
177946 /*
177947 ** json_valid(JSON)
177948 **
177949 ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
177950 ** Return 0 otherwise.
177951 */
177952 static void jsonValidFunc(
177953  sqlite3_context *ctx,
177954  int argc,
177955  sqlite3_value **argv
177956 ){
177957  JsonParse x; /* The parse */
177958  int rc = 0;
177959 
177960  UNUSED_PARAM(argc);
177961  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
177962  rc = 1;
177963  }
177964  jsonParseReset(&x);
177965  sqlite3_result_int(ctx, rc);
177966 }
177967 
177968 
177969 /****************************************************************************
177970 ** Aggregate SQL function implementations
177971 ****************************************************************************/
177972 /*
177973 ** json_group_array(VALUE)
177974 **
177975 ** Return a JSON array composed of all values in the aggregate.
177976 */
177977 static void jsonArrayStep(
177978  sqlite3_context *ctx,
177979  int argc,
177980  sqlite3_value **argv
177981 ){
177982  JsonString *pStr;
177983  UNUSED_PARAM(argc);
177984  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
177985  if( pStr ){
177986  if( pStr->zBuf==0 ){
177987  jsonInit(pStr, ctx);
177988  jsonAppendChar(pStr, '[');
177989  }else{
177990  jsonAppendChar(pStr, ',');
177991  pStr->pCtx = ctx;
177992  }
177993  jsonAppendValue(pStr, argv[0]);
177994  }
177995 }
177996 static void jsonArrayFinal(sqlite3_context *ctx){
177997  JsonString *pStr;
177998  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
177999  if( pStr ){
178000  pStr->pCtx = ctx;
178001  jsonAppendChar(pStr, ']');
178002  if( pStr->bErr ){
178003  if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
178004  assert( pStr->bStatic );
178005  }else{
178006  sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
178007  pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
178008  pStr->bStatic = 1;
178009  }
178010  }else{
178011  sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
178012  }
178013  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
178014 }
178015 
178016 /*
178017 ** json_group_obj(NAME,VALUE)
178018 **
178019 ** Return a JSON object composed of all names and values in the aggregate.
178020 */
178021 static void jsonObjectStep(
178022  sqlite3_context *ctx,
178023  int argc,
178024  sqlite3_value **argv
178025 ){
178026  JsonString *pStr;
178027  const char *z;
178028  u32 n;
178029  UNUSED_PARAM(argc);
178030  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
178031  if( pStr ){
178032  if( pStr->zBuf==0 ){
178033  jsonInit(pStr, ctx);
178034  jsonAppendChar(pStr, '{');
178035  }else{
178036  jsonAppendChar(pStr, ',');
178037  pStr->pCtx = ctx;
178038  }
178039  z = (const char*)sqlite3_value_text(argv[0]);
178040  n = (u32)sqlite3_value_bytes(argv[0]);
178041  jsonAppendString(pStr, z, n);
178042  jsonAppendChar(pStr, ':');
178043  jsonAppendValue(pStr, argv[1]);
178044  }
178045 }
178046 static void jsonObjectFinal(sqlite3_context *ctx){
178047  JsonString *pStr;
178048  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
178049  if( pStr ){
178050  jsonAppendChar(pStr, '}');
178051  if( pStr->bErr ){
178052  if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
178053  assert( pStr->bStatic );
178054  }else{
178055  sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
178056  pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
178057  pStr->bStatic = 1;
178058  }
178059  }else{
178060  sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
178061  }
178062  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
178063 }
178064 
178065 
178066 #ifndef SQLITE_OMIT_VIRTUALTABLE
178067 /****************************************************************************
178068 ** The json_each virtual table
178069 ****************************************************************************/
178070 typedef struct JsonEachCursor JsonEachCursor;
178071 struct JsonEachCursor {
178072  sqlite3_vtab_cursor base; /* Base class - must be first */
178073  u32 iRowid; /* The rowid */
178074  u32 iBegin; /* The first node of the scan */
178075  u32 i; /* Index in sParse.aNode[] of current row */
178076  u32 iEnd; /* EOF when i equals or exceeds this value */
178077  u8 eType; /* Type of top-level element */
178078  u8 bRecursive; /* True for json_tree(). False for json_each() */
178079  char *zJson; /* Input JSON */
178080  char *zRoot; /* Path by which to filter zJson */
178081  JsonParse sParse; /* Parse of the input JSON */
178082 };
178083 
178084 /* Constructor for the json_each virtual table */
178085 static int jsonEachConnect(
178086  sqlite3 *db,
178087  void *pAux,
178088  int argc, const char *const*argv,
178089  sqlite3_vtab **ppVtab,
178090  char **pzErr
178091 ){
178092  sqlite3_vtab *pNew;
178093  int rc;
178094 
178095 /* Column numbers */
178096 #define JEACH_KEY 0
178097 #define JEACH_VALUE 1
178098 #define JEACH_TYPE 2
178099 #define JEACH_ATOM 3
178100 #define JEACH_ID 4
178101 #define JEACH_PARENT 5
178102 #define JEACH_FULLKEY 6
178103 #define JEACH_PATH 7
178104 #define JEACH_JSON 8
178105 #define JEACH_ROOT 9
178106 
178107  UNUSED_PARAM(pzErr);
178108  UNUSED_PARAM(argv);
178109  UNUSED_PARAM(argc);
178110  UNUSED_PARAM(pAux);
178111  rc = sqlite3_declare_vtab(db,
178112  "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
178113  "json HIDDEN,root HIDDEN)");
178114  if( rc==SQLITE_OK ){
178115  pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
178116  if( pNew==0 ) return SQLITE_NOMEM;
178117  memset(pNew, 0, sizeof(*pNew));
178118  }
178119  return rc;
178120 }
178121 
178122 /* destructor for json_each virtual table */
178123 static int jsonEachDisconnect(sqlite3_vtab *pVtab){
178124  sqlite3_free(pVtab);
178125  return SQLITE_OK;
178126 }
178127 
178128 /* constructor for a JsonEachCursor object for json_each(). */
178129 static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
178130  JsonEachCursor *pCur;
178131 
178132  UNUSED_PARAM(p);
178133  pCur = sqlite3_malloc( sizeof(*pCur) );
178134  if( pCur==0 ) return SQLITE_NOMEM;
178135  memset(pCur, 0, sizeof(*pCur));
178136  *ppCursor = &pCur->base;
178137  return SQLITE_OK;
178138 }
178139 
178140 /* constructor for a JsonEachCursor object for json_tree(). */
178141 static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
178142  int rc = jsonEachOpenEach(p, ppCursor);
178143  if( rc==SQLITE_OK ){
178144  JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
178145  pCur->bRecursive = 1;
178146  }
178147  return rc;
178148 }
178149 
178150 /* Reset a JsonEachCursor back to its original state. Free any memory
178151 ** held. */
178152 static void jsonEachCursorReset(JsonEachCursor *p){
178153  sqlite3_free(p->zJson);
178154  sqlite3_free(p->zRoot);
178155  jsonParseReset(&p->sParse);
178156  p->iRowid = 0;
178157  p->i = 0;
178158  p->iEnd = 0;
178159  p->eType = 0;
178160  p->zJson = 0;
178161  p->zRoot = 0;
178162 }
178163 
178164 /* Destructor for a jsonEachCursor object */
178165 static int jsonEachClose(sqlite3_vtab_cursor *cur){
178166  JsonEachCursor *p = (JsonEachCursor*)cur;
178167  jsonEachCursorReset(p);
178168  sqlite3_free(cur);
178169  return SQLITE_OK;
178170 }
178171 
178172 /* Return TRUE if the jsonEachCursor object has been advanced off the end
178173 ** of the JSON object */
178174 static int jsonEachEof(sqlite3_vtab_cursor *cur){
178175  JsonEachCursor *p = (JsonEachCursor*)cur;
178176  return p->i >= p->iEnd;
178177 }
178178 
178179 /* Advance the cursor to the next element for json_tree() */
178180 static int jsonEachNext(sqlite3_vtab_cursor *cur){
178181  JsonEachCursor *p = (JsonEachCursor*)cur;
178182  if( p->bRecursive ){
178183  if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
178184  p->i++;
178185  p->iRowid++;
178186  if( p->i<p->iEnd ){
178187  u32 iUp = p->sParse.aUp[p->i];
178188  JsonNode *pUp = &p->sParse.aNode[iUp];
178189  p->eType = pUp->eType;
178190  if( pUp->eType==JSON_ARRAY ){
178191  if( iUp==p->i-1 ){
178192  pUp->u.iKey = 0;
178193  }else{
178194  pUp->u.iKey++;
178195  }
178196  }
178197  }
178198  }else{
178199  switch( p->eType ){
178200  case JSON_ARRAY: {
178201  p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
178202  p->iRowid++;
178203  break;
178204  }
178205  case JSON_OBJECT: {
178206  p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
178207  p->iRowid++;
178208  break;
178209  }
178210  default: {
178211  p->i = p->iEnd;
178212  break;
178213  }
178214  }
178215  }
178216  return SQLITE_OK;
178217 }
178218 
178219 /* Append the name of the path for element i to pStr
178220 */
178221 static void jsonEachComputePath(
178222  JsonEachCursor *p, /* The cursor */
178223  JsonString *pStr, /* Write the path here */
178224  u32 i /* Path to this element */
178225 ){
178226  JsonNode *pNode, *pUp;
178227  u32 iUp;
178228  if( i==0 ){
178229  jsonAppendChar(pStr, '$');
178230  return;
178231  }
178232  iUp = p->sParse.aUp[i];
178233  jsonEachComputePath(p, pStr, iUp);
178234  pNode = &p->sParse.aNode[i];
178235  pUp = &p->sParse.aNode[iUp];
178236  if( pUp->eType==JSON_ARRAY ){
178237  jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
178238  }else{
178239  assert( pUp->eType==JSON_OBJECT );
178240  if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
178241  assert( pNode->eType==JSON_STRING );
178242  assert( pNode->jnFlags & JNODE_LABEL );
178243  jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
178244  }
178245 }
178246 
178247 /* Return the value of a column */
178248 static int jsonEachColumn(
178249  sqlite3_vtab_cursor *cur, /* The cursor */
178250  sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
178251  int i /* Which column to return */
178252 ){
178253  JsonEachCursor *p = (JsonEachCursor*)cur;
178254  JsonNode *pThis = &p->sParse.aNode[p->i];
178255  switch( i ){
178256  case JEACH_KEY: {
178257  if( p->i==0 ) break;
178258  if( p->eType==JSON_OBJECT ){
178259  jsonReturn(pThis, ctx, 0);
178260  }else if( p->eType==JSON_ARRAY ){
178261  u32 iKey;
178262  if( p->bRecursive ){
178263  if( p->iRowid==0 ) break;
178264  iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
178265  }else{
178266  iKey = p->iRowid;
178267  }
178268  sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
178269  }
178270  break;
178271  }
178272  case JEACH_VALUE: {
178273  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
178274  jsonReturn(pThis, ctx, 0);
178275  break;
178276  }
178277  case JEACH_TYPE: {
178278  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
178279  sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
178280  break;
178281  }
178282  case JEACH_ATOM: {
178283  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
178284  if( pThis->eType>=JSON_ARRAY ) break;
178285  jsonReturn(pThis, ctx, 0);
178286  break;
178287  }
178288  case JEACH_ID: {
178289  sqlite3_result_int64(ctx,
178290  (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
178291  break;
178292  }
178293  case JEACH_PARENT: {
178294  if( p->i>p->iBegin && p->bRecursive ){
178295  sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
178296  }
178297  break;
178298  }
178299  case JEACH_FULLKEY: {
178300  JsonString x;
178301  jsonInit(&x, ctx);
178302  if( p->bRecursive ){
178303  jsonEachComputePath(p, &x, p->i);
178304  }else{
178305  if( p->zRoot ){
178306  jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
178307  }else{
178308  jsonAppendChar(&x, '$');
178309  }
178310  if( p->eType==JSON_ARRAY ){
178311  jsonPrintf(30, &x, "[%d]", p->iRowid);
178312  }else{
178313  jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
178314  }
178315  }
178316  jsonResult(&x);
178317  break;
178318  }
178319  case JEACH_PATH: {
178320  if( p->bRecursive ){
178321  JsonString x;
178322  jsonInit(&x, ctx);
178323  jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
178324  jsonResult(&x);
178325  break;
178326  }
178327  /* For json_each() path and root are the same so fall through
178328  ** into the root case */
178329  }
178330  default: {
178331  const char *zRoot = p->zRoot;
178332  if( zRoot==0 ) zRoot = "$";
178333  sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
178334  break;
178335  }
178336  case JEACH_JSON: {
178337  assert( i==JEACH_JSON );
178338  sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
178339  break;
178340  }
178341  }
178342  return SQLITE_OK;
178343 }
178344 
178345 /* Return the current rowid value */
178346 static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
178347  JsonEachCursor *p = (JsonEachCursor*)cur;
178348  *pRowid = p->iRowid;
178349  return SQLITE_OK;
178350 }
178351 
178352 /* The query strategy is to look for an equality constraint on the json
178353 ** column. Without such a constraint, the table cannot operate. idxNum is
178354 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
178355 ** and 0 otherwise.
178356 */
178357 static int jsonEachBestIndex(
178358  sqlite3_vtab *tab,
178359  sqlite3_index_info *pIdxInfo
178360 ){
178361  int i;
178362  int jsonIdx = -1;
178363  int rootIdx = -1;
178364  const struct sqlite3_index_constraint *pConstraint;
178365 
178366  UNUSED_PARAM(tab);
178367  pConstraint = pIdxInfo->aConstraint;
178368  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
178369  if( pConstraint->usable==0 ) continue;
178370  if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
178371  switch( pConstraint->iColumn ){
178372  case JEACH_JSON: jsonIdx = i; break;
178373  case JEACH_ROOT: rootIdx = i; break;
178374  default: /* no-op */ break;
178375  }
178376  }
178377  if( jsonIdx<0 ){
178378  pIdxInfo->idxNum = 0;
178379  pIdxInfo->estimatedCost = 1e99;
178380  }else{
178381  pIdxInfo->estimatedCost = 1.0;
178382  pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
178383  pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
178384  if( rootIdx<0 ){
178385  pIdxInfo->idxNum = 1;
178386  }else{
178387  pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
178388  pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
178389  pIdxInfo->idxNum = 3;
178390  }
178391  }
178392  return SQLITE_OK;
178393 }
178394 
178395 /* Start a search on a new JSON string */
178396 static int jsonEachFilter(
178397  sqlite3_vtab_cursor *cur,
178398  int idxNum, const char *idxStr,
178399  int argc, sqlite3_value **argv
178400 ){
178401  JsonEachCursor *p = (JsonEachCursor*)cur;
178402  const char *z;
178403  const char *zRoot = 0;
178404  sqlite3_int64 n;
178405 
178406  UNUSED_PARAM(idxStr);
178407  UNUSED_PARAM(argc);
178408  jsonEachCursorReset(p);
178409  if( idxNum==0 ) return SQLITE_OK;
178410  z = (const char*)sqlite3_value_text(argv[0]);
178411  if( z==0 ) return SQLITE_OK;
178412  n = sqlite3_value_bytes(argv[0]);
178413  p->zJson = sqlite3_malloc64( n+1 );
178414  if( p->zJson==0 ) return SQLITE_NOMEM;
178415  memcpy(p->zJson, z, (size_t)n+1);
178416  if( jsonParse(&p->sParse, 0, p->zJson) ){
178417  int rc = SQLITE_NOMEM;
178418  if( p->sParse.oom==0 ){
178419  sqlite3_free(cur->pVtab->zErrMsg);
178420  cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
178421  if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
178422  }
178423  jsonEachCursorReset(p);
178424  return rc;
178425  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
178426  jsonEachCursorReset(p);
178427  return SQLITE_NOMEM;
178428  }else{
178429  JsonNode *pNode = 0;
178430  if( idxNum==3 ){
178431  const char *zErr = 0;
178432  zRoot = (const char*)sqlite3_value_text(argv[1]);
178433  if( zRoot==0 ) return SQLITE_OK;
178434  n = sqlite3_value_bytes(argv[1]);
178435  p->zRoot = sqlite3_malloc64( n+1 );
178436  if( p->zRoot==0 ) return SQLITE_NOMEM;
178437  memcpy(p->zRoot, zRoot, (size_t)n+1);
178438  if( zRoot[0]!='$' ){
178439  zErr = zRoot;
178440  }else{
178441  pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
178442  }
178443  if( zErr ){
178444  sqlite3_free(cur->pVtab->zErrMsg);
178445  cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
178446  jsonEachCursorReset(p);
178447  return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
178448  }else if( pNode==0 ){
178449  return SQLITE_OK;
178450  }
178451  }else{
178452  pNode = p->sParse.aNode;
178453  }
178454  p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
178455  p->eType = pNode->eType;
178456  if( p->eType>=JSON_ARRAY ){
178457  pNode->u.iKey = 0;
178458  p->iEnd = p->i + pNode->n + 1;
178459  if( p->bRecursive ){
178460  p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
178461  if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
178462  p->i--;
178463  }
178464  }else{
178465  p->i++;
178466  }
178467  }else{
178468  p->iEnd = p->i+1;
178469  }
178470  }
178471  return SQLITE_OK;
178472 }
178473 
178474 /* The methods of the json_each virtual table */
178475 static sqlite3_module jsonEachModule = {
178476  0, /* iVersion */
178477  0, /* xCreate */
178478  jsonEachConnect, /* xConnect */
178479  jsonEachBestIndex, /* xBestIndex */
178480  jsonEachDisconnect, /* xDisconnect */
178481  0, /* xDestroy */
178482  jsonEachOpenEach, /* xOpen - open a cursor */
178483  jsonEachClose, /* xClose - close a cursor */
178484  jsonEachFilter, /* xFilter - configure scan constraints */
178485  jsonEachNext, /* xNext - advance a cursor */
178486  jsonEachEof, /* xEof - check for end of scan */
178487  jsonEachColumn, /* xColumn - read data */
178488  jsonEachRowid, /* xRowid - read data */
178489  0, /* xUpdate */
178490  0, /* xBegin */
178491  0, /* xSync */
178492  0, /* xCommit */
178493  0, /* xRollback */
178494  0, /* xFindMethod */
178495  0, /* xRename */
178496  0, /* xSavepoint */
178497  0, /* xRelease */
178498  0 /* xRollbackTo */
178499 };
178500 
178501 /* The methods of the json_tree virtual table. */
178502 static sqlite3_module jsonTreeModule = {
178503  0, /* iVersion */
178504  0, /* xCreate */
178505  jsonEachConnect, /* xConnect */
178506  jsonEachBestIndex, /* xBestIndex */
178507  jsonEachDisconnect, /* xDisconnect */
178508  0, /* xDestroy */
178509  jsonEachOpenTree, /* xOpen - open a cursor */
178510  jsonEachClose, /* xClose - close a cursor */
178511  jsonEachFilter, /* xFilter - configure scan constraints */
178512  jsonEachNext, /* xNext - advance a cursor */
178513  jsonEachEof, /* xEof - check for end of scan */
178514  jsonEachColumn, /* xColumn - read data */
178515  jsonEachRowid, /* xRowid - read data */
178516  0, /* xUpdate */
178517  0, /* xBegin */
178518  0, /* xSync */
178519  0, /* xCommit */
178520  0, /* xRollback */
178521  0, /* xFindMethod */
178522  0, /* xRename */
178523  0, /* xSavepoint */
178524  0, /* xRelease */
178525  0 /* xRollbackTo */
178526 };
178527 #endif /* SQLITE_OMIT_VIRTUALTABLE */
178528 
178529 /****************************************************************************
178530 ** The following routines are the only publically visible identifiers in this
178531 ** file. Call the following routines in order to register the various SQL
178532 ** functions and the virtual table implemented by this file.
178533 ****************************************************************************/
178534 
178535 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
178536  int rc = SQLITE_OK;
178537  unsigned int i;
178538  static const struct {
178539  const char *zName;
178540  int nArg;
178541  int flag;
178542  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
178543  } aFunc[] = {
178544  { "json", 1, 0, jsonRemoveFunc },
178545  { "json_array", -1, 0, jsonArrayFunc },
178546  { "json_array_length", 1, 0, jsonArrayLengthFunc },
178547  { "json_array_length", 2, 0, jsonArrayLengthFunc },
178548  { "json_extract", -1, 0, jsonExtractFunc },
178549  { "json_insert", -1, 0, jsonSetFunc },
178550  { "json_object", -1, 0, jsonObjectFunc },
178551  { "json_quote", 1, 0, jsonQuoteFunc },
178552  { "json_remove", -1, 0, jsonRemoveFunc },
178553  { "json_replace", -1, 0, jsonReplaceFunc },
178554  { "json_set", -1, 1, jsonSetFunc },
178555  { "json_type", 1, 0, jsonTypeFunc },
178556  { "json_type", 2, 0, jsonTypeFunc },
178557  { "json_valid", 1, 0, jsonValidFunc },
178558 
178559 #if SQLITE_DEBUG
178560  /* DEBUG and TESTING functions */
178561  { "json_parse", 1, 0, jsonParseFunc },
178562  { "json_test1", 1, 0, jsonTest1Func },
178563 #endif
178564  };
178565  static const struct {
178566  const char *zName;
178567  int nArg;
178568  void (*xStep)(sqlite3_context*,int,sqlite3_value**);
178569  void (*xFinal)(sqlite3_context*);
178570  } aAgg[] = {
178571  { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
178572  { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
178573  };
178574 #ifndef SQLITE_OMIT_VIRTUALTABLE
178575  static const struct {
178576  const char *zName;
178577  sqlite3_module *pModule;
178578  } aMod[] = {
178579  { "json_each", &jsonEachModule },
178580  { "json_tree", &jsonTreeModule },
178581  };
178582 #endif
178583  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
178584  rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
178586  (void*)&aFunc[i].flag,
178587  aFunc[i].xFunc, 0, 0);
178588  }
178589  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
178590  rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
178592  0, aAgg[i].xStep, aAgg[i].xFinal);
178593  }
178594 #ifndef SQLITE_OMIT_VIRTUALTABLE
178595  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
178596  rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
178597  }
178598 #endif
178599  return rc;
178600 }
178601 
178602 
178603 #ifndef SQLITE_CORE
178604 #ifdef _WIN32
178605 __declspec(dllexport)
178606 #endif
178607 SQLITE_API int sqlite3_json_init(
178608  sqlite3 *db,
178609  char **pzErrMsg,
178610  const sqlite3_api_routines *pApi
178611 ){
178612  SQLITE_EXTENSION_INIT2(pApi);
178613  (void)pzErrMsg; /* Unused parameter */
178614  return sqlite3Json1Init(db);
178615 }
178616 #endif
178617 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
178618 
178619 /************** End of json1.c ***********************************************/
178620 /************** Begin file fts5.c ********************************************/
178621 
178622 
178623 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
178624 
178625 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
178626 # define NDEBUG 1
178627 #endif
178628 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
178629 # undef NDEBUG
178630 #endif
178631 
178632 /*
178633 ** 2014 May 31
178634 **
178635 ** The author disclaims copyright to this source code. In place of
178636 ** a legal notice, here is a blessing:
178637 **
178638 ** May you do good and not evil.
178639 ** May you find forgiveness for yourself and forgive others.
178640 ** May you share freely, never taking more than you give.
178641 **
178642 ******************************************************************************
178643 **
178644 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
178645 ** FTS5 may be extended with:
178646 **
178647 ** * custom tokenizers, and
178648 ** * custom auxiliary functions.
178649 */
178650 
178651 
178652 #ifndef _FTS5_H
178653 #define _FTS5_H
178654 
178655 /* #include "sqlite3.h" */
178656 
178657 #if 0
178658 extern "C" {
178659 #endif
178660 
178661 /*************************************************************************
178662 ** CUSTOM AUXILIARY FUNCTIONS
178663 **
178664 ** Virtual table implementations may overload SQL functions by implementing
178665 ** the sqlite3_module.xFindFunction() method.
178666 */
178667 
178668 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
178669 typedef struct Fts5Context Fts5Context;
178670 typedef struct Fts5PhraseIter Fts5PhraseIter;
178671 
178672 typedef void (*fts5_extension_function)(
178673  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
178674  Fts5Context *pFts, /* First arg to pass to pApi functions */
178675  sqlite3_context *pCtx, /* Context for returning result/error */
178676  int nVal, /* Number of values in apVal[] array */
178677  sqlite3_value **apVal /* Array of trailing arguments */
178678 );
178679 
178680 struct Fts5PhraseIter {
178681  const unsigned char *a;
178682  const unsigned char *b;
178683 };
178684 
178685 /*
178686 ** EXTENSION API FUNCTIONS
178687 **
178688 ** xUserData(pFts):
178689 ** Return a copy of the context pointer the extension function was
178690 ** registered with.
178691 **
178692 ** xColumnTotalSize(pFts, iCol, pnToken):
178693 ** If parameter iCol is less than zero, set output variable *pnToken
178694 ** to the total number of tokens in the FTS5 table. Or, if iCol is
178695 ** non-negative but less than the number of columns in the table, return
178696 ** the total number of tokens in column iCol, considering all rows in
178697 ** the FTS5 table.
178698 **
178699 ** If parameter iCol is greater than or equal to the number of columns
178700 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
178701 ** an OOM condition or IO error), an appropriate SQLite error code is
178702 ** returned.
178703 **
178704 ** xColumnCount(pFts):
178705 ** Return the number of columns in the table.
178706 **
178707 ** xColumnSize(pFts, iCol, pnToken):
178708 ** If parameter iCol is less than zero, set output variable *pnToken
178709 ** to the total number of tokens in the current row. Or, if iCol is
178710 ** non-negative but less than the number of columns in the table, set
178711 ** *pnToken to the number of tokens in column iCol of the current row.
178712 **
178713 ** If parameter iCol is greater than or equal to the number of columns
178714 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
178715 ** an OOM condition or IO error), an appropriate SQLite error code is
178716 ** returned.
178717 **
178718 ** This function may be quite inefficient if used with an FTS5 table
178719 ** created with the "columnsize=0" option.
178720 **
178721 ** xColumnText:
178722 ** This function attempts to retrieve the text of column iCol of the
178723 ** current document. If successful, (*pz) is set to point to a buffer
178724 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
178725 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
178726 ** if an error occurs, an SQLite error code is returned and the final values
178727 ** of (*pz) and (*pn) are undefined.
178728 **
178729 ** xPhraseCount:
178730 ** Returns the number of phrases in the current query expression.
178731 **
178732 ** xPhraseSize:
178733 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
178734 ** are numbered starting from zero.
178735 **
178736 ** xInstCount:
178737 ** Set *pnInst to the total number of occurrences of all phrases within
178738 ** the query within the current row. Return SQLITE_OK if successful, or
178739 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
178740 **
178741 ** This API can be quite slow if used with an FTS5 table created with the
178742 ** "detail=none" or "detail=column" option. If the FTS5 table is created
178743 ** with either "detail=none" or "detail=column" and "content=" option
178744 ** (i.e. if it is a contentless table), then this API always returns 0.
178745 **
178746 ** xInst:
178747 ** Query for the details of phrase match iIdx within the current row.
178748 ** Phrase matches are numbered starting from zero, so the iIdx argument
178749 ** should be greater than or equal to zero and smaller than the value
178750 ** output by xInstCount().
178751 **
178752 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
178753 ** to the column in which it occurs and *piOff the token offset of the
178754 ** first token of the phrase. The exception is if the table was created
178755 ** with the offsets=0 option specified. In this case *piOff is always
178756 ** set to -1.
178757 **
178758 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
178759 ** if an error occurs.
178760 **
178761 ** This API can be quite slow if used with an FTS5 table created with the
178762 ** "detail=none" or "detail=column" option.
178763 **
178764 ** xRowid:
178765 ** Returns the rowid of the current row.
178766 **
178767 ** xTokenize:
178768 ** Tokenize text using the tokenizer belonging to the FTS5 table.
178769 **
178770 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
178771 ** This API function is used to query the FTS table for phrase iPhrase
178772 ** of the current query. Specifically, a query equivalent to:
178773 **
178774 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
178775 **
178776 ** with $p set to a phrase equivalent to the phrase iPhrase of the
178777 ** current query is executed. Any column filter that applies to
178778 ** phrase iPhrase of the current query is included in $p. For each
178779 ** row visited, the callback function passed as the fourth argument
178780 ** is invoked. The context and API objects passed to the callback
178781 ** function may be used to access the properties of each matched row.
178782 ** Invoking Api.xUserData() returns a copy of the pointer passed as
178783 ** the third argument to pUserData.
178784 **
178785 ** If the callback function returns any value other than SQLITE_OK, the
178786 ** query is abandoned and the xQueryPhrase function returns immediately.
178787 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
178788 ** Otherwise, the error code is propagated upwards.
178789 **
178790 ** If the query runs to completion without incident, SQLITE_OK is returned.
178791 ** Or, if some error occurs before the query completes or is aborted by
178792 ** the callback, an SQLite error code is returned.
178793 **
178794 **
178795 ** xSetAuxdata(pFts5, pAux, xDelete)
178796 **
178797 ** Save the pointer passed as the second argument as the extension functions
178798 ** "auxiliary data". The pointer may then be retrieved by the current or any
178799 ** future invocation of the same fts5 extension function made as part of
178800 ** of the same MATCH query using the xGetAuxdata() API.
178801 **
178802 ** Each extension function is allocated a single auxiliary data slot for
178803 ** each FTS query (MATCH expression). If the extension function is invoked
178804 ** more than once for a single FTS query, then all invocations share a
178805 ** single auxiliary data context.
178806 **
178807 ** If there is already an auxiliary data pointer when this function is
178808 ** invoked, then it is replaced by the new pointer. If an xDelete callback
178809 ** was specified along with the original pointer, it is invoked at this
178810 ** point.
178811 **
178812 ** The xDelete callback, if one is specified, is also invoked on the
178813 ** auxiliary data pointer after the FTS5 query has finished.
178814 **
178815 ** If an error (e.g. an OOM condition) occurs within this function, an
178816 ** the auxiliary data is set to NULL and an error code returned. If the
178817 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
178818 ** pointer before returning.
178819 **
178820 **
178821 ** xGetAuxdata(pFts5, bClear)
178822 **
178823 ** Returns the current auxiliary data pointer for the fts5 extension
178824 ** function. See the xSetAuxdata() method for details.
178825 **
178826 ** If the bClear argument is non-zero, then the auxiliary data is cleared
178827 ** (set to NULL) before this function returns. In this case the xDelete,
178828 ** if any, is not invoked.
178829 **
178830 **
178831 ** xRowCount(pFts5, pnRow)
178832 **
178833 ** This function is used to retrieve the total number of rows in the table.
178834 ** In other words, the same value that would be returned by:
178835 **
178836 ** SELECT count(*) FROM ftstable;
178837 **
178838 ** xPhraseFirst()
178839 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
178840 ** method, to iterate through all instances of a single query phrase within
178841 ** the current row. This is the same information as is accessible via the
178842 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
178843 ** to use, this API may be faster under some circumstances. To iterate
178844 ** through instances of phrase iPhrase, use the following code:
178845 **
178846 ** Fts5PhraseIter iter;
178847 ** int iCol, iOff;
178848 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
178849 ** iCol>=0;
178850 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
178851 ** ){
178852 ** // An instance of phrase iPhrase at offset iOff of column iCol
178853 ** }
178854 **
178855 ** The Fts5PhraseIter structure is defined above. Applications should not
178856 ** modify this structure directly - it should only be used as shown above
178857 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
178858 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
178859 **
178860 ** This API can be quite slow if used with an FTS5 table created with the
178861 ** "detail=none" or "detail=column" option. If the FTS5 table is created
178862 ** with either "detail=none" or "detail=column" and "content=" option
178863 ** (i.e. if it is a contentless table), then this API always iterates
178864 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
178865 **
178866 ** xPhraseNext()
178867 ** See xPhraseFirst above.
178868 **
178869 ** xPhraseFirstColumn()
178870 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
178871 ** and xPhraseNext() APIs described above. The difference is that instead
178872 ** of iterating through all instances of a phrase in the current row, these
178873 ** APIs are used to iterate through the set of columns in the current row
178874 ** that contain one or more instances of a specified phrase. For example:
178875 **
178876 ** Fts5PhraseIter iter;
178877 ** int iCol;
178878 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
178879 ** iCol>=0;
178880 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
178881 ** ){
178882 ** // Column iCol contains at least one instance of phrase iPhrase
178883 ** }
178884 **
178885 ** This API can be quite slow if used with an FTS5 table created with the
178886 ** "detail=none" option. If the FTS5 table is created with either
178887 ** "detail=none" "content=" option (i.e. if it is a contentless table),
178888 ** then this API always iterates through an empty set (all calls to
178889 ** xPhraseFirstColumn() set iCol to -1).
178890 **
178891 ** The information accessed using this API and its companion
178892 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
178893 ** (or xInst/xInstCount). The chief advantage of this API is that it is
178894 ** significantly more efficient than those alternatives when used with
178895 ** "detail=column" tables.
178896 **
178897 ** xPhraseNextColumn()
178898 ** See xPhraseFirstColumn above.
178899 */
178900 struct Fts5ExtensionApi {
178901  int iVersion; /* Currently always set to 3 */
178902 
178903  void *(*xUserData)(Fts5Context*);
178904 
178905  int (*xColumnCount)(Fts5Context*);
178906  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
178907  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
178908 
178909  int (*xTokenize)(Fts5Context*,
178910  const char *pText, int nText, /* Text to tokenize */
178911  void *pCtx, /* Context passed to xToken() */
178912  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
178913  );
178914 
178915  int (*xPhraseCount)(Fts5Context*);
178916  int (*xPhraseSize)(Fts5Context*, int iPhrase);
178917 
178918  int (*xInstCount)(Fts5Context*, int *pnInst);
178919  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
178920 
178921  sqlite3_int64 (*xRowid)(Fts5Context*);
178922  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
178923  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
178924 
178925  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
178926  int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
178927  );
178928  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
178929  void *(*xGetAuxdata)(Fts5Context*, int bClear);
178930 
178931  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
178932  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
178933 
178934  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
178935  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
178936 };
178937 
178938 /*
178939 ** CUSTOM AUXILIARY FUNCTIONS
178940 *************************************************************************/
178941 
178942 /*************************************************************************
178943 ** CUSTOM TOKENIZERS
178944 **
178945 ** Applications may also register custom tokenizer types. A tokenizer
178946 ** is registered by providing fts5 with a populated instance of the
178947 ** following structure. All structure methods must be defined, setting
178948 ** any member of the fts5_tokenizer struct to NULL leads to undefined
178949 ** behaviour. The structure methods are expected to function as follows:
178950 **
178951 ** xCreate:
178952 ** This function is used to allocate and initialize a tokenizer instance.
178953 ** A tokenizer instance is required to actually tokenize text.
178954 **
178955 ** The first argument passed to this function is a copy of the (void*)
178956 ** pointer provided by the application when the fts5_tokenizer object
178957 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
178958 ** The second and third arguments are an array of nul-terminated strings
178959 ** containing the tokenizer arguments, if any, specified following the
178960 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
178961 ** to create the FTS5 table.
178962 **
178963 ** The final argument is an output variable. If successful, (*ppOut)
178964 ** should be set to point to the new tokenizer handle and SQLITE_OK
178965 ** returned. If an error occurs, some value other than SQLITE_OK should
178966 ** be returned. In this case, fts5 assumes that the final value of *ppOut
178967 ** is undefined.
178968 **
178969 ** xDelete:
178970 ** This function is invoked to delete a tokenizer handle previously
178971 ** allocated using xCreate(). Fts5 guarantees that this function will
178972 ** be invoked exactly once for each successful call to xCreate().
178973 **
178974 ** xTokenize:
178975 ** This function is expected to tokenize the nText byte string indicated
178976 ** by argument pText. pText may or may not be nul-terminated. The first
178977 ** argument passed to this function is a pointer to an Fts5Tokenizer object
178978 ** returned by an earlier call to xCreate().
178979 **
178980 ** The second argument indicates the reason that FTS5 is requesting
178981 ** tokenization of the supplied text. This is always one of the following
178982 ** four values:
178983 **
178984 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
178985 ** or removed from the FTS table. The tokenizer is being invoked to
178986 ** determine the set of tokens to add to (or delete from) the
178987 ** FTS index.
178988 **
178989 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
178990 ** against the FTS index. The tokenizer is being called to tokenize
178991 ** a bareword or quoted string specified as part of the query.
178992 **
178993 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
178994 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
178995 ** followed by a "*" character, indicating that the last token
178996 ** returned by the tokenizer will be treated as a token prefix.
178997 **
178998 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
178999 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
179000 ** function. Or an fts5_api.xColumnSize() request made by the same
179001 ** on a columnsize=0 database.
179002 ** </ul>
179003 **
179004 ** For each token in the input string, the supplied callback xToken() must
179005 ** be invoked. The first argument to it should be a copy of the pointer
179006 ** passed as the second argument to xTokenize(). The third and fourth
179007 ** arguments are a pointer to a buffer containing the token text, and the
179008 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
179009 ** of the first byte of and first byte immediately following the text from
179010 ** which the token is derived within the input.
179011 **
179012 ** The second argument passed to the xToken() callback ("tflags") should
179013 ** normally be set to 0. The exception is if the tokenizer supports
179014 ** synonyms. In this case see the discussion below for details.
179015 **
179016 ** FTS5 assumes the xToken() callback is invoked for each token in the
179017 ** order that they occur within the input text.
179018 **
179019 ** If an xToken() callback returns any value other than SQLITE_OK, then
179020 ** the tokenization should be abandoned and the xTokenize() method should
179021 ** immediately return a copy of the xToken() return value. Or, if the
179022 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
179023 ** if an error occurs with the xTokenize() implementation itself, it
179024 ** may abandon the tokenization and return any error code other than
179025 ** SQLITE_OK or SQLITE_DONE.
179026 **
179027 ** SYNONYM SUPPORT
179028 **
179029 ** Custom tokenizers may also support synonyms. Consider a case in which a
179030 ** user wishes to query for a phrase such as "first place". Using the
179031 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
179032 ** of "first place" within the document set, but not alternative forms
179033 ** such as "1st place". In some applications, it would be better to match
179034 ** all instances of "first place" or "1st place" regardless of which form
179035 ** the user specified in the MATCH query text.
179036 **
179037 ** There are several ways to approach this in FTS5:
179038 **
179039 ** <ol><li> By mapping all synonyms to a single token. In this case, the
179040 ** In the above example, this means that the tokenizer returns the
179041 ** same token for inputs "first" and "1st". Say that token is in
179042 ** fact "first", so that when the user inserts the document "I won
179043 ** 1st place" entries are added to the index for tokens "i", "won",
179044 ** "first" and "place". If the user then queries for '1st + place',
179045 ** the tokenizer substitutes "first" for "1st" and the query works
179046 ** as expected.
179047 **
179048 ** <li> By adding multiple synonyms for a single term to the FTS index.
179049 ** In this case, when tokenizing query text, the tokenizer may
179050 ** provide multiple synonyms for a single term within the document.
179051 ** FTS5 then queries the index for each synonym individually. For
179052 ** example, faced with the query:
179053 **
179054 ** <codeblock>
179055 ** ... MATCH 'first place'</codeblock>
179056 **
179057 ** the tokenizer offers both "1st" and "first" as synonyms for the
179058 ** first token in the MATCH query and FTS5 effectively runs a query
179059 ** similar to:
179060 **
179061 ** <codeblock>
179062 ** ... MATCH '(first OR 1st) place'</codeblock>
179063 **
179064 ** except that, for the purposes of auxiliary functions, the query
179065 ** still appears to contain just two phrases - "(first OR 1st)"
179066 ** being treated as a single phrase.
179067 **
179068 ** <li> By adding multiple synonyms for a single term to the FTS index.
179069 ** Using this method, when tokenizing document text, the tokenizer
179070 ** provides multiple synonyms for each token. So that when a
179071 ** document such as "I won first place" is tokenized, entries are
179072 ** added to the FTS index for "i", "won", "first", "1st" and
179073 ** "place".
179074 **
179075 ** This way, even if the tokenizer does not provide synonyms
179076 ** when tokenizing query text (it should not - to do would be
179077 ** inefficient), it doesn't matter if the user queries for
179078 ** 'first + place' or '1st + place', as there are entires in the
179079 ** FTS index corresponding to both forms of the first token.
179080 ** </ol>
179081 **
179082 ** Whether it is parsing document or query text, any call to xToken that
179083 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
179084 ** is considered to supply a synonym for the previous token. For example,
179085 ** when parsing the document "I won first place", a tokenizer that supports
179086 ** synonyms would call xToken() 5 times, as follows:
179087 **
179088 ** <codeblock>
179089 ** xToken(pCtx, 0, "i", 1, 0, 1);
179090 ** xToken(pCtx, 0, "won", 3, 2, 5);
179091 ** xToken(pCtx, 0, "first", 5, 6, 11);
179092 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
179093 ** xToken(pCtx, 0, "place", 5, 12, 17);
179094 **</codeblock>
179095 **
179096 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
179097 ** xToken() is called. Multiple synonyms may be specified for a single token
179098 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
179099 ** There is no limit to the number of synonyms that may be provided for a
179100 ** single token.
179101 **
179102 ** In many cases, method (1) above is the best approach. It does not add
179103 ** extra data to the FTS index or require FTS5 to query for multiple terms,
179104 ** so it is efficient in terms of disk space and query speed. However, it
179105 ** does not support prefix queries very well. If, as suggested above, the
179106 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
179107 **
179108 ** <codeblock>
179109 ** ... MATCH '1s*'</codeblock>
179110 **
179111 ** will not match documents that contain the token "1st" (as the tokenizer
179112 ** will probably not map "1s" to any prefix of "first").
179113 **
179114 ** For full prefix support, method (3) may be preferred. In this case,
179115 ** because the index contains entries for both "first" and "1st", prefix
179116 ** queries such as 'fi*' or '1s*' will match correctly. However, because
179117 ** extra entries are added to the FTS index, this method uses more space
179118 ** within the database.
179119 **
179120 ** Method (2) offers a midpoint between (1) and (3). Using this method,
179121 ** a query such as '1s*' will match documents that contain the literal
179122 ** token "1st", but not "first" (assuming the tokenizer is not able to
179123 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
179124 ** will match against "1st" and "first". This method does not require
179125 ** extra disk space, as no extra entries are added to the FTS index.
179126 ** On the other hand, it may require more CPU cycles to run MATCH queries,
179127 ** as separate queries of the FTS index are required for each synonym.
179128 **
179129 ** When using methods (2) or (3), it is important that the tokenizer only
179130 ** provide synonyms when tokenizing document text (method (2)) or query
179131 ** text (method (3)), not both. Doing so will not cause any errors, but is
179132 ** inefficient.
179133 */
179134 typedef struct Fts5Tokenizer Fts5Tokenizer;
179135 typedef struct fts5_tokenizer fts5_tokenizer;
179136 struct fts5_tokenizer {
179137  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
179138  void (*xDelete)(Fts5Tokenizer*);
179139  int (*xTokenize)(Fts5Tokenizer*,
179140  void *pCtx,
179141  int flags, /* Mask of FTS5_TOKENIZE_* flags */
179142  const char *pText, int nText,
179143  int (*xToken)(
179144  void *pCtx, /* Copy of 2nd argument to xTokenize() */
179145  int tflags, /* Mask of FTS5_TOKEN_* flags */
179146  const char *pToken, /* Pointer to buffer containing token */
179147  int nToken, /* Size of token in bytes */
179148  int iStart, /* Byte offset of token within input text */
179149  int iEnd /* Byte offset of end of token within input text */
179150  )
179151  );
179152 };
179153 
179154 /* Flags that may be passed as the third argument to xTokenize() */
179155 #define FTS5_TOKENIZE_QUERY 0x0001
179156 #define FTS5_TOKENIZE_PREFIX 0x0002
179157 #define FTS5_TOKENIZE_DOCUMENT 0x0004
179158 #define FTS5_TOKENIZE_AUX 0x0008
179159 
179160 /* Flags that may be passed by the tokenizer implementation back to FTS5
179161 ** as the third argument to the supplied xToken callback. */
179162 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
179163 
179164 /*
179165 ** END OF CUSTOM TOKENIZERS
179166 *************************************************************************/
179167 
179168 /*************************************************************************
179169 ** FTS5 EXTENSION REGISTRATION API
179170 */
179171 typedef struct fts5_api fts5_api;
179172 struct fts5_api {
179173  int iVersion; /* Currently always set to 2 */
179174 
179175  /* Create a new tokenizer */
179176  int (*xCreateTokenizer)(
179177  fts5_api *pApi,
179178  const char *zName,
179179  void *pContext,
179180  fts5_tokenizer *pTokenizer,
179181  void (*xDestroy)(void*)
179182  );
179183 
179184  /* Find an existing tokenizer */
179185  int (*xFindTokenizer)(
179186  fts5_api *pApi,
179187  const char *zName,
179188  void **ppContext,
179189  fts5_tokenizer *pTokenizer
179190  );
179191 
179192  /* Create a new auxiliary function */
179193  int (*xCreateFunction)(
179194  fts5_api *pApi,
179195  const char *zName,
179196  void *pContext,
179197  fts5_extension_function xFunction,
179198  void (*xDestroy)(void*)
179199  );
179200 };
179201 
179202 /*
179203 ** END OF REGISTRATION API
179204 *************************************************************************/
179205 
179206 #if 0
179207 } /* end of the 'extern "C"' block */
179208 #endif
179209 
179210 #endif /* _FTS5_H */
179211 
179212 /*
179213 ** 2014 May 31
179214 **
179215 ** The author disclaims copyright to this source code. In place of
179216 ** a legal notice, here is a blessing:
179217 **
179218 ** May you do good and not evil.
179219 ** May you find forgiveness for yourself and forgive others.
179220 ** May you share freely, never taking more than you give.
179221 **
179222 ******************************************************************************
179223 **
179224 */
179225 #ifndef _FTS5INT_H
179226 #define _FTS5INT_H
179227 
179228 /* #include "fts5.h" */
179229 /* #include "sqlite3ext.h" */
179231 
179232 /* #include <string.h> */
179233 /* #include <assert.h> */
179234 
179235 #ifndef SQLITE_AMALGAMATION
179236 
179237 typedef unsigned char u8;
179238 typedef unsigned int u32;
179239 typedef unsigned short u16;
179240 typedef short i16;
179241 typedef sqlite3_int64 i64;
179242 typedef sqlite3_uint64 u64;
179243 
179244 #define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
179245 
179246 #define testcase(x)
179247 #define ALWAYS(x) 1
179248 #define NEVER(x) 0
179249 
179250 #define MIN(x,y) (((x) < (y)) ? (x) : (y))
179251 #define MAX(x,y) (((x) > (y)) ? (x) : (y))
179252 
179253 /*
179254 ** Constants for the largest and smallest possible 64-bit signed integers.
179255 */
179256 # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
179257 # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
179258 
179259 #endif
179260 
179261 /* Truncate very long tokens to this many bytes. Hard limit is
179262 ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
179263 ** field that occurs at the start of each leaf page (see fts5_index.c). */
179264 #define FTS5_MAX_TOKEN_SIZE 32768
179265 
179266 /*
179267 ** Maximum number of prefix indexes on single FTS5 table. This must be
179268 ** less than 32. If it is set to anything large than that, an #error
179269 ** directive in fts5_index.c will cause the build to fail.
179270 */
179271 #define FTS5_MAX_PREFIX_INDEXES 31
179272 
179273 #define FTS5_DEFAULT_NEARDIST 10
179274 #define FTS5_DEFAULT_RANK "bm25"
179275 
179276 /* Name of rank and rowid columns */
179277 #define FTS5_RANK_NAME "rank"
179278 #define FTS5_ROWID_NAME "rowid"
179279 
179280 #ifdef SQLITE_DEBUG
179281 # define FTS5_CORRUPT sqlite3Fts5Corrupt()
179282 static int sqlite3Fts5Corrupt(void);
179283 #else
179284 # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
179285 #endif
179286 
179287 /*
179288 ** The assert_nc() macro is similar to the assert() macro, except that it
179289 ** is used for assert() conditions that are true only if it can be
179290 ** guranteed that the database is not corrupt.
179291 */
179292 #ifdef SQLITE_DEBUG
179293 SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
179294 # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
179295 #else
179296 # define assert_nc(x) assert(x)
179297 #endif
179298 
179299 /* Mark a function parameter as unused, to suppress nuisance compiler
179300 ** warnings. */
179301 #ifndef UNUSED_PARAM
179302 # define UNUSED_PARAM(X) (void)(X)
179303 #endif
179304 
179305 #ifndef UNUSED_PARAM2
179306 # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
179307 #endif
179308 
179309 typedef struct Fts5Global Fts5Global;
179310 typedef struct Fts5Colset Fts5Colset;
179311 
179312 /* If a NEAR() clump or phrase may only match a specific set of columns,
179313 ** then an object of the following type is used to record the set of columns.
179314 ** Each entry in the aiCol[] array is a column that may be matched.
179315 **
179316 ** This object is used by fts5_expr.c and fts5_index.c.
179317 */
179318 struct Fts5Colset {
179319  int nCol;
179320  int aiCol[1];
179321 };
179322 
179323 
179324 
179325 /**************************************************************************
179326 ** Interface to code in fts5_config.c. fts5_config.c contains contains code
179327 ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
179328 */
179329 
179330 typedef struct Fts5Config Fts5Config;
179331 
179332 /*
179333 ** An instance of the following structure encodes all information that can
179334 ** be gleaned from the CREATE VIRTUAL TABLE statement.
179335 **
179336 ** And all information loaded from the %_config table.
179337 **
179338 ** nAutomerge:
179339 ** The minimum number of segments that an auto-merge operation should
179340 ** attempt to merge together. A value of 1 sets the object to use the
179341 ** compile time default. Zero disables auto-merge altogether.
179342 **
179343 ** zContent:
179344 **
179345 ** zContentRowid:
179346 ** The value of the content_rowid= option, if one was specified. Or
179347 ** the string "rowid" otherwise. This text is not quoted - if it is
179348 ** used as part of an SQL statement it needs to be quoted appropriately.
179349 **
179350 ** zContentExprlist:
179351 **
179352 ** pzErrmsg:
179353 ** This exists in order to allow the fts5_index.c module to return a
179354 ** decent error message if it encounters a file-format version it does
179355 ** not understand.
179356 **
179357 ** bColumnsize:
179358 ** True if the %_docsize table is created.
179359 **
179360 ** bPrefixIndex:
179361 ** This is only used for debugging. If set to false, any prefix indexes
179362 ** are ignored. This value is configured using:
179363 **
179364 ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
179365 **
179366 */
179367 struct Fts5Config {
179368  sqlite3 *db; /* Database handle */
179369  char *zDb; /* Database holding FTS index (e.g. "main") */
179370  char *zName; /* Name of FTS index */
179371  int nCol; /* Number of columns */
179372  char **azCol; /* Column names */
179373  u8 *abUnindexed; /* True for unindexed columns */
179374  int nPrefix; /* Number of prefix indexes */
179375  int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
179376  int eContent; /* An FTS5_CONTENT value */
179377  char *zContent; /* content table */
179378  char *zContentRowid; /* "content_rowid=" option value */
179379  int bColumnsize; /* "columnsize=" option value (dflt==1) */
179380  int eDetail; /* FTS5_DETAIL_XXX value */
179381  char *zContentExprlist;
179382  Fts5Tokenizer *pTok;
179383  fts5_tokenizer *pTokApi;
179384 
179385  /* Values loaded from the %_config table */
179386  int iCookie; /* Incremented when %_config is modified */
179387  int pgsz; /* Approximate page size used in %_data */
179388  int nAutomerge; /* 'automerge' setting */
179389  int nCrisisMerge; /* Maximum allowed segments per level */
179390  int nUsermerge; /* 'usermerge' setting */
179391  int nHashSize; /* Bytes of memory for in-memory hash */
179392  char *zRank; /* Name of rank function */
179393  char *zRankArgs; /* Arguments to rank function */
179394 
179395  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
179396  char **pzErrmsg;
179397 
179398 #ifdef SQLITE_DEBUG
179399  int bPrefixIndex; /* True to use prefix-indexes */
179400 #endif
179401 };
179402 
179403 /* Current expected value of %_config table 'version' field */
179404 #define FTS5_CURRENT_VERSION 4
179405 
179406 #define FTS5_CONTENT_NORMAL 0
179407 #define FTS5_CONTENT_NONE 1
179408 #define FTS5_CONTENT_EXTERNAL 2
179409 
179410 #define FTS5_DETAIL_FULL 0
179411 #define FTS5_DETAIL_NONE 1
179412 #define FTS5_DETAIL_COLUMNS 2
179413 
179414 
179415 
179416 static int sqlite3Fts5ConfigParse(
179417  Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
179418 );
179419 static void sqlite3Fts5ConfigFree(Fts5Config*);
179420 
179421 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
179422 
179423 static int sqlite3Fts5Tokenize(
179424  Fts5Config *pConfig, /* FTS5 Configuration object */
179425  int flags, /* FTS5_TOKENIZE_* flags */
179426  const char *pText, int nText, /* Text to tokenize */
179427  void *pCtx, /* Context passed to xToken() */
179428  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
179429 );
179430 
179431 static void sqlite3Fts5Dequote(char *z);
179432 
179433 /* Load the contents of the %_config table */
179434 static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
179435 
179436 /* Set the value of a single config attribute */
179437 static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
179438 
179439 static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
179440 
179441 /*
179442 ** End of interface to code in fts5_config.c.
179443 **************************************************************************/
179444 
179445 /**************************************************************************
179446 ** Interface to code in fts5_buffer.c.
179447 */
179448 
179449 /*
179450 ** Buffer object for the incremental building of string data.
179451 */
179452 typedef struct Fts5Buffer Fts5Buffer;
179453 struct Fts5Buffer {
179454  u8 *p;
179455  int n;
179456  int nSpace;
179457 };
179458 
179459 static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
179460 static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
179461 static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
179462 static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
179463 static void sqlite3Fts5BufferFree(Fts5Buffer*);
179464 static void sqlite3Fts5BufferZero(Fts5Buffer*);
179465 static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
179466 static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
179467 
179468 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
179469 
179470 #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
179471 #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
179472 #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
179473 #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
179474 #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
179475 
179476 #define fts5BufferGrow(pRc,pBuf,nn) ( \
179477  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
179478  sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
179479 )
179480 
179481 /* Write and decode big-endian 32-bit integer values */
179482 static void sqlite3Fts5Put32(u8*, int);
179483 static int sqlite3Fts5Get32(const u8*);
179484 
179485 #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
179486 #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
179487 
179488 typedef struct Fts5PoslistReader Fts5PoslistReader;
179489 struct Fts5PoslistReader {
179490  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
179491  const u8 *a; /* Position list to iterate through */
179492  int n; /* Size of buffer at a[] in bytes */
179493  int i; /* Current offset in a[] */
179494 
179495  u8 bFlag; /* For client use (any custom purpose) */
179496 
179497  /* Output variables */
179498  u8 bEof; /* Set to true at EOF */
179499  i64 iPos; /* (iCol<<32) + iPos */
179500 };
179501 static int sqlite3Fts5PoslistReaderInit(
179502  const u8 *a, int n, /* Poslist buffer to iterate through */
179503  Fts5PoslistReader *pIter /* Iterator object to initialize */
179504 );
179505 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
179506 
179507 typedef struct Fts5PoslistWriter Fts5PoslistWriter;
179508 struct Fts5PoslistWriter {
179509  i64 iPrev;
179510 };
179511 static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
179512 static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
179513 
179514 static int sqlite3Fts5PoslistNext64(
179515  const u8 *a, int n, /* Buffer containing poslist */
179516  int *pi, /* IN/OUT: Offset within a[] */
179517  i64 *piOff /* IN/OUT: Current offset */
179518 );
179519 
179520 /* Malloc utility */
179521 static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
179522 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
179523 
179524 /* Character set tests (like isspace(), isalpha() etc.) */
179525 static int sqlite3Fts5IsBareword(char t);
179526 
179527 
179528 /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
179529 typedef struct Fts5Termset Fts5Termset;
179530 static int sqlite3Fts5TermsetNew(Fts5Termset**);
179531 static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
179532 static void sqlite3Fts5TermsetFree(Fts5Termset*);
179533 
179534 /*
179535 ** End of interface to code in fts5_buffer.c.
179536 **************************************************************************/
179537 
179538 /**************************************************************************
179539 ** Interface to code in fts5_index.c. fts5_index.c contains contains code
179540 ** to access the data stored in the %_data table.
179541 */
179542 
179543 typedef struct Fts5Index Fts5Index;
179544 typedef struct Fts5IndexIter Fts5IndexIter;
179545 
179546 struct Fts5IndexIter {
179547  i64 iRowid;
179548  const u8 *pData;
179549  int nData;
179550  u8 bEof;
179551 };
179552 
179553 #define sqlite3Fts5IterEof(x) ((x)->bEof)
179554 
179555 /*
179556 ** Values used as part of the flags argument passed to IndexQuery().
179557 */
179558 #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
179559 #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
179560 #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
179561 #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
179562 
179563 /* The following are used internally by the fts5_index.c module. They are
179564 ** defined here only to make it easier to avoid clashes with the flags
179565 ** above. */
179566 #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
179567 #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
179568 
179569 /*
179570 ** Create/destroy an Fts5Index object.
179571 */
179572 static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
179573 static int sqlite3Fts5IndexClose(Fts5Index *p);
179574 
179575 /*
179576 ** Return a simple checksum value based on the arguments.
179577 */
179578 static u64 sqlite3Fts5IndexEntryCksum(
179579  i64 iRowid,
179580  int iCol,
179581  int iPos,
179582  int iIdx,
179583  const char *pTerm,
179584  int nTerm
179585 );
179586 
179587 /*
179588 ** Argument p points to a buffer containing utf-8 text that is n bytes in
179589 ** size. Return the number of bytes in the nChar character prefix of the
179590 ** buffer, or 0 if there are less than nChar characters in total.
179591 */
179592 static int sqlite3Fts5IndexCharlenToBytelen(
179593  const char *p,
179594  int nByte,
179595  int nChar
179596 );
179597 
179598 /*
179599 ** Open a new iterator to iterate though all rowids that match the
179600 ** specified token or token prefix.
179601 */
179602 static int sqlite3Fts5IndexQuery(
179603  Fts5Index *p, /* FTS index to query */
179604  const char *pToken, int nToken, /* Token (or prefix) to query for */
179605  int flags, /* Mask of FTS5INDEX_QUERY_X flags */
179606  Fts5Colset *pColset, /* Match these columns only */
179607  Fts5IndexIter **ppIter /* OUT: New iterator object */
179608 );
179609 
179610 /*
179611 ** The various operations on open token or token prefix iterators opened
179612 ** using sqlite3Fts5IndexQuery().
179613 */
179614 static int sqlite3Fts5IterNext(Fts5IndexIter*);
179615 static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
179616 
179617 /*
179618 ** Close an iterator opened by sqlite3Fts5IndexQuery().
179619 */
179620 static void sqlite3Fts5IterClose(Fts5IndexIter*);
179621 
179622 /*
179623 ** This interface is used by the fts5vocab module.
179624 */
179625 static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
179626 static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
179627 
179628 
179629 /*
179630 ** Insert or remove data to or from the index. Each time a document is
179631 ** added to or removed from the index, this function is called one or more
179632 ** times.
179633 **
179634 ** For an insert, it must be called once for each token in the new document.
179635 ** If the operation is a delete, it must be called (at least) once for each
179636 ** unique token in the document with an iCol value less than zero. The iPos
179637 ** argument is ignored for a delete.
179638 */
179639 static int sqlite3Fts5IndexWrite(
179640  Fts5Index *p, /* Index to write to */
179641  int iCol, /* Column token appears in (-ve -> delete) */
179642  int iPos, /* Position of token within column */
179643  const char *pToken, int nToken /* Token to add or remove to or from index */
179644 );
179645 
179646 /*
179647 ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
179648 ** document iDocid.
179649 */
179650 static int sqlite3Fts5IndexBeginWrite(
179651  Fts5Index *p, /* Index to write to */
179652  int bDelete, /* True if current operation is a delete */
179653  i64 iDocid /* Docid to add or remove data from */
179654 );
179655 
179656 /*
179657 ** Flush any data stored in the in-memory hash tables to the database.
179658 ** If the bCommit flag is true, also close any open blob handles.
179659 */
179660 static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
179661 
179662 /*
179663 ** Discard any data stored in the in-memory hash tables. Do not write it
179664 ** to the database. Additionally, assume that the contents of the %_data
179665 ** table may have changed on disk. So any in-memory caches of %_data
179666 ** records must be invalidated.
179667 */
179668 static int sqlite3Fts5IndexRollback(Fts5Index *p);
179669 
179670 /*
179671 ** Get or set the "averages" values.
179672 */
179673 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
179674 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
179675 
179676 /*
179677 ** Functions called by the storage module as part of integrity-check.
179678 */
179679 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
179680 
179681 /*
179682 ** Called during virtual module initialization to register UDF
179683 ** fts5_decode() with SQLite
179684 */
179685 static int sqlite3Fts5IndexInit(sqlite3*);
179686 
179687 static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
179688 
179689 /*
179690 ** Return the total number of entries read from the %_data table by
179691 ** this connection since it was created.
179692 */
179693 static int sqlite3Fts5IndexReads(Fts5Index *p);
179694 
179695 static int sqlite3Fts5IndexReinit(Fts5Index *p);
179696 static int sqlite3Fts5IndexOptimize(Fts5Index *p);
179697 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
179698 static int sqlite3Fts5IndexReset(Fts5Index *p);
179699 
179700 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
179701 
179702 /*
179703 ** End of interface to code in fts5_index.c.
179704 **************************************************************************/
179705 
179706 /**************************************************************************
179707 ** Interface to code in fts5_varint.c.
179708 */
179709 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
179710 static int sqlite3Fts5GetVarintLen(u32 iVal);
179711 static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
179712 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
179713 
179714 #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
179715 #define fts5GetVarint sqlite3Fts5GetVarint
179716 
179717 #define fts5FastGetVarint32(a, iOff, nVal) { \
179718  nVal = (a)[iOff++]; \
179719  if( nVal & 0x80 ){ \
179720  iOff--; \
179721  iOff += fts5GetVarint32(&(a)[iOff], nVal); \
179722  } \
179723 }
179724 
179725 
179726 /*
179727 ** End of interface to code in fts5_varint.c.
179728 **************************************************************************/
179729 
179730 
179731 /**************************************************************************
179732 ** Interface to code in fts5.c.
179733 */
179734 
179735 static int sqlite3Fts5GetTokenizer(
179736  Fts5Global*,
179737  const char **azArg,
179738  int nArg,
179739  Fts5Tokenizer**,
179740  fts5_tokenizer**,
179741  char **pzErr
179742 );
179743 
179744 static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
179745 
179746 /*
179747 ** End of interface to code in fts5.c.
179748 **************************************************************************/
179749 
179750 /**************************************************************************
179751 ** Interface to code in fts5_hash.c.
179752 */
179753 typedef struct Fts5Hash Fts5Hash;
179754 
179755 /*
179756 ** Create a hash table, free a hash table.
179757 */
179758 static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
179759 static void sqlite3Fts5HashFree(Fts5Hash*);
179760 
179761 static int sqlite3Fts5HashWrite(
179762  Fts5Hash*,
179763  i64 iRowid, /* Rowid for this entry */
179764  int iCol, /* Column token appears in (-ve -> delete) */
179765  int iPos, /* Position of token within column */
179766  char bByte,
179767  const char *pToken, int nToken /* Token to add or remove to or from index */
179768 );
179769 
179770 /*
179771 ** Empty (but do not delete) a hash table.
179772 */
179773 static void sqlite3Fts5HashClear(Fts5Hash*);
179774 
179775 static int sqlite3Fts5HashQuery(
179776  Fts5Hash*, /* Hash table to query */
179777  const char *pTerm, int nTerm, /* Query term */
179778  const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
179779  int *pnDoclist /* OUT: Size of doclist in bytes */
179780 );
179781 
179782 static int sqlite3Fts5HashScanInit(
179783  Fts5Hash*, /* Hash table to query */
179784  const char *pTerm, int nTerm /* Query prefix */
179785 );
179786 static void sqlite3Fts5HashScanNext(Fts5Hash*);
179787 static int sqlite3Fts5HashScanEof(Fts5Hash*);
179788 static void sqlite3Fts5HashScanEntry(Fts5Hash *,
179789  const char **pzTerm, /* OUT: term (nul-terminated) */
179790  const u8 **ppDoclist, /* OUT: pointer to doclist */
179791  int *pnDoclist /* OUT: size of doclist in bytes */
179792 );
179793 
179794 
179795 /*
179796 ** End of interface to code in fts5_hash.c.
179797 **************************************************************************/
179798 
179799 /**************************************************************************
179800 ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
179801 ** code to access the data stored in the %_content and %_docsize tables.
179802 */
179803 
179804 #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
179805 #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
179806 #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
179807 
179808 typedef struct Fts5Storage Fts5Storage;
179809 
179810 static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
179811 static int sqlite3Fts5StorageClose(Fts5Storage *p);
179812 static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
179813 
179814 static int sqlite3Fts5DropAll(Fts5Config*);
179815 static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
179816 
179817 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
179818 static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
179819 static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
179820 
179821 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
179822 
179823 static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
179824 static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
179825 
179826 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
179827 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
179828 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
179829 
179830 static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
179831 static int sqlite3Fts5StorageRollback(Fts5Storage *p);
179832 
179833 static int sqlite3Fts5StorageConfigValue(
179834  Fts5Storage *p, const char*, sqlite3_value*, int
179835 );
179836 
179837 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
179838 static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
179839 static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
179840 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
179841 static int sqlite3Fts5StorageReset(Fts5Storage *p);
179842 
179843 /*
179844 ** End of interface to code in fts5_storage.c.
179845 **************************************************************************/
179846 
179847 
179848 /**************************************************************************
179849 ** Interface to code in fts5_expr.c.
179850 */
179851 typedef struct Fts5Expr Fts5Expr;
179852 typedef struct Fts5ExprNode Fts5ExprNode;
179853 typedef struct Fts5Parse Fts5Parse;
179854 typedef struct Fts5Token Fts5Token;
179855 typedef struct Fts5ExprPhrase Fts5ExprPhrase;
179856 typedef struct Fts5ExprNearset Fts5ExprNearset;
179857 
179858 struct Fts5Token {
179859  const char *p; /* Token text (not NULL terminated) */
179860  int n; /* Size of buffer p in bytes */
179861 };
179862 
179863 /* Parse a MATCH expression. */
179864 static int sqlite3Fts5ExprNew(
179865  Fts5Config *pConfig,
179866  const char *zExpr,
179867  Fts5Expr **ppNew,
179868  char **pzErr
179869 );
179870 
179871 /*
179872 ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
179873 ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
179874 ** rc = sqlite3Fts5ExprNext(pExpr)
179875 ** ){
179876 ** // The document with rowid iRowid matches the expression!
179877 ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
179878 ** }
179879 */
179880 static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
179881 static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
179882 static int sqlite3Fts5ExprEof(Fts5Expr*);
179883 static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
179884 
179885 static void sqlite3Fts5ExprFree(Fts5Expr*);
179886 
179887 /* Called during startup to register a UDF with SQLite */
179888 static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
179889 
179890 static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
179891 static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
179892 static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
179893 
179894 typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
179895 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
179896 static int sqlite3Fts5ExprPopulatePoslists(
179897  Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
179898 );
179899 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
179900 
179901 static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
179902 
179903 static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
179904 
179905 /*******************************************
179906 ** The fts5_expr.c API above this point is used by the other hand-written
179907 ** C code in this module. The interfaces below this point are called by
179908 ** the parser code in fts5parse.y. */
179909 
179910 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
179911 
179912 static Fts5ExprNode *sqlite3Fts5ParseNode(
179913  Fts5Parse *pParse,
179914  int eType,
179915  Fts5ExprNode *pLeft,
179916  Fts5ExprNode *pRight,
179917  Fts5ExprNearset *pNear
179918 );
179919 
179920 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
179921  Fts5Parse *pParse,
179922  Fts5ExprNode *pLeft,
179923  Fts5ExprNode *pRight
179924 );
179925 
179926 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
179927  Fts5Parse *pParse,
179928  Fts5ExprPhrase *pPhrase,
179929  Fts5Token *pToken,
179930  int bPrefix
179931 );
179932 
179933 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
179934  Fts5Parse*,
179935  Fts5ExprNearset*,
179936  Fts5ExprPhrase*
179937 );
179938 
179939 static Fts5Colset *sqlite3Fts5ParseColset(
179940  Fts5Parse*,
179941  Fts5Colset*,
179942  Fts5Token *
179943 );
179944 
179945 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
179946 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
179947 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
179948 
179949 static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
179950 static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
179951 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
179952 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
179953 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
179954 
179955 /*
179956 ** End of interface to code in fts5_expr.c.
179957 **************************************************************************/
179958 
179959 
179960 
179961 /**************************************************************************
179962 ** Interface to code in fts5_aux.c.
179963 */
179964 
179965 static int sqlite3Fts5AuxInit(fts5_api*);
179966 /*
179967 ** End of interface to code in fts5_aux.c.
179968 **************************************************************************/
179969 
179970 /**************************************************************************
179971 ** Interface to code in fts5_tokenizer.c.
179972 */
179973 
179974 static int sqlite3Fts5TokenizerInit(fts5_api*);
179975 /*
179976 ** End of interface to code in fts5_tokenizer.c.
179977 **************************************************************************/
179978 
179979 /**************************************************************************
179980 ** Interface to code in fts5_vocab.c.
179981 */
179982 
179983 static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
179984 
179985 /*
179986 ** End of interface to code in fts5_vocab.c.
179987 **************************************************************************/
179988 
179989 
179990 /**************************************************************************
179991 ** Interface to automatically generated code in fts5_unicode2.c.
179992 */
179993 static int sqlite3Fts5UnicodeIsalnum(int c);
179994 static int sqlite3Fts5UnicodeIsdiacritic(int c);
179995 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
179996 /*
179997 ** End of interface to code in fts5_unicode2.c.
179998 **************************************************************************/
179999 
180000 #endif
180001 
180002 #define FTS5_OR 1
180003 #define FTS5_AND 2
180004 #define FTS5_NOT 3
180005 #define FTS5_TERM 4
180006 #define FTS5_COLON 5
180007 #define FTS5_LP 6
180008 #define FTS5_RP 7
180009 #define FTS5_MINUS 8
180010 #define FTS5_LCP 9
180011 #define FTS5_RCP 10
180012 #define FTS5_STRING 11
180013 #define FTS5_COMMA 12
180014 #define FTS5_PLUS 13
180015 #define FTS5_STAR 14
180016 
180017 /*
180018 ** 2000-05-29
180019 **
180020 ** The author disclaims copyright to this source code. In place of
180021 ** a legal notice, here is a blessing:
180022 **
180023 ** May you do good and not evil.
180024 ** May you find forgiveness for yourself and forgive others.
180025 ** May you share freely, never taking more than you give.
180026 **
180027 *************************************************************************
180028 ** Driver template for the LEMON parser generator.
180029 **
180030 ** The "lemon" program processes an LALR(1) input grammar file, then uses
180031 ** this template to construct a parser. The "lemon" program inserts text
180032 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
180033 ** interstitial "-" characters) contained in this template is changed into
180034 ** the value of the %name directive from the grammar. Otherwise, the content
180035 ** of this template is copied straight through into the generate parser
180036 ** source file.
180037 **
180038 ** The following is the concatenation of all %include directives from the
180039 ** input grammar file:
180040 */
180041 /* #include <stdio.h> */
180042 /************ Begin %include sections from the grammar ************************/
180043 
180044 /* #include "fts5Int.h" */
180045 /* #include "fts5parse.h" */
180046 
180047 /*
180048 ** Disable all error recovery processing in the parser push-down
180049 ** automaton.
180050 */
180051 #define fts5YYNOERRORRECOVERY 1
180052 
180053 /*
180054 ** Make fts5yytestcase() the same as testcase()
180055 */
180056 #define fts5yytestcase(X) testcase(X)
180057 
180058 /*
180059 ** Indicate that sqlite3ParserFree() will never be called with a null
180060 ** pointer.
180061 */
180062 #define fts5YYPARSEFREENOTNULL 1
180063 
180064 /*
180065 ** Alternative datatype for the argument to the malloc() routine passed
180066 ** into sqlite3ParserAlloc(). The default is size_t.
180067 */
180068 #define fts5YYMALLOCARGTYPE u64
180069 
180070 /**************** End of %include directives **********************************/
180071 /* These constants specify the various numeric values for terminal symbols
180072 ** in a format understandable to "makeheaders". This section is blank unless
180073 ** "lemon" is run with the "-m" command-line option.
180074 ***************** Begin makeheaders token definitions *************************/
180075 /**************** End makeheaders token definitions ***************************/
180076 
180077 /* The next sections is a series of control #defines.
180078 ** various aspects of the generated parser.
180079 ** fts5YYCODETYPE is the data type used to store the integer codes
180080 ** that represent terminal and non-terminal symbols.
180081 ** "unsigned char" is used if there are fewer than
180082 ** 256 symbols. Larger types otherwise.
180083 ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
180084 ** any terminal or nonterminal symbol.
180085 ** fts5YYFALLBACK If defined, this indicates that one or more tokens
180086 ** (also known as: "terminal symbols") have fall-back
180087 ** values which should be used if the original symbol
180088 ** would not parse. This permits keywords to sometimes
180089 ** be used as identifiers, for example.
180090 ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
180091 ** that indicate what to do in response to the next
180092 ** token.
180093 ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
180094 ** symbols. Background: A "minor type" is a semantic
180095 ** value associated with a terminal or non-terminal
180096 ** symbols. For example, for an "ID" terminal symbol,
180097 ** the minor type might be the name of the identifier.
180098 ** Each non-terminal can have a different minor type.
180099 ** Terminal symbols all have the same minor type, though.
180100 ** This macros defines the minor type for terminal
180101 ** symbols.
180102 ** fts5YYMINORTYPE is the data type used for all minor types.
180103 ** This is typically a union of many types, one of
180104 ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
180105 ** for terminal symbols is called "fts5yy0".
180106 ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
180107 ** zero the stack is dynamically sized using realloc()
180108 ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
180109 ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
180110 ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
180111 ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
180112 ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
180113 ** defined, then do no error processing.
180114 ** fts5YYNSTATE the combined number of states.
180115 ** fts5YYNRULE the number of rules in the grammar
180116 ** fts5YY_MAX_SHIFT Maximum value for shift actions
180117 ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
180118 ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
180119 ** fts5YY_MIN_REDUCE Maximum value for reduce actions
180120 ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
180121 ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
180122 ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
180123 */
180124 #ifndef INTERFACE
180125 # define INTERFACE 1
180126 #endif
180127 /************* Begin control #defines *****************************************/
180128 #define fts5YYCODETYPE unsigned char
180129 #define fts5YYNOCODE 28
180130 #define fts5YYACTIONTYPE unsigned char
180131 #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
180132 typedef union {
180133  int fts5yyinit;
180134  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
180135  int fts5yy4;
180136  Fts5Colset* fts5yy11;
180137  Fts5ExprNode* fts5yy24;
180138  Fts5ExprNearset* fts5yy46;
180139  Fts5ExprPhrase* fts5yy53;
180140 } fts5YYMINORTYPE;
180141 #ifndef fts5YYSTACKDEPTH
180142 #define fts5YYSTACKDEPTH 100
180143 #endif
180144 #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
180145 #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
180146 #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
180147 #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
180148 #define fts5YYNSTATE 29
180149 #define fts5YYNRULE 26
180150 #define fts5YY_MAX_SHIFT 28
180151 #define fts5YY_MIN_SHIFTREDUCE 45
180152 #define fts5YY_MAX_SHIFTREDUCE 70
180153 #define fts5YY_MIN_REDUCE 71
180154 #define fts5YY_MAX_REDUCE 96
180155 #define fts5YY_ERROR_ACTION 97
180156 #define fts5YY_ACCEPT_ACTION 98
180157 #define fts5YY_NO_ACTION 99
180158 /************* End control #defines *******************************************/
180159 
180160 /* Define the fts5yytestcase() macro to be a no-op if is not already defined
180161 ** otherwise.
180162 **
180163 ** Applications can choose to define fts5yytestcase() in the %include section
180164 ** to a macro that can assist in verifying code coverage. For production
180165 ** code the fts5yytestcase() macro should be turned off. But it is useful
180166 ** for testing.
180167 */
180168 #ifndef fts5yytestcase
180169 # define fts5yytestcase(X)
180170 #endif
180171 
180172 
180173 /* Next are the tables used to determine what action to take based on the
180174 ** current state and lookahead token. These tables are used to implement
180175 ** functions that take a state number and lookahead value and return an
180176 ** action integer.
180177 **
180178 ** Suppose the action integer is N. Then the action is determined as
180179 ** follows
180180 **
180181 ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
180182 ** token onto the stack and goto state N.
180183 **
180184 ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
180185 ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
180186 **
180187 ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
180188 ** and fts5YY_MAX_REDUCE
180189 **
180190 ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
180191 **
180192 ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
180193 **
180194 ** N == fts5YY_NO_ACTION No such action. Denotes unused
180195 ** slots in the fts5yy_action[] table.
180196 **
180197 ** The action table is constructed as a single large table named fts5yy_action[].
180198 ** Given state S and lookahead X, the action is computed as either:
180199 **
180200 ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
180201 ** (B) N = fts5yy_default[S]
180202 **
180203 ** The (A) formula is preferred. The B formula is used instead if:
180204 ** (1) The fts5yy_shift_ofst[S]+X value is out of range, or
180205 ** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
180206 ** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
180207 ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
180208 ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
180209 ** Hence only tests (1) and (2) need to be evaluated.)
180210 **
180211 ** The formulas above are for computing the action when the lookahead is
180212 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
180213 ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
180214 ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
180215 ** fts5YY_SHIFT_USE_DFLT.
180216 **
180217 ** The following are the tables generated in this section:
180218 **
180219 ** fts5yy_action[] A single table containing all actions.
180220 ** fts5yy_lookahead[] A table containing the lookahead for each entry in
180221 ** fts5yy_action. Used to detect hash collisions.
180222 ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
180223 ** shifting terminals.
180224 ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
180225 ** shifting non-terminals after a reduce.
180226 ** fts5yy_default[] Default action for each state.
180227 **
180228 *********** Begin parsing tables **********************************************/
180229 #define fts5YY_ACTTAB_COUNT (85)
180230 static const fts5YYACTIONTYPE fts5yy_action[] = {
180231  /* 0 */ 98, 16, 51, 5, 53, 27, 83, 7, 26, 15,
180232  /* 10 */ 51, 5, 53, 27, 13, 69, 26, 48, 51, 5,
180233  /* 20 */ 53, 27, 19, 11, 26, 9, 20, 51, 5, 53,
180234  /* 30 */ 27, 13, 22, 26, 28, 51, 5, 53, 27, 68,
180235  /* 40 */ 1, 26, 19, 11, 17, 9, 52, 10, 53, 27,
180236  /* 50 */ 23, 24, 26, 54, 3, 4, 2, 26, 6, 21,
180237  /* 60 */ 49, 71, 3, 4, 2, 7, 56, 59, 55, 59,
180238  /* 70 */ 4, 2, 12, 69, 58, 60, 18, 67, 62, 69,
180239  /* 80 */ 25, 66, 8, 14, 2,
180240 };
180241 static const fts5YYCODETYPE fts5yy_lookahead[] = {
180242  /* 0 */ 16, 17, 18, 19, 20, 21, 5, 6, 24, 17,
180243  /* 10 */ 18, 19, 20, 21, 11, 14, 24, 17, 18, 19,
180244  /* 20 */ 20, 21, 8, 9, 24, 11, 17, 18, 19, 20,
180245  /* 30 */ 21, 11, 12, 24, 17, 18, 19, 20, 21, 26,
180246  /* 40 */ 6, 24, 8, 9, 22, 11, 18, 11, 20, 21,
180247  /* 50 */ 24, 25, 24, 20, 1, 2, 3, 24, 23, 24,
180248  /* 60 */ 7, 0, 1, 2, 3, 6, 10, 11, 10, 11,
180249  /* 70 */ 2, 3, 9, 14, 11, 11, 22, 26, 7, 14,
180250  /* 80 */ 13, 11, 5, 11, 3,
180251 };
180252 #define fts5YY_SHIFT_USE_DFLT (85)
180253 #define fts5YY_SHIFT_COUNT (28)
180254 #define fts5YY_SHIFT_MIN (0)
180255 #define fts5YY_SHIFT_MAX (81)
180256 static const unsigned char fts5yy_shift_ofst[] = {
180257  /* 0 */ 34, 34, 34, 34, 34, 14, 20, 3, 36, 1,
180258  /* 10 */ 59, 64, 64, 65, 65, 53, 61, 56, 58, 63,
180259  /* 20 */ 68, 67, 70, 67, 71, 72, 67, 77, 81,
180260 };
180261 #define fts5YY_REDUCE_USE_DFLT (-17)
180262 #define fts5YY_REDUCE_COUNT (14)
180263 #define fts5YY_REDUCE_MIN (-16)
180264 #define fts5YY_REDUCE_MAX (54)
180265 static const signed char fts5yy_reduce_ofst[] = {
180266  /* 0 */ -16, -8, 0, 9, 17, 28, 26, 35, 33, 13,
180267  /* 10 */ 13, 22, 54, 13, 51,
180268 };
180269 static const fts5YYACTIONTYPE fts5yy_default[] = {
180270  /* 0 */ 97, 97, 97, 97, 97, 76, 91, 97, 97, 96,
180271  /* 10 */ 96, 97, 97, 96, 96, 97, 97, 97, 97, 97,
180272  /* 20 */ 73, 89, 97, 90, 97, 97, 87, 97, 72,
180273 };
180274 /********** End of lemon-generated parsing tables *****************************/
180275 
180276 /* The next table maps tokens (terminal symbols) into fallback tokens.
180277 ** If a construct like the following:
180278 **
180279 ** %fallback ID X Y Z.
180280 **
180281 ** appears in the grammar, then ID becomes a fallback token for X, Y,
180282 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
180283 ** but it does not parse, the type of the token is changed to ID and
180284 ** the parse is retried before an error is thrown.
180285 **
180286 ** This feature can be used, for example, to cause some keywords in a language
180287 ** to revert to identifiers if they keyword does not apply in the context where
180288 ** it appears.
180289 */
180290 #ifdef fts5YYFALLBACK
180291 static const fts5YYCODETYPE fts5yyFallback[] = {
180292 };
180293 #endif /* fts5YYFALLBACK */
180294 
180295 /* The following structure represents a single element of the
180296 ** parser's stack. Information stored includes:
180297 **
180298 ** + The state number for the parser at this level of the stack.
180299 **
180300 ** + The value of the token stored at this level of the stack.
180301 ** (In other words, the "major" token.)
180302 **
180303 ** + The semantic value stored at this level of the stack. This is
180304 ** the information used by the action routines in the grammar.
180305 ** It is sometimes called the "minor" token.
180306 **
180307 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
180308 ** actually contains the reduce action for the second half of the
180309 ** SHIFTREDUCE.
180310 */
180311 struct fts5yyStackEntry {
180312  fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
180313  fts5YYCODETYPE major; /* The major token value. This is the code
180314  ** number for the token at this stack level */
180315  fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
180316  ** is the value of the token */
180317 };
180318 typedef struct fts5yyStackEntry fts5yyStackEntry;
180319 
180320 /* The state of the parser is completely contained in an instance of
180321 ** the following structure */
180322 struct fts5yyParser {
180323  fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
180324 #ifdef fts5YYTRACKMAXSTACKDEPTH
180325  int fts5yyhwm; /* High-water mark of the stack */
180326 #endif
180327 #ifndef fts5YYNOERRORRECOVERY
180328  int fts5yyerrcnt; /* Shifts left before out of the error */
180329 #endif
180330  sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
180331 #if fts5YYSTACKDEPTH<=0
180332  int fts5yystksz; /* Current side of the stack */
180333  fts5yyStackEntry *fts5yystack; /* The parser's stack */
180334  fts5yyStackEntry fts5yystk0; /* First stack entry */
180335 #else
180336  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
180337 #endif
180338 };
180339 typedef struct fts5yyParser fts5yyParser;
180340 
180341 #ifndef NDEBUG
180342 /* #include <stdio.h> */
180343 static FILE *fts5yyTraceFILE = 0;
180344 static char *fts5yyTracePrompt = 0;
180345 #endif /* NDEBUG */
180346 
180347 #ifndef NDEBUG
180348 /*
180349 ** Turn parser tracing on by giving a stream to which to write the trace
180350 ** and a prompt to preface each trace message. Tracing is turned off
180351 ** by making either argument NULL
180352 **
180353 ** Inputs:
180354 ** <ul>
180355 ** <li> A FILE* to which trace output should be written.
180356 ** If NULL, then tracing is turned off.
180357 ** <li> A prefix string written at the beginning of every
180358 ** line of trace output. If NULL, then tracing is
180359 ** turned off.
180360 ** </ul>
180361 **
180362 ** Outputs:
180363 ** None.
180364 */
180365 static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
180366  fts5yyTraceFILE = TraceFILE;
180367  fts5yyTracePrompt = zTracePrompt;
180368  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
180369  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
180370 }
180371 #endif /* NDEBUG */
180372 
180373 #ifndef NDEBUG
180374 /* For tracing shifts, the names of all terminals and nonterminals
180375 ** are required. The following table supplies these names */
180376 static const char *const fts5yyTokenName[] = {
180377  "$", "OR", "AND", "NOT",
180378  "TERM", "COLON", "LP", "RP",
180379  "MINUS", "LCP", "RCP", "STRING",
180380  "COMMA", "PLUS", "STAR", "error",
180381  "input", "expr", "cnearset", "exprlist",
180382  "nearset", "colset", "colsetlist", "nearphrases",
180383  "phrase", "neardist_opt", "star_opt",
180384 };
180385 #endif /* NDEBUG */
180386 
180387 #ifndef NDEBUG
180388 /* For tracing reduce actions, the names of all rules are required.
180389 */
180390 static const char *const fts5yyRuleName[] = {
180391  /* 0 */ "input ::= expr",
180392  /* 1 */ "expr ::= expr AND expr",
180393  /* 2 */ "expr ::= expr OR expr",
180394  /* 3 */ "expr ::= expr NOT expr",
180395  /* 4 */ "expr ::= LP expr RP",
180396  /* 5 */ "expr ::= exprlist",
180397  /* 6 */ "exprlist ::= cnearset",
180398  /* 7 */ "exprlist ::= exprlist cnearset",
180399  /* 8 */ "cnearset ::= nearset",
180400  /* 9 */ "cnearset ::= colset COLON nearset",
180401  /* 10 */ "colset ::= MINUS LCP colsetlist RCP",
180402  /* 11 */ "colset ::= LCP colsetlist RCP",
180403  /* 12 */ "colset ::= STRING",
180404  /* 13 */ "colset ::= MINUS STRING",
180405  /* 14 */ "colsetlist ::= colsetlist STRING",
180406  /* 15 */ "colsetlist ::= STRING",
180407  /* 16 */ "nearset ::= phrase",
180408  /* 17 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
180409  /* 18 */ "nearphrases ::= phrase",
180410  /* 19 */ "nearphrases ::= nearphrases phrase",
180411  /* 20 */ "neardist_opt ::=",
180412  /* 21 */ "neardist_opt ::= COMMA STRING",
180413  /* 22 */ "phrase ::= phrase PLUS STRING star_opt",
180414  /* 23 */ "phrase ::= STRING star_opt",
180415  /* 24 */ "star_opt ::= STAR",
180416  /* 25 */ "star_opt ::=",
180417 };
180418 #endif /* NDEBUG */
180419 
180420 
180421 #if fts5YYSTACKDEPTH<=0
180422 /*
180423 ** Try to increase the size of the parser stack. Return the number
180424 ** of errors. Return 0 on success.
180425 */
180426 static int fts5yyGrowStack(fts5yyParser *p){
180427  int newSize;
180428  int idx;
180429  fts5yyStackEntry *pNew;
180430 
180431  newSize = p->fts5yystksz*2 + 100;
180432  idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
180433  if( p->fts5yystack==&p->fts5yystk0 ){
180434  pNew = malloc(newSize*sizeof(pNew[0]));
180435  if( pNew ) pNew[0] = p->fts5yystk0;
180436  }else{
180437  pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
180438  }
180439  if( pNew ){
180440  p->fts5yystack = pNew;
180441  p->fts5yytos = &p->fts5yystack[idx];
180442 #ifndef NDEBUG
180443  if( fts5yyTraceFILE ){
180444  fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
180445  fts5yyTracePrompt, p->fts5yystksz, newSize);
180446  }
180447 #endif
180448  p->fts5yystksz = newSize;
180449  }
180450  return pNew==0;
180451 }
180452 #endif
180453 
180454 /* Datatype of the argument to the memory allocated passed as the
180455 ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
180456 ** putting an appropriate #define in the %include section of the input
180457 ** grammar.
180458 */
180459 #ifndef fts5YYMALLOCARGTYPE
180460 # define fts5YYMALLOCARGTYPE size_t
180461 #endif
180462 
180463 /*
180464 ** This function allocates a new parser.
180465 ** The only argument is a pointer to a function which works like
180466 ** malloc.
180467 **
180468 ** Inputs:
180469 ** A pointer to the function used to allocate memory.
180470 **
180471 ** Outputs:
180472 ** A pointer to a parser. This pointer is used in subsequent calls
180473 ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
180474 */
180475 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
180476  fts5yyParser *pParser;
180477  pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
180478  if( pParser ){
180479 #ifdef fts5YYTRACKMAXSTACKDEPTH
180480  pParser->fts5yyhwm = 0;
180481 #endif
180482 #if fts5YYSTACKDEPTH<=0
180483  pParser->fts5yytos = NULL;
180484  pParser->fts5yystack = NULL;
180485  pParser->fts5yystksz = 0;
180486  if( fts5yyGrowStack(pParser) ){
180487  pParser->fts5yystack = &pParser->fts5yystk0;
180488  pParser->fts5yystksz = 1;
180489  }
180490 #endif
180491 #ifndef fts5YYNOERRORRECOVERY
180492  pParser->fts5yyerrcnt = -1;
180493 #endif
180494  pParser->fts5yytos = pParser->fts5yystack;
180495  pParser->fts5yystack[0].stateno = 0;
180496  pParser->fts5yystack[0].major = 0;
180497  }
180498  return pParser;
180499 }
180500 
180501 /* The following function deletes the "minor type" or semantic value
180502 ** associated with a symbol. The symbol can be either a terminal
180503 ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
180504 ** a pointer to the value to be deleted. The code used to do the
180505 ** deletions is derived from the %destructor and/or %token_destructor
180506 ** directives of the input grammar.
180507 */
180508 static void fts5yy_destructor(
180509  fts5yyParser *fts5yypParser, /* The parser */
180510  fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
180511  fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
180512 ){
180513  sqlite3Fts5ParserARG_FETCH;
180514  switch( fts5yymajor ){
180515  /* Here is inserted the actions which take place when a
180516  ** terminal or non-terminal is destroyed. This can happen
180517  ** when the symbol is popped from the stack during a
180518  ** reduce or during error processing or when a parser is
180519  ** being destroyed before it is finished parsing.
180520  **
180521  ** Note: during a reduce, the only symbols destroyed are those
180522  ** which appear on the RHS of the rule, but which are *not* used
180523  ** inside the C code.
180524  */
180525 /********* Begin destructor definitions ***************************************/
180526  case 16: /* input */
180527 {
180528  (void)pParse;
180529 }
180530  break;
180531  case 17: /* expr */
180532  case 18: /* cnearset */
180533  case 19: /* exprlist */
180534 {
180535  sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
180536 }
180537  break;
180538  case 20: /* nearset */
180539  case 23: /* nearphrases */
180540 {
180541  sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
180542 }
180543  break;
180544  case 21: /* colset */
180545  case 22: /* colsetlist */
180546 {
180547  sqlite3_free((fts5yypminor->fts5yy11));
180548 }
180549  break;
180550  case 24: /* phrase */
180551 {
180552  sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
180553 }
180554  break;
180555 /********* End destructor definitions *****************************************/
180556  default: break; /* If no destructor action specified: do nothing */
180557  }
180558 }
180559 
180560 /*
180561 ** Pop the parser's stack once.
180562 **
180563 ** If there is a destructor routine associated with the token which
180564 ** is popped from the stack, then call it.
180565 */
180566 static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
180567  fts5yyStackEntry *fts5yytos;
180568  assert( pParser->fts5yytos!=0 );
180569  assert( pParser->fts5yytos > pParser->fts5yystack );
180570  fts5yytos = pParser->fts5yytos--;
180571 #ifndef NDEBUG
180572  if( fts5yyTraceFILE ){
180573  fprintf(fts5yyTraceFILE,"%sPopping %s\n",
180574  fts5yyTracePrompt,
180575  fts5yyTokenName[fts5yytos->major]);
180576  }
180577 #endif
180578  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
180579 }
180580 
180581 /*
180582 ** Deallocate and destroy a parser. Destructors are called for
180583 ** all stack elements before shutting the parser down.
180584 **
180585 ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
180586 ** is defined in a %include section of the input grammar) then it is
180587 ** assumed that the input pointer is never NULL.
180588 */
180589 static void sqlite3Fts5ParserFree(
180590  void *p, /* The parser to be deleted */
180591  void (*freeProc)(void*) /* Function used to reclaim memory */
180592 ){
180593  fts5yyParser *pParser = (fts5yyParser*)p;
180594 #ifndef fts5YYPARSEFREENEVERNULL
180595  if( pParser==0 ) return;
180596 #endif
180597  while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
180598 #if fts5YYSTACKDEPTH<=0
180599  if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
180600 #endif
180601  (*freeProc)((void*)pParser);
180602 }
180603 
180604 /*
180605 ** Return the peak depth of the stack for a parser.
180606 */
180607 #ifdef fts5YYTRACKMAXSTACKDEPTH
180608 static int sqlite3Fts5ParserStackPeak(void *p){
180609  fts5yyParser *pParser = (fts5yyParser*)p;
180610  return pParser->fts5yyhwm;
180611 }
180612 #endif
180613 
180614 /*
180615 ** Find the appropriate action for a parser given the terminal
180616 ** look-ahead token iLookAhead.
180617 */
180618 static unsigned int fts5yy_find_shift_action(
180619  fts5yyParser *pParser, /* The parser */
180620  fts5YYCODETYPE iLookAhead /* The look-ahead token */
180621 ){
180622  int i;
180623  int stateno = pParser->fts5yytos->stateno;
180624 
180625  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
180626  assert( stateno <= fts5YY_SHIFT_COUNT );
180627  do{
180628  i = fts5yy_shift_ofst[stateno];
180629  assert( iLookAhead!=fts5YYNOCODE );
180630  i += iLookAhead;
180631  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
180632 #ifdef fts5YYFALLBACK
180633  fts5YYCODETYPE iFallback; /* Fallback token */
180634  if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
180635  && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
180636 #ifndef NDEBUG
180637  if( fts5yyTraceFILE ){
180638  fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
180639  fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
180640  }
180641 #endif
180642  assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
180643  iLookAhead = iFallback;
180644  continue;
180645  }
180646 #endif
180647 #ifdef fts5YYWILDCARD
180648  {
180649  int j = i - iLookAhead + fts5YYWILDCARD;
180650  if(
180651 #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
180652  j>=0 &&
180653 #endif
180654 #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
180655  j<fts5YY_ACTTAB_COUNT &&
180656 #endif
180657  fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
180658  ){
180659 #ifndef NDEBUG
180660  if( fts5yyTraceFILE ){
180661  fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
180662  fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
180663  fts5yyTokenName[fts5YYWILDCARD]);
180664  }
180665 #endif /* NDEBUG */
180666  return fts5yy_action[j];
180667  }
180668  }
180669 #endif /* fts5YYWILDCARD */
180670  return fts5yy_default[stateno];
180671  }else{
180672  return fts5yy_action[i];
180673  }
180674  }while(1);
180675 }
180676 
180677 /*
180678 ** Find the appropriate action for a parser given the non-terminal
180679 ** look-ahead token iLookAhead.
180680 */
180681 static int fts5yy_find_reduce_action(
180682  int stateno, /* Current state number */
180683  fts5YYCODETYPE iLookAhead /* The look-ahead token */
180684 ){
180685  int i;
180686 #ifdef fts5YYERRORSYMBOL
180687  if( stateno>fts5YY_REDUCE_COUNT ){
180688  return fts5yy_default[stateno];
180689  }
180690 #else
180691  assert( stateno<=fts5YY_REDUCE_COUNT );
180692 #endif
180693  i = fts5yy_reduce_ofst[stateno];
180694  assert( i!=fts5YY_REDUCE_USE_DFLT );
180695  assert( iLookAhead!=fts5YYNOCODE );
180696  i += iLookAhead;
180697 #ifdef fts5YYERRORSYMBOL
180698  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
180699  return fts5yy_default[stateno];
180700  }
180701 #else
180702  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
180703  assert( fts5yy_lookahead[i]==iLookAhead );
180704 #endif
180705  return fts5yy_action[i];
180706 }
180707 
180708 /*
180709 ** The following routine is called if the stack overflows.
180710 */
180711 static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
180712  sqlite3Fts5ParserARG_FETCH;
180713  fts5yypParser->fts5yytos--;
180714 #ifndef NDEBUG
180715  if( fts5yyTraceFILE ){
180716  fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
180717  }
180718 #endif
180719  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
180720  /* Here code is inserted which will execute if the parser
180721  ** stack every overflows */
180722 /******** Begin %stack_overflow code ******************************************/
180723 
180724  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
180725 /******** End %stack_overflow code ********************************************/
180726  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
180727 }
180728 
180729 /*
180730 ** Print tracing information for a SHIFT action
180731 */
180732 #ifndef NDEBUG
180733 static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
180734  if( fts5yyTraceFILE ){
180735  if( fts5yyNewState<fts5YYNSTATE ){
180736  fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
180737  fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
180738  fts5yyNewState);
180739  }else{
180740  fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
180741  fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
180742  }
180743  }
180744 }
180745 #else
180746 # define fts5yyTraceShift(X,Y)
180747 #endif
180748 
180749 /*
180750 ** Perform a shift action.
180751 */
180752 static void fts5yy_shift(
180753  fts5yyParser *fts5yypParser, /* The parser to be shifted */
180754  int fts5yyNewState, /* The new state to shift in */
180755  int fts5yyMajor, /* The major token to shift in */
180756  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
180757 ){
180758  fts5yyStackEntry *fts5yytos;
180759  fts5yypParser->fts5yytos++;
180760 #ifdef fts5YYTRACKMAXSTACKDEPTH
180761  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
180762  fts5yypParser->fts5yyhwm++;
180763  assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
180764  }
180765 #endif
180766 #if fts5YYSTACKDEPTH>0
180767  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
180768  fts5yyStackOverflow(fts5yypParser);
180769  return;
180770  }
180771 #else
180772  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
180773  if( fts5yyGrowStack(fts5yypParser) ){
180774  fts5yyStackOverflow(fts5yypParser);
180775  return;
180776  }
180777  }
180778 #endif
180779  if( fts5yyNewState > fts5YY_MAX_SHIFT ){
180780  fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
180781  }
180782  fts5yytos = fts5yypParser->fts5yytos;
180783  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
180784  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
180785  fts5yytos->minor.fts5yy0 = fts5yyMinor;
180786  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
180787 }
180788 
180789 /* The following table contains information about every rule that
180790 ** is used during the reduce.
180791 */
180792 static const struct {
180793  fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
180794  unsigned char nrhs; /* Number of right-hand side symbols in the rule */
180795 } fts5yyRuleInfo[] = {
180796  { 16, 1 },
180797  { 17, 3 },
180798  { 17, 3 },
180799  { 17, 3 },
180800  { 17, 3 },
180801  { 17, 1 },
180802  { 19, 1 },
180803  { 19, 2 },
180804  { 18, 1 },
180805  { 18, 3 },
180806  { 21, 4 },
180807  { 21, 3 },
180808  { 21, 1 },
180809  { 21, 2 },
180810  { 22, 2 },
180811  { 22, 1 },
180812  { 20, 1 },
180813  { 20, 5 },
180814  { 23, 1 },
180815  { 23, 2 },
180816  { 25, 0 },
180817  { 25, 2 },
180818  { 24, 4 },
180819  { 24, 2 },
180820  { 26, 1 },
180821  { 26, 0 },
180822 };
180823 
180824 static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
180825 
180826 /*
180827 ** Perform a reduce action and the shift that must immediately
180828 ** follow the reduce.
180829 */
180830 static void fts5yy_reduce(
180831  fts5yyParser *fts5yypParser, /* The parser */
180832  unsigned int fts5yyruleno /* Number of the rule by which to reduce */
180833 ){
180834  int fts5yygoto; /* The next state */
180835  int fts5yyact; /* The next action */
180836  fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
180837  int fts5yysize; /* Amount to pop the stack */
180838  sqlite3Fts5ParserARG_FETCH;
180839  fts5yymsp = fts5yypParser->fts5yytos;
180840 #ifndef NDEBUG
180841  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
180842  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
180843  fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
180844  fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
180845  }
180846 #endif /* NDEBUG */
180847 
180848  /* Check that the stack is large enough to grow by a single entry
180849  ** if the RHS of the rule is empty. This ensures that there is room
180850  ** enough on the stack to push the LHS value */
180851  if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
180852 #ifdef fts5YYTRACKMAXSTACKDEPTH
180853  if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
180854  fts5yypParser->fts5yyhwm++;
180855  assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
180856  }
180857 #endif
180858 #if fts5YYSTACKDEPTH>0
180859  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
180860  fts5yyStackOverflow(fts5yypParser);
180861  return;
180862  }
180863 #else
180864  if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
180865  if( fts5yyGrowStack(fts5yypParser) ){
180866  fts5yyStackOverflow(fts5yypParser);
180867  return;
180868  }
180869  fts5yymsp = fts5yypParser->fts5yytos;
180870  }
180871 #endif
180872  }
180873 
180874  switch( fts5yyruleno ){
180875  /* Beginning here are the reduction cases. A typical example
180876  ** follows:
180877  ** case 0:
180878  ** #line <lineno> <grammarfile>
180879  ** { ... } // User supplied code
180880  ** #line <lineno> <thisfile>
180881  ** break;
180882  */
180883 /********** Begin reduce actions **********************************************/
180884  fts5YYMINORTYPE fts5yylhsminor;
180885  case 0: /* input ::= expr */
180886 { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
180887  break;
180888  case 1: /* expr ::= expr AND expr */
180889 {
180890  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
180891 }
180892  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180893  break;
180894  case 2: /* expr ::= expr OR expr */
180895 {
180896  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
180897 }
180898  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180899  break;
180900  case 3: /* expr ::= expr NOT expr */
180901 {
180902  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
180903 }
180904  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180905  break;
180906  case 4: /* expr ::= LP expr RP */
180907 {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
180908  break;
180909  case 5: /* expr ::= exprlist */
180910  case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
180911 {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
180912  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180913  break;
180914  case 7: /* exprlist ::= exprlist cnearset */
180915 {
180916  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
180917 }
180918  fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180919  break;
180920  case 8: /* cnearset ::= nearset */
180921 {
180922  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
180923 }
180924  fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180925  break;
180926  case 9: /* cnearset ::= colset COLON nearset */
180927 {
180928  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy46, fts5yymsp[-2].minor.fts5yy11);
180929  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
180930 }
180931  fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
180932  break;
180933  case 10: /* colset ::= MINUS LCP colsetlist RCP */
180934 {
180935  fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
180936 }
180937  break;
180938  case 11: /* colset ::= LCP colsetlist RCP */
180939 { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
180940  break;
180941  case 12: /* colset ::= STRING */
180942 {
180943  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
180944 }
180945  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
180946  break;
180947  case 13: /* colset ::= MINUS STRING */
180948 {
180949  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
180950  fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
180951 }
180952  break;
180953  case 14: /* colsetlist ::= colsetlist STRING */
180954 {
180955  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
180956  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
180957  break;
180958  case 15: /* colsetlist ::= STRING */
180959 {
180960  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
180961 }
180962  fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
180963  break;
180964  case 16: /* nearset ::= phrase */
180965 { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
180966  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180967  break;
180968  case 17: /* nearset ::= STRING LP nearphrases neardist_opt RP */
180969 {
180970  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
180971  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
180972  fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
180973 }
180974  fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180975  break;
180976  case 18: /* nearphrases ::= phrase */
180977 {
180978  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
180979 }
180980  fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180981  break;
180982  case 19: /* nearphrases ::= nearphrases phrase */
180983 {
180984  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
180985 }
180986  fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
180987  break;
180988  case 20: /* neardist_opt ::= */
180989 { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
180990  break;
180991  case 21: /* neardist_opt ::= COMMA STRING */
180992 { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
180993  break;
180994  case 22: /* phrase ::= phrase PLUS STRING star_opt */
180995 {
180996  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
180997 }
180998  fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
180999  break;
181000  case 23: /* phrase ::= STRING star_opt */
181001 {
181002  fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
181003 }
181004  fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
181005  break;
181006  case 24: /* star_opt ::= STAR */
181007 { fts5yymsp[0].minor.fts5yy4 = 1; }
181008  break;
181009  case 25: /* star_opt ::= */
181010 { fts5yymsp[1].minor.fts5yy4 = 0; }
181011  break;
181012  default:
181013  break;
181014 /********** End reduce actions ************************************************/
181015  };
181016  assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
181017  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
181018  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
181019  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
181020  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
181021  if( fts5yyact>fts5YY_MAX_SHIFT ){
181022  fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
181023  }
181024  fts5yymsp -= fts5yysize-1;
181025  fts5yypParser->fts5yytos = fts5yymsp;
181026  fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
181027  fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
181028  fts5yyTraceShift(fts5yypParser, fts5yyact);
181029  }else{
181030  assert( fts5yyact == fts5YY_ACCEPT_ACTION );
181031  fts5yypParser->fts5yytos -= fts5yysize;
181032  fts5yy_accept(fts5yypParser);
181033  }
181034 }
181035 
181036 /*
181037 ** The following code executes when the parse fails
181038 */
181039 #ifndef fts5YYNOERRORRECOVERY
181040 static void fts5yy_parse_failed(
181041  fts5yyParser *fts5yypParser /* The parser */
181042 ){
181043  sqlite3Fts5ParserARG_FETCH;
181044 #ifndef NDEBUG
181045  if( fts5yyTraceFILE ){
181046  fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
181047  }
181048 #endif
181049  while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
181050  /* Here code is inserted which will be executed whenever the
181051  ** parser fails */
181052 /************ Begin %parse_failure code ***************************************/
181053 /************ End %parse_failure code *****************************************/
181054  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
181055 }
181056 #endif /* fts5YYNOERRORRECOVERY */
181057 
181058 /*
181059 ** The following code executes when a syntax error first occurs.
181060 */
181061 static void fts5yy_syntax_error(
181062  fts5yyParser *fts5yypParser, /* The parser */
181063  int fts5yymajor, /* The major type of the error token */
181064  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
181065 ){
181066  sqlite3Fts5ParserARG_FETCH;
181067 #define FTS5TOKEN fts5yyminor
181068 /************ Begin %syntax_error code ****************************************/
181069 
181070  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
181071  sqlite3Fts5ParseError(
181072  pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
181073  );
181074 /************ End %syntax_error code ******************************************/
181075  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
181076 }
181077 
181078 /*
181079 ** The following is executed when the parser accepts
181080 */
181081 static void fts5yy_accept(
181082  fts5yyParser *fts5yypParser /* The parser */
181083 ){
181084  sqlite3Fts5ParserARG_FETCH;
181085 #ifndef NDEBUG
181086  if( fts5yyTraceFILE ){
181087  fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
181088  }
181089 #endif
181090 #ifndef fts5YYNOERRORRECOVERY
181091  fts5yypParser->fts5yyerrcnt = -1;
181092 #endif
181093  assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
181094  /* Here code is inserted which will be executed whenever the
181095  ** parser accepts */
181096 /*********** Begin %parse_accept code *****************************************/
181097 /*********** End %parse_accept code *******************************************/
181098  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
181099 }
181100 
181101 /* The main parser program.
181102 ** The first argument is a pointer to a structure obtained from
181103 ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
181104 ** The second argument is the major token number. The third is
181105 ** the minor token. The fourth optional argument is whatever the
181106 ** user wants (and specified in the grammar) and is available for
181107 ** use by the action routines.
181108 **
181109 ** Inputs:
181110 ** <ul>
181111 ** <li> A pointer to the parser (an opaque structure.)
181112 ** <li> The major token number.
181113 ** <li> The minor token number.
181114 ** <li> An option argument of a grammar-specified type.
181115 ** </ul>
181116 **
181117 ** Outputs:
181118 ** None.
181119 */
181120 static void sqlite3Fts5Parser(
181121  void *fts5yyp, /* The parser */
181122  int fts5yymajor, /* The major token code number */
181123  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
181124  sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
181125 ){
181126  fts5YYMINORTYPE fts5yyminorunion;
181127  unsigned int fts5yyact; /* The parser action. */
181128 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
181129  int fts5yyendofinput; /* True if we are at the end of input */
181130 #endif
181131 #ifdef fts5YYERRORSYMBOL
181132  int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
181133 #endif
181134  fts5yyParser *fts5yypParser; /* The parser */
181135 
181136  fts5yypParser = (fts5yyParser*)fts5yyp;
181137  assert( fts5yypParser->fts5yytos!=0 );
181138 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
181139  fts5yyendofinput = (fts5yymajor==0);
181140 #endif
181141  sqlite3Fts5ParserARG_STORE;
181142 
181143 #ifndef NDEBUG
181144  if( fts5yyTraceFILE ){
181145  fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
181146  }
181147 #endif
181148 
181149  do{
181150  fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
181151  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
181152  fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
181153 #ifndef fts5YYNOERRORRECOVERY
181154  fts5yypParser->fts5yyerrcnt--;
181155 #endif
181156  fts5yymajor = fts5YYNOCODE;
181157  }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
181158  fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
181159  }else{
181160  assert( fts5yyact == fts5YY_ERROR_ACTION );
181161  fts5yyminorunion.fts5yy0 = fts5yyminor;
181162 #ifdef fts5YYERRORSYMBOL
181163  int fts5yymx;
181164 #endif
181165 #ifndef NDEBUG
181166  if( fts5yyTraceFILE ){
181167  fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
181168  }
181169 #endif
181170 #ifdef fts5YYERRORSYMBOL
181171  /* A syntax error has occurred.
181172  ** The response to an error depends upon whether or not the
181173  ** grammar defines an error token "ERROR".
181174  **
181175  ** This is what we do if the grammar does define ERROR:
181176  **
181177  ** * Call the %syntax_error function.
181178  **
181179  ** * Begin popping the stack until we enter a state where
181180  ** it is legal to shift the error symbol, then shift
181181  ** the error symbol.
181182  **
181183  ** * Set the error count to three.
181184  **
181185  ** * Begin accepting and shifting new tokens. No new error
181186  ** processing will occur until three tokens have been
181187  ** shifted successfully.
181188  **
181189  */
181190  if( fts5yypParser->fts5yyerrcnt<0 ){
181191  fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
181192  }
181193  fts5yymx = fts5yypParser->fts5yytos->major;
181194  if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
181195 #ifndef NDEBUG
181196  if( fts5yyTraceFILE ){
181197  fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
181198  fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
181199  }
181200 #endif
181201  fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
181202  fts5yymajor = fts5YYNOCODE;
181203  }else{
181204  while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
181205  && fts5yymx != fts5YYERRORSYMBOL
181206  && (fts5yyact = fts5yy_find_reduce_action(
181207  fts5yypParser->fts5yytos->stateno,
181208  fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
181209  ){
181210  fts5yy_pop_parser_stack(fts5yypParser);
181211  }
181212  if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
181213  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
181214  fts5yy_parse_failed(fts5yypParser);
181215 #ifndef fts5YYNOERRORRECOVERY
181216  fts5yypParser->fts5yyerrcnt = -1;
181217 #endif
181218  fts5yymajor = fts5YYNOCODE;
181219  }else if( fts5yymx!=fts5YYERRORSYMBOL ){
181220  fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
181221  }
181222  }
181223  fts5yypParser->fts5yyerrcnt = 3;
181224  fts5yyerrorhit = 1;
181225 #elif defined(fts5YYNOERRORRECOVERY)
181226  /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
181227  ** do any kind of error recovery. Instead, simply invoke the syntax
181228  ** error routine and continue going as if nothing had happened.
181229  **
181230  ** Applications can set this macro (for example inside %include) if
181231  ** they intend to abandon the parse upon the first syntax error seen.
181232  */
181233  fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
181234  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
181235  fts5yymajor = fts5YYNOCODE;
181236 
181237 #else /* fts5YYERRORSYMBOL is not defined */
181238  /* This is what we do if the grammar does not define ERROR:
181239  **
181240  ** * Report an error message, and throw away the input token.
181241  **
181242  ** * If the input token is $, then fail the parse.
181243  **
181244  ** As before, subsequent error messages are suppressed until
181245  ** three input tokens have been successfully shifted.
181246  */
181247  if( fts5yypParser->fts5yyerrcnt<=0 ){
181248  fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
181249  }
181250  fts5yypParser->fts5yyerrcnt = 3;
181251  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
181252  if( fts5yyendofinput ){
181253  fts5yy_parse_failed(fts5yypParser);
181254 #ifndef fts5YYNOERRORRECOVERY
181255  fts5yypParser->fts5yyerrcnt = -1;
181256 #endif
181257  }
181258  fts5yymajor = fts5YYNOCODE;
181259 #endif
181260  }
181261  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
181262 #ifndef NDEBUG
181263  if( fts5yyTraceFILE ){
181264  fts5yyStackEntry *i;
181265  char cDiv = '[';
181266  fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
181267  for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
181268  fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
181269  cDiv = ' ';
181270  }
181271  fprintf(fts5yyTraceFILE,"]\n");
181272  }
181273 #endif
181274  return;
181275 }
181276 
181277 /*
181278 ** 2014 May 31
181279 **
181280 ** The author disclaims copyright to this source code. In place of
181281 ** a legal notice, here is a blessing:
181282 **
181283 ** May you do good and not evil.
181284 ** May you find forgiveness for yourself and forgive others.
181285 ** May you share freely, never taking more than you give.
181286 **
181287 ******************************************************************************
181288 */
181289 
181290 
181291 /* #include "fts5Int.h" */
181292 #include <math.h> /* amalgamator: keep */
181293 
181294 /*
181295 ** Object used to iterate through all "coalesced phrase instances" in
181296 ** a single column of the current row. If the phrase instances in the
181297 ** column being considered do not overlap, this object simply iterates
181298 ** through them. Or, if they do overlap (share one or more tokens in
181299 ** common), each set of overlapping instances is treated as a single
181300 ** match. See documentation for the highlight() auxiliary function for
181301 ** details.
181302 **
181303 ** Usage is:
181304 **
181305 ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
181306 ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
181307 ** rc = fts5CInstIterNext(&iter)
181308 ** ){
181309 ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
181310 ** }
181311 **
181312 */
181313 typedef struct CInstIter CInstIter;
181314 struct CInstIter {
181315  const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
181316  Fts5Context *pFts; /* First arg to pass to pApi functions */
181317  int iCol; /* Column to search */
181318  int iInst; /* Next phrase instance index */
181319  int nInst; /* Total number of phrase instances */
181320 
181321  /* Output variables */
181322  int iStart; /* First token in coalesced phrase instance */
181323  int iEnd; /* Last token in coalesced phrase instance */
181324 };
181325 
181326 /*
181327 ** Advance the iterator to the next coalesced phrase instance. Return
181328 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
181329 */
181330 static int fts5CInstIterNext(CInstIter *pIter){
181331  int rc = SQLITE_OK;
181332  pIter->iStart = -1;
181333  pIter->iEnd = -1;
181334 
181335  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
181336  int ip; int ic; int io;
181337  rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
181338  if( rc==SQLITE_OK ){
181339  if( ic==pIter->iCol ){
181340  int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
181341  if( pIter->iStart<0 ){
181342  pIter->iStart = io;
181343  pIter->iEnd = iEnd;
181344  }else if( io<=pIter->iEnd ){
181345  if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
181346  }else{
181347  break;
181348  }
181349  }
181350  pIter->iInst++;
181351  }
181352  }
181353 
181354  return rc;
181355 }
181356 
181357 /*
181358 ** Initialize the iterator object indicated by the final parameter to
181359 ** iterate through coalesced phrase instances in column iCol.
181360 */
181361 static int fts5CInstIterInit(
181362  const Fts5ExtensionApi *pApi,
181363  Fts5Context *pFts,
181364  int iCol,
181365  CInstIter *pIter
181366 ){
181367  int rc;
181368 
181369  memset(pIter, 0, sizeof(CInstIter));
181370  pIter->pApi = pApi;
181371  pIter->pFts = pFts;
181372  pIter->iCol = iCol;
181373  rc = pApi->xInstCount(pFts, &pIter->nInst);
181374 
181375  if( rc==SQLITE_OK ){
181376  rc = fts5CInstIterNext(pIter);
181377  }
181378 
181379  return rc;
181380 }
181381 
181382 
181383 
181384 /*************************************************************************
181385 ** Start of highlight() implementation.
181386 */
181387 typedef struct HighlightContext HighlightContext;
181388 struct HighlightContext {
181389  CInstIter iter; /* Coalesced Instance Iterator */
181390  int iPos; /* Current token offset in zIn[] */
181391  int iRangeStart; /* First token to include */
181392  int iRangeEnd; /* If non-zero, last token to include */
181393  const char *zOpen; /* Opening highlight */
181394  const char *zClose; /* Closing highlight */
181395  const char *zIn; /* Input text */
181396  int nIn; /* Size of input text in bytes */
181397  int iOff; /* Current offset within zIn[] */
181398  char *zOut; /* Output value */
181399 };
181400 
181401 /*
181402 ** Append text to the HighlightContext output string - p->zOut. Argument
181403 ** z points to a buffer containing n bytes of text to append. If n is
181404 ** negative, everything up until the first '\0' is appended to the output.
181405 **
181406 ** If *pRc is set to any value other than SQLITE_OK when this function is
181407 ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
181408 ** *pRc is set to an error code before returning.
181409 */
181410 static void fts5HighlightAppend(
181411  int *pRc,
181412  HighlightContext *p,
181413  const char *z, int n
181414 ){
181415  if( *pRc==SQLITE_OK ){
181416  if( n<0 ) n = (int)strlen(z);
181417  p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
181418  if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
181419  }
181420 }
181421 
181422 /*
181423 ** Tokenizer callback used by implementation of highlight() function.
181424 */
181425 static int fts5HighlightCb(
181426  void *pContext, /* Pointer to HighlightContext object */
181427  int tflags, /* Mask of FTS5_TOKEN_* flags */
181428  const char *pToken, /* Buffer containing token */
181429  int nToken, /* Size of token in bytes */
181430  int iStartOff, /* Start offset of token */
181431  int iEndOff /* End offset of token */
181432 ){
181433  HighlightContext *p = (HighlightContext*)pContext;
181434  int rc = SQLITE_OK;
181435  int iPos;
181436 
181437  UNUSED_PARAM2(pToken, nToken);
181438 
181439  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
181440  iPos = p->iPos++;
181441 
181442  if( p->iRangeEnd>0 ){
181443  if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
181444  if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
181445  }
181446 
181447  if( iPos==p->iter.iStart ){
181448  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
181449  fts5HighlightAppend(&rc, p, p->zOpen, -1);
181450  p->iOff = iStartOff;
181451  }
181452 
181453  if( iPos==p->iter.iEnd ){
181454  if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
181455  fts5HighlightAppend(&rc, p, p->zOpen, -1);
181456  }
181457  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
181458  fts5HighlightAppend(&rc, p, p->zClose, -1);
181459  p->iOff = iEndOff;
181460  if( rc==SQLITE_OK ){
181461  rc = fts5CInstIterNext(&p->iter);
181462  }
181463  }
181464 
181465  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
181466  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
181467  p->iOff = iEndOff;
181468  if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
181469  fts5HighlightAppend(&rc, p, p->zClose, -1);
181470  }
181471  }
181472 
181473  return rc;
181474 }
181475 
181476 /*
181477 ** Implementation of highlight() function.
181478 */
181479 static void fts5HighlightFunction(
181480  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181481  Fts5Context *pFts, /* First arg to pass to pApi functions */
181482  sqlite3_context *pCtx, /* Context for returning result/error */
181483  int nVal, /* Number of values in apVal[] array */
181484  sqlite3_value **apVal /* Array of trailing arguments */
181485 ){
181486  HighlightContext ctx;
181487  int rc;
181488  int iCol;
181489 
181490  if( nVal!=3 ){
181491  const char *zErr = "wrong number of arguments to function highlight()";
181492  sqlite3_result_error(pCtx, zErr, -1);
181493  return;
181494  }
181495 
181496  iCol = sqlite3_value_int(apVal[0]);
181497  memset(&ctx, 0, sizeof(HighlightContext));
181498  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
181499  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
181500  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
181501 
181502  if( ctx.zIn ){
181503  if( rc==SQLITE_OK ){
181504  rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
181505  }
181506 
181507  if( rc==SQLITE_OK ){
181508  rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
181509  }
181510  fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
181511 
181512  if( rc==SQLITE_OK ){
181513  sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
181514  }
181515  sqlite3_free(ctx.zOut);
181516  }
181517  if( rc!=SQLITE_OK ){
181518  sqlite3_result_error_code(pCtx, rc);
181519  }
181520 }
181521 /*
181522 ** End of highlight() implementation.
181523 **************************************************************************/
181524 
181525 /*
181526 ** Context object passed to the fts5SentenceFinderCb() function.
181527 */
181528 typedef struct Fts5SFinder Fts5SFinder;
181529 struct Fts5SFinder {
181530  int iPos; /* Current token position */
181531  int nFirstAlloc; /* Allocated size of aFirst[] */
181532  int nFirst; /* Number of entries in aFirst[] */
181533  int *aFirst; /* Array of first token in each sentence */
181534  const char *zDoc; /* Document being tokenized */
181535 };
181536 
181537 /*
181538 ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
181539 ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
181540 ** error occurs.
181541 */
181542 static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
181543  if( p->nFirstAlloc==p->nFirst ){
181544  int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
181545  int *aNew;
181546 
181547  aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
181548  if( aNew==0 ) return SQLITE_NOMEM;
181549  p->aFirst = aNew;
181550  p->nFirstAlloc = nNew;
181551  }
181552  p->aFirst[p->nFirst++] = iAdd;
181553  return SQLITE_OK;
181554 }
181555 
181556 /*
181557 ** This function is an xTokenize() callback used by the auxiliary snippet()
181558 ** function. Its job is to identify tokens that are the first in a sentence.
181559 ** For each such token, an entry is added to the SFinder.aFirst[] array.
181560 */
181561 static int fts5SentenceFinderCb(
181562  void *pContext, /* Pointer to HighlightContext object */
181563  int tflags, /* Mask of FTS5_TOKEN_* flags */
181564  const char *pToken, /* Buffer containing token */
181565  int nToken, /* Size of token in bytes */
181566  int iStartOff, /* Start offset of token */
181567  int iEndOff /* End offset of token */
181568 ){
181569  int rc = SQLITE_OK;
181570 
181571  UNUSED_PARAM2(pToken, nToken);
181572  UNUSED_PARAM(iEndOff);
181573 
181574  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
181575  Fts5SFinder *p = (Fts5SFinder*)pContext;
181576  if( p->iPos>0 ){
181577  int i;
181578  char c = 0;
181579  for(i=iStartOff-1; i>=0; i--){
181580  c = p->zDoc[i];
181581  if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
181582  }
181583  if( i!=iStartOff-1 && (c=='.' || c==':') ){
181584  rc = fts5SentenceFinderAdd(p, p->iPos);
181585  }
181586  }else{
181587  rc = fts5SentenceFinderAdd(p, 0);
181588  }
181589  p->iPos++;
181590  }
181591  return rc;
181592 }
181593 
181594 static int fts5SnippetScore(
181595  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181596  Fts5Context *pFts, /* First arg to pass to pApi functions */
181597  int nDocsize, /* Size of column in tokens */
181598  unsigned char *aSeen, /* Array with one element per query phrase */
181599  int iCol, /* Column to score */
181600  int iPos, /* Starting offset to score */
181601  int nToken, /* Max tokens per snippet */
181602  int *pnScore, /* OUT: Score */
181603  int *piPos /* OUT: Adjusted offset */
181604 ){
181605  int rc;
181606  int i;
181607  int ip = 0;
181608  int ic = 0;
181609  int iOff = 0;
181610  int iFirst = -1;
181611  int nInst;
181612  int nScore = 0;
181613  int iLast = 0;
181614 
181615  rc = pApi->xInstCount(pFts, &nInst);
181616  for(i=0; i<nInst && rc==SQLITE_OK; i++){
181617  rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
181618  if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
181619  nScore += (aSeen[ip] ? 1 : 1000);
181620  aSeen[ip] = 1;
181621  if( iFirst<0 ) iFirst = iOff;
181622  iLast = iOff + pApi->xPhraseSize(pFts, ip);
181623  }
181624  }
181625 
181626  *pnScore = nScore;
181627  if( piPos ){
181628  int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
181629  if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
181630  if( iAdj<0 ) iAdj = 0;
181631  *piPos = iAdj;
181632  }
181633 
181634  return rc;
181635 }
181636 
181637 /*
181638 ** Implementation of snippet() function.
181639 */
181640 static void fts5SnippetFunction(
181641  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181642  Fts5Context *pFts, /* First arg to pass to pApi functions */
181643  sqlite3_context *pCtx, /* Context for returning result/error */
181644  int nVal, /* Number of values in apVal[] array */
181645  sqlite3_value **apVal /* Array of trailing arguments */
181646 ){
181647  HighlightContext ctx;
181648  int rc = SQLITE_OK; /* Return code */
181649  int iCol; /* 1st argument to snippet() */
181650  const char *zEllips; /* 4th argument to snippet() */
181651  int nToken; /* 5th argument to snippet() */
181652  int nInst = 0; /* Number of instance matches this row */
181653  int i; /* Used to iterate through instances */
181654  int nPhrase; /* Number of phrases in query */
181655  unsigned char *aSeen; /* Array of "seen instance" flags */
181656  int iBestCol; /* Column containing best snippet */
181657  int iBestStart = 0; /* First token of best snippet */
181658  int nBestScore = 0; /* Score of best snippet */
181659  int nColSize = 0; /* Total size of iBestCol in tokens */
181660  Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
181661  int nCol;
181662 
181663  if( nVal!=5 ){
181664  const char *zErr = "wrong number of arguments to function snippet()";
181665  sqlite3_result_error(pCtx, zErr, -1);
181666  return;
181667  }
181668 
181669  nCol = pApi->xColumnCount(pFts);
181670  memset(&ctx, 0, sizeof(HighlightContext));
181671  iCol = sqlite3_value_int(apVal[0]);
181672  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
181673  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
181674  zEllips = (const char*)sqlite3_value_text(apVal[3]);
181675  nToken = sqlite3_value_int(apVal[4]);
181676 
181677  iBestCol = (iCol>=0 ? iCol : 0);
181678  nPhrase = pApi->xPhraseCount(pFts);
181679  aSeen = sqlite3_malloc(nPhrase);
181680  if( aSeen==0 ){
181681  rc = SQLITE_NOMEM;
181682  }
181683  if( rc==SQLITE_OK ){
181684  rc = pApi->xInstCount(pFts, &nInst);
181685  }
181686 
181687  memset(&sFinder, 0, sizeof(Fts5SFinder));
181688  for(i=0; i<nCol; i++){
181689  if( iCol<0 || iCol==i ){
181690  int nDoc;
181691  int nDocsize;
181692  int ii;
181693  sFinder.iPos = 0;
181694  sFinder.nFirst = 0;
181695  rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
181696  if( rc!=SQLITE_OK ) break;
181697  rc = pApi->xTokenize(pFts,
181698  sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
181699  );
181700  if( rc!=SQLITE_OK ) break;
181701  rc = pApi->xColumnSize(pFts, i, &nDocsize);
181702  if( rc!=SQLITE_OK ) break;
181703 
181704  for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
181705  int ip, ic, io;
181706  int iAdj;
181707  int nScore;
181708  int jj;
181709 
181710  rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
181711  if( ic!=i || rc!=SQLITE_OK ) continue;
181712  memset(aSeen, 0, nPhrase);
181713  rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
181714  io, nToken, &nScore, &iAdj
181715  );
181716  if( rc==SQLITE_OK && nScore>nBestScore ){
181717  nBestScore = nScore;
181718  iBestCol = i;
181719  iBestStart = iAdj;
181720  nColSize = nDocsize;
181721  }
181722 
181723  if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
181724  for(jj=0; jj<(sFinder.nFirst-1); jj++){
181725  if( sFinder.aFirst[jj+1]>io ) break;
181726  }
181727 
181728  if( sFinder.aFirst[jj]<io ){
181729  memset(aSeen, 0, nPhrase);
181730  rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
181731  sFinder.aFirst[jj], nToken, &nScore, 0
181732  );
181733 
181734  nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
181735  if( rc==SQLITE_OK && nScore>nBestScore ){
181736  nBestScore = nScore;
181737  iBestCol = i;
181738  iBestStart = sFinder.aFirst[jj];
181739  nColSize = nDocsize;
181740  }
181741  }
181742  }
181743  }
181744  }
181745  }
181746 
181747  if( rc==SQLITE_OK ){
181748  rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
181749  }
181750  if( rc==SQLITE_OK && nColSize==0 ){
181751  rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
181752  }
181753  if( ctx.zIn ){
181754  if( rc==SQLITE_OK ){
181755  rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
181756  }
181757 
181758  ctx.iRangeStart = iBestStart;
181759  ctx.iRangeEnd = iBestStart + nToken - 1;
181760 
181761  if( iBestStart>0 ){
181762  fts5HighlightAppend(&rc, &ctx, zEllips, -1);
181763  }
181764 
181765  /* Advance iterator ctx.iter so that it points to the first coalesced
181766  ** phrase instance at or following position iBestStart. */
181767  while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
181768  rc = fts5CInstIterNext(&ctx.iter);
181769  }
181770 
181771  if( rc==SQLITE_OK ){
181772  rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
181773  }
181774  if( ctx.iRangeEnd>=(nColSize-1) ){
181775  fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
181776  }else{
181777  fts5HighlightAppend(&rc, &ctx, zEllips, -1);
181778  }
181779  }
181780  if( rc==SQLITE_OK ){
181781  sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
181782  }else{
181783  sqlite3_result_error_code(pCtx, rc);
181784  }
181785  sqlite3_free(ctx.zOut);
181786  sqlite3_free(aSeen);
181787  sqlite3_free(sFinder.aFirst);
181788 }
181789 
181790 /************************************************************************/
181791 
181792 /*
181793 ** The first time the bm25() function is called for a query, an instance
181794 ** of the following structure is allocated and populated.
181795 */
181796 typedef struct Fts5Bm25Data Fts5Bm25Data;
181797 struct Fts5Bm25Data {
181798  int nPhrase; /* Number of phrases in query */
181799  double avgdl; /* Average number of tokens in each row */
181800  double *aIDF; /* IDF for each phrase */
181801  double *aFreq; /* Array used to calculate phrase freq. */
181802 };
181803 
181804 /*
181805 ** Callback used by fts5Bm25GetData() to count the number of rows in the
181806 ** table matched by each individual phrase within the query.
181807 */
181808 static int fts5CountCb(
181809  const Fts5ExtensionApi *pApi,
181810  Fts5Context *pFts,
181811  void *pUserData /* Pointer to sqlite3_int64 variable */
181812 ){
181813  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
181814  UNUSED_PARAM2(pApi, pFts);
181815  (*pn)++;
181816  return SQLITE_OK;
181817 }
181818 
181819 /*
181820 ** Set *ppData to point to the Fts5Bm25Data object for the current query.
181821 ** If the object has not already been allocated, allocate and populate it
181822 ** now.
181823 */
181824 static int fts5Bm25GetData(
181825  const Fts5ExtensionApi *pApi,
181826  Fts5Context *pFts,
181827  Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
181828 ){
181829  int rc = SQLITE_OK; /* Return code */
181830  Fts5Bm25Data *p; /* Object to return */
181831 
181832  p = pApi->xGetAuxdata(pFts, 0);
181833  if( p==0 ){
181834  int nPhrase; /* Number of phrases in query */
181835  sqlite3_int64 nRow = 0; /* Number of rows in table */
181836  sqlite3_int64 nToken = 0; /* Number of tokens in table */
181837  int nByte; /* Bytes of space to allocate */
181838  int i;
181839 
181840  /* Allocate the Fts5Bm25Data object */
181841  nPhrase = pApi->xPhraseCount(pFts);
181842  nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
181843  p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
181844  if( p==0 ){
181845  rc = SQLITE_NOMEM;
181846  }else{
181847  memset(p, 0, nByte);
181848  p->nPhrase = nPhrase;
181849  p->aIDF = (double*)&p[1];
181850  p->aFreq = &p->aIDF[nPhrase];
181851  }
181852 
181853  /* Calculate the average document length for this FTS5 table */
181854  if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
181855  if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
181856  if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
181857 
181858  /* Calculate an IDF for each phrase in the query */
181859  for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
181860  sqlite3_int64 nHit = 0;
181861  rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
181862  if( rc==SQLITE_OK ){
181863  /* Calculate the IDF (Inverse Document Frequency) for phrase i.
181864  ** This is done using the standard BM25 formula as found on wikipedia:
181865  **
181866  ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
181867  **
181868  ** where "N" is the total number of documents in the set and nHit
181869  ** is the number that contain at least one instance of the phrase
181870  ** under consideration.
181871  **
181872  ** The problem with this is that if (N < 2*nHit), the IDF is
181873  ** negative. Which is undesirable. So the mimimum allowable IDF is
181874  ** (1e-6) - roughly the same as a term that appears in just over
181875  ** half of set of 5,000,000 documents. */
181876  double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
181877  if( idf<=0.0 ) idf = 1e-6;
181878  p->aIDF[i] = idf;
181879  }
181880  }
181881 
181882  if( rc!=SQLITE_OK ){
181883  sqlite3_free(p);
181884  }else{
181885  rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
181886  }
181887  if( rc!=SQLITE_OK ) p = 0;
181888  }
181889  *ppData = p;
181890  return rc;
181891 }
181892 
181893 /*
181894 ** Implementation of bm25() function.
181895 */
181896 static void fts5Bm25Function(
181897  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
181898  Fts5Context *pFts, /* First arg to pass to pApi functions */
181899  sqlite3_context *pCtx, /* Context for returning result/error */
181900  int nVal, /* Number of values in apVal[] array */
181901  sqlite3_value **apVal /* Array of trailing arguments */
181902 ){
181903  const double k1 = 1.2; /* Constant "k1" from BM25 formula */
181904  const double b = 0.75; /* Constant "b" from BM25 formula */
181905  int rc = SQLITE_OK; /* Error code */
181906  double score = 0.0; /* SQL function return value */
181907  Fts5Bm25Data *pData; /* Values allocated/calculated once only */
181908  int i; /* Iterator variable */
181909  int nInst = 0; /* Value returned by xInstCount() */
181910  double D = 0.0; /* Total number of tokens in row */
181911  double *aFreq = 0; /* Array of phrase freq. for current row */
181912 
181913  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
181914  ** for each phrase in the query for the current row. */
181915  rc = fts5Bm25GetData(pApi, pFts, &pData);
181916  if( rc==SQLITE_OK ){
181917  aFreq = pData->aFreq;
181918  memset(aFreq, 0, sizeof(double) * pData->nPhrase);
181919  rc = pApi->xInstCount(pFts, &nInst);
181920  }
181921  for(i=0; rc==SQLITE_OK && i<nInst; i++){
181922  int ip; int ic; int io;
181923  rc = pApi->xInst(pFts, i, &ip, &ic, &io);
181924  if( rc==SQLITE_OK ){
181925  double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
181926  aFreq[ip] += w;
181927  }
181928  }
181929 
181930  /* Figure out the total size of the current row in tokens. */
181931  if( rc==SQLITE_OK ){
181932  int nTok;
181933  rc = pApi->xColumnSize(pFts, -1, &nTok);
181934  D = (double)nTok;
181935  }
181936 
181937  /* Determine the BM25 score for the current row. */
181938  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
181939  score += pData->aIDF[i] * (
181940  ( aFreq[i] * (k1 + 1.0) ) /
181941  ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
181942  );
181943  }
181944 
181945  /* If no error has occurred, return the calculated score. Otherwise,
181946  ** throw an SQL exception. */
181947  if( rc==SQLITE_OK ){
181948  sqlite3_result_double(pCtx, -1.0 * score);
181949  }else{
181950  sqlite3_result_error_code(pCtx, rc);
181951  }
181952 }
181953 
181954 static int sqlite3Fts5AuxInit(fts5_api *pApi){
181955  struct Builtin {
181956  const char *zFunc; /* Function name (nul-terminated) */
181957  void *pUserData; /* User-data pointer */
181958  fts5_extension_function xFunc;/* Callback function */
181959  void (*xDestroy)(void*); /* Destructor function */
181960  } aBuiltin [] = {
181961  { "snippet", 0, fts5SnippetFunction, 0 },
181962  { "highlight", 0, fts5HighlightFunction, 0 },
181963  { "bm25", 0, fts5Bm25Function, 0 },
181964  };
181965  int rc = SQLITE_OK; /* Return code */
181966  int i; /* To iterate through builtin functions */
181967 
181968  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
181969  rc = pApi->xCreateFunction(pApi,
181970  aBuiltin[i].zFunc,
181971  aBuiltin[i].pUserData,
181972  aBuiltin[i].xFunc,
181973  aBuiltin[i].xDestroy
181974  );
181975  }
181976 
181977  return rc;
181978 }
181979 
181980 
181981 
181982 /*
181983 ** 2014 May 31
181984 **
181985 ** The author disclaims copyright to this source code. In place of
181986 ** a legal notice, here is a blessing:
181987 **
181988 ** May you do good and not evil.
181989 ** May you find forgiveness for yourself and forgive others.
181990 ** May you share freely, never taking more than you give.
181991 **
181992 ******************************************************************************
181993 */
181994 
181995 
181996 
181997 /* #include "fts5Int.h" */
181998 
181999 static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
182000  if( (u32)pBuf->nSpace<nByte ){
182001  u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
182002  u8 *pNew;
182003  while( nNew<nByte ){
182004  nNew = nNew * 2;
182005  }
182006  pNew = sqlite3_realloc(pBuf->p, nNew);
182007  if( pNew==0 ){
182008  *pRc = SQLITE_NOMEM;
182009  return 1;
182010  }else{
182011  pBuf->nSpace = nNew;
182012  pBuf->p = pNew;
182013  }
182014  }
182015  return 0;
182016 }
182017 
182018 
182019 /*
182020 ** Encode value iVal as an SQLite varint and append it to the buffer object
182021 ** pBuf. If an OOM error occurs, set the error code in p.
182022 */
182023 static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
182024  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
182025  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
182026 }
182027 
182028 static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
182029  aBuf[0] = (iVal>>24) & 0x00FF;
182030  aBuf[1] = (iVal>>16) & 0x00FF;
182031  aBuf[2] = (iVal>> 8) & 0x00FF;
182032  aBuf[3] = (iVal>> 0) & 0x00FF;
182033 }
182034 
182035 static int sqlite3Fts5Get32(const u8 *aBuf){
182036  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
182037 }
182038 
182039 /*
182040 ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
182041 ** the error code in p. If an error has already occurred when this function
182042 ** is called, it is a no-op.
182043 */
182044 static void sqlite3Fts5BufferAppendBlob(
182045  int *pRc,
182046  Fts5Buffer *pBuf,
182047  u32 nData,
182048  const u8 *pData
182049 ){
182050  assert_nc( *pRc || nData>=0 );
182051  if( fts5BufferGrow(pRc, pBuf, nData) ) return;
182052  memcpy(&pBuf->p[pBuf->n], pData, nData);
182053  pBuf->n += nData;
182054 }
182055 
182056 /*
182057 ** Append the nul-terminated string zStr to the buffer pBuf. This function
182058 ** ensures that the byte following the buffer data is set to 0x00, even
182059 ** though this byte is not included in the pBuf->n count.
182060 */
182061 static void sqlite3Fts5BufferAppendString(
182062  int *pRc,
182063  Fts5Buffer *pBuf,
182064  const char *zStr
182065 ){
182066  int nStr = (int)strlen(zStr);
182067  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
182068  pBuf->n--;
182069 }
182070 
182071 /*
182072 ** Argument zFmt is a printf() style format string. This function performs
182073 ** the printf() style processing, then appends the results to buffer pBuf.
182074 **
182075 ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
182076 ** following the buffer data is set to 0x00, even though this byte is not
182077 ** included in the pBuf->n count.
182078 */
182079 static void sqlite3Fts5BufferAppendPrintf(
182080  int *pRc,
182081  Fts5Buffer *pBuf,
182082  char *zFmt, ...
182083 ){
182084  if( *pRc==SQLITE_OK ){
182085  char *zTmp;
182086  va_list ap;
182087  va_start(ap, zFmt);
182088  zTmp = sqlite3_vmprintf(zFmt, ap);
182089  va_end(ap);
182090 
182091  if( zTmp==0 ){
182092  *pRc = SQLITE_NOMEM;
182093  }else{
182094  sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
182095  sqlite3_free(zTmp);
182096  }
182097  }
182098 }
182099 
182100 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
182101  char *zRet = 0;
182102  if( *pRc==SQLITE_OK ){
182103  va_list ap;
182104  va_start(ap, zFmt);
182105  zRet = sqlite3_vmprintf(zFmt, ap);
182106  va_end(ap);
182107  if( zRet==0 ){
182108  *pRc = SQLITE_NOMEM;
182109  }
182110  }
182111  return zRet;
182112 }
182113 
182114 
182115 /*
182116 ** Free any buffer allocated by pBuf. Zero the structure before returning.
182117 */
182118 static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
182119  sqlite3_free(pBuf->p);
182120  memset(pBuf, 0, sizeof(Fts5Buffer));
182121 }
182122 
182123 /*
182124 ** Zero the contents of the buffer object. But do not free the associated
182125 ** memory allocation.
182126 */
182127 static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
182128  pBuf->n = 0;
182129 }
182130 
182131 /*
182132 ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
182133 ** the error code in p. If an error has already occurred when this function
182134 ** is called, it is a no-op.
182135 */
182136 static void sqlite3Fts5BufferSet(
182137  int *pRc,
182138  Fts5Buffer *pBuf,
182139  int nData,
182140  const u8 *pData
182141 ){
182142  pBuf->n = 0;
182143  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
182144 }
182145 
182146 static int sqlite3Fts5PoslistNext64(
182147  const u8 *a, int n, /* Buffer containing poslist */
182148  int *pi, /* IN/OUT: Offset within a[] */
182149  i64 *piOff /* IN/OUT: Current offset */
182150 ){
182151  int i = *pi;
182152  if( i>=n ){
182153  /* EOF */
182154  *piOff = -1;
182155  return 1;
182156  }else{
182157  i64 iOff = *piOff;
182158  int iVal;
182159  fts5FastGetVarint32(a, i, iVal);
182160  if( iVal==1 ){
182161  fts5FastGetVarint32(a, i, iVal);
182162  iOff = ((i64)iVal) << 32;
182163  fts5FastGetVarint32(a, i, iVal);
182164  }
182165  *piOff = iOff + (iVal-2);
182166  *pi = i;
182167  return 0;
182168  }
182169 }
182170 
182171 
182172 /*
182173 ** Advance the iterator object passed as the only argument. Return true
182174 ** if the iterator reaches EOF, or false otherwise.
182175 */
182176 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
182177  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
182178  pIter->bEof = 1;
182179  }
182180  return pIter->bEof;
182181 }
182182 
182183 static int sqlite3Fts5PoslistReaderInit(
182184  const u8 *a, int n, /* Poslist buffer to iterate through */
182185  Fts5PoslistReader *pIter /* Iterator object to initialize */
182186 ){
182187  memset(pIter, 0, sizeof(*pIter));
182188  pIter->a = a;
182189  pIter->n = n;
182190  sqlite3Fts5PoslistReaderNext(pIter);
182191  return pIter->bEof;
182192 }
182193 
182194 /*
182195 ** Append position iPos to the position list being accumulated in buffer
182196 ** pBuf, which must be already be large enough to hold the new data.
182197 ** The previous position written to this list is *piPrev. *piPrev is set
182198 ** to iPos before returning.
182199 */
182200 static void sqlite3Fts5PoslistSafeAppend(
182201  Fts5Buffer *pBuf,
182202  i64 *piPrev,
182203  i64 iPos
182204 ){
182205  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
182206  if( (iPos & colmask) != (*piPrev & colmask) ){
182207  pBuf->p[pBuf->n++] = 1;
182208  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
182209  *piPrev = (iPos & colmask);
182210  }
182211  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
182212  *piPrev = iPos;
182213 }
182214 
182215 static int sqlite3Fts5PoslistWriterAppend(
182216  Fts5Buffer *pBuf,
182217  Fts5PoslistWriter *pWriter,
182218  i64 iPos
182219 ){
182220  int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
182221  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
182222  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
182223  return SQLITE_OK;
182224 }
182225 
182226 static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
182227  void *pRet = 0;
182228  if( *pRc==SQLITE_OK ){
182229  pRet = sqlite3_malloc(nByte);
182230  if( pRet==0 && nByte>0 ){
182231  *pRc = SQLITE_NOMEM;
182232  }else{
182233  memset(pRet, 0, nByte);
182234  }
182235  }
182236  return pRet;
182237 }
182238 
182239 /*
182240 ** Return a nul-terminated copy of the string indicated by pIn. If nIn
182241 ** is non-negative, then it is the length of the string in bytes. Otherwise,
182242 ** the length of the string is determined using strlen().
182243 **
182244 ** It is the responsibility of the caller to eventually free the returned
182245 ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
182246 */
182247 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
182248  char *zRet = 0;
182249  if( *pRc==SQLITE_OK ){
182250  if( nIn<0 ){
182251  nIn = (int)strlen(pIn);
182252  }
182253  zRet = (char*)sqlite3_malloc(nIn+1);
182254  if( zRet ){
182255  memcpy(zRet, pIn, nIn);
182256  zRet[nIn] = '\0';
182257  }else{
182258  *pRc = SQLITE_NOMEM;
182259  }
182260  }
182261  return zRet;
182262 }
182263 
182264 
182265 /*
182266 ** Return true if character 't' may be part of an FTS5 bareword, or false
182267 ** otherwise. Characters that may be part of barewords:
182268 **
182269 ** * All non-ASCII characters,
182270 ** * The 52 upper and lower case ASCII characters, and
182271 ** * The 10 integer ASCII characters.
182272 ** * The underscore character "_" (0x5F).
182273 ** * The unicode "subsitute" character (0x1A).
182274 */
182275 static int sqlite3Fts5IsBareword(char t){
182276  u8 aBareword[128] = {
182277  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
182278  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
182279  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
182280  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
182281  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
182282  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
182283  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
182284  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
182285  };
182286 
182287  return (t & 0x80) || aBareword[(int)t];
182288 }
182289 
182290 
182291 /*************************************************************************
182292 */
182293 typedef struct Fts5TermsetEntry Fts5TermsetEntry;
182294 struct Fts5TermsetEntry {
182295  char *pTerm;
182296  int nTerm;
182297  int iIdx; /* Index (main or aPrefix[] entry) */
182298  Fts5TermsetEntry *pNext;
182299 };
182300 
182301 struct Fts5Termset {
182302  Fts5TermsetEntry *apHash[512];
182303 };
182304 
182305 static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
182306  int rc = SQLITE_OK;
182307  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
182308  return rc;
182309 }
182310 
182311 static int sqlite3Fts5TermsetAdd(
182312  Fts5Termset *p,
182313  int iIdx,
182314  const char *pTerm, int nTerm,
182315  int *pbPresent
182316 ){
182317  int rc = SQLITE_OK;
182318  *pbPresent = 0;
182319  if( p ){
182320  int i;
182321  u32 hash = 13;
182322  Fts5TermsetEntry *pEntry;
182323 
182324  /* Calculate a hash value for this term. This is the same hash checksum
182325  ** used by the fts5_hash.c module. This is not important for correct
182326  ** operation of the module, but is necessary to ensure that some tests
182327  ** designed to produce hash table collisions really do work. */
182328  for(i=nTerm-1; i>=0; i--){
182329  hash = (hash << 3) ^ hash ^ pTerm[i];
182330  }
182331  hash = (hash << 3) ^ hash ^ iIdx;
182332  hash = hash % ArraySize(p->apHash);
182333 
182334  for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
182335  if( pEntry->iIdx==iIdx
182336  && pEntry->nTerm==nTerm
182337  && memcmp(pEntry->pTerm, pTerm, nTerm)==0
182338  ){
182339  *pbPresent = 1;
182340  break;
182341  }
182342  }
182343 
182344  if( pEntry==0 ){
182345  pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
182346  if( pEntry ){
182347  pEntry->pTerm = (char*)&pEntry[1];
182348  pEntry->nTerm = nTerm;
182349  pEntry->iIdx = iIdx;
182350  memcpy(pEntry->pTerm, pTerm, nTerm);
182351  pEntry->pNext = p->apHash[hash];
182352  p->apHash[hash] = pEntry;
182353  }
182354  }
182355  }
182356 
182357  return rc;
182358 }
182359 
182360 static void sqlite3Fts5TermsetFree(Fts5Termset *p){
182361  if( p ){
182362  u32 i;
182363  for(i=0; i<ArraySize(p->apHash); i++){
182364  Fts5TermsetEntry *pEntry = p->apHash[i];
182365  while( pEntry ){
182366  Fts5TermsetEntry *pDel = pEntry;
182367  pEntry = pEntry->pNext;
182368  sqlite3_free(pDel);
182369  }
182370  }
182371  sqlite3_free(p);
182372  }
182373 }
182374 
182375 /*
182376 ** 2014 Jun 09
182377 **
182378 ** The author disclaims copyright to this source code. In place of
182379 ** a legal notice, here is a blessing:
182380 **
182381 ** May you do good and not evil.
182382 ** May you find forgiveness for yourself and forgive others.
182383 ** May you share freely, never taking more than you give.
182384 **
182385 ******************************************************************************
182386 **
182387 ** This is an SQLite module implementing full-text search.
182388 */
182389 
182390 
182391 /* #include "fts5Int.h" */
182392 
182393 #define FTS5_DEFAULT_PAGE_SIZE 4050
182394 #define FTS5_DEFAULT_AUTOMERGE 4
182395 #define FTS5_DEFAULT_USERMERGE 4
182396 #define FTS5_DEFAULT_CRISISMERGE 16
182397 #define FTS5_DEFAULT_HASHSIZE (1024*1024)
182398 
182399 /* Maximum allowed page size */
182400 #define FTS5_MAX_PAGE_SIZE (128*1024)
182401 
182402 static int fts5_iswhitespace(char x){
182403  return (x==' ');
182404 }
182405 
182406 static int fts5_isopenquote(char x){
182407  return (x=='"' || x=='\'' || x=='[' || x=='`');
182408 }
182409 
182410 /*
182411 ** Argument pIn points to a character that is part of a nul-terminated
182412 ** string. Return a pointer to the first character following *pIn in
182413 ** the string that is not a white-space character.
182414 */
182415 static const char *fts5ConfigSkipWhitespace(const char *pIn){
182416  const char *p = pIn;
182417  if( p ){
182418  while( fts5_iswhitespace(*p) ){ p++; }
182419  }
182420  return p;
182421 }
182422 
182423 /*
182424 ** Argument pIn points to a character that is part of a nul-terminated
182425 ** string. Return a pointer to the first character following *pIn in
182426 ** the string that is not a "bareword" character.
182427 */
182428 static const char *fts5ConfigSkipBareword(const char *pIn){
182429  const char *p = pIn;
182430  while ( sqlite3Fts5IsBareword(*p) ) p++;
182431  if( p==pIn ) p = 0;
182432  return p;
182433 }
182434 
182435 static int fts5_isdigit(char a){
182436  return (a>='0' && a<='9');
182437 }
182438 
182439 
182440 
182441 static const char *fts5ConfigSkipLiteral(const char *pIn){
182442  const char *p = pIn;
182443  switch( *p ){
182444  case 'n': case 'N':
182445  if( sqlite3_strnicmp("null", p, 4)==0 ){
182446  p = &p[4];
182447  }else{
182448  p = 0;
182449  }
182450  break;
182451 
182452  case 'x': case 'X':
182453  p++;
182454  if( *p=='\'' ){
182455  p++;
182456  while( (*p>='a' && *p<='f')
182457  || (*p>='A' && *p<='F')
182458  || (*p>='0' && *p<='9')
182459  ){
182460  p++;
182461  }
182462  if( *p=='\'' && 0==((p-pIn)%2) ){
182463  p++;
182464  }else{
182465  p = 0;
182466  }
182467  }else{
182468  p = 0;
182469  }
182470  break;
182471 
182472  case '\'':
182473  p++;
182474  while( p ){
182475  if( *p=='\'' ){
182476  p++;
182477  if( *p!='\'' ) break;
182478  }
182479  p++;
182480  if( *p==0 ) p = 0;
182481  }
182482  break;
182483 
182484  default:
182485  /* maybe a number */
182486  if( *p=='+' || *p=='-' ) p++;
182487  while( fts5_isdigit(*p) ) p++;
182488 
182489  /* At this point, if the literal was an integer, the parse is
182490  ** finished. Or, if it is a floating point value, it may continue
182491  ** with either a decimal point or an 'E' character. */
182492  if( *p=='.' && fts5_isdigit(p[1]) ){
182493  p += 2;
182494  while( fts5_isdigit(*p) ) p++;
182495  }
182496  if( p==pIn ) p = 0;
182497 
182498  break;
182499  }
182500 
182501  return p;
182502 }
182503 
182504 /*
182505 ** The first character of the string pointed to by argument z is guaranteed
182506 ** to be an open-quote character (see function fts5_isopenquote()).
182507 **
182508 ** This function searches for the corresponding close-quote character within
182509 ** the string and, if found, dequotes the string in place and adds a new
182510 ** nul-terminator byte.
182511 **
182512 ** If the close-quote is found, the value returned is the byte offset of
182513 ** the character immediately following it. Or, if the close-quote is not
182514 ** found, -1 is returned. If -1 is returned, the buffer is left in an
182515 ** undefined state.
182516 */
182517 static int fts5Dequote(char *z){
182518  char q;
182519  int iIn = 1;
182520  int iOut = 0;
182521  q = z[0];
182522 
182523  /* Set stack variable q to the close-quote character */
182524  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
182525  if( q=='[' ) q = ']';
182526 
182527  while( ALWAYS(z[iIn]) ){
182528  if( z[iIn]==q ){
182529  if( z[iIn+1]!=q ){
182530  /* Character iIn was the close quote. */
182531  iIn++;
182532  break;
182533  }else{
182534  /* Character iIn and iIn+1 form an escaped quote character. Skip
182535  ** the input cursor past both and copy a single quote character
182536  ** to the output buffer. */
182537  iIn += 2;
182538  z[iOut++] = q;
182539  }
182540  }else{
182541  z[iOut++] = z[iIn++];
182542  }
182543  }
182544 
182545  z[iOut] = '\0';
182546  return iIn;
182547 }
182548 
182549 /*
182550 ** Convert an SQL-style quoted string into a normal string by removing
182551 ** the quote characters. The conversion is done in-place. If the
182552 ** input does not begin with a quote character, then this routine
182553 ** is a no-op.
182554 **
182555 ** Examples:
182556 **
182557 ** "abc" becomes abc
182558 ** 'xyz' becomes xyz
182559 ** [pqr] becomes pqr
182560 ** `mno` becomes mno
182561 */
182562 static void sqlite3Fts5Dequote(char *z){
182563  char quote; /* Quote character (if any ) */
182564 
182565  assert( 0==fts5_iswhitespace(z[0]) );
182566  quote = z[0];
182567  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
182568  fts5Dequote(z);
182569  }
182570 }
182571 
182572 
182573 struct Fts5Enum {
182574  const char *zName;
182575  int eVal;
182576 };
182577 typedef struct Fts5Enum Fts5Enum;
182578 
182579 static int fts5ConfigSetEnum(
182580  const Fts5Enum *aEnum,
182581  const char *zEnum,
182582  int *peVal
182583 ){
182584  int nEnum = (int)strlen(zEnum);
182585  int i;
182586  int iVal = -1;
182587 
182588  for(i=0; aEnum[i].zName; i++){
182589  if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
182590  if( iVal>=0 ) return SQLITE_ERROR;
182591  iVal = aEnum[i].eVal;
182592  }
182593  }
182594 
182595  *peVal = iVal;
182596  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
182597 }
182598 
182599 /*
182600 ** Parse a "special" CREATE VIRTUAL TABLE directive and update
182601 ** configuration object pConfig as appropriate.
182602 **
182603 ** If successful, object pConfig is updated and SQLITE_OK returned. If
182604 ** an error occurs, an SQLite error code is returned and an error message
182605 ** may be left in *pzErr. It is the responsibility of the caller to
182606 ** eventually free any such error message using sqlite3_free().
182607 */
182608 static int fts5ConfigParseSpecial(
182609  Fts5Global *pGlobal,
182610  Fts5Config *pConfig, /* Configuration object to update */
182611  const char *zCmd, /* Special command to parse */
182612  const char *zArg, /* Argument to parse */
182613  char **pzErr /* OUT: Error message */
182614 ){
182615  int rc = SQLITE_OK;
182616  int nCmd = (int)strlen(zCmd);
182617  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
182618  const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
182619  const char *p;
182620  int bFirst = 1;
182621  if( pConfig->aPrefix==0 ){
182622  pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
182623  if( rc ) return rc;
182624  }
182625 
182626  p = zArg;
182627  while( 1 ){
182628  int nPre = 0;
182629 
182630  while( p[0]==' ' ) p++;
182631  if( bFirst==0 && p[0]==',' ){
182632  p++;
182633  while( p[0]==' ' ) p++;
182634  }else if( p[0]=='\0' ){
182635  break;
182636  }
182637  if( p[0]<'0' || p[0]>'9' ){
182638  *pzErr = sqlite3_mprintf("malformed prefix=... directive");
182639  rc = SQLITE_ERROR;
182640  break;
182641  }
182642 
182643  if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
182644  *pzErr = sqlite3_mprintf(
182645  "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
182646  );
182647  rc = SQLITE_ERROR;
182648  break;
182649  }
182650 
182651  while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
182652  nPre = nPre*10 + (p[0] - '0');
182653  p++;
182654  }
182655 
182656  if( nPre<=0 || nPre>=1000 ){
182657  *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
182658  rc = SQLITE_ERROR;
182659  break;
182660  }
182661 
182662  pConfig->aPrefix[pConfig->nPrefix] = nPre;
182663  pConfig->nPrefix++;
182664  bFirst = 0;
182665  }
182666  assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
182667  return rc;
182668  }
182669 
182670  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
182671  const char *p = (const char*)zArg;
182672  int nArg = (int)strlen(zArg) + 1;
182673  char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
182674  char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
182675  char *pSpace = pDel;
182676 
182677  if( azArg && pSpace ){
182678  if( pConfig->pTok ){
182679  *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
182680  rc = SQLITE_ERROR;
182681  }else{
182682  for(nArg=0; p && *p; nArg++){
182683  const char *p2 = fts5ConfigSkipWhitespace(p);
182684  if( *p2=='\'' ){
182685  p = fts5ConfigSkipLiteral(p2);
182686  }else{
182687  p = fts5ConfigSkipBareword(p2);
182688  }
182689  if( p ){
182690  memcpy(pSpace, p2, p-p2);
182691  azArg[nArg] = pSpace;
182692  sqlite3Fts5Dequote(pSpace);
182693  pSpace += (p - p2) + 1;
182694  p = fts5ConfigSkipWhitespace(p);
182695  }
182696  }
182697  if( p==0 ){
182698  *pzErr = sqlite3_mprintf("parse error in tokenize directive");
182699  rc = SQLITE_ERROR;
182700  }else{
182701  rc = sqlite3Fts5GetTokenizer(pGlobal,
182702  (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
182703  pzErr
182704  );
182705  }
182706  }
182707  }
182708 
182709  sqlite3_free(azArg);
182710  sqlite3_free(pDel);
182711  return rc;
182712  }
182713 
182714  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
182715  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
182716  *pzErr = sqlite3_mprintf("multiple content=... directives");
182717  rc = SQLITE_ERROR;
182718  }else{
182719  if( zArg[0] ){
182720  pConfig->eContent = FTS5_CONTENT_EXTERNAL;
182721  pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
182722  }else{
182723  pConfig->eContent = FTS5_CONTENT_NONE;
182724  }
182725  }
182726  return rc;
182727  }
182728 
182729  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
182730  if( pConfig->zContentRowid ){
182731  *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
182732  rc = SQLITE_ERROR;
182733  }else{
182734  pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
182735  }
182736  return rc;
182737  }
182738 
182739  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
182740  if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
182741  *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
182742  rc = SQLITE_ERROR;
182743  }else{
182744  pConfig->bColumnsize = (zArg[0]=='1');
182745  }
182746  return rc;
182747  }
182748 
182749  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
182750  const Fts5Enum aDetail[] = {
182751  { "none", FTS5_DETAIL_NONE },
182752  { "full", FTS5_DETAIL_FULL },
182753  { "columns", FTS5_DETAIL_COLUMNS },
182754  { 0, 0 }
182755  };
182756 
182757  if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
182758  *pzErr = sqlite3_mprintf("malformed detail=... directive");
182759  }
182760  return rc;
182761  }
182762 
182763  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
182764  return SQLITE_ERROR;
182765 }
182766 
182767 /*
182768 ** Allocate an instance of the default tokenizer ("simple") at
182769 ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
182770 ** code if an error occurs.
182771 */
182772 static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
182773  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
182774  return sqlite3Fts5GetTokenizer(
182775  pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
182776  );
182777 }
182778 
182779 /*
182780 ** Gobble up the first bareword or quoted word from the input buffer zIn.
182781 ** Return a pointer to the character immediately following the last in
182782 ** the gobbled word if successful, or a NULL pointer otherwise (failed
182783 ** to find close-quote character).
182784 **
182785 ** Before returning, set pzOut to point to a new buffer containing a
182786 ** nul-terminated, dequoted copy of the gobbled word. If the word was
182787 ** quoted, *pbQuoted is also set to 1 before returning.
182788 **
182789 ** If *pRc is other than SQLITE_OK when this function is called, it is
182790 ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
182791 ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
182792 ** set if a parse error (failed to find close quote) occurs.
182793 */
182794 static const char *fts5ConfigGobbleWord(
182795  int *pRc, /* IN/OUT: Error code */
182796  const char *zIn, /* Buffer to gobble string/bareword from */
182797  char **pzOut, /* OUT: malloc'd buffer containing str/bw */
182798  int *pbQuoted /* OUT: Set to true if dequoting required */
182799 ){
182800  const char *zRet = 0;
182801 
182802  int nIn = (int)strlen(zIn);
182803  char *zOut = sqlite3_malloc(nIn+1);
182804 
182805  assert( *pRc==SQLITE_OK );
182806  *pbQuoted = 0;
182807  *pzOut = 0;
182808 
182809  if( zOut==0 ){
182810  *pRc = SQLITE_NOMEM;
182811  }else{
182812  memcpy(zOut, zIn, nIn+1);
182813  if( fts5_isopenquote(zOut[0]) ){
182814  int ii = fts5Dequote(zOut);
182815  zRet = &zIn[ii];
182816  *pbQuoted = 1;
182817  }else{
182818  zRet = fts5ConfigSkipBareword(zIn);
182819  if( zRet ){
182820  zOut[zRet-zIn] = '\0';
182821  }
182822  }
182823  }
182824 
182825  if( zRet==0 ){
182826  sqlite3_free(zOut);
182827  }else{
182828  *pzOut = zOut;
182829  }
182830 
182831  return zRet;
182832 }
182833 
182834 static int fts5ConfigParseColumn(
182835  Fts5Config *p,
182836  char *zCol,
182837  char *zArg,
182838  char **pzErr
182839 ){
182840  int rc = SQLITE_OK;
182841  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
182842  || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
182843  ){
182844  *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
182845  rc = SQLITE_ERROR;
182846  }else if( zArg ){
182847  if( 0==sqlite3_stricmp(zArg, "unindexed") ){
182848  p->abUnindexed[p->nCol] = 1;
182849  }else{
182850  *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
182851  rc = SQLITE_ERROR;
182852  }
182853  }
182854 
182855  p->azCol[p->nCol++] = zCol;
182856  return rc;
182857 }
182858 
182859 /*
182860 ** Populate the Fts5Config.zContentExprlist string.
182861 */
182862 static int fts5ConfigMakeExprlist(Fts5Config *p){
182863  int i;
182864  int rc = SQLITE_OK;
182865  Fts5Buffer buf = {0, 0, 0};
182866 
182867  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
182868  if( p->eContent!=FTS5_CONTENT_NONE ){
182869  for(i=0; i<p->nCol; i++){
182870  if( p->eContent==FTS5_CONTENT_EXTERNAL ){
182871  sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
182872  }else{
182873  sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
182874  }
182875  }
182876  }
182877 
182878  assert( p->zContentExprlist==0 );
182879  p->zContentExprlist = (char*)buf.p;
182880  return rc;
182881 }
182882 
182883 /*
182884 ** Arguments nArg/azArg contain the string arguments passed to the xCreate
182885 ** or xConnect method of the virtual table. This function attempts to
182886 ** allocate an instance of Fts5Config containing the results of parsing
182887 ** those arguments.
182888 **
182889 ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
182890 ** new Fts5Config object. If an error occurs, an SQLite error code is
182891 ** returned, *ppOut is set to NULL and an error message may be left in
182892 ** *pzErr. It is the responsibility of the caller to eventually free any
182893 ** such error message using sqlite3_free().
182894 */
182895 static int sqlite3Fts5ConfigParse(
182896  Fts5Global *pGlobal,
182897  sqlite3 *db,
182898  int nArg, /* Number of arguments */
182899  const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
182900  Fts5Config **ppOut, /* OUT: Results of parse */
182901  char **pzErr /* OUT: Error message */
182902 ){
182903  int rc = SQLITE_OK; /* Return code */
182904  Fts5Config *pRet; /* New object to return */
182905  int i;
182906  int nByte;
182907 
182908  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
182909  if( pRet==0 ) return SQLITE_NOMEM;
182910  memset(pRet, 0, sizeof(Fts5Config));
182911  pRet->db = db;
182912  pRet->iCookie = -1;
182913 
182914  nByte = nArg * (sizeof(char*) + sizeof(u8));
182915  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
182916  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
182917  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
182918  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
182919  pRet->bColumnsize = 1;
182920  pRet->eDetail = FTS5_DETAIL_FULL;
182921 #ifdef SQLITE_DEBUG
182922  pRet->bPrefixIndex = 1;
182923 #endif
182924  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
182925  *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
182926  rc = SQLITE_ERROR;
182927  }
182928 
182929  for(i=3; rc==SQLITE_OK && i<nArg; i++){
182930  const char *zOrig = azArg[i];
182931  const char *z;
182932  char *zOne = 0;
182933  char *zTwo = 0;
182934  int bOption = 0;
182935  int bMustBeCol = 0;
182936 
182937  z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
182938  z = fts5ConfigSkipWhitespace(z);
182939  if( z && *z=='=' ){
182940  bOption = 1;
182941  z++;
182942  if( bMustBeCol ) z = 0;
182943  }
182944  z = fts5ConfigSkipWhitespace(z);
182945  if( z && z[0] ){
182946  int bDummy;
182947  z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
182948  if( z && z[0] ) z = 0;
182949  }
182950 
182951  if( rc==SQLITE_OK ){
182952  if( z==0 ){
182953  *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
182954  rc = SQLITE_ERROR;
182955  }else{
182956  if( bOption ){
182957  rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
182958  }else{
182959  rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
182960  zOne = 0;
182961  }
182962  }
182963  }
182964 
182965  sqlite3_free(zOne);
182966  sqlite3_free(zTwo);
182967  }
182968 
182969  /* If a tokenizer= option was successfully parsed, the tokenizer has
182970  ** already been allocated. Otherwise, allocate an instance of the default
182971  ** tokenizer (unicode61) now. */
182972  if( rc==SQLITE_OK && pRet->pTok==0 ){
182973  rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
182974  }
182975 
182976  /* If no zContent option was specified, fill in the default values. */
182977  if( rc==SQLITE_OK && pRet->zContent==0 ){
182978  const char *zTail = 0;
182979  assert( pRet->eContent==FTS5_CONTENT_NORMAL
182980  || pRet->eContent==FTS5_CONTENT_NONE
182981  );
182982  if( pRet->eContent==FTS5_CONTENT_NORMAL ){
182983  zTail = "content";
182984  }else if( pRet->bColumnsize ){
182985  zTail = "docsize";
182986  }
182987 
182988  if( zTail ){
182989  pRet->zContent = sqlite3Fts5Mprintf(
182990  &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
182991  );
182992  }
182993  }
182994 
182995  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
182996  pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
182997  }
182998 
182999  /* Formulate the zContentExprlist text */
183000  if( rc==SQLITE_OK ){
183001  rc = fts5ConfigMakeExprlist(pRet);
183002  }
183003 
183004  if( rc!=SQLITE_OK ){
183005  sqlite3Fts5ConfigFree(pRet);
183006  *ppOut = 0;
183007  }
183008  return rc;
183009 }
183010 
183011 /*
183012 ** Free the configuration object passed as the only argument.
183013 */
183014 static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
183015  if( pConfig ){
183016  int i;
183017  if( pConfig->pTok ){
183018  pConfig->pTokApi->xDelete(pConfig->pTok);
183019  }
183020  sqlite3_free(pConfig->zDb);
183021  sqlite3_free(pConfig->zName);
183022  for(i=0; i<pConfig->nCol; i++){
183023  sqlite3_free(pConfig->azCol[i]);
183024  }
183025  sqlite3_free(pConfig->azCol);
183026  sqlite3_free(pConfig->aPrefix);
183027  sqlite3_free(pConfig->zRank);
183028  sqlite3_free(pConfig->zRankArgs);
183029  sqlite3_free(pConfig->zContent);
183030  sqlite3_free(pConfig->zContentRowid);
183031  sqlite3_free(pConfig->zContentExprlist);
183032  sqlite3_free(pConfig);
183033  }
183034 }
183035 
183036 /*
183037 ** Call sqlite3_declare_vtab() based on the contents of the configuration
183038 ** object passed as the only argument. Return SQLITE_OK if successful, or
183039 ** an SQLite error code if an error occurs.
183040 */
183041 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
183042  int i;
183043  int rc = SQLITE_OK;
183044  char *zSql;
183045 
183046  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
183047  for(i=0; zSql && i<pConfig->nCol; i++){
183048  const char *zSep = (i==0?"":", ");
183049  zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
183050  }
183051  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
183052  zSql, pConfig->zName, FTS5_RANK_NAME
183053  );
183054 
183055  assert( zSql || rc==SQLITE_NOMEM );
183056  if( zSql ){
183057  rc = sqlite3_declare_vtab(pConfig->db, zSql);
183058  sqlite3_free(zSql);
183059  }
183060 
183061  return rc;
183062 }
183063 
183064 /*
183065 ** Tokenize the text passed via the second and third arguments.
183066 **
183067 ** The callback is invoked once for each token in the input text. The
183068 ** arguments passed to it are, in order:
183069 **
183070 ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
183071 ** const char *pToken // Pointer to buffer containing token
183072 ** int nToken // Size of token in bytes
183073 ** int iStart // Byte offset of start of token within input text
183074 ** int iEnd // Byte offset of end of token within input text
183075 ** int iPos // Position of token in input (first token is 0)
183076 **
183077 ** If the callback returns a non-zero value the tokenization is abandoned
183078 ** and no further callbacks are issued.
183079 **
183080 ** This function returns SQLITE_OK if successful or an SQLite error code
183081 ** if an error occurs. If the tokenization was abandoned early because
183082 ** the callback returned SQLITE_DONE, this is not an error and this function
183083 ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
183084 ** because the callback returned another non-zero value, it is assumed
183085 ** to be an SQLite error code and returned to the caller.
183086 */
183087 static int sqlite3Fts5Tokenize(
183088  Fts5Config *pConfig, /* FTS5 Configuration object */
183089  int flags, /* FTS5_TOKENIZE_* flags */
183090  const char *pText, int nText, /* Text to tokenize */
183091  void *pCtx, /* Context passed to xToken() */
183092  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
183093 ){
183094  if( pText==0 ) return SQLITE_OK;
183095  return pConfig->pTokApi->xTokenize(
183096  pConfig->pTok, pCtx, flags, pText, nText, xToken
183097  );
183098 }
183099 
183100 /*
183101 ** Argument pIn points to the first character in what is expected to be
183102 ** a comma-separated list of SQL literals followed by a ')' character.
183103 ** If it actually is this, return a pointer to the ')'. Otherwise, return
183104 ** NULL to indicate a parse error.
183105 */
183106 static const char *fts5ConfigSkipArgs(const char *pIn){
183107  const char *p = pIn;
183108 
183109  while( 1 ){
183110  p = fts5ConfigSkipWhitespace(p);
183111  p = fts5ConfigSkipLiteral(p);
183112  p = fts5ConfigSkipWhitespace(p);
183113  if( p==0 || *p==')' ) break;
183114  if( *p!=',' ){
183115  p = 0;
183116  break;
183117  }
183118  p++;
183119  }
183120 
183121  return p;
183122 }
183123 
183124 /*
183125 ** Parameter zIn contains a rank() function specification. The format of
183126 ** this is:
183127 **
183128 ** + Bareword (function name)
183129 ** + Open parenthesis - "("
183130 ** + Zero or more SQL literals in a comma separated list
183131 ** + Close parenthesis - ")"
183132 */
183133 static int sqlite3Fts5ConfigParseRank(
183134  const char *zIn, /* Input string */
183135  char **pzRank, /* OUT: Rank function name */
183136  char **pzRankArgs /* OUT: Rank function arguments */
183137 ){
183138  const char *p = zIn;
183139  const char *pRank;
183140  char *zRank = 0;
183141  char *zRankArgs = 0;
183142  int rc = SQLITE_OK;
183143 
183144  *pzRank = 0;
183145  *pzRankArgs = 0;
183146 
183147  if( p==0 ){
183148  rc = SQLITE_ERROR;
183149  }else{
183150  p = fts5ConfigSkipWhitespace(p);
183151  pRank = p;
183152  p = fts5ConfigSkipBareword(p);
183153 
183154  if( p ){
183155  zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
183156  if( zRank ) memcpy(zRank, pRank, p-pRank);
183157  }else{
183158  rc = SQLITE_ERROR;
183159  }
183160 
183161  if( rc==SQLITE_OK ){
183162  p = fts5ConfigSkipWhitespace(p);
183163  if( *p!='(' ) rc = SQLITE_ERROR;
183164  p++;
183165  }
183166  if( rc==SQLITE_OK ){
183167  const char *pArgs;
183168  p = fts5ConfigSkipWhitespace(p);
183169  pArgs = p;
183170  if( *p!=')' ){
183171  p = fts5ConfigSkipArgs(p);
183172  if( p==0 ){
183173  rc = SQLITE_ERROR;
183174  }else{
183175  zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
183176  if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
183177  }
183178  }
183179  }
183180  }
183181 
183182  if( rc!=SQLITE_OK ){
183183  sqlite3_free(zRank);
183184  assert( zRankArgs==0 );
183185  }else{
183186  *pzRank = zRank;
183187  *pzRankArgs = zRankArgs;
183188  }
183189  return rc;
183190 }
183191 
183192 static int sqlite3Fts5ConfigSetValue(
183193  Fts5Config *pConfig,
183194  const char *zKey,
183195  sqlite3_value *pVal,
183196  int *pbBadkey
183197 ){
183198  int rc = SQLITE_OK;
183199 
183200  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
183201  int pgsz = 0;
183203  pgsz = sqlite3_value_int(pVal);
183204  }
183205  if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
183206  *pbBadkey = 1;
183207  }else{
183208  pConfig->pgsz = pgsz;
183209  }
183210  }
183211 
183212  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
183213  int nHashSize = -1;
183215  nHashSize = sqlite3_value_int(pVal);
183216  }
183217  if( nHashSize<=0 ){
183218  *pbBadkey = 1;
183219  }else{
183220  pConfig->nHashSize = nHashSize;
183221  }
183222  }
183223 
183224  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
183225  int nAutomerge = -1;
183227  nAutomerge = sqlite3_value_int(pVal);
183228  }
183229  if( nAutomerge<0 || nAutomerge>64 ){
183230  *pbBadkey = 1;
183231  }else{
183232  if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
183233  pConfig->nAutomerge = nAutomerge;
183234  }
183235  }
183236 
183237  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
183238  int nUsermerge = -1;
183240  nUsermerge = sqlite3_value_int(pVal);
183241  }
183242  if( nUsermerge<2 || nUsermerge>16 ){
183243  *pbBadkey = 1;
183244  }else{
183245  pConfig->nUsermerge = nUsermerge;
183246  }
183247  }
183248 
183249  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
183250  int nCrisisMerge = -1;
183252  nCrisisMerge = sqlite3_value_int(pVal);
183253  }
183254  if( nCrisisMerge<0 ){
183255  *pbBadkey = 1;
183256  }else{
183257  if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
183258  pConfig->nCrisisMerge = nCrisisMerge;
183259  }
183260  }
183261 
183262  else if( 0==sqlite3_stricmp(zKey, "rank") ){
183263  const char *zIn = (const char*)sqlite3_value_text(pVal);
183264  char *zRank;
183265  char *zRankArgs;
183266  rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
183267  if( rc==SQLITE_OK ){
183268  sqlite3_free(pConfig->zRank);
183269  sqlite3_free(pConfig->zRankArgs);
183270  pConfig->zRank = zRank;
183271  pConfig->zRankArgs = zRankArgs;
183272  }else if( rc==SQLITE_ERROR ){
183273  rc = SQLITE_OK;
183274  *pbBadkey = 1;
183275  }
183276  }else{
183277  *pbBadkey = 1;
183278  }
183279  return rc;
183280 }
183281 
183282 /*
183283 ** Load the contents of the %_config table into memory.
183284 */
183285 static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
183286  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
183287  char *zSql;
183288  sqlite3_stmt *p = 0;
183289  int rc = SQLITE_OK;
183290  int iVersion = 0;
183291 
183292  /* Set default values */
183293  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
183294  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
183295  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
183296  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
183297  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
183298 
183299  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
183300  if( zSql ){
183301  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
183302  sqlite3_free(zSql);
183303  }
183304 
183305  assert( rc==SQLITE_OK || p==0 );
183306  if( rc==SQLITE_OK ){
183307  while( SQLITE_ROW==sqlite3_step(p) ){
183308  const char *zK = (const char*)sqlite3_column_text(p, 0);
183309  sqlite3_value *pVal = sqlite3_column_value(p, 1);
183310  if( 0==sqlite3_stricmp(zK, "version") ){
183311  iVersion = sqlite3_value_int(pVal);
183312  }else{
183313  int bDummy = 0;
183314  sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
183315  }
183316  }
183317  rc = sqlite3_finalize(p);
183318  }
183319 
183320  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
183321  rc = SQLITE_ERROR;
183322  if( pConfig->pzErrmsg ){
183323  assert( 0==*pConfig->pzErrmsg );
183324  *pConfig->pzErrmsg = sqlite3_mprintf(
183325  "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
183326  iVersion, FTS5_CURRENT_VERSION
183327  );
183328  }
183329  }
183330 
183331  if( rc==SQLITE_OK ){
183332  pConfig->iCookie = iCookie;
183333  }
183334  return rc;
183335 }
183336 
183337 /*
183338 ** 2014 May 31
183339 **
183340 ** The author disclaims copyright to this source code. In place of
183341 ** a legal notice, here is a blessing:
183342 **
183343 ** May you do good and not evil.
183344 ** May you find forgiveness for yourself and forgive others.
183345 ** May you share freely, never taking more than you give.
183346 **
183347 ******************************************************************************
183348 **
183349 */
183350 
183351 
183352 
183353 /* #include "fts5Int.h" */
183354 /* #include "fts5parse.h" */
183355 
183356 /*
183357 ** All token types in the generated fts5parse.h file are greater than 0.
183358 */
183359 #define FTS5_EOF 0
183360 
183361 #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
183362 
183363 typedef struct Fts5ExprTerm Fts5ExprTerm;
183364 
183365 /*
183366 ** Functions generated by lemon from fts5parse.y.
183367 */
183368 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
183369 static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
183370 static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
183371 #ifndef NDEBUG
183372 /* #include <stdio.h> */
183373 static void sqlite3Fts5ParserTrace(FILE*, char*);
183374 #endif
183375 
183376 
183377 struct Fts5Expr {
183378  Fts5Index *pIndex;
183379  Fts5Config *pConfig;
183380  Fts5ExprNode *pRoot;
183381  int bDesc; /* Iterate in descending rowid order */
183382  int nPhrase; /* Number of phrases in expression */
183383  Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
183384 };
183385 
183386 /*
183387 ** eType:
183388 ** Expression node type. Always one of:
183389 **
183390 ** FTS5_AND (nChild, apChild valid)
183391 ** FTS5_OR (nChild, apChild valid)
183392 ** FTS5_NOT (nChild, apChild valid)
183393 ** FTS5_STRING (pNear valid)
183394 ** FTS5_TERM (pNear valid)
183395 */
183396 struct Fts5ExprNode {
183397  int eType; /* Node type */
183398  int bEof; /* True at EOF */
183399  int bNomatch; /* True if entry is not a match */
183400 
183401  /* Next method for this node. */
183402  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
183403 
183404  i64 iRowid; /* Current rowid */
183405  Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
183406 
183407  /* Child nodes. For a NOT node, this array always contains 2 entries. For
183408  ** AND or OR nodes, it contains 2 or more entries. */
183409  int nChild; /* Number of child nodes */
183410  Fts5ExprNode *apChild[1]; /* Array of child nodes */
183411 };
183412 
183413 #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
183414 
183415 /*
183416 ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
183417 ** used as if it has the same signature as the xNext() methods themselves.
183418 */
183419 #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
183420 
183421 /*
183422 ** An instance of the following structure represents a single search term
183423 ** or term prefix.
183424 */
183425 struct Fts5ExprTerm {
183426  int bPrefix; /* True for a prefix term */
183427  char *zTerm; /* nul-terminated term */
183428  Fts5IndexIter *pIter; /* Iterator for this term */
183429  Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
183430 };
183431 
183432 /*
183433 ** A phrase. One or more terms that must appear in a contiguous sequence
183434 ** within a document for it to match.
183435 */
183436 struct Fts5ExprPhrase {
183437  Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
183438  Fts5Buffer poslist; /* Current position list */
183439  int nTerm; /* Number of entries in aTerm[] */
183440  Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
183441 };
183442 
183443 /*
183444 ** One or more phrases that must appear within a certain token distance of
183445 ** each other within each matching document.
183446 */
183447 struct Fts5ExprNearset {
183448  int nNear; /* NEAR parameter */
183449  Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
183450  int nPhrase; /* Number of entries in aPhrase[] array */
183451  Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
183452 };
183453 
183454 
183455 /*
183456 ** Parse context.
183457 */
183458 struct Fts5Parse {
183459  Fts5Config *pConfig;
183460  char *zErr;
183461  int rc;
183462  int nPhrase; /* Size of apPhrase array */
183463  Fts5ExprPhrase **apPhrase; /* Array of all phrases */
183464  Fts5ExprNode *pExpr; /* Result of a successful parse */
183465 };
183466 
183467 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
183468  va_list ap;
183469  va_start(ap, zFmt);
183470  if( pParse->rc==SQLITE_OK ){
183471  pParse->zErr = sqlite3_vmprintf(zFmt, ap);
183472  pParse->rc = SQLITE_ERROR;
183473  }
183474  va_end(ap);
183475 }
183476 
183477 static int fts5ExprIsspace(char t){
183478  return t==' ' || t=='\t' || t=='\n' || t=='\r';
183479 }
183480 
183481 /*
183482 ** Read the first token from the nul-terminated string at *pz.
183483 */
183484 static int fts5ExprGetToken(
183485  Fts5Parse *pParse,
183486  const char **pz, /* IN/OUT: Pointer into buffer */
183487  Fts5Token *pToken
183488 ){
183489  const char *z = *pz;
183490  int tok;
183491 
183492  /* Skip past any whitespace */
183493  while( fts5ExprIsspace(*z) ) z++;
183494 
183495  pToken->p = z;
183496  pToken->n = 1;
183497  switch( *z ){
183498  case '(': tok = FTS5_LP; break;
183499  case ')': tok = FTS5_RP; break;
183500  case '{': tok = FTS5_LCP; break;
183501  case '}': tok = FTS5_RCP; break;
183502  case ':': tok = FTS5_COLON; break;
183503  case ',': tok = FTS5_COMMA; break;
183504  case '+': tok = FTS5_PLUS; break;
183505  case '*': tok = FTS5_STAR; break;
183506  case '-': tok = FTS5_MINUS; break;
183507  case '\0': tok = FTS5_EOF; break;
183508 
183509  case '"': {
183510  const char *z2;
183511  tok = FTS5_STRING;
183512 
183513  for(z2=&z[1]; 1; z2++){
183514  if( z2[0]=='"' ){
183515  z2++;
183516  if( z2[0]!='"' ) break;
183517  }
183518  if( z2[0]=='\0' ){
183519  sqlite3Fts5ParseError(pParse, "unterminated string");
183520  return FTS5_EOF;
183521  }
183522  }
183523  pToken->n = (z2 - z);
183524  break;
183525  }
183526 
183527  default: {
183528  const char *z2;
183529  if( sqlite3Fts5IsBareword(z[0])==0 ){
183530  sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
183531  return FTS5_EOF;
183532  }
183533  tok = FTS5_STRING;
183534  for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
183535  pToken->n = (z2 - z);
183536  if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
183537  if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
183538  if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
183539  break;
183540  }
183541  }
183542 
183543  *pz = &pToken->p[pToken->n];
183544  return tok;
183545 }
183546 
183547 static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
183548 static void fts5ParseFree(void *p){ sqlite3_free(p); }
183549 
183550 static int sqlite3Fts5ExprNew(
183551  Fts5Config *pConfig, /* FTS5 Configuration */
183552  const char *zExpr, /* Expression text */
183553  Fts5Expr **ppNew,
183554  char **pzErr
183555 ){
183556  Fts5Parse sParse;
183557  Fts5Token token;
183558  const char *z = zExpr;
183559  int t; /* Next token type */
183560  void *pEngine;
183561  Fts5Expr *pNew;
183562 
183563  *ppNew = 0;
183564  *pzErr = 0;
183565  memset(&sParse, 0, sizeof(sParse));
183566  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
183567  if( pEngine==0 ){ return SQLITE_NOMEM; }
183568  sParse.pConfig = pConfig;
183569 
183570  do {
183571  t = fts5ExprGetToken(&sParse, &z, &token);
183572  sqlite3Fts5Parser(pEngine, t, token, &sParse);
183573  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
183574  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
183575 
183576  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
183577  if( sParse.rc==SQLITE_OK ){
183578  *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
183579  if( pNew==0 ){
183580  sParse.rc = SQLITE_NOMEM;
183581  sqlite3Fts5ParseNodeFree(sParse.pExpr);
183582  }else{
183583  if( !sParse.pExpr ){
183584  const int nByte = sizeof(Fts5ExprNode);
183585  pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
183586  if( pNew->pRoot ){
183587  pNew->pRoot->bEof = 1;
183588  }
183589  }else{
183590  pNew->pRoot = sParse.pExpr;
183591  }
183592  pNew->pIndex = 0;
183593  pNew->pConfig = pConfig;
183594  pNew->apExprPhrase = sParse.apPhrase;
183595  pNew->nPhrase = sParse.nPhrase;
183596  sParse.apPhrase = 0;
183597  }
183598  }else{
183599  sqlite3Fts5ParseNodeFree(sParse.pExpr);
183600  }
183601 
183602  sqlite3_free(sParse.apPhrase);
183603  *pzErr = sParse.zErr;
183604  return sParse.rc;
183605 }
183606 
183607 /*
183608 ** Free the expression node object passed as the only argument.
183609 */
183610 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
183611  if( p ){
183612  int i;
183613  for(i=0; i<p->nChild; i++){
183614  sqlite3Fts5ParseNodeFree(p->apChild[i]);
183615  }
183616  sqlite3Fts5ParseNearsetFree(p->pNear);
183617  sqlite3_free(p);
183618  }
183619 }
183620 
183621 /*
183622 ** Free the expression object passed as the only argument.
183623 */
183624 static void sqlite3Fts5ExprFree(Fts5Expr *p){
183625  if( p ){
183626  sqlite3Fts5ParseNodeFree(p->pRoot);
183627  sqlite3_free(p->apExprPhrase);
183628  sqlite3_free(p);
183629  }
183630 }
183631 
183632 /*
183633 ** Argument pTerm must be a synonym iterator. Return the current rowid
183634 ** that it points to.
183635 */
183636 static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
183637  i64 iRet = 0;
183638  int bRetValid = 0;
183639  Fts5ExprTerm *p;
183640 
183641  assert( pTerm->pSynonym );
183642  assert( bDesc==0 || bDesc==1 );
183643  for(p=pTerm; p; p=p->pSynonym){
183644  if( 0==sqlite3Fts5IterEof(p->pIter) ){
183645  i64 iRowid = p->pIter->iRowid;
183646  if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
183647  iRet = iRowid;
183648  bRetValid = 1;
183649  }
183650  }
183651  }
183652 
183653  if( pbEof && bRetValid==0 ) *pbEof = 1;
183654  return iRet;
183655 }
183656 
183657 /*
183658 ** Argument pTerm must be a synonym iterator.
183659 */
183660 static int fts5ExprSynonymList(
183661  Fts5ExprTerm *pTerm,
183662  i64 iRowid,
183663  Fts5Buffer *pBuf, /* Use this buffer for space if required */
183664  u8 **pa, int *pn
183665 ){
183666  Fts5PoslistReader aStatic[4];
183667  Fts5PoslistReader *aIter = aStatic;
183668  int nIter = 0;
183669  int nAlloc = 4;
183670  int rc = SQLITE_OK;
183671  Fts5ExprTerm *p;
183672 
183673  assert( pTerm->pSynonym );
183674  for(p=pTerm; p; p=p->pSynonym){
183675  Fts5IndexIter *pIter = p->pIter;
183676  if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
183677  if( pIter->nData==0 ) continue;
183678  if( nIter==nAlloc ){
183679  int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
183680  Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
183681  if( aNew==0 ){
183682  rc = SQLITE_NOMEM;
183683  goto synonym_poslist_out;
183684  }
183685  memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
183686  nAlloc = nAlloc*2;
183687  if( aIter!=aStatic ) sqlite3_free(aIter);
183688  aIter = aNew;
183689  }
183690  sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
183691  assert( aIter[nIter].bEof==0 );
183692  nIter++;
183693  }
183694  }
183695 
183696  if( nIter==1 ){
183697  *pa = (u8*)aIter[0].a;
183698  *pn = aIter[0].n;
183699  }else{
183700  Fts5PoslistWriter writer = {0};
183701  i64 iPrev = -1;
183702  fts5BufferZero(pBuf);
183703  while( 1 ){
183704  int i;
183705  i64 iMin = FTS5_LARGEST_INT64;
183706  for(i=0; i<nIter; i++){
183707  if( aIter[i].bEof==0 ){
183708  if( aIter[i].iPos==iPrev ){
183709  if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
183710  }
183711  if( aIter[i].iPos<iMin ){
183712  iMin = aIter[i].iPos;
183713  }
183714  }
183715  }
183716  if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
183717  rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
183718  iPrev = iMin;
183719  }
183720  if( rc==SQLITE_OK ){
183721  *pa = pBuf->p;
183722  *pn = pBuf->n;
183723  }
183724  }
183725 
183726  synonym_poslist_out:
183727  if( aIter!=aStatic ) sqlite3_free(aIter);
183728  return rc;
183729 }
183730 
183731 
183732 /*
183733 ** All individual term iterators in pPhrase are guaranteed to be valid and
183734 ** pointing to the same rowid when this function is called. This function
183735 ** checks if the current rowid really is a match, and if so populates
183736 ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
183737 ** is set to true if this is really a match, or false otherwise.
183738 **
183739 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
183740 ** otherwise. It is not considered an error code if the current rowid is
183741 ** not a match.
183742 */
183743 static int fts5ExprPhraseIsMatch(
183744  Fts5ExprNode *pNode, /* Node pPhrase belongs to */
183745  Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
183746  int *pbMatch /* OUT: Set to true if really a match */
183747 ){
183748  Fts5PoslistWriter writer = {0};
183749  Fts5PoslistReader aStatic[4];
183750  Fts5PoslistReader *aIter = aStatic;
183751  int i;
183752  int rc = SQLITE_OK;
183753 
183754  fts5BufferZero(&pPhrase->poslist);
183755 
183756  /* If the aStatic[] array is not large enough, allocate a large array
183757  ** using sqlite3_malloc(). This approach could be improved upon. */
183758  if( pPhrase->nTerm>ArraySize(aStatic) ){
183759  int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
183760  aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
183761  if( !aIter ) return SQLITE_NOMEM;
183762  }
183763  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
183764 
183765  /* Initialize a term iterator for each term in the phrase */
183766  for(i=0; i<pPhrase->nTerm; i++){
183767  Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
183768  int n = 0;
183769  int bFlag = 0;
183770  u8 *a = 0;
183771  if( pTerm->pSynonym ){
183772  Fts5Buffer buf = {0, 0, 0};
183773  rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
183774  if( rc ){
183775  sqlite3_free(a);
183776  goto ismatch_out;
183777  }
183778  if( a==buf.p ) bFlag = 1;
183779  }else{
183780  a = (u8*)pTerm->pIter->pData;
183781  n = pTerm->pIter->nData;
183782  }
183783  sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
183784  aIter[i].bFlag = (u8)bFlag;
183785  if( aIter[i].bEof ) goto ismatch_out;
183786  }
183787 
183788  while( 1 ){
183789  int bMatch;
183790  i64 iPos = aIter[0].iPos;
183791  do {
183792  bMatch = 1;
183793  for(i=0; i<pPhrase->nTerm; i++){
183794  Fts5PoslistReader *pPos = &aIter[i];
183795  i64 iAdj = iPos + i;
183796  if( pPos->iPos!=iAdj ){
183797  bMatch = 0;
183798  while( pPos->iPos<iAdj ){
183799  if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
183800  }
183801  if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
183802  }
183803  }
183804  }while( bMatch==0 );
183805 
183806  /* Append position iPos to the output */
183807  rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
183808  if( rc!=SQLITE_OK ) goto ismatch_out;
183809 
183810  for(i=0; i<pPhrase->nTerm; i++){
183811  if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
183812  }
183813  }
183814 
183815  ismatch_out:
183816  *pbMatch = (pPhrase->poslist.n>0);
183817  for(i=0; i<pPhrase->nTerm; i++){
183818  if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
183819  }
183820  if( aIter!=aStatic ) sqlite3_free(aIter);
183821  return rc;
183822 }
183823 
183824 typedef struct Fts5LookaheadReader Fts5LookaheadReader;
183825 struct Fts5LookaheadReader {
183826  const u8 *a; /* Buffer containing position list */
183827  int n; /* Size of buffer a[] in bytes */
183828  int i; /* Current offset in position list */
183829  i64 iPos; /* Current position */
183830  i64 iLookahead; /* Next position */
183831 };
183832 
183833 #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
183834 
183835 static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
183836  p->iPos = p->iLookahead;
183837  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
183838  p->iLookahead = FTS5_LOOKAHEAD_EOF;
183839  }
183840  return (p->iPos==FTS5_LOOKAHEAD_EOF);
183841 }
183842 
183843 static int fts5LookaheadReaderInit(
183844  const u8 *a, int n, /* Buffer to read position list from */
183845  Fts5LookaheadReader *p /* Iterator object to initialize */
183846 ){
183847  memset(p, 0, sizeof(Fts5LookaheadReader));
183848  p->a = a;
183849  p->n = n;
183850  fts5LookaheadReaderNext(p);
183851  return fts5LookaheadReaderNext(p);
183852 }
183853 
183854 typedef struct Fts5NearTrimmer Fts5NearTrimmer;
183855 struct Fts5NearTrimmer {
183856  Fts5LookaheadReader reader; /* Input iterator */
183857  Fts5PoslistWriter writer; /* Writer context */
183858  Fts5Buffer *pOut; /* Output poslist */
183859 };
183860 
183861 /*
183862 ** The near-set object passed as the first argument contains more than
183863 ** one phrase. All phrases currently point to the same row. The
183864 ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
183865 ** tests if the current row contains instances of each phrase sufficiently
183866 ** close together to meet the NEAR constraint. Non-zero is returned if it
183867 ** does, or zero otherwise.
183868 **
183869 ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
183870 ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
183871 ** occurs within this function (*pRc) is set accordingly before returning.
183872 ** The return value is undefined in both these cases.
183873 **
183874 ** If no error occurs and non-zero (a match) is returned, the position-list
183875 ** of each phrase object is edited to contain only those entries that
183876 ** meet the constraint before returning.
183877 */
183878 static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
183879  Fts5NearTrimmer aStatic[4];
183880  Fts5NearTrimmer *a = aStatic;
183881  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
183882 
183883  int i;
183884  int rc = *pRc;
183885  int bMatch;
183886 
183887  assert( pNear->nPhrase>1 );
183888 
183889  /* If the aStatic[] array is not large enough, allocate a large array
183890  ** using sqlite3_malloc(). This approach could be improved upon. */
183891  if( pNear->nPhrase>ArraySize(aStatic) ){
183892  int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
183893  a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
183894  }else{
183895  memset(aStatic, 0, sizeof(aStatic));
183896  }
183897  if( rc!=SQLITE_OK ){
183898  *pRc = rc;
183899  return 0;
183900  }
183901 
183902  /* Initialize a lookahead iterator for each phrase. After passing the
183903  ** buffer and buffer size to the lookaside-reader init function, zero
183904  ** the phrase poslist buffer. The new poslist for the phrase (containing
183905  ** the same entries as the original with some entries removed on account
183906  ** of the NEAR constraint) is written over the original even as it is
183907  ** being read. This is safe as the entries for the new poslist are a
183908  ** subset of the old, so it is not possible for data yet to be read to
183909  ** be overwritten. */
183910  for(i=0; i<pNear->nPhrase; i++){
183911  Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
183912  fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
183913  pPoslist->n = 0;
183914  a[i].pOut = pPoslist;
183915  }
183916 
183917  while( 1 ){
183918  int iAdv;
183919  i64 iMin;
183920  i64 iMax;
183921 
183922  /* This block advances the phrase iterators until they point to a set of
183923  ** entries that together comprise a match. */
183924  iMax = a[0].reader.iPos;
183925  do {
183926  bMatch = 1;
183927  for(i=0; i<pNear->nPhrase; i++){
183928  Fts5LookaheadReader *pPos = &a[i].reader;
183929  iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
183930  if( pPos->iPos<iMin || pPos->iPos>iMax ){
183931  bMatch = 0;
183932  while( pPos->iPos<iMin ){
183933  if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
183934  }
183935  if( pPos->iPos>iMax ) iMax = pPos->iPos;
183936  }
183937  }
183938  }while( bMatch==0 );
183939 
183940  /* Add an entry to each output position list */
183941  for(i=0; i<pNear->nPhrase; i++){
183942  i64 iPos = a[i].reader.iPos;
183943  Fts5PoslistWriter *pWriter = &a[i].writer;
183944  if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
183945  sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
183946  }
183947  }
183948 
183949  iAdv = 0;
183950  iMin = a[0].reader.iLookahead;
183951  for(i=0; i<pNear->nPhrase; i++){
183952  if( a[i].reader.iLookahead < iMin ){
183953  iMin = a[i].reader.iLookahead;
183954  iAdv = i;
183955  }
183956  }
183957  if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
183958  }
183959 
183960  ismatch_out: {
183961  int bRet = a[0].pOut->n>0;
183962  *pRc = rc;
183963  if( a!=aStatic ) sqlite3_free(a);
183964  return bRet;
183965  }
183966 }
183967 
183968 /*
183969 ** Advance iterator pIter until it points to a value equal to or laster
183970 ** than the initial value of *piLast. If this means the iterator points
183971 ** to a value laster than *piLast, update *piLast to the new lastest value.
183972 **
183973 ** If the iterator reaches EOF, set *pbEof to true before returning. If
183974 ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
183975 ** are set, return a non-zero value. Otherwise, return zero.
183976 */
183977 static int fts5ExprAdvanceto(
183978  Fts5IndexIter *pIter, /* Iterator to advance */
183979  int bDesc, /* True if iterator is "rowid DESC" */
183980  i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
183981  int *pRc, /* OUT: Error code */
183982  int *pbEof /* OUT: Set to true if EOF */
183983 ){
183984  i64 iLast = *piLast;
183985  i64 iRowid;
183986 
183987  iRowid = pIter->iRowid;
183988  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
183989  int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
183990  if( rc || sqlite3Fts5IterEof(pIter) ){
183991  *pRc = rc;
183992  *pbEof = 1;
183993  return 1;
183994  }
183995  iRowid = pIter->iRowid;
183996  assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
183997  }
183998  *piLast = iRowid;
183999 
184000  return 0;
184001 }
184002 
184003 static int fts5ExprSynonymAdvanceto(
184004  Fts5ExprTerm *pTerm, /* Term iterator to advance */
184005  int bDesc, /* True if iterator is "rowid DESC" */
184006  i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
184007  int *pRc /* OUT: Error code */
184008 ){
184009  int rc = SQLITE_OK;
184010  i64 iLast = *piLast;
184011  Fts5ExprTerm *p;
184012  int bEof = 0;
184013 
184014  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
184015  if( sqlite3Fts5IterEof(p->pIter)==0 ){
184016  i64 iRowid = p->pIter->iRowid;
184017  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
184018  rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
184019  }
184020  }
184021  }
184022 
184023  if( rc!=SQLITE_OK ){
184024  *pRc = rc;
184025  bEof = 1;
184026  }else{
184027  *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
184028  }
184029  return bEof;
184030 }
184031 
184032 
184033 static int fts5ExprNearTest(
184034  int *pRc,
184035  Fts5Expr *pExpr, /* Expression that pNear is a part of */
184036  Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
184037 ){
184038  Fts5ExprNearset *pNear = pNode->pNear;
184039  int rc = *pRc;
184040 
184041  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
184042  Fts5ExprTerm *pTerm;
184043  Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
184044  pPhrase->poslist.n = 0;
184045  for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
184046  Fts5IndexIter *pIter = pTerm->pIter;
184047  if( sqlite3Fts5IterEof(pIter)==0 ){
184048  if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
184049  pPhrase->poslist.n = 1;
184050  }
184051  }
184052  }
184053  return pPhrase->poslist.n;
184054  }else{
184055  int i;
184056 
184057  /* Check that each phrase in the nearset matches the current row.
184058  ** Populate the pPhrase->poslist buffers at the same time. If any
184059  ** phrase is not a match, break out of the loop early. */
184060  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
184061  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184062  if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
184063  int bMatch = 0;
184064  rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
184065  if( bMatch==0 ) break;
184066  }else{
184067  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
184068  fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
184069  }
184070  }
184071 
184072  *pRc = rc;
184073  if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
184074  return 1;
184075  }
184076  return 0;
184077  }
184078 }
184079 
184080 
184081 /*
184082 ** Initialize all term iterators in the pNear object. If any term is found
184083 ** to match no documents at all, return immediately without initializing any
184084 ** further iterators.
184085 */
184086 static int fts5ExprNearInitAll(
184087  Fts5Expr *pExpr,
184088  Fts5ExprNode *pNode
184089 ){
184090  Fts5ExprNearset *pNear = pNode->pNear;
184091  int i, j;
184092  int rc = SQLITE_OK;
184093  int bEof = 1;
184094 
184095  assert( pNode->bNomatch==0 );
184096  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
184097  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184098  for(j=0; j<pPhrase->nTerm; j++){
184099  Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
184100  Fts5ExprTerm *p;
184101 
184102  for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
184103  if( p->pIter ){
184104  sqlite3Fts5IterClose(p->pIter);
184105  p->pIter = 0;
184106  }
184107  rc = sqlite3Fts5IndexQuery(
184108  pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
184109  (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
184110  (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
184111  pNear->pColset,
184112  &p->pIter
184113  );
184114  assert( rc==SQLITE_OK || p->pIter==0 );
184115  if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
184116  bEof = 0;
184117  }
184118  }
184119 
184120  if( bEof ) break;
184121  }
184122  if( bEof ) break;
184123  }
184124 
184125  pNode->bEof = bEof;
184126  return rc;
184127 }
184128 
184129 /*
184130 ** If pExpr is an ASC iterator, this function returns a value with the
184131 ** same sign as:
184132 **
184133 ** (iLhs - iRhs)
184134 **
184135 ** Otherwise, if this is a DESC iterator, the opposite is returned:
184136 **
184137 ** (iRhs - iLhs)
184138 */
184139 static int fts5RowidCmp(
184140  Fts5Expr *pExpr,
184141  i64 iLhs,
184142  i64 iRhs
184143 ){
184144  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
184145  if( pExpr->bDesc==0 ){
184146  if( iLhs<iRhs ) return -1;
184147  return (iLhs > iRhs);
184148  }else{
184149  if( iLhs>iRhs ) return -1;
184150  return (iLhs < iRhs);
184151  }
184152 }
184153 
184154 static void fts5ExprSetEof(Fts5ExprNode *pNode){
184155  int i;
184156  pNode->bEof = 1;
184157  pNode->bNomatch = 0;
184158  for(i=0; i<pNode->nChild; i++){
184159  fts5ExprSetEof(pNode->apChild[i]);
184160  }
184161 }
184162 
184163 static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
184164  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
184165  Fts5ExprNearset *pNear = pNode->pNear;
184166  int i;
184167  for(i=0; i<pNear->nPhrase; i++){
184168  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184169  pPhrase->poslist.n = 0;
184170  }
184171  }else{
184172  int i;
184173  for(i=0; i<pNode->nChild; i++){
184174  fts5ExprNodeZeroPoslist(pNode->apChild[i]);
184175  }
184176  }
184177 }
184178 
184179 
184180 
184181 /*
184182 ** Compare the values currently indicated by the two nodes as follows:
184183 **
184184 ** res = (*p1) - (*p2)
184185 **
184186 ** Nodes that point to values that come later in the iteration order are
184187 ** considered to be larger. Nodes at EOF are the largest of all.
184188 **
184189 ** This means that if the iteration order is ASC, then numerically larger
184190 ** rowids are considered larger. Or if it is the default DESC, numerically
184191 ** smaller rowids are larger.
184192 */
184193 static int fts5NodeCompare(
184194  Fts5Expr *pExpr,
184195  Fts5ExprNode *p1,
184196  Fts5ExprNode *p2
184197 ){
184198  if( p2->bEof ) return -1;
184199  if( p1->bEof ) return +1;
184200  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
184201 }
184202 
184203 /*
184204 ** All individual term iterators in pNear are guaranteed to be valid when
184205 ** this function is called. This function checks if all term iterators
184206 ** point to the same rowid, and if not, advances them until they do.
184207 ** If an EOF is reached before this happens, *pbEof is set to true before
184208 ** returning.
184209 **
184210 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
184211 ** otherwise. It is not considered an error code if an iterator reaches
184212 ** EOF.
184213 */
184214 static int fts5ExprNodeTest_STRING(
184215  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184216  Fts5ExprNode *pNode
184217 ){
184218  Fts5ExprNearset *pNear = pNode->pNear;
184219  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
184220  int rc = SQLITE_OK;
184221  i64 iLast; /* Lastest rowid any iterator points to */
184222  int i, j; /* Phrase and token index, respectively */
184223  int bMatch; /* True if all terms are at the same rowid */
184224  const int bDesc = pExpr->bDesc;
184225 
184226  /* Check that this node should not be FTS5_TERM */
184227  assert( pNear->nPhrase>1
184228  || pNear->apPhrase[0]->nTerm>1
184229  || pNear->apPhrase[0]->aTerm[0].pSynonym
184230  );
184231 
184232  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
184233  ** iterator skips through rowids in the default ascending order, this means
184234  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
184235  ** means the minimum rowid. */
184236  if( pLeft->aTerm[0].pSynonym ){
184237  iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
184238  }else{
184239  iLast = pLeft->aTerm[0].pIter->iRowid;
184240  }
184241 
184242  do {
184243  bMatch = 1;
184244  for(i=0; i<pNear->nPhrase; i++){
184245  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
184246  for(j=0; j<pPhrase->nTerm; j++){
184247  Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
184248  if( pTerm->pSynonym ){
184249  i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
184250  if( iRowid==iLast ) continue;
184251  bMatch = 0;
184252  if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
184253  pNode->bNomatch = 0;
184254  pNode->bEof = 1;
184255  return rc;
184256  }
184257  }else{
184258  Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
184259  if( pIter->iRowid==iLast || pIter->bEof ) continue;
184260  bMatch = 0;
184261  if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
184262  return rc;
184263  }
184264  }
184265  }
184266  }
184267  }while( bMatch==0 );
184268 
184269  pNode->iRowid = iLast;
184270  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
184271  assert( pNode->bEof==0 || pNode->bNomatch==0 );
184272 
184273  return rc;
184274 }
184275 
184276 /*
184277 ** Advance the first term iterator in the first phrase of pNear. Set output
184278 ** variable *pbEof to true if it reaches EOF or if an error occurs.
184279 **
184280 ** Return SQLITE_OK if successful, or an SQLite error code if an error
184281 ** occurs.
184282 */
184283 static int fts5ExprNodeNext_STRING(
184284  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184285  Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
184286  int bFromValid,
184287  i64 iFrom
184288 ){
184289  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
184290  int rc = SQLITE_OK;
184291 
184292  pNode->bNomatch = 0;
184293  if( pTerm->pSynonym ){
184294  int bEof = 1;
184295  Fts5ExprTerm *p;
184296 
184297  /* Find the firstest rowid any synonym points to. */
184298  i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
184299 
184300  /* Advance each iterator that currently points to iRowid. Or, if iFrom
184301  ** is valid - each iterator that points to a rowid before iFrom. */
184302  for(p=pTerm; p; p=p->pSynonym){
184303  if( sqlite3Fts5IterEof(p->pIter)==0 ){
184304  i64 ii = p->pIter->iRowid;
184305  if( ii==iRowid
184306  || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
184307  ){
184308  if( bFromValid ){
184309  rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
184310  }else{
184311  rc = sqlite3Fts5IterNext(p->pIter);
184312  }
184313  if( rc!=SQLITE_OK ) break;
184314  if( sqlite3Fts5IterEof(p->pIter)==0 ){
184315  bEof = 0;
184316  }
184317  }else{
184318  bEof = 0;
184319  }
184320  }
184321  }
184322 
184323  /* Set the EOF flag if either all synonym iterators are at EOF or an
184324  ** error has occurred. */
184325  pNode->bEof = (rc || bEof);
184326  }else{
184327  Fts5IndexIter *pIter = pTerm->pIter;
184328 
184329  assert( Fts5NodeIsString(pNode) );
184330  if( bFromValid ){
184331  rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
184332  }else{
184333  rc = sqlite3Fts5IterNext(pIter);
184334  }
184335 
184336  pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
184337  }
184338 
184339  if( pNode->bEof==0 ){
184340  assert( rc==SQLITE_OK );
184341  rc = fts5ExprNodeTest_STRING(pExpr, pNode);
184342  }
184343 
184344  return rc;
184345 }
184346 
184347 
184348 static int fts5ExprNodeTest_TERM(
184349  Fts5Expr *pExpr, /* Expression that pNear is a part of */
184350  Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
184351 ){
184352  /* As this "NEAR" object is actually a single phrase that consists
184353  ** of a single term only, grab pointers into the poslist managed by the
184354  ** fts5_index.c iterator object. This is much faster than synthesizing
184355  ** a new poslist the way we have to for more complicated phrase or NEAR
184356  ** expressions. */
184357  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
184358  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
184359 
184360  assert( pNode->eType==FTS5_TERM );
184361  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
184362  assert( pPhrase->aTerm[0].pSynonym==0 );
184363 
184364  pPhrase->poslist.n = pIter->nData;
184365  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
184366  pPhrase->poslist.p = (u8*)pIter->pData;
184367  }
184368  pNode->iRowid = pIter->iRowid;
184369  pNode->bNomatch = (pPhrase->poslist.n==0);
184370  return SQLITE_OK;
184371 }
184372 
184373 /*
184374 ** xNext() method for a node of type FTS5_TERM.
184375 */
184376 static int fts5ExprNodeNext_TERM(
184377  Fts5Expr *pExpr,
184378  Fts5ExprNode *pNode,
184379  int bFromValid,
184380  i64 iFrom
184381 ){
184382  int rc;
184383  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
184384 
184385  assert( pNode->bEof==0 );
184386  if( bFromValid ){
184387  rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
184388  }else{
184389  rc = sqlite3Fts5IterNext(pIter);
184390  }
184391  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
184392  rc = fts5ExprNodeTest_TERM(pExpr, pNode);
184393  }else{
184394  pNode->bEof = 1;
184395  pNode->bNomatch = 0;
184396  }
184397  return rc;
184398 }
184399 
184400 static void fts5ExprNodeTest_OR(
184401  Fts5Expr *pExpr, /* Expression of which pNode is a part */
184402  Fts5ExprNode *pNode /* Expression node to test */
184403 ){
184404  Fts5ExprNode *pNext = pNode->apChild[0];
184405  int i;
184406 
184407  for(i=1; i<pNode->nChild; i++){
184408  Fts5ExprNode *pChild = pNode->apChild[i];
184409  int cmp = fts5NodeCompare(pExpr, pNext, pChild);
184410  if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
184411  pNext = pChild;
184412  }
184413  }
184414  pNode->iRowid = pNext->iRowid;
184415  pNode->bEof = pNext->bEof;
184416  pNode->bNomatch = pNext->bNomatch;
184417 }
184418 
184419 static int fts5ExprNodeNext_OR(
184420  Fts5Expr *pExpr,
184421  Fts5ExprNode *pNode,
184422  int bFromValid,
184423  i64 iFrom
184424 ){
184425  int i;
184426  i64 iLast = pNode->iRowid;
184427 
184428  for(i=0; i<pNode->nChild; i++){
184429  Fts5ExprNode *p1 = pNode->apChild[i];
184430  assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
184431  if( p1->bEof==0 ){
184432  if( (p1->iRowid==iLast)
184433  || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
184434  ){
184435  int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
184436  if( rc!=SQLITE_OK ) return rc;
184437  }
184438  }
184439  }
184440 
184441  fts5ExprNodeTest_OR(pExpr, pNode);
184442  return SQLITE_OK;
184443 }
184444 
184445 /*
184446 ** Argument pNode is an FTS5_AND node.
184447 */
184448 static int fts5ExprNodeTest_AND(
184449  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184450  Fts5ExprNode *pAnd /* FTS5_AND node to advance */
184451 ){
184452  int iChild;
184453  i64 iLast = pAnd->iRowid;
184454  int rc = SQLITE_OK;
184455  int bMatch;
184456 
184457  assert( pAnd->bEof==0 );
184458  do {
184459  pAnd->bNomatch = 0;
184460  bMatch = 1;
184461  for(iChild=0; iChild<pAnd->nChild; iChild++){
184462  Fts5ExprNode *pChild = pAnd->apChild[iChild];
184463  int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
184464  if( cmp>0 ){
184465  /* Advance pChild until it points to iLast or laster */
184466  rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
184467  if( rc!=SQLITE_OK ) return rc;
184468  }
184469 
184470  /* If the child node is now at EOF, so is the parent AND node. Otherwise,
184471  ** the child node is guaranteed to have advanced at least as far as
184472  ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
184473  ** new lastest rowid seen so far. */
184474  assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
184475  if( pChild->bEof ){
184476  fts5ExprSetEof(pAnd);
184477  bMatch = 1;
184478  break;
184479  }else if( iLast!=pChild->iRowid ){
184480  bMatch = 0;
184481  iLast = pChild->iRowid;
184482  }
184483 
184484  if( pChild->bNomatch ){
184485  pAnd->bNomatch = 1;
184486  }
184487  }
184488  }while( bMatch==0 );
184489 
184490  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
184491  fts5ExprNodeZeroPoslist(pAnd);
184492  }
184493  pAnd->iRowid = iLast;
184494  return SQLITE_OK;
184495 }
184496 
184497 static int fts5ExprNodeNext_AND(
184498  Fts5Expr *pExpr,
184499  Fts5ExprNode *pNode,
184500  int bFromValid,
184501  i64 iFrom
184502 ){
184503  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
184504  if( rc==SQLITE_OK ){
184505  rc = fts5ExprNodeTest_AND(pExpr, pNode);
184506  }
184507  return rc;
184508 }
184509 
184510 static int fts5ExprNodeTest_NOT(
184511  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
184512  Fts5ExprNode *pNode /* FTS5_NOT node to advance */
184513 ){
184514  int rc = SQLITE_OK;
184515  Fts5ExprNode *p1 = pNode->apChild[0];
184516  Fts5ExprNode *p2 = pNode->apChild[1];
184517  assert( pNode->nChild==2 );
184518 
184519  while( rc==SQLITE_OK && p1->bEof==0 ){
184520  int cmp = fts5NodeCompare(pExpr, p1, p2);
184521  if( cmp>0 ){
184522  rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
184523  cmp = fts5NodeCompare(pExpr, p1, p2);
184524  }
184525  assert( rc!=SQLITE_OK || cmp<=0 );
184526  if( cmp || p2->bNomatch ) break;
184527  rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
184528  }
184529  pNode->bEof = p1->bEof;
184530  pNode->bNomatch = p1->bNomatch;
184531  pNode->iRowid = p1->iRowid;
184532  if( p1->bEof ){
184533  fts5ExprNodeZeroPoslist(p2);
184534  }
184535  return rc;
184536 }
184537 
184538 static int fts5ExprNodeNext_NOT(
184539  Fts5Expr *pExpr,
184540  Fts5ExprNode *pNode,
184541  int bFromValid,
184542  i64 iFrom
184543 ){
184544  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
184545  if( rc==SQLITE_OK ){
184546  rc = fts5ExprNodeTest_NOT(pExpr, pNode);
184547  }
184548  return rc;
184549 }
184550 
184551 /*
184552 ** If pNode currently points to a match, this function returns SQLITE_OK
184553 ** without modifying it. Otherwise, pNode is advanced until it does point
184554 ** to a match or EOF is reached.
184555 */
184556 static int fts5ExprNodeTest(
184557  Fts5Expr *pExpr, /* Expression of which pNode is a part */
184558  Fts5ExprNode *pNode /* Expression node to test */
184559 ){
184560  int rc = SQLITE_OK;
184561  if( pNode->bEof==0 ){
184562  switch( pNode->eType ){
184563 
184564  case FTS5_STRING: {
184565  rc = fts5ExprNodeTest_STRING(pExpr, pNode);
184566  break;
184567  }
184568 
184569  case FTS5_TERM: {
184570  rc = fts5ExprNodeTest_TERM(pExpr, pNode);
184571  break;
184572  }
184573 
184574  case FTS5_AND: {
184575  rc = fts5ExprNodeTest_AND(pExpr, pNode);
184576  break;
184577  }
184578 
184579  case FTS5_OR: {
184580  fts5ExprNodeTest_OR(pExpr, pNode);
184581  break;
184582  }
184583 
184584  default: assert( pNode->eType==FTS5_NOT ); {
184585  rc = fts5ExprNodeTest_NOT(pExpr, pNode);
184586  break;
184587  }
184588  }
184589  }
184590  return rc;
184591 }
184592 
184593 
184594 /*
184595 ** Set node pNode, which is part of expression pExpr, to point to the first
184596 ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
184597 **
184598 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
184599 ** It is not an error if there are no matches.
184600 */
184601 static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
184602  int rc = SQLITE_OK;
184603  pNode->bEof = 0;
184604  pNode->bNomatch = 0;
184605 
184606  if( Fts5NodeIsString(pNode) ){
184607  /* Initialize all term iterators in the NEAR object. */
184608  rc = fts5ExprNearInitAll(pExpr, pNode);
184609  }else if( pNode->xNext==0 ){
184610  pNode->bEof = 1;
184611  }else{
184612  int i;
184613  int nEof = 0;
184614  for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
184615  Fts5ExprNode *pChild = pNode->apChild[i];
184616  rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
184617  assert( pChild->bEof==0 || pChild->bEof==1 );
184618  nEof += pChild->bEof;
184619  }
184620  pNode->iRowid = pNode->apChild[0]->iRowid;
184621 
184622  switch( pNode->eType ){
184623  case FTS5_AND:
184624  if( nEof>0 ) fts5ExprSetEof(pNode);
184625  break;
184626 
184627  case FTS5_OR:
184628  if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
184629  break;
184630 
184631  default:
184632  assert( pNode->eType==FTS5_NOT );
184633  pNode->bEof = pNode->apChild[0]->bEof;
184634  break;
184635  }
184636  }
184637 
184638  if( rc==SQLITE_OK ){
184639  rc = fts5ExprNodeTest(pExpr, pNode);
184640  }
184641  return rc;
184642 }
184643 
184644 
184645 /*
184646 ** Begin iterating through the set of documents in index pIdx matched by
184647 ** the MATCH expression passed as the first argument. If the "bDesc"
184648 ** parameter is passed a non-zero value, iteration is in descending rowid
184649 ** order. Or, if it is zero, in ascending order.
184650 **
184651 ** If iterating in ascending rowid order (bDesc==0), the first document
184652 ** visited is that with the smallest rowid that is larger than or equal
184653 ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
184654 ** then the first document visited must have a rowid smaller than or
184655 ** equal to iFirst.
184656 **
184657 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
184658 ** is not considered an error if the query does not match any documents.
184659 */
184660 static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
184661  Fts5ExprNode *pRoot = p->pRoot;
184662  int rc; /* Return code */
184663 
184664  p->pIndex = pIdx;
184665  p->bDesc = bDesc;
184666  rc = fts5ExprNodeFirst(p, pRoot);
184667 
184668  /* If not at EOF but the current rowid occurs earlier than iFirst in
184669  ** the iteration order, move to document iFirst or later. */
184670  if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
184671  rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
184672  }
184673 
184674  /* If the iterator is not at a real match, skip forward until it is. */
184675  while( pRoot->bNomatch ){
184676  assert( pRoot->bEof==0 && rc==SQLITE_OK );
184677  rc = fts5ExprNodeNext(p, pRoot, 0, 0);
184678  }
184679  return rc;
184680 }
184681 
184682 /*
184683 ** Move to the next document
184684 **
184685 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
184686 ** is not considered an error if the query does not match any documents.
184687 */
184688 static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
184689  int rc;
184690  Fts5ExprNode *pRoot = p->pRoot;
184691  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
184692  do {
184693  rc = fts5ExprNodeNext(p, pRoot, 0, 0);
184694  assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
184695  }while( pRoot->bNomatch );
184696  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
184697  pRoot->bEof = 1;
184698  }
184699  return rc;
184700 }
184701 
184702 static int sqlite3Fts5ExprEof(Fts5Expr *p){
184703  return p->pRoot->bEof;
184704 }
184705 
184706 static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
184707  return p->pRoot->iRowid;
184708 }
184709 
184710 static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
184711  int rc = SQLITE_OK;
184712  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
184713  return rc;
184714 }
184715 
184716 /*
184717 ** Free the phrase object passed as the only argument.
184718 */
184719 static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
184720  if( pPhrase ){
184721  int i;
184722  for(i=0; i<pPhrase->nTerm; i++){
184723  Fts5ExprTerm *pSyn;
184724  Fts5ExprTerm *pNext;
184725  Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
184726  sqlite3_free(pTerm->zTerm);
184727  sqlite3Fts5IterClose(pTerm->pIter);
184728  for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
184729  pNext = pSyn->pSynonym;
184730  sqlite3Fts5IterClose(pSyn->pIter);
184731  fts5BufferFree((Fts5Buffer*)&pSyn[1]);
184732  sqlite3_free(pSyn);
184733  }
184734  }
184735  if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
184736  sqlite3_free(pPhrase);
184737  }
184738 }
184739 
184740 /*
184741 ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
184742 ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
184743 ** appended to it and the results returned.
184744 **
184745 ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
184746 ** NULL returned.
184747 */
184748 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
184749  Fts5Parse *pParse, /* Parse context */
184750  Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
184751  Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
184752 ){
184753  const int SZALLOC = 8;
184754  Fts5ExprNearset *pRet = 0;
184755 
184756  if( pParse->rc==SQLITE_OK ){
184757  if( pPhrase==0 ){
184758  return pNear;
184759  }
184760  if( pNear==0 ){
184761  int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
184762  pRet = sqlite3_malloc(nByte);
184763  if( pRet==0 ){
184764  pParse->rc = SQLITE_NOMEM;
184765  }else{
184766  memset(pRet, 0, nByte);
184767  }
184768  }else if( (pNear->nPhrase % SZALLOC)==0 ){
184769  int nNew = pNear->nPhrase + SZALLOC;
184770  int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
184771 
184772  pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
184773  if( pRet==0 ){
184774  pParse->rc = SQLITE_NOMEM;
184775  }
184776  }else{
184777  pRet = pNear;
184778  }
184779  }
184780 
184781  if( pRet==0 ){
184782  assert( pParse->rc!=SQLITE_OK );
184783  sqlite3Fts5ParseNearsetFree(pNear);
184784  sqlite3Fts5ParsePhraseFree(pPhrase);
184785  }else{
184786  if( pRet->nPhrase>0 ){
184787  Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
184788  assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
184789  if( pPhrase->nTerm==0 ){
184790  fts5ExprPhraseFree(pPhrase);
184791  pRet->nPhrase--;
184792  pParse->nPhrase--;
184793  pPhrase = pLast;
184794  }else if( pLast->nTerm==0 ){
184795  fts5ExprPhraseFree(pLast);
184796  pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
184797  pParse->nPhrase--;
184798  pRet->nPhrase--;
184799  }
184800  }
184801  pRet->apPhrase[pRet->nPhrase++] = pPhrase;
184802  }
184803  return pRet;
184804 }
184805 
184806 typedef struct TokenCtx TokenCtx;
184807 struct TokenCtx {
184808  Fts5ExprPhrase *pPhrase;
184809  int rc;
184810 };
184811 
184812 /*
184813 ** Callback for tokenizing terms used by ParseTerm().
184814 */
184815 static int fts5ParseTokenize(
184816  void *pContext, /* Pointer to Fts5InsertCtx object */
184817  int tflags, /* Mask of FTS5_TOKEN_* flags */
184818  const char *pToken, /* Buffer containing token */
184819  int nToken, /* Size of token in bytes */
184820  int iUnused1, /* Start offset of token */
184821  int iUnused2 /* End offset of token */
184822 ){
184823  int rc = SQLITE_OK;
184824  const int SZALLOC = 8;
184825  TokenCtx *pCtx = (TokenCtx*)pContext;
184826  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
184827 
184828  UNUSED_PARAM2(iUnused1, iUnused2);
184829 
184830  /* If an error has already occurred, this is a no-op */
184831  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
184832  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
184833 
184834  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
184835  Fts5ExprTerm *pSyn;
184836  int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
184837  pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
184838  if( pSyn==0 ){
184839  rc = SQLITE_NOMEM;
184840  }else{
184841  memset(pSyn, 0, nByte);
184842  pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
184843  memcpy(pSyn->zTerm, pToken, nToken);
184844  pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
184845  pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
184846  }
184847  }else{
184848  Fts5ExprTerm *pTerm;
184849  if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
184850  Fts5ExprPhrase *pNew;
184851  int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
184852 
184853  pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
184854  sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
184855  );
184856  if( pNew==0 ){
184857  rc = SQLITE_NOMEM;
184858  }else{
184859  if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
184860  pCtx->pPhrase = pPhrase = pNew;
184861  pNew->nTerm = nNew - SZALLOC;
184862  }
184863  }
184864 
184865  if( rc==SQLITE_OK ){
184866  pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
184867  memset(pTerm, 0, sizeof(Fts5ExprTerm));
184868  pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
184869  }
184870  }
184871 
184872  pCtx->rc = rc;
184873  return rc;
184874 }
184875 
184876 
184877 /*
184878 ** Free the phrase object passed as the only argument.
184879 */
184880 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
184881  fts5ExprPhraseFree(pPhrase);
184882 }
184883 
184884 /*
184885 ** Free the phrase object passed as the second argument.
184886 */
184887 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
184888  if( pNear ){
184889  int i;
184890  for(i=0; i<pNear->nPhrase; i++){
184891  fts5ExprPhraseFree(pNear->apPhrase[i]);
184892  }
184893  sqlite3_free(pNear->pColset);
184894  sqlite3_free(pNear);
184895  }
184896 }
184897 
184898 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
184899  assert( pParse->pExpr==0 );
184900  pParse->pExpr = p;
184901 }
184902 
184903 /*
184904 ** This function is called by the parser to process a string token. The
184905 ** string may or may not be quoted. In any case it is tokenized and a
184906 ** phrase object consisting of all tokens returned.
184907 */
184908 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
184909  Fts5Parse *pParse, /* Parse context */
184910  Fts5ExprPhrase *pAppend, /* Phrase to append to */
184911  Fts5Token *pToken, /* String to tokenize */
184912  int bPrefix /* True if there is a trailing "*" */
184913 ){
184914  Fts5Config *pConfig = pParse->pConfig;
184915  TokenCtx sCtx; /* Context object passed to callback */
184916  int rc; /* Tokenize return code */
184917  char *z = 0;
184918 
184919  memset(&sCtx, 0, sizeof(TokenCtx));
184920  sCtx.pPhrase = pAppend;
184921 
184922  rc = fts5ParseStringFromToken(pToken, &z);
184923  if( rc==SQLITE_OK ){
184924  int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
184925  int n;
184926  sqlite3Fts5Dequote(z);
184927  n = (int)strlen(z);
184928  rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
184929  }
184930  sqlite3_free(z);
184931  if( rc || (rc = sCtx.rc) ){
184932  pParse->rc = rc;
184933  fts5ExprPhraseFree(sCtx.pPhrase);
184934  sCtx.pPhrase = 0;
184935  }else{
184936 
184937  if( pAppend==0 ){
184938  if( (pParse->nPhrase % 8)==0 ){
184939  int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
184940  Fts5ExprPhrase **apNew;
184941  apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
184942  if( apNew==0 ){
184943  pParse->rc = SQLITE_NOMEM;
184944  fts5ExprPhraseFree(sCtx.pPhrase);
184945  return 0;
184946  }
184947  pParse->apPhrase = apNew;
184948  }
184949  pParse->nPhrase++;
184950  }
184951 
184952  if( sCtx.pPhrase==0 ){
184953  /* This happens when parsing a token or quoted phrase that contains
184954  ** no token characters at all. (e.g ... MATCH '""'). */
184955  sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
184956  }else if( sCtx.pPhrase->nTerm ){
184957  sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
184958  }
184959  pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
184960  }
184961 
184962  return sCtx.pPhrase;
184963 }
184964 
184965 /*
184966 ** Create a new FTS5 expression by cloning phrase iPhrase of the
184967 ** expression passed as the second argument.
184968 */
184969 static int sqlite3Fts5ExprClonePhrase(
184970  Fts5Expr *pExpr,
184971  int iPhrase,
184972  Fts5Expr **ppNew
184973 ){
184974  int rc = SQLITE_OK; /* Return code */
184975  Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
184976  Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
184977  TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
184978 
184979  pOrig = pExpr->apExprPhrase[iPhrase];
184980  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
184981  if( rc==SQLITE_OK ){
184982  pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
184983  sizeof(Fts5ExprPhrase*));
184984  }
184985  if( rc==SQLITE_OK ){
184986  pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
184987  sizeof(Fts5ExprNode));
184988  }
184989  if( rc==SQLITE_OK ){
184990  pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
184991  sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
184992  }
184993  if( rc==SQLITE_OK ){
184994  Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
184995  if( pColsetOrig ){
184996  int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
184997  Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
184998  if( pColset ){
184999  memcpy(pColset, pColsetOrig, nByte);
185000  }
185001  pNew->pRoot->pNear->pColset = pColset;
185002  }
185003  }
185004 
185005  if( pOrig->nTerm ){
185006  int i; /* Used to iterate through phrase terms */
185007  for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
185008  int tflags = 0;
185009  Fts5ExprTerm *p;
185010  for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
185011  const char *zTerm = p->zTerm;
185012  rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
185013  0, 0);
185014  tflags = FTS5_TOKEN_COLOCATED;
185015  }
185016  if( rc==SQLITE_OK ){
185017  sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
185018  }
185019  }
185020  }else{
185021  /* This happens when parsing a token or quoted phrase that contains
185022  ** no token characters at all. (e.g ... MATCH '""'). */
185023  sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
185024  }
185025 
185026  if( rc==SQLITE_OK ){
185027  /* All the allocations succeeded. Put the expression object together. */
185028  pNew->pIndex = pExpr->pIndex;
185029  pNew->pConfig = pExpr->pConfig;
185030  pNew->nPhrase = 1;
185031  pNew->apExprPhrase[0] = sCtx.pPhrase;
185032  pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
185033  pNew->pRoot->pNear->nPhrase = 1;
185034  sCtx.pPhrase->pNode = pNew->pRoot;
185035 
185036  if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
185037  pNew->pRoot->eType = FTS5_TERM;
185038  pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
185039  }else{
185040  pNew->pRoot->eType = FTS5_STRING;
185041  pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
185042  }
185043  }else{
185044  sqlite3Fts5ExprFree(pNew);
185045  fts5ExprPhraseFree(sCtx.pPhrase);
185046  pNew = 0;
185047  }
185048 
185049  *ppNew = pNew;
185050  return rc;
185051 }
185052 
185053 
185054 /*
185055 ** Token pTok has appeared in a MATCH expression where the NEAR operator
185056 ** is expected. If token pTok does not contain "NEAR", store an error
185057 ** in the pParse object.
185058 */
185059 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
185060  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
185061  sqlite3Fts5ParseError(
185062  pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
185063  );
185064  }
185065 }
185066 
185067 static void sqlite3Fts5ParseSetDistance(
185068  Fts5Parse *pParse,
185069  Fts5ExprNearset *pNear,
185070  Fts5Token *p
185071 ){
185072  if( pNear ){
185073  int nNear = 0;
185074  int i;
185075  if( p->n ){
185076  for(i=0; i<p->n; i++){
185077  char c = (char)p->p[i];
185078  if( c<'0' || c>'9' ){
185079  sqlite3Fts5ParseError(
185080  pParse, "expected integer, got \"%.*s\"", p->n, p->p
185081  );
185082  return;
185083  }
185084  nNear = nNear * 10 + (p->p[i] - '0');
185085  }
185086  }else{
185087  nNear = FTS5_DEFAULT_NEARDIST;
185088  }
185089  pNear->nNear = nNear;
185090  }
185091 }
185092 
185093 /*
185094 ** The second argument passed to this function may be NULL, or it may be
185095 ** an existing Fts5Colset object. This function returns a pointer to
185096 ** a new colset object containing the contents of (p) with new value column
185097 ** number iCol appended.
185098 **
185099 ** If an OOM error occurs, store an error code in pParse and return NULL.
185100 ** The old colset object (if any) is not freed in this case.
185101 */
185102 static Fts5Colset *fts5ParseColset(
185103  Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
185104  Fts5Colset *p, /* Existing colset object */
185105  int iCol /* New column to add to colset object */
185106 ){
185107  int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
185108  Fts5Colset *pNew; /* New colset object to return */
185109 
185110  assert( pParse->rc==SQLITE_OK );
185111  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
185112 
185113  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
185114  if( pNew==0 ){
185115  pParse->rc = SQLITE_NOMEM;
185116  }else{
185117  int *aiCol = pNew->aiCol;
185118  int i, j;
185119  for(i=0; i<nCol; i++){
185120  if( aiCol[i]==iCol ) return pNew;
185121  if( aiCol[i]>iCol ) break;
185122  }
185123  for(j=nCol; j>i; j--){
185124  aiCol[j] = aiCol[j-1];
185125  }
185126  aiCol[i] = iCol;
185127  pNew->nCol = nCol+1;
185128 
185129 #ifndef NDEBUG
185130  /* Check that the array is in order and contains no duplicate entries. */
185131  for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
185132 #endif
185133  }
185134 
185135  return pNew;
185136 }
185137 
185138 /*
185139 ** Allocate and return an Fts5Colset object specifying the inverse of
185140 ** the colset passed as the second argument. Free the colset passed
185141 ** as the second argument before returning.
185142 */
185143 static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
185144  Fts5Colset *pRet;
185145  int nCol = pParse->pConfig->nCol;
185146 
185147  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
185148  sizeof(Fts5Colset) + sizeof(int)*nCol
185149  );
185150  if( pRet ){
185151  int i;
185152  int iOld = 0;
185153  for(i=0; i<nCol; i++){
185154  if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
185155  pRet->aiCol[pRet->nCol++] = i;
185156  }else{
185157  iOld++;
185158  }
185159  }
185160  }
185161 
185162  sqlite3_free(p);
185163  return pRet;
185164 }
185165 
185166 static Fts5Colset *sqlite3Fts5ParseColset(
185167  Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
185168  Fts5Colset *pColset, /* Existing colset object */
185169  Fts5Token *p
185170 ){
185171  Fts5Colset *pRet = 0;
185172  int iCol;
185173  char *z; /* Dequoted copy of token p */
185174 
185175  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
185176  if( pParse->rc==SQLITE_OK ){
185177  Fts5Config *pConfig = pParse->pConfig;
185178  sqlite3Fts5Dequote(z);
185179  for(iCol=0; iCol<pConfig->nCol; iCol++){
185180  if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
185181  }
185182  if( iCol==pConfig->nCol ){
185183  sqlite3Fts5ParseError(pParse, "no such column: %s", z);
185184  }else{
185185  pRet = fts5ParseColset(pParse, pColset, iCol);
185186  }
185187  sqlite3_free(z);
185188  }
185189 
185190  if( pRet==0 ){
185191  assert( pParse->rc!=SQLITE_OK );
185192  sqlite3_free(pColset);
185193  }
185194 
185195  return pRet;
185196 }
185197 
185198 static void sqlite3Fts5ParseSetColset(
185199  Fts5Parse *pParse,
185200  Fts5ExprNearset *pNear,
185201  Fts5Colset *pColset
185202 ){
185203  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
185204  pParse->rc = SQLITE_ERROR;
185205  pParse->zErr = sqlite3_mprintf(
185206  "fts5: column queries are not supported (detail=none)"
185207  );
185208  sqlite3_free(pColset);
185209  return;
185210  }
185211 
185212  if( pNear ){
185213  pNear->pColset = pColset;
185214  }else{
185215  sqlite3_free(pColset);
185216  }
185217 }
185218 
185219 static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
185220  switch( pNode->eType ){
185221  case FTS5_STRING: {
185222  Fts5ExprNearset *pNear = pNode->pNear;
185223  if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
185224  && pNear->apPhrase[0]->aTerm[0].pSynonym==0
185225  ){
185226  pNode->eType = FTS5_TERM;
185227  pNode->xNext = fts5ExprNodeNext_TERM;
185228  }else{
185229  pNode->xNext = fts5ExprNodeNext_STRING;
185230  }
185231  break;
185232  };
185233 
185234  case FTS5_OR: {
185235  pNode->xNext = fts5ExprNodeNext_OR;
185236  break;
185237  };
185238 
185239  case FTS5_AND: {
185240  pNode->xNext = fts5ExprNodeNext_AND;
185241  break;
185242  };
185243 
185244  default: assert( pNode->eType==FTS5_NOT ); {
185245  pNode->xNext = fts5ExprNodeNext_NOT;
185246  break;
185247  };
185248  }
185249 }
185250 
185251 static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
185252  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
185253  int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
185254  memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
185255  p->nChild += pSub->nChild;
185256  sqlite3_free(pSub);
185257  }else{
185258  p->apChild[p->nChild++] = pSub;
185259  }
185260 }
185261 
185262 /*
185263 ** Allocate and return a new expression object. If anything goes wrong (i.e.
185264 ** OOM error), leave an error code in pParse and return NULL.
185265 */
185266 static Fts5ExprNode *sqlite3Fts5ParseNode(
185267  Fts5Parse *pParse, /* Parse context */
185268  int eType, /* FTS5_STRING, AND, OR or NOT */
185269  Fts5ExprNode *pLeft, /* Left hand child expression */
185270  Fts5ExprNode *pRight, /* Right hand child expression */
185271  Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
185272 ){
185273  Fts5ExprNode *pRet = 0;
185274 
185275  if( pParse->rc==SQLITE_OK ){
185276  int nChild = 0; /* Number of children of returned node */
185277  int nByte; /* Bytes of space to allocate for this node */
185278 
185279  assert( (eType!=FTS5_STRING && !pNear)
185280  || (eType==FTS5_STRING && !pLeft && !pRight)
185281  );
185282  if( eType==FTS5_STRING && pNear==0 ) return 0;
185283  if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
185284  if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
185285 
185286  if( eType==FTS5_NOT ){
185287  nChild = 2;
185288  }else if( eType==FTS5_AND || eType==FTS5_OR ){
185289  nChild = 2;
185290  if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
185291  if( pRight->eType==eType ) nChild += pRight->nChild-1;
185292  }
185293 
185294  nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
185295  pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
185296 
185297  if( pRet ){
185298  pRet->eType = eType;
185299  pRet->pNear = pNear;
185300  fts5ExprAssignXNext(pRet);
185301  if( eType==FTS5_STRING ){
185302  int iPhrase;
185303  for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
185304  pNear->apPhrase[iPhrase]->pNode = pRet;
185305  if( pNear->apPhrase[iPhrase]->nTerm==0 ){
185306  pRet->xNext = 0;
185307  pRet->eType = FTS5_EOF;
185308  }
185309  }
185310 
185311  if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
185312  && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
185313  ){
185314  assert( pParse->rc==SQLITE_OK );
185315  pParse->rc = SQLITE_ERROR;
185316  assert( pParse->zErr==0 );
185317  pParse->zErr = sqlite3_mprintf(
185318  "fts5: %s queries are not supported (detail!=full)",
185319  pNear->nPhrase==1 ? "phrase": "NEAR"
185320  );
185321  sqlite3_free(pRet);
185322  pRet = 0;
185323  }
185324 
185325  }else{
185326  fts5ExprAddChildren(pRet, pLeft);
185327  fts5ExprAddChildren(pRet, pRight);
185328  }
185329  }
185330  }
185331 
185332  if( pRet==0 ){
185333  assert( pParse->rc!=SQLITE_OK );
185334  sqlite3Fts5ParseNodeFree(pLeft);
185335  sqlite3Fts5ParseNodeFree(pRight);
185336  sqlite3Fts5ParseNearsetFree(pNear);
185337  }
185338  return pRet;
185339 }
185340 
185341 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
185342  Fts5Parse *pParse, /* Parse context */
185343  Fts5ExprNode *pLeft, /* Left hand child expression */
185344  Fts5ExprNode *pRight /* Right hand child expression */
185345 ){
185346  Fts5ExprNode *pRet = 0;
185347  Fts5ExprNode *pPrev;
185348 
185349  if( pParse->rc ){
185350  sqlite3Fts5ParseNodeFree(pLeft);
185351  sqlite3Fts5ParseNodeFree(pRight);
185352  }else{
185353 
185354  assert( pLeft->eType==FTS5_STRING
185355  || pLeft->eType==FTS5_TERM
185356  || pLeft->eType==FTS5_EOF
185357  || pLeft->eType==FTS5_AND
185358  );
185359  assert( pRight->eType==FTS5_STRING
185360  || pRight->eType==FTS5_TERM
185361  || pRight->eType==FTS5_EOF
185362  );
185363 
185364  if( pLeft->eType==FTS5_AND ){
185365  pPrev = pLeft->apChild[pLeft->nChild-1];
185366  }else{
185367  pPrev = pLeft;
185368  }
185369  assert( pPrev->eType==FTS5_STRING
185370  || pPrev->eType==FTS5_TERM
185371  || pPrev->eType==FTS5_EOF
185372  );
185373 
185374  if( pRight->eType==FTS5_EOF ){
185375  assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
185376  sqlite3Fts5ParseNodeFree(pRight);
185377  pRet = pLeft;
185378  pParse->nPhrase--;
185379  }
185380  else if( pPrev->eType==FTS5_EOF ){
185381  Fts5ExprPhrase **ap;
185382 
185383  if( pPrev==pLeft ){
185384  pRet = pRight;
185385  }else{
185386  pLeft->apChild[pLeft->nChild-1] = pRight;
185387  pRet = pLeft;
185388  }
185389 
185390  ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
185391  assert( ap[0]==pPrev->pNear->apPhrase[0] );
185392  memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
185393  pParse->nPhrase--;
185394 
185395  sqlite3Fts5ParseNodeFree(pPrev);
185396  }
185397  else{
185398  pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
185399  }
185400  }
185401 
185402  return pRet;
185403 }
185404 
185405 static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
185406  int nByte = 0;
185407  Fts5ExprTerm *p;
185408  char *zQuoted;
185409 
185410  /* Determine the maximum amount of space required. */
185411  for(p=pTerm; p; p=p->pSynonym){
185412  nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
185413  }
185414  zQuoted = sqlite3_malloc(nByte);
185415 
185416  if( zQuoted ){
185417  int i = 0;
185418  for(p=pTerm; p; p=p->pSynonym){
185419  char *zIn = p->zTerm;
185420  zQuoted[i++] = '"';
185421  while( *zIn ){
185422  if( *zIn=='"' ) zQuoted[i++] = '"';
185423  zQuoted[i++] = *zIn++;
185424  }
185425  zQuoted[i++] = '"';
185426  if( p->pSynonym ) zQuoted[i++] = '|';
185427  }
185428  if( pTerm->bPrefix ){
185429  zQuoted[i++] = ' ';
185430  zQuoted[i++] = '*';
185431  }
185432  zQuoted[i++] = '\0';
185433  }
185434  return zQuoted;
185435 }
185436 
185437 static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
185438  char *zNew;
185439  va_list ap;
185440  va_start(ap, zFmt);
185441  zNew = sqlite3_vmprintf(zFmt, ap);
185442  va_end(ap);
185443  if( zApp && zNew ){
185444  char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
185445  sqlite3_free(zNew);
185446  zNew = zNew2;
185447  }
185448  sqlite3_free(zApp);
185449  return zNew;
185450 }
185451 
185452 /*
185453 ** Compose a tcl-readable representation of expression pExpr. Return a
185454 ** pointer to a buffer containing that representation. It is the
185455 ** responsibility of the caller to at some point free the buffer using
185456 ** sqlite3_free().
185457 */
185458 static char *fts5ExprPrintTcl(
185459  Fts5Config *pConfig,
185460  const char *zNearsetCmd,
185461  Fts5ExprNode *pExpr
185462 ){
185463  char *zRet = 0;
185464  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
185465  Fts5ExprNearset *pNear = pExpr->pNear;
185466  int i;
185467  int iTerm;
185468 
185469  zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
185470  if( zRet==0 ) return 0;
185471  if( pNear->pColset ){
185472  int *aiCol = pNear->pColset->aiCol;
185473  int nCol = pNear->pColset->nCol;
185474  if( nCol==1 ){
185475  zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
185476  }else{
185477  zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
185478  for(i=1; i<pNear->pColset->nCol; i++){
185479  zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
185480  }
185481  zRet = fts5PrintfAppend(zRet, "} ");
185482  }
185483  if( zRet==0 ) return 0;
185484  }
185485 
185486  if( pNear->nPhrase>1 ){
185487  zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
185488  if( zRet==0 ) return 0;
185489  }
185490 
185491  zRet = fts5PrintfAppend(zRet, "--");
185492  if( zRet==0 ) return 0;
185493 
185494  for(i=0; i<pNear->nPhrase; i++){
185495  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
185496 
185497  zRet = fts5PrintfAppend(zRet, " {");
185498  for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
185499  char *zTerm = pPhrase->aTerm[iTerm].zTerm;
185500  zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
185501  if( pPhrase->aTerm[iTerm].bPrefix ){
185502  zRet = fts5PrintfAppend(zRet, "*");
185503  }
185504  }
185505 
185506  if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
185507  if( zRet==0 ) return 0;
185508  }
185509 
185510  }else{
185511  char const *zOp = 0;
185512  int i;
185513  switch( pExpr->eType ){
185514  case FTS5_AND: zOp = "AND"; break;
185515  case FTS5_NOT: zOp = "NOT"; break;
185516  default:
185517  assert( pExpr->eType==FTS5_OR );
185518  zOp = "OR";
185519  break;
185520  }
185521 
185522  zRet = sqlite3_mprintf("%s", zOp);
185523  for(i=0; zRet && i<pExpr->nChild; i++){
185524  char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
185525  if( !z ){
185526  sqlite3_free(zRet);
185527  zRet = 0;
185528  }else{
185529  zRet = fts5PrintfAppend(zRet, " [%z]", z);
185530  }
185531  }
185532  }
185533 
185534  return zRet;
185535 }
185536 
185537 static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
185538  char *zRet = 0;
185539  if( pExpr->eType==0 ){
185540  return sqlite3_mprintf("\"\"");
185541  }else
185542  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
185543  Fts5ExprNearset *pNear = pExpr->pNear;
185544  int i;
185545  int iTerm;
185546 
185547  if( pNear->pColset ){
185548  int iCol = pNear->pColset->aiCol[0];
185549  zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
185550  if( zRet==0 ) return 0;
185551  }
185552 
185553  if( pNear->nPhrase>1 ){
185554  zRet = fts5PrintfAppend(zRet, "NEAR(");
185555  if( zRet==0 ) return 0;
185556  }
185557 
185558  for(i=0; i<pNear->nPhrase; i++){
185559  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
185560  if( i!=0 ){
185561  zRet = fts5PrintfAppend(zRet, " ");
185562  if( zRet==0 ) return 0;
185563  }
185564  for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
185565  char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
185566  if( zTerm ){
185567  zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
185568  sqlite3_free(zTerm);
185569  }
185570  if( zTerm==0 || zRet==0 ){
185571  sqlite3_free(zRet);
185572  return 0;
185573  }
185574  }
185575  }
185576 
185577  if( pNear->nPhrase>1 ){
185578  zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
185579  if( zRet==0 ) return 0;
185580  }
185581 
185582  }else{
185583  char const *zOp = 0;
185584  int i;
185585 
185586  switch( pExpr->eType ){
185587  case FTS5_AND: zOp = " AND "; break;
185588  case FTS5_NOT: zOp = " NOT "; break;
185589  default:
185590  assert( pExpr->eType==FTS5_OR );
185591  zOp = " OR ";
185592  break;
185593  }
185594 
185595  for(i=0; i<pExpr->nChild; i++){
185596  char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
185597  if( z==0 ){
185598  sqlite3_free(zRet);
185599  zRet = 0;
185600  }else{
185601  int e = pExpr->apChild[i]->eType;
185602  int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
185603  zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
185604  (i==0 ? "" : zOp),
185605  (b?"(":""), z, (b?")":"")
185606  );
185607  }
185608  if( zRet==0 ) break;
185609  }
185610  }
185611 
185612  return zRet;
185613 }
185614 
185615 /*
185616 ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
185617 ** and fts5_expr_tcl() (bTcl!=0).
185618 */
185619 static void fts5ExprFunction(
185620  sqlite3_context *pCtx, /* Function call context */
185621  int nArg, /* Number of args */
185622  sqlite3_value **apVal, /* Function arguments */
185623  int bTcl
185624 ){
185625  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
185626  sqlite3 *db = sqlite3_context_db_handle(pCtx);
185627  const char *zExpr = 0;
185628  char *zErr = 0;
185629  Fts5Expr *pExpr = 0;
185630  int rc;
185631  int i;
185632 
185633  const char **azConfig; /* Array of arguments for Fts5Config */
185634  const char *zNearsetCmd = "nearset";
185635  int nConfig; /* Size of azConfig[] */
185636  Fts5Config *pConfig = 0;
185637  int iArg = 1;
185638 
185639  if( nArg<1 ){
185640  zErr = sqlite3_mprintf("wrong number of arguments to function %s",
185641  bTcl ? "fts5_expr_tcl" : "fts5_expr"
185642  );
185643  sqlite3_result_error(pCtx, zErr, -1);
185644  sqlite3_free(zErr);
185645  return;
185646  }
185647 
185648  if( bTcl && nArg>1 ){
185649  zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
185650  iArg = 2;
185651  }
185652 
185653  nConfig = 3 + (nArg-iArg);
185654  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
185655  if( azConfig==0 ){
185657  return;
185658  }
185659  azConfig[0] = 0;
185660  azConfig[1] = "main";
185661  azConfig[2] = "tbl";
185662  for(i=3; iArg<nArg; iArg++){
185663  azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
185664  }
185665 
185666  zExpr = (const char*)sqlite3_value_text(apVal[0]);
185667 
185668  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
185669  if( rc==SQLITE_OK ){
185670  rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
185671  }
185672  if( rc==SQLITE_OK ){
185673  char *zText;
185674  if( pExpr->pRoot->xNext==0 ){
185675  zText = sqlite3_mprintf("");
185676  }else if( bTcl ){
185677  zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
185678  }else{
185679  zText = fts5ExprPrint(pConfig, pExpr->pRoot);
185680  }
185681  if( zText==0 ){
185682  rc = SQLITE_NOMEM;
185683  }else{
185684  sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
185685  sqlite3_free(zText);
185686  }
185687  }
185688 
185689  if( rc!=SQLITE_OK ){
185690  if( zErr ){
185691  sqlite3_result_error(pCtx, zErr, -1);
185692  sqlite3_free(zErr);
185693  }else{
185694  sqlite3_result_error_code(pCtx, rc);
185695  }
185696  }
185697  sqlite3_free((void *)azConfig);
185698  sqlite3Fts5ConfigFree(pConfig);
185699  sqlite3Fts5ExprFree(pExpr);
185700 }
185701 
185702 static void fts5ExprFunctionHr(
185703  sqlite3_context *pCtx, /* Function call context */
185704  int nArg, /* Number of args */
185705  sqlite3_value **apVal /* Function arguments */
185706 ){
185707  fts5ExprFunction(pCtx, nArg, apVal, 0);
185708 }
185709 static void fts5ExprFunctionTcl(
185710  sqlite3_context *pCtx, /* Function call context */
185711  int nArg, /* Number of args */
185712  sqlite3_value **apVal /* Function arguments */
185713 ){
185714  fts5ExprFunction(pCtx, nArg, apVal, 1);
185715 }
185716 
185717 /*
185718 ** The implementation of an SQLite user-defined-function that accepts a
185719 ** single integer as an argument. If the integer is an alpha-numeric
185720 ** unicode code point, 1 is returned. Otherwise 0.
185721 */
185722 static void fts5ExprIsAlnum(
185723  sqlite3_context *pCtx, /* Function call context */
185724  int nArg, /* Number of args */
185725  sqlite3_value **apVal /* Function arguments */
185726 ){
185727  int iCode;
185728  if( nArg!=1 ){
185729  sqlite3_result_error(pCtx,
185730  "wrong number of arguments to function fts5_isalnum", -1
185731  );
185732  return;
185733  }
185734  iCode = sqlite3_value_int(apVal[0]);
185735  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
185736 }
185737 
185738 static void fts5ExprFold(
185739  sqlite3_context *pCtx, /* Function call context */
185740  int nArg, /* Number of args */
185741  sqlite3_value **apVal /* Function arguments */
185742 ){
185743  if( nArg!=1 && nArg!=2 ){
185744  sqlite3_result_error(pCtx,
185745  "wrong number of arguments to function fts5_fold", -1
185746  );
185747  }else{
185748  int iCode;
185749  int bRemoveDiacritics = 0;
185750  iCode = sqlite3_value_int(apVal[0]);
185751  if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
185752  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
185753  }
185754 }
185755 
185756 /*
185757 ** This is called during initialization to register the fts5_expr() scalar
185758 ** UDF with the SQLite handle passed as the only argument.
185759 */
185760 static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
185761  struct Fts5ExprFunc {
185762  const char *z;
185763  void (*x)(sqlite3_context*,int,sqlite3_value**);
185764  } aFunc[] = {
185765  { "fts5_expr", fts5ExprFunctionHr },
185766  { "fts5_expr_tcl", fts5ExprFunctionTcl },
185767  { "fts5_isalnum", fts5ExprIsAlnum },
185768  { "fts5_fold", fts5ExprFold },
185769  };
185770  int i;
185771  int rc = SQLITE_OK;
185772  void *pCtx = (void*)pGlobal;
185773 
185774  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
185775  struct Fts5ExprFunc *p = &aFunc[i];
185776  rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
185777  }
185778 
185779  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
185780 #ifndef NDEBUG
185781  (void)sqlite3Fts5ParserTrace;
185782 #endif
185783 
185784  return rc;
185785 }
185786 
185787 /*
185788 ** Return the number of phrases in expression pExpr.
185789 */
185790 static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
185791  return (pExpr ? pExpr->nPhrase : 0);
185792 }
185793 
185794 /*
185795 ** Return the number of terms in the iPhrase'th phrase in pExpr.
185796 */
185797 static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
185798  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
185799  return pExpr->apExprPhrase[iPhrase]->nTerm;
185800 }
185801 
185802 /*
185803 ** This function is used to access the current position list for phrase
185804 ** iPhrase.
185805 */
185806 static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
185807  int nRet;
185808  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
185809  Fts5ExprNode *pNode = pPhrase->pNode;
185810  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
185811  *pa = pPhrase->poslist.p;
185812  nRet = pPhrase->poslist.n;
185813  }else{
185814  *pa = 0;
185815  nRet = 0;
185816  }
185817  return nRet;
185818 }
185819 
185820 struct Fts5PoslistPopulator {
185821  Fts5PoslistWriter writer;
185822  int bOk; /* True if ok to populate */
185823  int bMiss;
185824 };
185825 
185826 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
185827  Fts5PoslistPopulator *pRet;
185828  pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
185829  if( pRet ){
185830  int i;
185831  memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
185832  for(i=0; i<pExpr->nPhrase; i++){
185833  Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
185834  Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
185835  assert( pExpr->apExprPhrase[i]->nTerm==1 );
185836  if( bLive &&
185837  (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
185838  ){
185839  pRet[i].bMiss = 1;
185840  }else{
185841  pBuf->n = 0;
185842  }
185843  }
185844  }
185845  return pRet;
185846 }
185847 
185848 struct Fts5ExprCtx {
185849  Fts5Expr *pExpr;
185850  Fts5PoslistPopulator *aPopulator;
185851  i64 iOff;
185852 };
185853 typedef struct Fts5ExprCtx Fts5ExprCtx;
185854 
185855 /*
185856 ** TODO: Make this more efficient!
185857 */
185858 static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
185859  int i;
185860  for(i=0; i<pColset->nCol; i++){
185861  if( pColset->aiCol[i]==iCol ) return 1;
185862  }
185863  return 0;
185864 }
185865 
185866 static int fts5ExprPopulatePoslistsCb(
185867  void *pCtx, /* Copy of 2nd argument to xTokenize() */
185868  int tflags, /* Mask of FTS5_TOKEN_* flags */
185869  const char *pToken, /* Pointer to buffer containing token */
185870  int nToken, /* Size of token in bytes */
185871  int iUnused1, /* Byte offset of token within input text */
185872  int iUnused2 /* Byte offset of end of token within input text */
185873 ){
185874  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
185875  Fts5Expr *pExpr = p->pExpr;
185876  int i;
185877 
185878  UNUSED_PARAM2(iUnused1, iUnused2);
185879 
185880  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
185881  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
185882  for(i=0; i<pExpr->nPhrase; i++){
185883  Fts5ExprTerm *pTerm;
185884  if( p->aPopulator[i].bOk==0 ) continue;
185885  for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
185886  int nTerm = (int)strlen(pTerm->zTerm);
185887  if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
185888  && memcmp(pTerm->zTerm, pToken, nTerm)==0
185889  ){
185890  int rc = sqlite3Fts5PoslistWriterAppend(
185891  &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
185892  );
185893  if( rc ) return rc;
185894  break;
185895  }
185896  }
185897  }
185898  return SQLITE_OK;
185899 }
185900 
185901 static int sqlite3Fts5ExprPopulatePoslists(
185902  Fts5Config *pConfig,
185903  Fts5Expr *pExpr,
185904  Fts5PoslistPopulator *aPopulator,
185905  int iCol,
185906  const char *z, int n
185907 ){
185908  int i;
185909  Fts5ExprCtx sCtx;
185910  sCtx.pExpr = pExpr;
185911  sCtx.aPopulator = aPopulator;
185912  sCtx.iOff = (((i64)iCol) << 32) - 1;
185913 
185914  for(i=0; i<pExpr->nPhrase; i++){
185915  Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
185916  Fts5Colset *pColset = pNode->pNear->pColset;
185917  if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
185918  || aPopulator[i].bMiss
185919  ){
185920  aPopulator[i].bOk = 0;
185921  }else{
185922  aPopulator[i].bOk = 1;
185923  }
185924  }
185925 
185926  return sqlite3Fts5Tokenize(pConfig,
185927  FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
185928  );
185929 }
185930 
185931 static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
185932  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
185933  pNode->pNear->apPhrase[0]->poslist.n = 0;
185934  }else{
185935  int i;
185936  for(i=0; i<pNode->nChild; i++){
185937  fts5ExprClearPoslists(pNode->apChild[i]);
185938  }
185939  }
185940 }
185941 
185942 static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
185943  pNode->iRowid = iRowid;
185944  pNode->bEof = 0;
185945  switch( pNode->eType ){
185946  case FTS5_TERM:
185947  case FTS5_STRING:
185948  return (pNode->pNear->apPhrase[0]->poslist.n>0);
185949 
185950  case FTS5_AND: {
185951  int i;
185952  for(i=0; i<pNode->nChild; i++){
185953  if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
185954  fts5ExprClearPoslists(pNode);
185955  return 0;
185956  }
185957  }
185958  break;
185959  }
185960 
185961  case FTS5_OR: {
185962  int i;
185963  int bRet = 0;
185964  for(i=0; i<pNode->nChild; i++){
185965  if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
185966  bRet = 1;
185967  }
185968  }
185969  return bRet;
185970  }
185971 
185972  default: {
185973  assert( pNode->eType==FTS5_NOT );
185974  if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
185975  || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
185976  ){
185977  fts5ExprClearPoslists(pNode);
185978  return 0;
185979  }
185980  break;
185981  }
185982  }
185983  return 1;
185984 }
185985 
185986 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
185987  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
185988 }
185989 
185990 /*
185991 ** This function is only called for detail=columns tables.
185992 */
185993 static int sqlite3Fts5ExprPhraseCollist(
185994  Fts5Expr *pExpr,
185995  int iPhrase,
185996  const u8 **ppCollist,
185997  int *pnCollist
185998 ){
185999  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
186000  Fts5ExprNode *pNode = pPhrase->pNode;
186001  int rc = SQLITE_OK;
186002 
186003  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
186004  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
186005 
186006  if( pNode->bEof==0
186007  && pNode->iRowid==pExpr->pRoot->iRowid
186008  && pPhrase->poslist.n>0
186009  ){
186010  Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
186011  if( pTerm->pSynonym ){
186012  Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
186013  rc = fts5ExprSynonymList(
186014  pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
186015  );
186016  }else{
186017  *ppCollist = pPhrase->aTerm[0].pIter->pData;
186018  *pnCollist = pPhrase->aTerm[0].pIter->nData;
186019  }
186020  }else{
186021  *ppCollist = 0;
186022  *pnCollist = 0;
186023  }
186024 
186025  return rc;
186026 }
186027 
186028 
186029 /*
186030 ** 2014 August 11
186031 **
186032 ** The author disclaims copyright to this source code. In place of
186033 ** a legal notice, here is a blessing:
186034 **
186035 ** May you do good and not evil.
186036 ** May you find forgiveness for yourself and forgive others.
186037 ** May you share freely, never taking more than you give.
186038 **
186039 ******************************************************************************
186040 **
186041 */
186042 
186043 
186044 
186045 /* #include "fts5Int.h" */
186046 
186047 typedef struct Fts5HashEntry Fts5HashEntry;
186048 
186049 /*
186050 ** This file contains the implementation of an in-memory hash table used
186051 ** to accumuluate "term -> doclist" content before it is flused to a level-0
186052 ** segment.
186053 */
186054 
186055 
186056 struct Fts5Hash {
186057  int eDetail; /* Copy of Fts5Config.eDetail */
186058  int *pnByte; /* Pointer to bytes counter */
186059  int nEntry; /* Number of entries currently in hash */
186060  int nSlot; /* Size of aSlot[] array */
186061  Fts5HashEntry *pScan; /* Current ordered scan item */
186062  Fts5HashEntry **aSlot; /* Array of hash slots */
186063 };
186064 
186065 /*
186066 ** Each entry in the hash table is represented by an object of the
186067 ** following type. Each object, its key (zKey[]) and its current data
186068 ** are stored in a single memory allocation. The position list data
186069 ** immediately follows the key data in memory.
186070 **
186071 ** The data that follows the key is in a similar, but not identical format
186072 ** to the doclist data stored in the database. It is:
186073 **
186074 ** * Rowid, as a varint
186075 ** * Position list, without 0x00 terminator.
186076 ** * Size of previous position list and rowid, as a 4 byte
186077 ** big-endian integer.
186078 **
186079 ** iRowidOff:
186080 ** Offset of last rowid written to data area. Relative to first byte of
186081 ** structure.
186082 **
186083 ** nData:
186084 ** Bytes of data written since iRowidOff.
186085 */
186086 struct Fts5HashEntry {
186087  Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
186088  Fts5HashEntry *pScanNext; /* Next entry in sorted order */
186089 
186090  int nAlloc; /* Total size of allocation */
186091  int iSzPoslist; /* Offset of space for 4-byte poslist size */
186092  int nData; /* Total bytes of data (incl. structure) */
186093  int nKey; /* Length of zKey[] in bytes */
186094  u8 bDel; /* Set delete-flag @ iSzPoslist */
186095  u8 bContent; /* Set content-flag (detail=none mode) */
186096  i16 iCol; /* Column of last value written */
186097  int iPos; /* Position of last value written */
186098  i64 iRowid; /* Rowid of last value written */
186099  char zKey[8]; /* Nul-terminated entry key */
186100 };
186101 
186102 /*
186103 ** Size of Fts5HashEntry without the zKey[] array.
186104 */
186105 #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
186106 
186107 
186108 
186109 /*
186110 ** Allocate a new hash table.
186111 */
186112 static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
186113  int rc = SQLITE_OK;
186114  Fts5Hash *pNew;
186115 
186116  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
186117  if( pNew==0 ){
186118  rc = SQLITE_NOMEM;
186119  }else{
186120  int nByte;
186121  memset(pNew, 0, sizeof(Fts5Hash));
186122  pNew->pnByte = pnByte;
186123  pNew->eDetail = pConfig->eDetail;
186124 
186125  pNew->nSlot = 1024;
186126  nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
186127  pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
186128  if( pNew->aSlot==0 ){
186129  sqlite3_free(pNew);
186130  *ppNew = 0;
186131  rc = SQLITE_NOMEM;
186132  }else{
186133  memset(pNew->aSlot, 0, nByte);
186134  }
186135  }
186136  return rc;
186137 }
186138 
186139 /*
186140 ** Free a hash table object.
186141 */
186142 static void sqlite3Fts5HashFree(Fts5Hash *pHash){
186143  if( pHash ){
186144  sqlite3Fts5HashClear(pHash);
186145  sqlite3_free(pHash->aSlot);
186146  sqlite3_free(pHash);
186147  }
186148 }
186149 
186150 /*
186151 ** Empty (but do not delete) a hash table.
186152 */
186153 static void sqlite3Fts5HashClear(Fts5Hash *pHash){
186154  int i;
186155  for(i=0; i<pHash->nSlot; i++){
186156  Fts5HashEntry *pNext;
186157  Fts5HashEntry *pSlot;
186158  for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
186159  pNext = pSlot->pHashNext;
186160  sqlite3_free(pSlot);
186161  }
186162  }
186163  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
186164  pHash->nEntry = 0;
186165 }
186166 
186167 static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
186168  int i;
186169  unsigned int h = 13;
186170  for(i=n-1; i>=0; i--){
186171  h = (h << 3) ^ h ^ p[i];
186172  }
186173  return (h % nSlot);
186174 }
186175 
186176 static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
186177  int i;
186178  unsigned int h = 13;
186179  for(i=n-1; i>=0; i--){
186180  h = (h << 3) ^ h ^ p[i];
186181  }
186182  h = (h << 3) ^ h ^ b;
186183  return (h % nSlot);
186184 }
186185 
186186 /*
186187 ** Resize the hash table by doubling the number of slots.
186188 */
186189 static int fts5HashResize(Fts5Hash *pHash){
186190  int nNew = pHash->nSlot*2;
186191  int i;
186192  Fts5HashEntry **apNew;
186193  Fts5HashEntry **apOld = pHash->aSlot;
186194 
186195  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
186196  if( !apNew ) return SQLITE_NOMEM;
186197  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
186198 
186199  for(i=0; i<pHash->nSlot; i++){
186200  while( apOld[i] ){
186201  int iHash;
186202  Fts5HashEntry *p = apOld[i];
186203  apOld[i] = p->pHashNext;
186204  iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
186205  p->pHashNext = apNew[iHash];
186206  apNew[iHash] = p;
186207  }
186208  }
186209 
186210  sqlite3_free(apOld);
186211  pHash->nSlot = nNew;
186212  pHash->aSlot = apNew;
186213  return SQLITE_OK;
186214 }
186215 
186216 static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
186217  if( p->iSzPoslist ){
186218  u8 *pPtr = (u8*)p;
186219  if( pHash->eDetail==FTS5_DETAIL_NONE ){
186220  assert( p->nData==p->iSzPoslist );
186221  if( p->bDel ){
186222  pPtr[p->nData++] = 0x00;
186223  if( p->bContent ){
186224  pPtr[p->nData++] = 0x00;
186225  }
186226  }
186227  }else{
186228  int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
186229  int nPos = nSz*2 + p->bDel; /* Value of nPos field */
186230 
186231  assert( p->bDel==0 || p->bDel==1 );
186232  if( nPos<=127 ){
186233  pPtr[p->iSzPoslist] = (u8)nPos;
186234  }else{
186235  int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
186236  memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
186237  sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
186238  p->nData += (nByte-1);
186239  }
186240  }
186241 
186242  p->iSzPoslist = 0;
186243  p->bDel = 0;
186244  p->bContent = 0;
186245  }
186246 }
186247 
186248 /*
186249 ** Add an entry to the in-memory hash table. The key is the concatenation
186250 ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
186251 **
186252 ** (bByte || pToken) -> (iRowid,iCol,iPos)
186253 **
186254 ** Or, if iCol is negative, then the value is a delete marker.
186255 */
186256 static int sqlite3Fts5HashWrite(
186257  Fts5Hash *pHash,
186258  i64 iRowid, /* Rowid for this entry */
186259  int iCol, /* Column token appears in (-ve -> delete) */
186260  int iPos, /* Position of token within column */
186261  char bByte, /* First byte of token */
186262  const char *pToken, int nToken /* Token to add or remove to or from index */
186263 ){
186264  unsigned int iHash;
186265  Fts5HashEntry *p;
186266  u8 *pPtr;
186267  int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
186268  int bNew; /* If non-delete entry should be written */
186269 
186270  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
186271 
186272  /* Attempt to locate an existing hash entry */
186273  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
186274  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
186275  if( p->zKey[0]==bByte
186276  && p->nKey==nToken
186277  && memcmp(&p->zKey[1], pToken, nToken)==0
186278  ){
186279  break;
186280  }
186281  }
186282 
186283  /* If an existing hash entry cannot be found, create a new one. */
186284  if( p==0 ){
186285  /* Figure out how much space to allocate */
186286  int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
186287  if( nByte<128 ) nByte = 128;
186288 
186289  /* Grow the Fts5Hash.aSlot[] array if necessary. */
186290  if( (pHash->nEntry*2)>=pHash->nSlot ){
186291  int rc = fts5HashResize(pHash);
186292  if( rc!=SQLITE_OK ) return rc;
186293  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
186294  }
186295 
186296  /* Allocate new Fts5HashEntry and add it to the hash table. */
186297  p = (Fts5HashEntry*)sqlite3_malloc(nByte);
186298  if( !p ) return SQLITE_NOMEM;
186299  memset(p, 0, FTS5_HASHENTRYSIZE);
186300  p->nAlloc = nByte;
186301  p->zKey[0] = bByte;
186302  memcpy(&p->zKey[1], pToken, nToken);
186303  assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
186304  p->nKey = nToken;
186305  p->zKey[nToken+1] = '\0';
186306  p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
186307  p->pHashNext = pHash->aSlot[iHash];
186308  pHash->aSlot[iHash] = p;
186309  pHash->nEntry++;
186310 
186311  /* Add the first rowid field to the hash-entry */
186312  p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
186313  p->iRowid = iRowid;
186314 
186315  p->iSzPoslist = p->nData;
186316  if( pHash->eDetail!=FTS5_DETAIL_NONE ){
186317  p->nData += 1;
186318  p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
186319  }
186320 
186321  nIncr += p->nData;
186322  }else{
186323 
186324  /* Appending to an existing hash-entry. Check that there is enough
186325  ** space to append the largest possible new entry. Worst case scenario
186326  ** is:
186327  **
186328  ** + 9 bytes for a new rowid,
186329  ** + 4 byte reserved for the "poslist size" varint.
186330  ** + 1 byte for a "new column" byte,
186331  ** + 3 bytes for a new column number (16-bit max) as a varint,
186332  ** + 5 bytes for the new position offset (32-bit max).
186333  */
186334  if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
186335  int nNew = p->nAlloc * 2;
186336  Fts5HashEntry *pNew;
186337  Fts5HashEntry **pp;
186338  pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
186339  if( pNew==0 ) return SQLITE_NOMEM;
186340  pNew->nAlloc = nNew;
186341  for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
186342  *pp = pNew;
186343  p = pNew;
186344  }
186345  nIncr -= p->nData;
186346  }
186347  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
186348 
186349  pPtr = (u8*)p;
186350 
186351  /* If this is a new rowid, append the 4-byte size field for the previous
186352  ** entry, and the new rowid for this entry. */
186353  if( iRowid!=p->iRowid ){
186354  fts5HashAddPoslistSize(pHash, p);
186355  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
186356  p->iRowid = iRowid;
186357  bNew = 1;
186358  p->iSzPoslist = p->nData;
186359  if( pHash->eDetail!=FTS5_DETAIL_NONE ){
186360  p->nData += 1;
186361  p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
186362  p->iPos = 0;
186363  }
186364  }
186365 
186366  if( iCol>=0 ){
186367  if( pHash->eDetail==FTS5_DETAIL_NONE ){
186368  p->bContent = 1;
186369  }else{
186370  /* Append a new column value, if necessary */
186371  assert( iCol>=p->iCol );
186372  if( iCol!=p->iCol ){
186373  if( pHash->eDetail==FTS5_DETAIL_FULL ){
186374  pPtr[p->nData++] = 0x01;
186375  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
186376  p->iCol = (i16)iCol;
186377  p->iPos = 0;
186378  }else{
186379  bNew = 1;
186380  p->iCol = (i16)(iPos = iCol);
186381  }
186382  }
186383 
186384  /* Append the new position offset, if necessary */
186385  if( bNew ){
186386  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
186387  p->iPos = iPos;
186388  }
186389  }
186390  }else{
186391  /* This is a delete. Set the delete flag. */
186392  p->bDel = 1;
186393  }
186394 
186395  nIncr += p->nData;
186396  *pHash->pnByte += nIncr;
186397  return SQLITE_OK;
186398 }
186399 
186400 
186401 /*
186402 ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
186403 ** each sorted in key order. This function merges the two lists into a
186404 ** single list and returns a pointer to its first element.
186405 */
186406 static Fts5HashEntry *fts5HashEntryMerge(
186407  Fts5HashEntry *pLeft,
186408  Fts5HashEntry *pRight
186409 ){
186410  Fts5HashEntry *p1 = pLeft;
186411  Fts5HashEntry *p2 = pRight;
186412  Fts5HashEntry *pRet = 0;
186413  Fts5HashEntry **ppOut = &pRet;
186414 
186415  while( p1 || p2 ){
186416  if( p1==0 ){
186417  *ppOut = p2;
186418  p2 = 0;
186419  }else if( p2==0 ){
186420  *ppOut = p1;
186421  p1 = 0;
186422  }else{
186423  int i = 0;
186424  while( p1->zKey[i]==p2->zKey[i] ) i++;
186425 
186426  if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
186427  /* p2 is smaller */
186428  *ppOut = p2;
186429  ppOut = &p2->pScanNext;
186430  p2 = p2->pScanNext;
186431  }else{
186432  /* p1 is smaller */
186433  *ppOut = p1;
186434  ppOut = &p1->pScanNext;
186435  p1 = p1->pScanNext;
186436  }
186437  *ppOut = 0;
186438  }
186439  }
186440 
186441  return pRet;
186442 }
186443 
186444 /*
186445 ** Extract all tokens from hash table iHash and link them into a list
186446 ** in sorted order. The hash table is cleared before returning. It is
186447 ** the responsibility of the caller to free the elements of the returned
186448 ** list.
186449 */
186450 static int fts5HashEntrySort(
186451  Fts5Hash *pHash,
186452  const char *pTerm, int nTerm, /* Query prefix, if any */
186453  Fts5HashEntry **ppSorted
186454 ){
186455  const int nMergeSlot = 32;
186456  Fts5HashEntry **ap;
186457  Fts5HashEntry *pList;
186458  int iSlot;
186459  int i;
186460 
186461  *ppSorted = 0;
186462  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
186463  if( !ap ) return SQLITE_NOMEM;
186464  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
186465 
186466  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
186467  Fts5HashEntry *pIter;
186468  for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
186469  if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
186470  Fts5HashEntry *pEntry = pIter;
186471  pEntry->pScanNext = 0;
186472  for(i=0; ap[i]; i++){
186473  pEntry = fts5HashEntryMerge(pEntry, ap[i]);
186474  ap[i] = 0;
186475  }
186476  ap[i] = pEntry;
186477  }
186478  }
186479  }
186480 
186481  pList = 0;
186482  for(i=0; i<nMergeSlot; i++){
186483  pList = fts5HashEntryMerge(pList, ap[i]);
186484  }
186485 
186486  pHash->nEntry = 0;
186487  sqlite3_free(ap);
186488  *ppSorted = pList;
186489  return SQLITE_OK;
186490 }
186491 
186492 /*
186493 ** Query the hash table for a doclist associated with term pTerm/nTerm.
186494 */
186495 static int sqlite3Fts5HashQuery(
186496  Fts5Hash *pHash, /* Hash table to query */
186497  const char *pTerm, int nTerm, /* Query term */
186498  const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
186499  int *pnDoclist /* OUT: Size of doclist in bytes */
186500 ){
186501  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
186502  Fts5HashEntry *p;
186503 
186504  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
186505  if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
186506  }
186507 
186508  if( p ){
186509  fts5HashAddPoslistSize(pHash, p);
186510  *ppDoclist = (const u8*)&p->zKey[nTerm+1];
186511  *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
186512  }else{
186513  *ppDoclist = 0;
186514  *pnDoclist = 0;
186515  }
186516 
186517  return SQLITE_OK;
186518 }
186519 
186520 static int sqlite3Fts5HashScanInit(
186521  Fts5Hash *p, /* Hash table to query */
186522  const char *pTerm, int nTerm /* Query prefix */
186523 ){
186524  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
186525 }
186526 
186527 static void sqlite3Fts5HashScanNext(Fts5Hash *p){
186528  assert( !sqlite3Fts5HashScanEof(p) );
186529  p->pScan = p->pScan->pScanNext;
186530 }
186531 
186532 static int sqlite3Fts5HashScanEof(Fts5Hash *p){
186533  return (p->pScan==0);
186534 }
186535 
186536 static void sqlite3Fts5HashScanEntry(
186537  Fts5Hash *pHash,
186538  const char **pzTerm, /* OUT: term (nul-terminated) */
186539  const u8 **ppDoclist, /* OUT: pointer to doclist */
186540  int *pnDoclist /* OUT: size of doclist in bytes */
186541 ){
186542  Fts5HashEntry *p;
186543  if( (p = pHash->pScan) ){
186544  int nTerm = (int)strlen(p->zKey);
186545  fts5HashAddPoslistSize(pHash, p);
186546  *pzTerm = p->zKey;
186547  *ppDoclist = (const u8*)&p->zKey[nTerm+1];
186548  *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
186549  }else{
186550  *pzTerm = 0;
186551  *ppDoclist = 0;
186552  *pnDoclist = 0;
186553  }
186554 }
186555 
186556 
186557 /*
186558 ** 2014 May 31
186559 **
186560 ** The author disclaims copyright to this source code. In place of
186561 ** a legal notice, here is a blessing:
186562 **
186563 ** May you do good and not evil.
186564 ** May you find forgiveness for yourself and forgive others.
186565 ** May you share freely, never taking more than you give.
186566 **
186567 ******************************************************************************
186568 **
186569 ** Low level access to the FTS index stored in the database file. The
186570 ** routines in this file file implement all read and write access to the
186571 ** %_data table. Other parts of the system access this functionality via
186572 ** the interface defined in fts5Int.h.
186573 */
186574 
186575 
186576 /* #include "fts5Int.h" */
186577 
186578 /*
186579 ** Overview:
186580 **
186581 ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
186582 ** As well as the main term index, there may be up to 31 prefix indexes.
186583 ** The format is similar to FTS3/4, except that:
186584 **
186585 ** * all segment b-tree leaf data is stored in fixed size page records
186586 ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
186587 ** taken to ensure it is possible to iterate in either direction through
186588 ** the entries in a doclist, or to seek to a specific entry within a
186589 ** doclist, without loading it into memory.
186590 **
186591 ** * large doclists that span many pages have associated "doclist index"
186592 ** records that contain a copy of the first rowid on each page spanned by
186593 ** the doclist. This is used to speed up seek operations, and merges of
186594 ** large doclists with very small doclists.
186595 **
186596 ** * extra fields in the "structure record" record the state of ongoing
186597 ** incremental merge operations.
186598 **
186599 */
186600 
186601 
186602 #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
186603 #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
186604 
186605 #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
186606 
186607 #define FTS5_MAIN_PREFIX '0'
186608 
186609 #if FTS5_MAX_PREFIX_INDEXES > 31
186610 # error "FTS5_MAX_PREFIX_INDEXES is too large"
186611 #endif
186612 
186613 /*
186614 ** Details:
186615 **
186616 ** The %_data table managed by this module,
186617 **
186618 ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
186619 **
186620 ** , contains the following 5 types of records. See the comments surrounding
186621 ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
186622 ** assigned to each fo them.
186623 **
186624 ** 1. Structure Records:
186625 **
186626 ** The set of segments that make up an index - the index structure - are
186627 ** recorded in a single record within the %_data table. The record consists
186628 ** of a single 32-bit configuration cookie value followed by a list of
186629 ** SQLite varints. If the FTS table features more than one index (because
186630 ** there are one or more prefix indexes), it is guaranteed that all share
186631 ** the same cookie value.
186632 **
186633 ** Immediately following the configuration cookie, the record begins with
186634 ** three varints:
186635 **
186636 ** + number of levels,
186637 ** + total number of segments on all levels,
186638 ** + value of write counter.
186639 **
186640 ** Then, for each level from 0 to nMax:
186641 **
186642 ** + number of input segments in ongoing merge.
186643 ** + total number of segments in level.
186644 ** + for each segment from oldest to newest:
186645 ** + segment id (always > 0)
186646 ** + first leaf page number (often 1, always greater than 0)
186647 ** + final leaf page number
186648 **
186649 ** 2. The Averages Record:
186650 **
186651 ** A single record within the %_data table. The data is a list of varints.
186652 ** The first value is the number of rows in the index. Then, for each column
186653 ** from left to right, the total number of tokens in the column for all
186654 ** rows of the table.
186655 **
186656 ** 3. Segment leaves:
186657 **
186658 ** TERM/DOCLIST FORMAT:
186659 **
186660 ** Most of each segment leaf is taken up by term/doclist data. The
186661 ** general format of term/doclist, starting with the first term
186662 ** on the leaf page, is:
186663 **
186664 ** varint : size of first term
186665 ** blob: first term data
186666 ** doclist: first doclist
186667 ** zero-or-more {
186668 ** varint: number of bytes in common with previous term
186669 ** varint: number of bytes of new term data (nNew)
186670 ** blob: nNew bytes of new term data
186671 ** doclist: next doclist
186672 ** }
186673 **
186674 ** doclist format:
186675 **
186676 ** varint: first rowid
186677 ** poslist: first poslist
186678 ** zero-or-more {
186679 ** varint: rowid delta (always > 0)
186680 ** poslist: next poslist
186681 ** }
186682 **
186683 ** poslist format:
186684 **
186685 ** varint: size of poslist in bytes multiplied by 2, not including
186686 ** this field. Plus 1 if this entry carries the "delete" flag.
186687 ** collist: collist for column 0
186688 ** zero-or-more {
186689 ** 0x01 byte
186690 ** varint: column number (I)
186691 ** collist: collist for column I
186692 ** }
186693 **
186694 ** collist format:
186695 **
186696 ** varint: first offset + 2
186697 ** zero-or-more {
186698 ** varint: offset delta + 2
186699 ** }
186700 **
186701 ** PAGE FORMAT
186702 **
186703 ** Each leaf page begins with a 4-byte header containing 2 16-bit
186704 ** unsigned integer fields in big-endian format. They are:
186705 **
186706 ** * The byte offset of the first rowid on the page, if it exists
186707 ** and occurs before the first term (otherwise 0).
186708 **
186709 ** * The byte offset of the start of the page footer. If the page
186710 ** footer is 0 bytes in size, then this field is the same as the
186711 ** size of the leaf page in bytes.
186712 **
186713 ** The page footer consists of a single varint for each term located
186714 ** on the page. Each varint is the byte offset of the current term
186715 ** within the page, delta-compressed against the previous value. In
186716 ** other words, the first varint in the footer is the byte offset of
186717 ** the first term, the second is the byte offset of the second less that
186718 ** of the first, and so on.
186719 **
186720 ** The term/doclist format described above is accurate if the entire
186721 ** term/doclist data fits on a single leaf page. If this is not the case,
186722 ** the format is changed in two ways:
186723 **
186724 ** + if the first rowid on a page occurs before the first term, it
186725 ** is stored as a literal value:
186726 **
186727 ** varint: first rowid
186728 **
186729 ** + the first term on each page is stored in the same way as the
186730 ** very first term of the segment:
186731 **
186732 ** varint : size of first term
186733 ** blob: first term data
186734 **
186735 ** 5. Segment doclist indexes:
186736 **
186737 ** Doclist indexes are themselves b-trees, however they usually consist of
186738 ** a single leaf record only. The format of each doclist index leaf page
186739 ** is:
186740 **
186741 ** * Flags byte. Bits are:
186742 ** 0x01: Clear if leaf is also the root page, otherwise set.
186743 **
186744 ** * Page number of fts index leaf page. As a varint.
186745 **
186746 ** * First rowid on page indicated by previous field. As a varint.
186747 **
186748 ** * A list of varints, one for each subsequent termless page. A
186749 ** positive delta if the termless page contains at least one rowid,
186750 ** or an 0x00 byte otherwise.
186751 **
186752 ** Internal doclist index nodes are:
186753 **
186754 ** * Flags byte. Bits are:
186755 ** 0x01: Clear for root page, otherwise set.
186756 **
186757 ** * Page number of first child page. As a varint.
186758 **
186759 ** * Copy of first rowid on page indicated by previous field. As a varint.
186760 **
186761 ** * A list of delta-encoded varints - the first rowid on each subsequent
186762 ** child page.
186763 **
186764 */
186765 
186766 /*
186767 ** Rowids for the averages and structure records in the %_data table.
186768 */
186769 #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
186770 #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
186771 
186772 /*
186773 ** Macros determining the rowids used by segment leaves and dlidx leaves
186774 ** and nodes. All nodes and leaves are stored in the %_data table with large
186775 ** positive rowids.
186776 **
186777 ** Each segment has a unique non-zero 16-bit id.
186778 **
186779 ** The rowid for each segment leaf is found by passing the segment id and
186780 ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
186781 ** sequentially starting from 1.
186782 */
186783 #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
186784 #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
186785 #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
186786 #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
186787 
186788 #define fts5_dri(segid, dlidx, height, pgno) ( \
186789  ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
186790  ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
186791  ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
186792  ((i64)(pgno)) \
186793 )
186794 
186795 #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
186796 #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
186797 
186798 /*
186799 ** Maximum segments permitted in a single index
186800 */
186801 #define FTS5_MAX_SEGMENT 2000
186802 
186803 #ifdef SQLITE_DEBUG
186804 static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
186805 #endif
186806 
186807 
186808 /*
186809 ** Each time a blob is read from the %_data table, it is padded with this
186810 ** many zero bytes. This makes it easier to decode the various record formats
186811 ** without overreading if the records are corrupt.
186812 */
186813 #define FTS5_DATA_ZERO_PADDING 8
186814 #define FTS5_DATA_PADDING 20
186815 
186816 typedef struct Fts5Data Fts5Data;
186817 typedef struct Fts5DlidxIter Fts5DlidxIter;
186818 typedef struct Fts5DlidxLvl Fts5DlidxLvl;
186819 typedef struct Fts5DlidxWriter Fts5DlidxWriter;
186820 typedef struct Fts5Iter Fts5Iter;
186821 typedef struct Fts5PageWriter Fts5PageWriter;
186822 typedef struct Fts5SegIter Fts5SegIter;
186823 typedef struct Fts5DoclistIter Fts5DoclistIter;
186824 typedef struct Fts5SegWriter Fts5SegWriter;
186825 typedef struct Fts5Structure Fts5Structure;
186826 typedef struct Fts5StructureLevel Fts5StructureLevel;
186827 typedef struct Fts5StructureSegment Fts5StructureSegment;
186828 
186829 struct Fts5Data {
186830  u8 *p; /* Pointer to buffer containing record */
186831  int nn; /* Size of record in bytes */
186832  int szLeaf; /* Size of leaf without page-index */
186833 };
186834 
186835 /*
186836 ** One object per %_data table.
186837 */
186838 struct Fts5Index {
186839  Fts5Config *pConfig; /* Virtual table configuration */
186840  char *zDataTbl; /* Name of %_data table */
186841  int nWorkUnit; /* Leaf pages in a "unit" of work */
186842 
186843  /*
186844  ** Variables related to the accumulation of tokens and doclists within the
186845  ** in-memory hash tables before they are flushed to disk.
186846  */
186847  Fts5Hash *pHash; /* Hash table for in-memory data */
186848  int nPendingData; /* Current bytes of pending data */
186849  i64 iWriteRowid; /* Rowid for current doc being written */
186850  int bDelete; /* Current write is a delete */
186851 
186852  /* Error state. */
186853  int rc; /* Current error code */
186854 
186855  /* State used by the fts5DataXXX() functions. */
186856  sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
186857  sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
186858  sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
186859  sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
186860  sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
186861  sqlite3_stmt *pIdxSelect;
186862  int nRead; /* Total number of blocks read */
186863 
186864  sqlite3_stmt *pDataVersion;
186865  i64 iStructVersion; /* data_version when pStruct read */
186866  Fts5Structure *pStruct; /* Current db structure (or NULL) */
186867 };
186868 
186869 struct Fts5DoclistIter {
186870  u8 *aEof; /* Pointer to 1 byte past end of doclist */
186871 
186872  /* Output variables. aPoslist==0 at EOF */
186873  i64 iRowid;
186874  u8 *aPoslist;
186875  int nPoslist;
186876  int nSize;
186877 };
186878 
186879 /*
186880 ** The contents of the "structure" record for each index are represented
186881 ** using an Fts5Structure record in memory. Which uses instances of the
186882 ** other Fts5StructureXXX types as components.
186883 */
186884 struct Fts5StructureSegment {
186885  int iSegid; /* Segment id */
186886  int pgnoFirst; /* First leaf page number in segment */
186887  int pgnoLast; /* Last leaf page number in segment */
186888 };
186889 struct Fts5StructureLevel {
186890  int nMerge; /* Number of segments in incr-merge */
186891  int nSeg; /* Total number of segments on level */
186892  Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
186893 };
186894 struct Fts5Structure {
186895  int nRef; /* Object reference count */
186896  u64 nWriteCounter; /* Total leaves written to level 0 */
186897  int nSegment; /* Total segments in this structure */
186898  int nLevel; /* Number of levels in this index */
186899  Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
186900 };
186901 
186902 /*
186903 ** An object of type Fts5SegWriter is used to write to segments.
186904 */
186905 struct Fts5PageWriter {
186906  int pgno; /* Page number for this page */
186907  int iPrevPgidx; /* Previous value written into pgidx */
186908  Fts5Buffer buf; /* Buffer containing leaf data */
186909  Fts5Buffer pgidx; /* Buffer containing page-index */
186910  Fts5Buffer term; /* Buffer containing previous term on page */
186911 };
186912 struct Fts5DlidxWriter {
186913  int pgno; /* Page number for this page */
186914  int bPrevValid; /* True if iPrev is valid */
186915  i64 iPrev; /* Previous rowid value written to page */
186916  Fts5Buffer buf; /* Buffer containing page data */
186917 };
186918 struct Fts5SegWriter {
186919  int iSegid; /* Segid to write to */
186920  Fts5PageWriter writer; /* PageWriter object */
186921  i64 iPrevRowid; /* Previous rowid written to current leaf */
186922  u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
186923  u8 bFirstRowidInPage; /* True if next rowid is first in page */
186924  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
186925  u8 bFirstTermInPage; /* True if next term will be first in leaf */
186926  int nLeafWritten; /* Number of leaf pages written */
186927  int nEmpty; /* Number of contiguous term-less nodes */
186928 
186929  int nDlidx; /* Allocated size of aDlidx[] array */
186930  Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
186931 
186932  /* Values to insert into the %_idx table */
186933  Fts5Buffer btterm; /* Next term to insert into %_idx table */
186934  int iBtPage; /* Page number corresponding to btterm */
186935 };
186936 
186937 typedef struct Fts5CResult Fts5CResult;
186938 struct Fts5CResult {
186939  u16 iFirst; /* aSeg[] index of firstest iterator */
186940  u8 bTermEq; /* True if the terms are equal */
186941 };
186942 
186943 /*
186944 ** Object for iterating through a single segment, visiting each term/rowid
186945 ** pair in the segment.
186946 **
186947 ** pSeg:
186948 ** The segment to iterate through.
186949 **
186950 ** iLeafPgno:
186951 ** Current leaf page number within segment.
186952 **
186953 ** iLeafOffset:
186954 ** Byte offset within the current leaf that is the first byte of the
186955 ** position list data (one byte passed the position-list size field).
186956 ** rowid field of the current entry. Usually this is the size field of the
186957 ** position list data. The exception is if the rowid for the current entry
186958 ** is the last thing on the leaf page.
186959 **
186960 ** pLeaf:
186961 ** Buffer containing current leaf page data. Set to NULL at EOF.
186962 **
186963 ** iTermLeafPgno, iTermLeafOffset:
186964 ** Leaf page number containing the last term read from the segment. And
186965 ** the offset immediately following the term data.
186966 **
186967 ** flags:
186968 ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
186969 **
186970 ** FTS5_SEGITER_ONETERM:
186971 ** If set, set the iterator to point to EOF after the current doclist
186972 ** has been exhausted. Do not proceed to the next term in the segment.
186973 **
186974 ** FTS5_SEGITER_REVERSE:
186975 ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
186976 ** it is set, iterate through rowid in descending order instead of the
186977 ** default ascending order.
186978 **
186979 ** iRowidOffset/nRowidOffset/aRowidOffset:
186980 ** These are used if the FTS5_SEGITER_REVERSE flag is set.
186981 **
186982 ** For each rowid on the page corresponding to the current term, the
186983 ** corresponding aRowidOffset[] entry is set to the byte offset of the
186984 ** start of the "position-list-size" field within the page.
186985 **
186986 ** iTermIdx:
186987 ** Index of current term on iTermLeafPgno.
186988 */
186989 struct Fts5SegIter {
186990  Fts5StructureSegment *pSeg; /* Segment to iterate through */
186991  int flags; /* Mask of configuration flags */
186992  int iLeafPgno; /* Current leaf page number */
186993  Fts5Data *pLeaf; /* Current leaf data */
186994  Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
186995  int iLeafOffset; /* Byte offset within current leaf */
186996 
186997  /* Next method */
186998  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
186999 
187000  /* The page and offset from which the current term was read. The offset
187001  ** is the offset of the first rowid in the current doclist. */
187002  int iTermLeafPgno;
187003  int iTermLeafOffset;
187004 
187005  int iPgidxOff; /* Next offset in pgidx */
187006  int iEndofDoclist;
187007 
187008  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
187009  int iRowidOffset; /* Current entry in aRowidOffset[] */
187010  int nRowidOffset; /* Allocated size of aRowidOffset[] array */
187011  int *aRowidOffset; /* Array of offset to rowid fields */
187012 
187013  Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
187014 
187015  /* Variables populated based on current entry. */
187016  Fts5Buffer term; /* Current term */
187017  i64 iRowid; /* Current rowid */
187018  int nPos; /* Number of bytes in current position list */
187019  u8 bDel; /* True if the delete flag is set */
187020 };
187021 
187022 /*
187023 ** Argument is a pointer to an Fts5Data structure that contains a
187024 ** leaf page.
187025 */
187026 #define ASSERT_SZLEAF_OK(x) assert( \
187027  (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
187028 )
187029 
187030 #define FTS5_SEGITER_ONETERM 0x01
187031 #define FTS5_SEGITER_REVERSE 0x02
187032 
187033 /*
187034 ** Argument is a pointer to an Fts5Data structure that contains a leaf
187035 ** page. This macro evaluates to true if the leaf contains no terms, or
187036 ** false if it contains at least one term.
187037 */
187038 #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
187039 
187040 #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
187041 
187042 #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
187043 
187044 /*
187045 ** Object for iterating through the merged results of one or more segments,
187046 ** visiting each term/rowid pair in the merged data.
187047 **
187048 ** nSeg is always a power of two greater than or equal to the number of
187049 ** segments that this object is merging data from. Both the aSeg[] and
187050 ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
187051 ** with zeroed objects - these are handled as if they were iterators opened
187052 ** on empty segments.
187053 **
187054 ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
187055 ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
187056 ** comparison in this context is the index of the iterator that currently
187057 ** points to the smaller term/rowid combination. Iterators at EOF are
187058 ** considered to be greater than all other iterators.
187059 **
187060 ** aFirst[1] contains the index in aSeg[] of the iterator that points to
187061 ** the smallest key overall. aFirst[0] is unused.
187062 **
187063 ** poslist:
187064 ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
187065 ** There is no way to tell if this is populated or not.
187066 */
187067 struct Fts5Iter {
187068  Fts5IndexIter base; /* Base class containing output vars */
187069 
187070  Fts5Index *pIndex; /* Index that owns this iterator */
187071  Fts5Structure *pStruct; /* Database structure for this iterator */
187072  Fts5Buffer poslist; /* Buffer containing current poslist */
187073  Fts5Colset *pColset; /* Restrict matches to these columns */
187074 
187075  /* Invoked to set output variables. */
187076  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
187077 
187078  int nSeg; /* Size of aSeg[] array */
187079  int bRev; /* True to iterate in reverse order */
187080  u8 bSkipEmpty; /* True to skip deleted entries */
187081 
187082  i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
187083  Fts5CResult *aFirst; /* Current merge state (see above) */
187084  Fts5SegIter aSeg[1]; /* Array of segment iterators */
187085 };
187086 
187087 
187088 /*
187089 ** An instance of the following type is used to iterate through the contents
187090 ** of a doclist-index record.
187091 **
187092 ** pData:
187093 ** Record containing the doclist-index data.
187094 **
187095 ** bEof:
187096 ** Set to true once iterator has reached EOF.
187097 **
187098 ** iOff:
187099 ** Set to the current offset within record pData.
187100 */
187101 struct Fts5DlidxLvl {
187102  Fts5Data *pData; /* Data for current page of this level */
187103  int iOff; /* Current offset into pData */
187104  int bEof; /* At EOF already */
187105  int iFirstOff; /* Used by reverse iterators */
187106 
187107  /* Output variables */
187108  int iLeafPgno; /* Page number of current leaf page */
187109  i64 iRowid; /* First rowid on leaf iLeafPgno */
187110 };
187111 struct Fts5DlidxIter {
187112  int nLvl;
187113  int iSegid;
187114  Fts5DlidxLvl aLvl[1];
187115 };
187116 
187117 static void fts5PutU16(u8 *aOut, u16 iVal){
187118  aOut[0] = (iVal>>8);
187119  aOut[1] = (iVal&0xFF);
187120 }
187121 
187122 static u16 fts5GetU16(const u8 *aIn){
187123  return ((u16)aIn[0] << 8) + aIn[1];
187124 }
187125 
187126 /*
187127 ** Allocate and return a buffer at least nByte bytes in size.
187128 **
187129 ** If an OOM error is encountered, return NULL and set the error code in
187130 ** the Fts5Index handle passed as the first argument.
187131 */
187132 static void *fts5IdxMalloc(Fts5Index *p, int nByte){
187133  return sqlite3Fts5MallocZero(&p->rc, nByte);
187134 }
187135 
187136 /*
187137 ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
187138 **
187139 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
187140 ** +ve if pRight is smaller than pLeft. In other words:
187141 **
187142 ** res = *pLeft - *pRight
187143 */
187144 #ifdef SQLITE_DEBUG
187145 static int fts5BufferCompareBlob(
187146  Fts5Buffer *pLeft, /* Left hand side of comparison */
187147  const u8 *pRight, int nRight /* Right hand side of comparison */
187148 ){
187149  int nCmp = MIN(pLeft->n, nRight);
187150  int res = memcmp(pLeft->p, pRight, nCmp);
187151  return (res==0 ? (pLeft->n - nRight) : res);
187152 }
187153 #endif
187154 
187155 /*
187156 ** Compare the contents of the two buffers using memcmp(). If one buffer
187157 ** is a prefix of the other, it is considered the lesser.
187158 **
187159 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
187160 ** +ve if pRight is smaller than pLeft. In other words:
187161 **
187162 ** res = *pLeft - *pRight
187163 */
187164 static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
187165  int nCmp = MIN(pLeft->n, pRight->n);
187166  int res = memcmp(pLeft->p, pRight->p, nCmp);
187167  return (res==0 ? (pLeft->n - pRight->n) : res);
187168 }
187169 
187170 static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
187171  int ret;
187172  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
187173  return ret;
187174 }
187175 
187176 /*
187177 ** Close the read-only blob handle, if it is open.
187178 */
187179 static void fts5CloseReader(Fts5Index *p){
187180  if( p->pReader ){
187181  sqlite3_blob *pReader = p->pReader;
187182  p->pReader = 0;
187183  sqlite3_blob_close(pReader);
187184  }
187185 }
187186 
187187 
187188 /*
187189 ** Retrieve a record from the %_data table.
187190 **
187191 ** If an error occurs, NULL is returned and an error left in the
187192 ** Fts5Index object.
187193 */
187194 static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
187195  Fts5Data *pRet = 0;
187196  if( p->rc==SQLITE_OK ){
187197  int rc = SQLITE_OK;
187198 
187199  if( p->pReader ){
187200  /* This call may return SQLITE_ABORT if there has been a savepoint
187201  ** rollback since it was last used. In this case a new blob handle
187202  ** is required. */
187203  sqlite3_blob *pBlob = p->pReader;
187204  p->pReader = 0;
187205  rc = sqlite3_blob_reopen(pBlob, iRowid);
187206  assert( p->pReader==0 );
187207  p->pReader = pBlob;
187208  if( rc!=SQLITE_OK ){
187209  fts5CloseReader(p);
187210  }
187211  if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
187212  }
187213 
187214  /* If the blob handle is not open at this point, open it and seek
187215  ** to the requested entry. */
187216  if( p->pReader==0 && rc==SQLITE_OK ){
187217  Fts5Config *pConfig = p->pConfig;
187218  rc = sqlite3_blob_open(pConfig->db,
187219  pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
187220  );
187221  }
187222 
187223  /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
187224  ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
187225  ** All the reasons those functions might return SQLITE_ERROR - missing
187226  ** table, missing row, non-blob/text in block column - indicate
187227  ** backing store corruption. */
187228  if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
187229 
187230  if( rc==SQLITE_OK ){
187231  u8 *aOut = 0; /* Read blob data into this buffer */
187232  int nByte = sqlite3_blob_bytes(p->pReader);
187233  int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
187234  pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
187235  if( pRet ){
187236  pRet->nn = nByte;
187237  aOut = pRet->p = (u8*)&pRet[1];
187238  }else{
187239  rc = SQLITE_NOMEM;
187240  }
187241 
187242  if( rc==SQLITE_OK ){
187243  rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
187244  }
187245  if( rc!=SQLITE_OK ){
187246  sqlite3_free(pRet);
187247  pRet = 0;
187248  }else{
187249  /* TODO1: Fix this */
187250  pRet->szLeaf = fts5GetU16(&pRet->p[2]);
187251  }
187252  }
187253  p->rc = rc;
187254  p->nRead++;
187255  }
187256 
187257  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
187258  return pRet;
187259 }
187260 
187261 /*
187262 ** Release a reference to data record returned by an earlier call to
187263 ** fts5DataRead().
187264 */
187265 static void fts5DataRelease(Fts5Data *pData){
187266  sqlite3_free(pData);
187267 }
187268 
187269 static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
187270  Fts5Data *pRet = fts5DataRead(p, iRowid);
187271  if( pRet ){
187272  if( pRet->szLeaf>pRet->nn ){
187273  p->rc = FTS5_CORRUPT;
187274  fts5DataRelease(pRet);
187275  pRet = 0;
187276  }
187277  }
187278  return pRet;
187279 }
187280 
187281 static int fts5IndexPrepareStmt(
187282  Fts5Index *p,
187283  sqlite3_stmt **ppStmt,
187284  char *zSql
187285 ){
187286  if( p->rc==SQLITE_OK ){
187287  if( zSql ){
187288  p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
187289  }else{
187290  p->rc = SQLITE_NOMEM;
187291  }
187292  }
187293  sqlite3_free(zSql);
187294  return p->rc;
187295 }
187296 
187297 
187298 /*
187299 ** INSERT OR REPLACE a record into the %_data table.
187300 */
187301 static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
187302  if( p->rc!=SQLITE_OK ) return;
187303 
187304  if( p->pWriter==0 ){
187305  Fts5Config *pConfig = p->pConfig;
187306  fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
187307  "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
187308  pConfig->zDb, pConfig->zName
187309  ));
187310  if( p->rc ) return;
187311  }
187312 
187313  sqlite3_bind_int64(p->pWriter, 1, iRowid);
187314  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
187315  sqlite3_step(p->pWriter);
187316  p->rc = sqlite3_reset(p->pWriter);
187317 }
187318 
187319 /*
187320 ** Execute the following SQL:
187321 **
187322 ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
187323 */
187324 static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
187325  if( p->rc!=SQLITE_OK ) return;
187326 
187327  if( p->pDeleter==0 ){
187328  int rc;
187329  Fts5Config *pConfig = p->pConfig;
187330  char *zSql = sqlite3_mprintf(
187331  "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
187332  pConfig->zDb, pConfig->zName
187333  );
187334  if( zSql==0 ){
187335  rc = SQLITE_NOMEM;
187336  }else{
187337  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
187338  sqlite3_free(zSql);
187339  }
187340  if( rc!=SQLITE_OK ){
187341  p->rc = rc;
187342  return;
187343  }
187344  }
187345 
187346  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
187347  sqlite3_bind_int64(p->pDeleter, 2, iLast);
187348  sqlite3_step(p->pDeleter);
187349  p->rc = sqlite3_reset(p->pDeleter);
187350 }
187351 
187352 /*
187353 ** Remove all records associated with segment iSegid.
187354 */
187355 static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
187356  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
187357  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
187358  fts5DataDelete(p, iFirst, iLast);
187359  if( p->pIdxDeleter==0 ){
187360  Fts5Config *pConfig = p->pConfig;
187361  fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
187362  "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
187363  pConfig->zDb, pConfig->zName
187364  ));
187365  }
187366  if( p->rc==SQLITE_OK ){
187367  sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
187368  sqlite3_step(p->pIdxDeleter);
187369  p->rc = sqlite3_reset(p->pIdxDeleter);
187370  }
187371 }
187372 
187373 /*
187374 ** Release a reference to an Fts5Structure object returned by an earlier
187375 ** call to fts5StructureRead() or fts5StructureDecode().
187376 */
187377 static void fts5StructureRelease(Fts5Structure *pStruct){
187378  if( pStruct && 0>=(--pStruct->nRef) ){
187379  int i;
187380  assert( pStruct->nRef==0 );
187381  for(i=0; i<pStruct->nLevel; i++){
187382  sqlite3_free(pStruct->aLevel[i].aSeg);
187383  }
187384  sqlite3_free(pStruct);
187385  }
187386 }
187387 
187388 static void fts5StructureRef(Fts5Structure *pStruct){
187389  pStruct->nRef++;
187390 }
187391 
187392 /*
187393 ** Deserialize and return the structure record currently stored in serialized
187394 ** form within buffer pData/nData.
187395 **
187396 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
187397 ** are over-allocated by one slot. This allows the structure contents
187398 ** to be more easily edited.
187399 **
187400 ** If an error occurs, *ppOut is set to NULL and an SQLite error code
187401 ** returned. Otherwise, *ppOut is set to point to the new object and
187402 ** SQLITE_OK returned.
187403 */
187404 static int fts5StructureDecode(
187405  const u8 *pData, /* Buffer containing serialized structure */
187406  int nData, /* Size of buffer pData in bytes */
187407  int *piCookie, /* Configuration cookie value */
187408  Fts5Structure **ppOut /* OUT: Deserialized object */
187409 ){
187410  int rc = SQLITE_OK;
187411  int i = 0;
187412  int iLvl;
187413  int nLevel = 0;
187414  int nSegment = 0;
187415  int nByte; /* Bytes of space to allocate at pRet */
187416  Fts5Structure *pRet = 0; /* Structure object to return */
187417 
187418  /* Grab the cookie value */
187419  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
187420  i = 4;
187421 
187422  /* Read the total number of levels and segments from the start of the
187423  ** structure record. */
187424  i += fts5GetVarint32(&pData[i], nLevel);
187425  i += fts5GetVarint32(&pData[i], nSegment);
187426  nByte = (
187427  sizeof(Fts5Structure) + /* Main structure */
187428  sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
187429  );
187430  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
187431 
187432  if( pRet ){
187433  pRet->nRef = 1;
187434  pRet->nLevel = nLevel;
187435  pRet->nSegment = nSegment;
187436  i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
187437 
187438  for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
187439  Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
187440  int nTotal = 0;
187441  int iSeg;
187442 
187443  if( i>=nData ){
187444  rc = FTS5_CORRUPT;
187445  }else{
187446  i += fts5GetVarint32(&pData[i], pLvl->nMerge);
187447  i += fts5GetVarint32(&pData[i], nTotal);
187448  assert( nTotal>=pLvl->nMerge );
187449  pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
187450  nTotal * sizeof(Fts5StructureSegment)
187451  );
187452  }
187453 
187454  if( rc==SQLITE_OK ){
187455  pLvl->nSeg = nTotal;
187456  for(iSeg=0; iSeg<nTotal; iSeg++){
187457  if( i>=nData ){
187458  rc = FTS5_CORRUPT;
187459  break;
187460  }
187461  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
187462  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
187463  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
187464  }
187465  }
187466  }
187467  if( rc!=SQLITE_OK ){
187468  fts5StructureRelease(pRet);
187469  pRet = 0;
187470  }
187471  }
187472 
187473  *ppOut = pRet;
187474  return rc;
187475 }
187476 
187477 /*
187478 **
187479 */
187480 static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
187481  if( *pRc==SQLITE_OK ){
187482  Fts5Structure *pStruct = *ppStruct;
187483  int nLevel = pStruct->nLevel;
187484  int nByte = (
187485  sizeof(Fts5Structure) + /* Main structure */
187486  sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
187487  );
187488 
187489  pStruct = sqlite3_realloc(pStruct, nByte);
187490  if( pStruct ){
187491  memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
187492  pStruct->nLevel++;
187493  *ppStruct = pStruct;
187494  }else{
187495  *pRc = SQLITE_NOMEM;
187496  }
187497  }
187498 }
187499 
187500 /*
187501 ** Extend level iLvl so that there is room for at least nExtra more
187502 ** segments.
187503 */
187504 static void fts5StructureExtendLevel(
187505  int *pRc,
187506  Fts5Structure *pStruct,
187507  int iLvl,
187508  int nExtra,
187509  int bInsert
187510 ){
187511  if( *pRc==SQLITE_OK ){
187512  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
187513  Fts5StructureSegment *aNew;
187514  int nByte;
187515 
187516  nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
187517  aNew = sqlite3_realloc(pLvl->aSeg, nByte);
187518  if( aNew ){
187519  if( bInsert==0 ){
187520  memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
187521  }else{
187522  int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
187523  memmove(&aNew[nExtra], aNew, nMove);
187524  memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
187525  }
187526  pLvl->aSeg = aNew;
187527  }else{
187528  *pRc = SQLITE_NOMEM;
187529  }
187530  }
187531 }
187532 
187533 static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
187534  Fts5Structure *pRet = 0;
187535  Fts5Config *pConfig = p->pConfig;
187536  int iCookie; /* Configuration cookie */
187537  Fts5Data *pData;
187538 
187539  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
187540  if( p->rc==SQLITE_OK ){
187541  /* TODO: Do we need this if the leaf-index is appended? Probably... */
187542  memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
187543  p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
187544  if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
187545  p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
187546  }
187547  fts5DataRelease(pData);
187548  if( p->rc!=SQLITE_OK ){
187549  fts5StructureRelease(pRet);
187550  pRet = 0;
187551  }
187552  }
187553 
187554  return pRet;
187555 }
187556 
187557 static i64 fts5IndexDataVersion(Fts5Index *p){
187558  i64 iVersion = 0;
187559 
187560  if( p->rc==SQLITE_OK ){
187561  if( p->pDataVersion==0 ){
187562  p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
187563  sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
187564  );
187565  if( p->rc ) return 0;
187566  }
187567 
187568  if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
187569  iVersion = sqlite3_column_int64(p->pDataVersion, 0);
187570  }
187571  p->rc = sqlite3_reset(p->pDataVersion);
187572  }
187573 
187574  return iVersion;
187575 }
187576 
187577 /*
187578 ** Read, deserialize and return the structure record.
187579 **
187580 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
187581 ** are over-allocated as described for function fts5StructureDecode()
187582 ** above.
187583 **
187584 ** If an error occurs, NULL is returned and an error code left in the
187585 ** Fts5Index handle. If an error has already occurred when this function
187586 ** is called, it is a no-op.
187587 */
187588 static Fts5Structure *fts5StructureRead(Fts5Index *p){
187589 
187590  if( p->pStruct==0 ){
187591  p->iStructVersion = fts5IndexDataVersion(p);
187592  if( p->rc==SQLITE_OK ){
187593  p->pStruct = fts5StructureReadUncached(p);
187594  }
187595  }
187596 
187597 #if 0
187598  else{
187599  Fts5Structure *pTest = fts5StructureReadUncached(p);
187600  if( pTest ){
187601  int i, j;
187602  assert_nc( p->pStruct->nSegment==pTest->nSegment );
187603  assert_nc( p->pStruct->nLevel==pTest->nLevel );
187604  for(i=0; i<pTest->nLevel; i++){
187605  assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
187606  assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
187607  for(j=0; j<pTest->aLevel[i].nSeg; j++){
187608  Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
187609  Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
187610  assert_nc( p1->iSegid==p2->iSegid );
187611  assert_nc( p1->pgnoFirst==p2->pgnoFirst );
187612  assert_nc( p1->pgnoLast==p2->pgnoLast );
187613  }
187614  }
187615  fts5StructureRelease(pTest);
187616  }
187617  }
187618 #endif
187619 
187620  if( p->rc!=SQLITE_OK ) return 0;
187621  assert( p->iStructVersion!=0 );
187622  assert( p->pStruct!=0 );
187623  fts5StructureRef(p->pStruct);
187624  return p->pStruct;
187625 }
187626 
187627 static void fts5StructureInvalidate(Fts5Index *p){
187628  if( p->pStruct ){
187629  fts5StructureRelease(p->pStruct);
187630  p->pStruct = 0;
187631  }
187632 }
187633 
187634 /*
187635 ** Return the total number of segments in index structure pStruct. This
187636 ** function is only ever used as part of assert() conditions.
187637 */
187638 #ifdef SQLITE_DEBUG
187639 static int fts5StructureCountSegments(Fts5Structure *pStruct){
187640  int nSegment = 0; /* Total number of segments */
187641  if( pStruct ){
187642  int iLvl; /* Used to iterate through levels */
187643  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
187644  nSegment += pStruct->aLevel[iLvl].nSeg;
187645  }
187646  }
187647 
187648  return nSegment;
187649 }
187650 #endif
187651 
187652 #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
187653  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
187654  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
187655  (pBuf)->n += nBlob; \
187656 }
187657 
187658 #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
187659  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
187660  assert( (pBuf)->nSpace>=(pBuf)->n ); \
187661 }
187662 
187663 
187664 /*
187665 ** Serialize and store the "structure" record.
187666 **
187667 ** If an error occurs, leave an error code in the Fts5Index object. If an
187668 ** error has already occurred, this function is a no-op.
187669 */
187670 static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
187671  if( p->rc==SQLITE_OK ){
187672  Fts5Buffer buf; /* Buffer to serialize record into */
187673  int iLvl; /* Used to iterate through levels */
187674  int iCookie; /* Cookie value to store */
187675 
187676  assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
187677  memset(&buf, 0, sizeof(Fts5Buffer));
187678 
187679  /* Append the current configuration cookie */
187680  iCookie = p->pConfig->iCookie;
187681  if( iCookie<0 ) iCookie = 0;
187682 
187683  if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
187684  sqlite3Fts5Put32(buf.p, iCookie);
187685  buf.n = 4;
187686  fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
187687  fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
187688  fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
187689  }
187690 
187691  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
187692  int iSeg; /* Used to iterate through segments */
187693  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
187694  fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
187695  fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
187696  assert( pLvl->nMerge<=pLvl->nSeg );
187697 
187698  for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
187699  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
187700  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
187701  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
187702  }
187703  }
187704 
187705  fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
187706  fts5BufferFree(&buf);
187707  }
187708 }
187709 
187710 #if 0
187711 static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
187712 static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
187713  int rc = SQLITE_OK;
187714  Fts5Buffer buf;
187715  memset(&buf, 0, sizeof(buf));
187716  fts5DebugStructure(&rc, &buf, pStruct);
187717  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
187718  fflush(stdout);
187719  fts5BufferFree(&buf);
187720 }
187721 #else
187722 # define fts5PrintStructure(x,y)
187723 #endif
187724 
187725 static int fts5SegmentSize(Fts5StructureSegment *pSeg){
187726  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
187727 }
187728 
187729 /*
187730 ** Return a copy of index structure pStruct. Except, promote as many
187731 ** segments as possible to level iPromote. If an OOM occurs, NULL is
187732 ** returned.
187733 */
187734 static void fts5StructurePromoteTo(
187735  Fts5Index *p,
187736  int iPromote,
187737  int szPromote,
187738  Fts5Structure *pStruct
187739 ){
187740  int il, is;
187741  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
187742 
187743  if( pOut->nMerge==0 ){
187744  for(il=iPromote+1; il<pStruct->nLevel; il++){
187745  Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
187746  if( pLvl->nMerge ) return;
187747  for(is=pLvl->nSeg-1; is>=0; is--){
187748  int sz = fts5SegmentSize(&pLvl->aSeg[is]);
187749  if( sz>szPromote ) return;
187750  fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
187751  if( p->rc ) return;
187752  memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
187753  pOut->nSeg++;
187754  pLvl->nSeg--;
187755  }
187756  }
187757  }
187758 }
187759 
187760 /*
187761 ** A new segment has just been written to level iLvl of index structure
187762 ** pStruct. This function determines if any segments should be promoted
187763 ** as a result. Segments are promoted in two scenarios:
187764 **
187765 ** a) If the segment just written is smaller than one or more segments
187766 ** within the previous populated level, it is promoted to the previous
187767 ** populated level.
187768 **
187769 ** b) If the segment just written is larger than the newest segment on
187770 ** the next populated level, then that segment, and any other adjacent
187771 ** segments that are also smaller than the one just written, are
187772 ** promoted.
187773 **
187774 ** If one or more segments are promoted, the structure object is updated
187775 ** to reflect this.
187776 */
187777 static void fts5StructurePromote(
187778  Fts5Index *p, /* FTS5 backend object */
187779  int iLvl, /* Index level just updated */
187780  Fts5Structure *pStruct /* Index structure */
187781 ){
187782  if( p->rc==SQLITE_OK ){
187783  int iTst;
187784  int iPromote = -1;
187785  int szPromote = 0; /* Promote anything this size or smaller */
187786  Fts5StructureSegment *pSeg; /* Segment just written */
187787  int szSeg; /* Size of segment just written */
187788  int nSeg = pStruct->aLevel[iLvl].nSeg;
187789 
187790  if( nSeg==0 ) return;
187791  pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
187792  szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
187793 
187794  /* Check for condition (a) */
187795  for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
187796  if( iTst>=0 ){
187797  int i;
187798  int szMax = 0;
187799  Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
187800  assert( pTst->nMerge==0 );
187801  for(i=0; i<pTst->nSeg; i++){
187802  int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
187803  if( sz>szMax ) szMax = sz;
187804  }
187805  if( szMax>=szSeg ){
187806  /* Condition (a) is true. Promote the newest segment on level
187807  ** iLvl to level iTst. */
187808  iPromote = iTst;
187809  szPromote = szMax;
187810  }
187811  }
187812 
187813  /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
187814  ** is a no-op if it is not. */
187815  if( iPromote<0 ){
187816  iPromote = iLvl;
187817  szPromote = szSeg;
187818  }
187819  fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
187820  }
187821 }
187822 
187823 
187824 /*
187825 ** Advance the iterator passed as the only argument. If the end of the
187826 ** doclist-index page is reached, return non-zero.
187827 */
187828 static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
187829  Fts5Data *pData = pLvl->pData;
187830 
187831  if( pLvl->iOff==0 ){
187832  assert( pLvl->bEof==0 );
187833  pLvl->iOff = 1;
187834  pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
187835  pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
187836  pLvl->iFirstOff = pLvl->iOff;
187837  }else{
187838  int iOff;
187839  for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
187840  if( pData->p[iOff] ) break;
187841  }
187842 
187843  if( iOff<pData->nn ){
187844  i64 iVal;
187845  pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
187846  iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
187847  pLvl->iRowid += iVal;
187848  pLvl->iOff = iOff;
187849  }else{
187850  pLvl->bEof = 1;
187851  }
187852  }
187853 
187854  return pLvl->bEof;
187855 }
187856 
187857 /*
187858 ** Advance the iterator passed as the only argument.
187859 */
187860 static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
187861  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
187862 
187863  assert( iLvl<pIter->nLvl );
187864  if( fts5DlidxLvlNext(pLvl) ){
187865  if( (iLvl+1) < pIter->nLvl ){
187866  fts5DlidxIterNextR(p, pIter, iLvl+1);
187867  if( pLvl[1].bEof==0 ){
187868  fts5DataRelease(pLvl->pData);
187869  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
187870  pLvl->pData = fts5DataRead(p,
187871  FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
187872  );
187873  if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
187874  }
187875  }
187876  }
187877 
187878  return pIter->aLvl[0].bEof;
187879 }
187880 static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
187881  return fts5DlidxIterNextR(p, pIter, 0);
187882 }
187883 
187884 /*
187885 ** The iterator passed as the first argument has the following fields set
187886 ** as follows. This function sets up the rest of the iterator so that it
187887 ** points to the first rowid in the doclist-index.
187888 **
187889 ** pData:
187890 ** pointer to doclist-index record,
187891 **
187892 ** When this function is called pIter->iLeafPgno is the page number the
187893 ** doclist is associated with (the one featuring the term).
187894 */
187895 static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
187896  int i;
187897  for(i=0; i<pIter->nLvl; i++){
187898  fts5DlidxLvlNext(&pIter->aLvl[i]);
187899  }
187900  return pIter->aLvl[0].bEof;
187901 }
187902 
187903 
187904 static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
187905  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
187906 }
187907 
187908 static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
187909  int i;
187910 
187911  /* Advance each level to the last entry on the last page */
187912  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
187913  Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
187914  while( fts5DlidxLvlNext(pLvl)==0 );
187915  pLvl->bEof = 0;
187916 
187917  if( i>0 ){
187918  Fts5DlidxLvl *pChild = &pLvl[-1];
187919  fts5DataRelease(pChild->pData);
187920  memset(pChild, 0, sizeof(Fts5DlidxLvl));
187921  pChild->pData = fts5DataRead(p,
187922  FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
187923  );
187924  }
187925  }
187926 }
187927 
187928 /*
187929 ** Move the iterator passed as the only argument to the previous entry.
187930 */
187931 static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
187932  int iOff = pLvl->iOff;
187933 
187934  assert( pLvl->bEof==0 );
187935  if( iOff<=pLvl->iFirstOff ){
187936  pLvl->bEof = 1;
187937  }else{
187938  u8 *a = pLvl->pData->p;
187939  i64 iVal;
187940  int iLimit;
187941  int ii;
187942  int nZero = 0;
187943 
187944  /* Currently iOff points to the first byte of a varint. This block
187945  ** decrements iOff until it points to the first byte of the previous
187946  ** varint. Taking care not to read any memory locations that occur
187947  ** before the buffer in memory. */
187948  iLimit = (iOff>9 ? iOff-9 : 0);
187949  for(iOff--; iOff>iLimit; iOff--){
187950  if( (a[iOff-1] & 0x80)==0 ) break;
187951  }
187952 
187953  fts5GetVarint(&a[iOff], (u64*)&iVal);
187954  pLvl->iRowid -= iVal;
187955  pLvl->iLeafPgno--;
187956 
187957  /* Skip backwards past any 0x00 varints. */
187958  for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
187959  nZero++;
187960  }
187961  if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
187962  /* The byte immediately before the last 0x00 byte has the 0x80 bit
187963  ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
187964  ** bytes before a[ii]. */
187965  int bZero = 0; /* True if last 0x00 counts */
187966  if( (ii-8)>=pLvl->iFirstOff ){
187967  int j;
187968  for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
187969  bZero = (j>8);
187970  }
187971  if( bZero==0 ) nZero--;
187972  }
187973  pLvl->iLeafPgno -= nZero;
187974  pLvl->iOff = iOff - nZero;
187975  }
187976 
187977  return pLvl->bEof;
187978 }
187979 
187980 static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
187981  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
187982 
187983  assert( iLvl<pIter->nLvl );
187984  if( fts5DlidxLvlPrev(pLvl) ){
187985  if( (iLvl+1) < pIter->nLvl ){
187986  fts5DlidxIterPrevR(p, pIter, iLvl+1);
187987  if( pLvl[1].bEof==0 ){
187988  fts5DataRelease(pLvl->pData);
187989  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
187990  pLvl->pData = fts5DataRead(p,
187991  FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
187992  );
187993  if( pLvl->pData ){
187994  while( fts5DlidxLvlNext(pLvl)==0 );
187995  pLvl->bEof = 0;
187996  }
187997  }
187998  }
187999  }
188000 
188001  return pIter->aLvl[0].bEof;
188002 }
188003 static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
188004  return fts5DlidxIterPrevR(p, pIter, 0);
188005 }
188006 
188007 /*
188008 ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
188009 */
188010 static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
188011  if( pIter ){
188012  int i;
188013  for(i=0; i<pIter->nLvl; i++){
188014  fts5DataRelease(pIter->aLvl[i].pData);
188015  }
188016  sqlite3_free(pIter);
188017  }
188018 }
188019 
188020 static Fts5DlidxIter *fts5DlidxIterInit(
188021  Fts5Index *p, /* Fts5 Backend to iterate within */
188022  int bRev, /* True for ORDER BY ASC */
188023  int iSegid, /* Segment id */
188024  int iLeafPg /* Leaf page number to load dlidx for */
188025 ){
188026  Fts5DlidxIter *pIter = 0;
188027  int i;
188028  int bDone = 0;
188029 
188030  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
188031  int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
188032  Fts5DlidxIter *pNew;
188033 
188034  pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
188035  if( pNew==0 ){
188036  p->rc = SQLITE_NOMEM;
188037  }else{
188038  i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
188039  Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
188040  pIter = pNew;
188041  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
188042  pLvl->pData = fts5DataRead(p, iRowid);
188043  if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
188044  bDone = 1;
188045  }
188046  pIter->nLvl = i+1;
188047  }
188048  }
188049 
188050  if( p->rc==SQLITE_OK ){
188051  pIter->iSegid = iSegid;
188052  if( bRev==0 ){
188053  fts5DlidxIterFirst(pIter);
188054  }else{
188055  fts5DlidxIterLast(p, pIter);
188056  }
188057  }
188058 
188059  if( p->rc!=SQLITE_OK ){
188060  fts5DlidxIterFree(pIter);
188061  pIter = 0;
188062  }
188063 
188064  return pIter;
188065 }
188066 
188067 static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
188068  return pIter->aLvl[0].iRowid;
188069 }
188070 static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
188071  return pIter->aLvl[0].iLeafPgno;
188072 }
188073 
188074 /*
188075 ** Load the next leaf page into the segment iterator.
188076 */
188077 static void fts5SegIterNextPage(
188078  Fts5Index *p, /* FTS5 backend object */
188079  Fts5SegIter *pIter /* Iterator to advance to next page */
188080 ){
188081  Fts5Data *pLeaf;
188082  Fts5StructureSegment *pSeg = pIter->pSeg;
188083  fts5DataRelease(pIter->pLeaf);
188084  pIter->iLeafPgno++;
188085  if( pIter->pNextLeaf ){
188086  pIter->pLeaf = pIter->pNextLeaf;
188087  pIter->pNextLeaf = 0;
188088  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
188089  pIter->pLeaf = fts5LeafRead(p,
188090  FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
188091  );
188092  }else{
188093  pIter->pLeaf = 0;
188094  }
188095  pLeaf = pIter->pLeaf;
188096 
188097  if( pLeaf ){
188098  pIter->iPgidxOff = pLeaf->szLeaf;
188099  if( fts5LeafIsTermless(pLeaf) ){
188100  pIter->iEndofDoclist = pLeaf->nn+1;
188101  }else{
188102  pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
188103  pIter->iEndofDoclist
188104  );
188105  }
188106  }
188107 }
188108 
188109 /*
188110 ** Argument p points to a buffer containing a varint to be interpreted as a
188111 ** position list size field. Read the varint and return the number of bytes
188112 ** read. Before returning, set *pnSz to the number of bytes in the position
188113 ** list, and *pbDel to true if the delete flag is set, or false otherwise.
188114 */
188115 static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
188116  int nSz;
188117  int n = 0;
188118  fts5FastGetVarint32(p, n, nSz);
188119  assert_nc( nSz>=0 );
188120  *pnSz = nSz/2;
188121  *pbDel = nSz & 0x0001;
188122  return n;
188123 }
188124 
188125 /*
188126 ** Fts5SegIter.iLeafOffset currently points to the first byte of a
188127 ** position-list size field. Read the value of the field and store it
188128 ** in the following variables:
188129 **
188130 ** Fts5SegIter.nPos
188131 ** Fts5SegIter.bDel
188132 **
188133 ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
188134 ** position list content (if any).
188135 */
188136 static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
188137  if( p->rc==SQLITE_OK ){
188138  int iOff = pIter->iLeafOffset; /* Offset to read at */
188139  ASSERT_SZLEAF_OK(pIter->pLeaf);
188140  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
188141  int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
188142  pIter->bDel = 0;
188143  pIter->nPos = 1;
188144  if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
188145  pIter->bDel = 1;
188146  iOff++;
188147  if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
188148  pIter->nPos = 1;
188149  iOff++;
188150  }else{
188151  pIter->nPos = 0;
188152  }
188153  }
188154  }else{
188155  int nSz;
188156  fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
188157  pIter->bDel = (nSz & 0x0001);
188158  pIter->nPos = nSz>>1;
188159  assert_nc( pIter->nPos>=0 );
188160  }
188161  pIter->iLeafOffset = iOff;
188162  }
188163 }
188164 
188165 static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
188166  u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
188167  int iOff = pIter->iLeafOffset;
188168 
188169  ASSERT_SZLEAF_OK(pIter->pLeaf);
188170  if( iOff>=pIter->pLeaf->szLeaf ){
188171  fts5SegIterNextPage(p, pIter);
188172  if( pIter->pLeaf==0 ){
188173  if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
188174  return;
188175  }
188176  iOff = 4;
188177  a = pIter->pLeaf->p;
188178  }
188179  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
188180  pIter->iLeafOffset = iOff;
188181 }
188182 
188183 /*
188184 ** Fts5SegIter.iLeafOffset currently points to the first byte of the
188185 ** "nSuffix" field of a term. Function parameter nKeep contains the value
188186 ** of the "nPrefix" field (if there was one - it is passed 0 if this is
188187 ** the first term in the segment).
188188 **
188189 ** This function populates:
188190 **
188191 ** Fts5SegIter.term
188192 ** Fts5SegIter.rowid
188193 **
188194 ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
188195 ** the first position list. The position list belonging to document
188196 ** (Fts5SegIter.iRowid).
188197 */
188198 static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
188199  u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
188200  int iOff = pIter->iLeafOffset; /* Offset to read at */
188201  int nNew; /* Bytes of new data */
188202 
188203  iOff += fts5GetVarint32(&a[iOff], nNew);
188204  if( iOff+nNew>pIter->pLeaf->nn ){
188205  p->rc = FTS5_CORRUPT;
188206  return;
188207  }
188208  pIter->term.n = nKeep;
188209  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
188210  iOff += nNew;
188211  pIter->iTermLeafOffset = iOff;
188212  pIter->iTermLeafPgno = pIter->iLeafPgno;
188213  pIter->iLeafOffset = iOff;
188214 
188215  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
188216  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
188217  }else{
188218  int nExtra;
188219  pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
188220  pIter->iEndofDoclist += nExtra;
188221  }
188222 
188223  fts5SegIterLoadRowid(p, pIter);
188224 }
188225 
188226 static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
188227 static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
188228 static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
188229 
188230 static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
188231  if( pIter->flags & FTS5_SEGITER_REVERSE ){
188232  pIter->xNext = fts5SegIterNext_Reverse;
188233  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
188234  pIter->xNext = fts5SegIterNext_None;
188235  }else{
188236  pIter->xNext = fts5SegIterNext;
188237  }
188238 }
188239 
188240 /*
188241 ** Initialize the iterator object pIter to iterate through the entries in
188242 ** segment pSeg. The iterator is left pointing to the first entry when
188243 ** this function returns.
188244 **
188245 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
188246 ** an error has already occurred when this function is called, it is a no-op.
188247 */
188248 static void fts5SegIterInit(
188249  Fts5Index *p, /* FTS index object */
188250  Fts5StructureSegment *pSeg, /* Description of segment */
188251  Fts5SegIter *pIter /* Object to populate */
188252 ){
188253  if( pSeg->pgnoFirst==0 ){
188254  /* This happens if the segment is being used as an input to an incremental
188255  ** merge and all data has already been "trimmed". See function
188256  ** fts5TrimSegments() for details. In this case leave the iterator empty.
188257  ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
188258  ** at EOF already. */
188259  assert( pIter->pLeaf==0 );
188260  return;
188261  }
188262 
188263  if( p->rc==SQLITE_OK ){
188264  memset(pIter, 0, sizeof(*pIter));
188265  fts5SegIterSetNext(p, pIter);
188266  pIter->pSeg = pSeg;
188267  pIter->iLeafPgno = pSeg->pgnoFirst-1;
188268  fts5SegIterNextPage(p, pIter);
188269  }
188270 
188271  if( p->rc==SQLITE_OK ){
188272  pIter->iLeafOffset = 4;
188273  assert_nc( pIter->pLeaf->nn>4 );
188274  assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
188275  pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
188276  fts5SegIterLoadTerm(p, pIter, 0);
188277  fts5SegIterLoadNPos(p, pIter);
188278  }
188279 }
188280 
188281 /*
188282 ** This function is only ever called on iterators created by calls to
188283 ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
188284 **
188285 ** The iterator is in an unusual state when this function is called: the
188286 ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
188287 ** the position-list size field for the first relevant rowid on the page.
188288 ** Fts5SegIter.rowid is set, but nPos and bDel are not.
188289 **
188290 ** This function advances the iterator so that it points to the last
188291 ** relevant rowid on the page and, if necessary, initializes the
188292 ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
188293 ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
188294 ** byte of the position list content associated with said rowid.
188295 */
188296 static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
188297  int eDetail = p->pConfig->eDetail;
188298  int n = pIter->pLeaf->szLeaf;
188299  int i = pIter->iLeafOffset;
188300  u8 *a = pIter->pLeaf->p;
188301  int iRowidOffset = 0;
188302 
188303  if( n>pIter->iEndofDoclist ){
188304  n = pIter->iEndofDoclist;
188305  }
188306 
188307  ASSERT_SZLEAF_OK(pIter->pLeaf);
188308  while( 1 ){
188309  i64 iDelta = 0;
188310 
188311  if( eDetail==FTS5_DETAIL_NONE ){
188312  /* todo */
188313  if( i<n && a[i]==0 ){
188314  i++;
188315  if( i<n && a[i]==0 ) i++;
188316  }
188317  }else{
188318  int nPos;
188319  int bDummy;
188320  i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
188321  i += nPos;
188322  }
188323  if( i>=n ) break;
188324  i += fts5GetVarint(&a[i], (u64*)&iDelta);
188325  pIter->iRowid += iDelta;
188326 
188327  /* If necessary, grow the pIter->aRowidOffset[] array. */
188328  if( iRowidOffset>=pIter->nRowidOffset ){
188329  int nNew = pIter->nRowidOffset + 8;
188330  int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
188331  if( aNew==0 ){
188332  p->rc = SQLITE_NOMEM;
188333  break;
188334  }
188335  pIter->aRowidOffset = aNew;
188336  pIter->nRowidOffset = nNew;
188337  }
188338 
188339  pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
188340  pIter->iLeafOffset = i;
188341  }
188342  pIter->iRowidOffset = iRowidOffset;
188343  fts5SegIterLoadNPos(p, pIter);
188344 }
188345 
188346 /*
188347 **
188348 */
188349 static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
188350  assert( pIter->flags & FTS5_SEGITER_REVERSE );
188351  assert( pIter->flags & FTS5_SEGITER_ONETERM );
188352 
188353  fts5DataRelease(pIter->pLeaf);
188354  pIter->pLeaf = 0;
188355  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
188356  Fts5Data *pNew;
188357  pIter->iLeafPgno--;
188358  pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
188359  pIter->pSeg->iSegid, pIter->iLeafPgno
188360  ));
188361  if( pNew ){
188362  /* iTermLeafOffset may be equal to szLeaf if the term is the last
188363  ** thing on the page - i.e. the first rowid is on the following page.
188364  ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
188365  if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
188366  assert( pIter->pLeaf==0 );
188367  if( pIter->iTermLeafOffset<pNew->szLeaf ){
188368  pIter->pLeaf = pNew;
188369  pIter->iLeafOffset = pIter->iTermLeafOffset;
188370  }
188371  }else{
188372  int iRowidOff;
188373  iRowidOff = fts5LeafFirstRowidOff(pNew);
188374  if( iRowidOff ){
188375  pIter->pLeaf = pNew;
188376  pIter->iLeafOffset = iRowidOff;
188377  }
188378  }
188379 
188380  if( pIter->pLeaf ){
188381  u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
188382  pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
188383  break;
188384  }else{
188385  fts5DataRelease(pNew);
188386  }
188387  }
188388  }
188389 
188390  if( pIter->pLeaf ){
188391  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
188392  fts5SegIterReverseInitPage(p, pIter);
188393  }
188394 }
188395 
188396 /*
188397 ** Return true if the iterator passed as the second argument currently
188398 ** points to a delete marker. A delete marker is an entry with a 0 byte
188399 ** position-list.
188400 */
188401 static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
188402  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
188403  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
188404 }
188405 
188406 /*
188407 ** Advance iterator pIter to the next entry.
188408 **
188409 ** This version of fts5SegIterNext() is only used by reverse iterators.
188410 */
188411 static void fts5SegIterNext_Reverse(
188412  Fts5Index *p, /* FTS5 backend object */
188413  Fts5SegIter *pIter, /* Iterator to advance */
188414  int *pbUnused /* Unused */
188415 ){
188416  assert( pIter->flags & FTS5_SEGITER_REVERSE );
188417  assert( pIter->pNextLeaf==0 );
188418  UNUSED_PARAM(pbUnused);
188419 
188420  if( pIter->iRowidOffset>0 ){
188421  u8 *a = pIter->pLeaf->p;
188422  int iOff;
188423  i64 iDelta;
188424 
188425  pIter->iRowidOffset--;
188426  pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
188427  fts5SegIterLoadNPos(p, pIter);
188428  iOff = pIter->iLeafOffset;
188429  if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
188430  iOff += pIter->nPos;
188431  }
188432  fts5GetVarint(&a[iOff], (u64*)&iDelta);
188433  pIter->iRowid -= iDelta;
188434  }else{
188435  fts5SegIterReverseNewPage(p, pIter);
188436  }
188437 }
188438 
188439 /*
188440 ** Advance iterator pIter to the next entry.
188441 **
188442 ** This version of fts5SegIterNext() is only used if detail=none and the
188443 ** iterator is not a reverse direction iterator.
188444 */
188445 static void fts5SegIterNext_None(
188446  Fts5Index *p, /* FTS5 backend object */
188447  Fts5SegIter *pIter, /* Iterator to advance */
188448  int *pbNewTerm /* OUT: Set for new term */
188449 ){
188450  int iOff;
188451 
188452  assert( p->rc==SQLITE_OK );
188453  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
188454  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
188455 
188456  ASSERT_SZLEAF_OK(pIter->pLeaf);
188457  iOff = pIter->iLeafOffset;
188458 
188459  /* Next entry is on the next page */
188460  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
188461  fts5SegIterNextPage(p, pIter);
188462  if( p->rc || pIter->pLeaf==0 ) return;
188463  pIter->iRowid = 0;
188464  iOff = 4;
188465  }
188466 
188467  if( iOff<pIter->iEndofDoclist ){
188468  /* Next entry is on the current page */
188469  i64 iDelta;
188470  iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
188471  pIter->iLeafOffset = iOff;
188472  pIter->iRowid += iDelta;
188473  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
188474  if( pIter->pSeg ){
188475  int nKeep = 0;
188476  if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
188477  iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
188478  }
188479  pIter->iLeafOffset = iOff;
188480  fts5SegIterLoadTerm(p, pIter, nKeep);
188481  }else{
188482  const u8 *pList = 0;
188483  const char *zTerm = 0;
188484  int nList;
188485  sqlite3Fts5HashScanNext(p->pHash);
188486  sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
188487  if( pList==0 ) goto next_none_eof;
188488  pIter->pLeaf->p = (u8*)pList;
188489  pIter->pLeaf->nn = nList;
188490  pIter->pLeaf->szLeaf = nList;
188491  pIter->iEndofDoclist = nList;
188492  sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
188493  pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
188494  }
188495 
188496  if( pbNewTerm ) *pbNewTerm = 1;
188497  }else{
188498  goto next_none_eof;
188499  }
188500 
188501  fts5SegIterLoadNPos(p, pIter);
188502 
188503  return;
188504  next_none_eof:
188505  fts5DataRelease(pIter->pLeaf);
188506  pIter->pLeaf = 0;
188507 }
188508 
188509 
188510 /*
188511 ** Advance iterator pIter to the next entry.
188512 **
188513 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
188514 ** is not considered an error if the iterator reaches EOF. If an error has
188515 ** already occurred when this function is called, it is a no-op.
188516 */
188517 static void fts5SegIterNext(
188518  Fts5Index *p, /* FTS5 backend object */
188519  Fts5SegIter *pIter, /* Iterator to advance */
188520  int *pbNewTerm /* OUT: Set for new term */
188521 ){
188522  Fts5Data *pLeaf = pIter->pLeaf;
188523  int iOff;
188524  int bNewTerm = 0;
188525  int nKeep = 0;
188526  u8 *a;
188527  int n;
188528 
188529  assert( pbNewTerm==0 || *pbNewTerm==0 );
188530  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
188531 
188532  /* Search for the end of the position list within the current page. */
188533  a = pLeaf->p;
188534  n = pLeaf->szLeaf;
188535 
188536  ASSERT_SZLEAF_OK(pLeaf);
188537  iOff = pIter->iLeafOffset + pIter->nPos;
188538 
188539  if( iOff<n ){
188540  /* The next entry is on the current page. */
188541  assert_nc( iOff<=pIter->iEndofDoclist );
188542  if( iOff>=pIter->iEndofDoclist ){
188543  bNewTerm = 1;
188544  if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
188545  iOff += fts5GetVarint32(&a[iOff], nKeep);
188546  }
188547  }else{
188548  u64 iDelta;
188549  iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
188550  pIter->iRowid += iDelta;
188551  assert_nc( iDelta>0 );
188552  }
188553  pIter->iLeafOffset = iOff;
188554 
188555  }else if( pIter->pSeg==0 ){
188556  const u8 *pList = 0;
188557  const char *zTerm = 0;
188558  int nList = 0;
188559  assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
188560  if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
188561  sqlite3Fts5HashScanNext(p->pHash);
188562  sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
188563  }
188564  if( pList==0 ){
188565  fts5DataRelease(pIter->pLeaf);
188566  pIter->pLeaf = 0;
188567  }else{
188568  pIter->pLeaf->p = (u8*)pList;
188569  pIter->pLeaf->nn = nList;
188570  pIter->pLeaf->szLeaf = nList;
188571  pIter->iEndofDoclist = nList+1;
188572  sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
188573  (u8*)zTerm);
188574  pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
188575  *pbNewTerm = 1;
188576  }
188577  }else{
188578  iOff = 0;
188579  /* Next entry is not on the current page */
188580  while( iOff==0 ){
188581  fts5SegIterNextPage(p, pIter);
188582  pLeaf = pIter->pLeaf;
188583  if( pLeaf==0 ) break;
188584  ASSERT_SZLEAF_OK(pLeaf);
188585  if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
188586  iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
188587  pIter->iLeafOffset = iOff;
188588 
188589  if( pLeaf->nn>pLeaf->szLeaf ){
188590  pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
188591  &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
188592  );
188593  }
188594  }
188595  else if( pLeaf->nn>pLeaf->szLeaf ){
188596  pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
188597  &pLeaf->p[pLeaf->szLeaf], iOff
188598  );
188599  pIter->iLeafOffset = iOff;
188600  pIter->iEndofDoclist = iOff;
188601  bNewTerm = 1;
188602  }
188603  assert_nc( iOff<pLeaf->szLeaf );
188604  if( iOff>pLeaf->szLeaf ){
188605  p->rc = FTS5_CORRUPT;
188606  return;
188607  }
188608  }
188609  }
188610 
188611  /* Check if the iterator is now at EOF. If so, return early. */
188612  if( pIter->pLeaf ){
188613  if( bNewTerm ){
188614  if( pIter->flags & FTS5_SEGITER_ONETERM ){
188615  fts5DataRelease(pIter->pLeaf);
188616  pIter->pLeaf = 0;
188617  }else{
188618  fts5SegIterLoadTerm(p, pIter, nKeep);
188619  fts5SegIterLoadNPos(p, pIter);
188620  if( pbNewTerm ) *pbNewTerm = 1;
188621  }
188622  }else{
188623  /* The following could be done by calling fts5SegIterLoadNPos(). But
188624  ** this block is particularly performance critical, so equivalent
188625  ** code is inlined.
188626  **
188627  ** Later: Switched back to fts5SegIterLoadNPos() because it supports
188628  ** detail=none mode. Not ideal.
188629  */
188630  int nSz;
188631  assert( p->rc==SQLITE_OK );
188632  fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
188633  pIter->bDel = (nSz & 0x0001);
188634  pIter->nPos = nSz>>1;
188635  assert_nc( pIter->nPos>=0 );
188636  }
188637  }
188638 }
188639 
188640 #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
188641 
188642 #define fts5IndexSkipVarint(a, iOff) { \
188643  int iEnd = iOff+9; \
188644  while( (a[iOff++] & 0x80) && iOff<iEnd ); \
188645 }
188646 
188647 /*
188648 ** Iterator pIter currently points to the first rowid in a doclist. This
188649 ** function sets the iterator up so that iterates in reverse order through
188650 ** the doclist.
188651 */
188652 static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
188653  Fts5DlidxIter *pDlidx = pIter->pDlidx;
188654  Fts5Data *pLast = 0;
188655  int pgnoLast = 0;
188656 
188657  if( pDlidx ){
188658  int iSegid = pIter->pSeg->iSegid;
188659  pgnoLast = fts5DlidxIterPgno(pDlidx);
188660  pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
188661  }else{
188662  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
188663 
188664  /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
188665  ** position-list content for the current rowid. Back it up so that it
188666  ** points to the start of the position-list size field. */
188667  int iPoslist;
188668  if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
188669  iPoslist = pIter->iTermLeafOffset;
188670  }else{
188671  iPoslist = 4;
188672  }
188673  fts5IndexSkipVarint(pLeaf->p, iPoslist);
188674  pIter->iLeafOffset = iPoslist;
188675 
188676  /* If this condition is true then the largest rowid for the current
188677  ** term may not be stored on the current page. So search forward to
188678  ** see where said rowid really is. */
188679  if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
188680  int pgno;
188681  Fts5StructureSegment *pSeg = pIter->pSeg;
188682 
188683  /* The last rowid in the doclist may not be on the current page. Search
188684  ** forward to find the page containing the last rowid. */
188685  for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
188686  i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
188687  Fts5Data *pNew = fts5DataRead(p, iAbs);
188688  if( pNew ){
188689  int iRowid, bTermless;
188690  iRowid = fts5LeafFirstRowidOff(pNew);
188691  bTermless = fts5LeafIsTermless(pNew);
188692  if( iRowid ){
188693  SWAPVAL(Fts5Data*, pNew, pLast);
188694  pgnoLast = pgno;
188695  }
188696  fts5DataRelease(pNew);
188697  if( bTermless==0 ) break;
188698  }
188699  }
188700  }
188701  }
188702 
188703  /* If pLast is NULL at this point, then the last rowid for this doclist
188704  ** lies on the page currently indicated by the iterator. In this case
188705  ** pIter->iLeafOffset is already set to point to the position-list size
188706  ** field associated with the first relevant rowid on the page.
188707  **
188708  ** Or, if pLast is non-NULL, then it is the page that contains the last
188709  ** rowid. In this case configure the iterator so that it points to the
188710  ** first rowid on this page.
188711  */
188712  if( pLast ){
188713  int iOff;
188714  fts5DataRelease(pIter->pLeaf);
188715  pIter->pLeaf = pLast;
188716  pIter->iLeafPgno = pgnoLast;
188717  iOff = fts5LeafFirstRowidOff(pLast);
188718  iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
188719  pIter->iLeafOffset = iOff;
188720 
188721  if( fts5LeafIsTermless(pLast) ){
188722  pIter->iEndofDoclist = pLast->nn+1;
188723  }else{
188724  pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
188725  }
188726 
188727  }
188728 
188729  fts5SegIterReverseInitPage(p, pIter);
188730 }
188731 
188732 /*
188733 ** Iterator pIter currently points to the first rowid of a doclist.
188734 ** There is a doclist-index associated with the final term on the current
188735 ** page. If the current term is the last term on the page, load the
188736 ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
188737 */
188738 static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
188739  int iSeg = pIter->pSeg->iSegid;
188740  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
188741  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
188742 
188743  assert( pIter->flags & FTS5_SEGITER_ONETERM );
188744  assert( pIter->pDlidx==0 );
188745 
188746  /* Check if the current doclist ends on this page. If it does, return
188747  ** early without loading the doclist-index (as it belongs to a different
188748  ** term. */
188749  if( pIter->iTermLeafPgno==pIter->iLeafPgno
188750  && pIter->iEndofDoclist<pLeaf->szLeaf
188751  ){
188752  return;
188753  }
188754 
188755  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
188756 }
188757 
188758 /*
188759 ** The iterator object passed as the second argument currently contains
188760 ** no valid values except for the Fts5SegIter.pLeaf member variable. This
188761 ** function searches the leaf page for a term matching (pTerm/nTerm).
188762 **
188763 ** If the specified term is found on the page, then the iterator is left
188764 ** pointing to it. If argument bGe is zero and the term is not found,
188765 ** the iterator is left pointing at EOF.
188766 **
188767 ** If bGe is non-zero and the specified term is not found, then the
188768 ** iterator is left pointing to the smallest term in the segment that
188769 ** is larger than the specified term, even if this term is not on the
188770 ** current page.
188771 */
188772 static void fts5LeafSeek(
188773  Fts5Index *p, /* Leave any error code here */
188774  int bGe, /* True for a >= search */
188775  Fts5SegIter *pIter, /* Iterator to seek */
188776  const u8 *pTerm, int nTerm /* Term to search for */
188777 ){
188778  int iOff;
188779  const u8 *a = pIter->pLeaf->p;
188780  int szLeaf = pIter->pLeaf->szLeaf;
188781  int n = pIter->pLeaf->nn;
188782 
188783  int nMatch = 0;
188784  int nKeep = 0;
188785  int nNew = 0;
188786  int iTermOff;
188787  int iPgidx; /* Current offset in pgidx */
188788  int bEndOfPage = 0;
188789 
188790  assert( p->rc==SQLITE_OK );
188791 
188792  iPgidx = szLeaf;
188793  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
188794  iOff = iTermOff;
188795  if( iOff>n ){
188796  p->rc = FTS5_CORRUPT;
188797  return;
188798  }
188799 
188800  while( 1 ){
188801 
188802  /* Figure out how many new bytes are in this term */
188803  fts5FastGetVarint32(a, iOff, nNew);
188804  if( nKeep<nMatch ){
188805  goto search_failed;
188806  }
188807 
188808  assert( nKeep>=nMatch );
188809  if( nKeep==nMatch ){
188810  int nCmp;
188811  int i;
188812  nCmp = MIN(nNew, nTerm-nMatch);
188813  for(i=0; i<nCmp; i++){
188814  if( a[iOff+i]!=pTerm[nMatch+i] ) break;
188815  }
188816  nMatch += i;
188817 
188818  if( nTerm==nMatch ){
188819  if( i==nNew ){
188820  goto search_success;
188821  }else{
188822  goto search_failed;
188823  }
188824  }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
188825  goto search_failed;
188826  }
188827  }
188828 
188829  if( iPgidx>=n ){
188830  bEndOfPage = 1;
188831  break;
188832  }
188833 
188834  iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
188835  iTermOff += nKeep;
188836  iOff = iTermOff;
188837 
188838  if( iOff>=n ){
188839  p->rc = FTS5_CORRUPT;
188840  return;
188841  }
188842 
188843  /* Read the nKeep field of the next term. */
188844  fts5FastGetVarint32(a, iOff, nKeep);
188845  }
188846 
188847  search_failed:
188848  if( bGe==0 ){
188849  fts5DataRelease(pIter->pLeaf);
188850  pIter->pLeaf = 0;
188851  return;
188852  }else if( bEndOfPage ){
188853  do {
188854  fts5SegIterNextPage(p, pIter);
188855  if( pIter->pLeaf==0 ) return;
188856  a = pIter->pLeaf->p;
188857  if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
188858  iPgidx = pIter->pLeaf->szLeaf;
188859  iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
188860  if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
188861  p->rc = FTS5_CORRUPT;
188862  }else{
188863  nKeep = 0;
188864  iTermOff = iOff;
188865  n = pIter->pLeaf->nn;
188866  iOff += fts5GetVarint32(&a[iOff], nNew);
188867  break;
188868  }
188869  }
188870  }while( 1 );
188871  }
188872 
188873  search_success:
188874 
188875  pIter->iLeafOffset = iOff + nNew;
188876  pIter->iTermLeafOffset = pIter->iLeafOffset;
188877  pIter->iTermLeafPgno = pIter->iLeafPgno;
188878 
188879  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
188880  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
188881 
188882  if( iPgidx>=n ){
188883  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
188884  }else{
188885  int nExtra;
188886  iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
188887  pIter->iEndofDoclist = iTermOff + nExtra;
188888  }
188889  pIter->iPgidxOff = iPgidx;
188890 
188891  fts5SegIterLoadRowid(p, pIter);
188892  fts5SegIterLoadNPos(p, pIter);
188893 }
188894 
188895 static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
188896  if( p->pIdxSelect==0 ){
188897  Fts5Config *pConfig = p->pConfig;
188898  fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
188899  "SELECT pgno FROM '%q'.'%q_idx' WHERE "
188900  "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
188901  pConfig->zDb, pConfig->zName
188902  ));
188903  }
188904  return p->pIdxSelect;
188905 }
188906 
188907 /*
188908 ** Initialize the object pIter to point to term pTerm/nTerm within segment
188909 ** pSeg. If there is no such term in the index, the iterator is set to EOF.
188910 **
188911 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
188912 ** an error has already occurred when this function is called, it is a no-op.
188913 */
188914 static void fts5SegIterSeekInit(
188915  Fts5Index *p, /* FTS5 backend */
188916  const u8 *pTerm, int nTerm, /* Term to seek to */
188917  int flags, /* Mask of FTS5INDEX_XXX flags */
188918  Fts5StructureSegment *pSeg, /* Description of segment */
188919  Fts5SegIter *pIter /* Object to populate */
188920 ){
188921  int iPg = 1;
188922  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
188923  int bDlidx = 0; /* True if there is a doclist-index */
188924  sqlite3_stmt *pIdxSelect = 0;
188925 
188926  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
188927  assert( pTerm && nTerm );
188928  memset(pIter, 0, sizeof(*pIter));
188929  pIter->pSeg = pSeg;
188930 
188931  /* This block sets stack variable iPg to the leaf page number that may
188932  ** contain term (pTerm/nTerm), if it is present in the segment. */
188933  pIdxSelect = fts5IdxSelectStmt(p);
188934  if( p->rc ) return;
188935  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
188936  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
188937  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
188938  i64 val = sqlite3_column_int(pIdxSelect, 0);
188939  iPg = (int)(val>>1);
188940  bDlidx = (val & 0x0001);
188941  }
188942  p->rc = sqlite3_reset(pIdxSelect);
188943 
188944  if( iPg<pSeg->pgnoFirst ){
188945  iPg = pSeg->pgnoFirst;
188946  bDlidx = 0;
188947  }
188948 
188949  pIter->iLeafPgno = iPg - 1;
188950  fts5SegIterNextPage(p, pIter);
188951 
188952  if( pIter->pLeaf ){
188953  fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
188954  }
188955 
188956  if( p->rc==SQLITE_OK && bGe==0 ){
188957  pIter->flags |= FTS5_SEGITER_ONETERM;
188958  if( pIter->pLeaf ){
188959  if( flags & FTS5INDEX_QUERY_DESC ){
188960  pIter->flags |= FTS5_SEGITER_REVERSE;
188961  }
188962  if( bDlidx ){
188963  fts5SegIterLoadDlidx(p, pIter);
188964  }
188965  if( flags & FTS5INDEX_QUERY_DESC ){
188966  fts5SegIterReverse(p, pIter);
188967  }
188968  }
188969  }
188970 
188971  fts5SegIterSetNext(p, pIter);
188972 
188973  /* Either:
188974  **
188975  ** 1) an error has occurred, or
188976  ** 2) the iterator points to EOF, or
188977  ** 3) the iterator points to an entry with term (pTerm/nTerm), or
188978  ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
188979  ** to an entry with a term greater than or equal to (pTerm/nTerm).
188980  */
188981  assert( p->rc!=SQLITE_OK /* 1 */
188982  || pIter->pLeaf==0 /* 2 */
188983  || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
188984  || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
188985  );
188986 }
188987 
188988 /*
188989 ** Initialize the object pIter to point to term pTerm/nTerm within the
188990 ** in-memory hash table. If there is no such term in the hash-table, the
188991 ** iterator is set to EOF.
188992 **
188993 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
188994 ** an error has already occurred when this function is called, it is a no-op.
188995 */
188996 static void fts5SegIterHashInit(
188997  Fts5Index *p, /* FTS5 backend */
188998  const u8 *pTerm, int nTerm, /* Term to seek to */
188999  int flags, /* Mask of FTS5INDEX_XXX flags */
189000  Fts5SegIter *pIter /* Object to populate */
189001 ){
189002  const u8 *pList = 0;
189003  int nList = 0;
189004  const u8 *z = 0;
189005  int n = 0;
189006 
189007  assert( p->pHash );
189008  assert( p->rc==SQLITE_OK );
189009 
189010  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
189011  p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
189012  sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
189013  n = (z ? (int)strlen((const char*)z) : 0);
189014  }else{
189015  pIter->flags |= FTS5_SEGITER_ONETERM;
189016  sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
189017  z = pTerm;
189018  n = nTerm;
189019  }
189020 
189021  if( pList ){
189022  Fts5Data *pLeaf;
189023  sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
189024  pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
189025  if( pLeaf==0 ) return;
189026  pLeaf->p = (u8*)pList;
189027  pLeaf->nn = pLeaf->szLeaf = nList;
189028  pIter->pLeaf = pLeaf;
189029  pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
189030  pIter->iEndofDoclist = pLeaf->nn;
189031 
189032  if( flags & FTS5INDEX_QUERY_DESC ){
189033  pIter->flags |= FTS5_SEGITER_REVERSE;
189034  fts5SegIterReverseInitPage(p, pIter);
189035  }else{
189036  fts5SegIterLoadNPos(p, pIter);
189037  }
189038  }
189039 
189040  fts5SegIterSetNext(p, pIter);
189041 }
189042 
189043 /*
189044 ** Zero the iterator passed as the only argument.
189045 */
189046 static void fts5SegIterClear(Fts5SegIter *pIter){
189047  fts5BufferFree(&pIter->term);
189048  fts5DataRelease(pIter->pLeaf);
189049  fts5DataRelease(pIter->pNextLeaf);
189050  fts5DlidxIterFree(pIter->pDlidx);
189051  sqlite3_free(pIter->aRowidOffset);
189052  memset(pIter, 0, sizeof(Fts5SegIter));
189053 }
189054 
189055 #ifdef SQLITE_DEBUG
189056 
189057 /*
189058 ** This function is used as part of the big assert() procedure implemented by
189059 ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
189060 ** in *pRes is the correct result of comparing the current positions of the
189061 ** two iterators.
189062 */
189063 static void fts5AssertComparisonResult(
189064  Fts5Iter *pIter,
189065  Fts5SegIter *p1,
189066  Fts5SegIter *p2,
189067  Fts5CResult *pRes
189068 ){
189069  int i1 = p1 - pIter->aSeg;
189070  int i2 = p2 - pIter->aSeg;
189071 
189072  if( p1->pLeaf || p2->pLeaf ){
189073  if( p1->pLeaf==0 ){
189074  assert( pRes->iFirst==i2 );
189075  }else if( p2->pLeaf==0 ){
189076  assert( pRes->iFirst==i1 );
189077  }else{
189078  int nMin = MIN(p1->term.n, p2->term.n);
189079  int res = memcmp(p1->term.p, p2->term.p, nMin);
189080  if( res==0 ) res = p1->term.n - p2->term.n;
189081 
189082  if( res==0 ){
189083  assert( pRes->bTermEq==1 );
189084  assert( p1->iRowid!=p2->iRowid );
189085  res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
189086  }else{
189087  assert( pRes->bTermEq==0 );
189088  }
189089 
189090  if( res<0 ){
189091  assert( pRes->iFirst==i1 );
189092  }else{
189093  assert( pRes->iFirst==i2 );
189094  }
189095  }
189096  }
189097 }
189098 
189099 /*
189100 ** This function is a no-op unless SQLITE_DEBUG is defined when this module
189101 ** is compiled. In that case, this function is essentially an assert()
189102 ** statement used to verify that the contents of the pIter->aFirst[] array
189103 ** are correct.
189104 */
189105 static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
189106  if( p->rc==SQLITE_OK ){
189107  Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189108  int i;
189109 
189110  assert( (pFirst->pLeaf==0)==pIter->base.bEof );
189111 
189112  /* Check that pIter->iSwitchRowid is set correctly. */
189113  for(i=0; i<pIter->nSeg; i++){
189114  Fts5SegIter *p1 = &pIter->aSeg[i];
189115  assert( p1==pFirst
189116  || p1->pLeaf==0
189117  || fts5BufferCompare(&pFirst->term, &p1->term)
189118  || p1->iRowid==pIter->iSwitchRowid
189119  || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
189120  );
189121  }
189122 
189123  for(i=0; i<pIter->nSeg; i+=2){
189124  Fts5SegIter *p1 = &pIter->aSeg[i];
189125  Fts5SegIter *p2 = &pIter->aSeg[i+1];
189126  Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
189127  fts5AssertComparisonResult(pIter, p1, p2, pRes);
189128  }
189129 
189130  for(i=1; i<(pIter->nSeg / 2); i+=2){
189131  Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
189132  Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
189133  Fts5CResult *pRes = &pIter->aFirst[i];
189134  fts5AssertComparisonResult(pIter, p1, p2, pRes);
189135  }
189136  }
189137 }
189138 #else
189139 # define fts5AssertMultiIterSetup(x,y)
189140 #endif
189141 
189142 /*
189143 ** Do the comparison necessary to populate pIter->aFirst[iOut].
189144 **
189145 ** If the returned value is non-zero, then it is the index of an entry
189146 ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
189147 ** to a key that is a duplicate of another, higher priority,
189148 ** segment-iterator in the pSeg->aSeg[] array.
189149 */
189150 static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
189151  int i1; /* Index of left-hand Fts5SegIter */
189152  int i2; /* Index of right-hand Fts5SegIter */
189153  int iRes;
189154  Fts5SegIter *p1; /* Left-hand Fts5SegIter */
189155  Fts5SegIter *p2; /* Right-hand Fts5SegIter */
189156  Fts5CResult *pRes = &pIter->aFirst[iOut];
189157 
189158  assert( iOut<pIter->nSeg && iOut>0 );
189159  assert( pIter->bRev==0 || pIter->bRev==1 );
189160 
189161  if( iOut>=(pIter->nSeg/2) ){
189162  i1 = (iOut - pIter->nSeg/2) * 2;
189163  i2 = i1 + 1;
189164  }else{
189165  i1 = pIter->aFirst[iOut*2].iFirst;
189166  i2 = pIter->aFirst[iOut*2+1].iFirst;
189167  }
189168  p1 = &pIter->aSeg[i1];
189169  p2 = &pIter->aSeg[i2];
189170 
189171  pRes->bTermEq = 0;
189172  if( p1->pLeaf==0 ){ /* If p1 is at EOF */
189173  iRes = i2;
189174  }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
189175  iRes = i1;
189176  }else{
189177  int res = fts5BufferCompare(&p1->term, &p2->term);
189178  if( res==0 ){
189179  assert( i2>i1 );
189180  assert( i2!=0 );
189181  pRes->bTermEq = 1;
189182  if( p1->iRowid==p2->iRowid ){
189183  p1->bDel = p2->bDel;
189184  return i2;
189185  }
189186  res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
189187  }
189188  assert( res!=0 );
189189  if( res<0 ){
189190  iRes = i1;
189191  }else{
189192  iRes = i2;
189193  }
189194  }
189195 
189196  pRes->iFirst = (u16)iRes;
189197  return 0;
189198 }
189199 
189200 /*
189201 ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
189202 ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
189203 */
189204 static void fts5SegIterGotoPage(
189205  Fts5Index *p, /* FTS5 backend object */
189206  Fts5SegIter *pIter, /* Iterator to advance */
189207  int iLeafPgno
189208 ){
189209  assert( iLeafPgno>pIter->iLeafPgno );
189210 
189211  if( iLeafPgno>pIter->pSeg->pgnoLast ){
189212  p->rc = FTS5_CORRUPT;
189213  }else{
189214  fts5DataRelease(pIter->pNextLeaf);
189215  pIter->pNextLeaf = 0;
189216  pIter->iLeafPgno = iLeafPgno-1;
189217  fts5SegIterNextPage(p, pIter);
189218  assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
189219 
189220  if( p->rc==SQLITE_OK ){
189221  int iOff;
189222  u8 *a = pIter->pLeaf->p;
189223  int n = pIter->pLeaf->szLeaf;
189224 
189225  iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
189226  if( iOff<4 || iOff>=n ){
189227  p->rc = FTS5_CORRUPT;
189228  }else{
189229  iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
189230  pIter->iLeafOffset = iOff;
189231  fts5SegIterLoadNPos(p, pIter);
189232  }
189233  }
189234  }
189235 }
189236 
189237 /*
189238 ** Advance the iterator passed as the second argument until it is at or
189239 ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
189240 ** always advanced at least once.
189241 */
189242 static void fts5SegIterNextFrom(
189243  Fts5Index *p, /* FTS5 backend object */
189244  Fts5SegIter *pIter, /* Iterator to advance */
189245  i64 iMatch /* Advance iterator at least this far */
189246 ){
189247  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
189248  Fts5DlidxIter *pDlidx = pIter->pDlidx;
189249  int iLeafPgno = pIter->iLeafPgno;
189250  int bMove = 1;
189251 
189252  assert( pIter->flags & FTS5_SEGITER_ONETERM );
189253  assert( pIter->pDlidx );
189254  assert( pIter->pLeaf );
189255 
189256  if( bRev==0 ){
189257  while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
189258  iLeafPgno = fts5DlidxIterPgno(pDlidx);
189259  fts5DlidxIterNext(p, pDlidx);
189260  }
189261  assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
189262  if( iLeafPgno>pIter->iLeafPgno ){
189263  fts5SegIterGotoPage(p, pIter, iLeafPgno);
189264  bMove = 0;
189265  }
189266  }else{
189267  assert( pIter->pNextLeaf==0 );
189268  assert( iMatch<pIter->iRowid );
189269  while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
189270  fts5DlidxIterPrev(p, pDlidx);
189271  }
189272  iLeafPgno = fts5DlidxIterPgno(pDlidx);
189273 
189274  assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
189275 
189276  if( iLeafPgno<pIter->iLeafPgno ){
189277  pIter->iLeafPgno = iLeafPgno+1;
189278  fts5SegIterReverseNewPage(p, pIter);
189279  bMove = 0;
189280  }
189281  }
189282 
189283  do{
189284  if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
189285  if( pIter->pLeaf==0 ) break;
189286  if( bRev==0 && pIter->iRowid>=iMatch ) break;
189287  if( bRev!=0 && pIter->iRowid<=iMatch ) break;
189288  bMove = 1;
189289  }while( p->rc==SQLITE_OK );
189290 }
189291 
189292 
189293 /*
189294 ** Free the iterator object passed as the second argument.
189295 */
189296 static void fts5MultiIterFree(Fts5Iter *pIter){
189297  if( pIter ){
189298  int i;
189299  for(i=0; i<pIter->nSeg; i++){
189300  fts5SegIterClear(&pIter->aSeg[i]);
189301  }
189302  fts5StructureRelease(pIter->pStruct);
189303  fts5BufferFree(&pIter->poslist);
189304  sqlite3_free(pIter);
189305  }
189306 }
189307 
189308 static void fts5MultiIterAdvanced(
189309  Fts5Index *p, /* FTS5 backend to iterate within */
189310  Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
189311  int iChanged, /* Index of sub-iterator just advanced */
189312  int iMinset /* Minimum entry in aFirst[] to set */
189313 ){
189314  int i;
189315  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
189316  int iEq;
189317  if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
189318  Fts5SegIter *pSeg = &pIter->aSeg[iEq];
189319  assert( p->rc==SQLITE_OK );
189320  pSeg->xNext(p, pSeg, 0);
189321  i = pIter->nSeg + iEq;
189322  }
189323  }
189324 }
189325 
189326 /*
189327 ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
189328 ** points to the same term though - just a different rowid. This function
189329 ** attempts to update the contents of the pIter->aFirst[] accordingly.
189330 ** If it does so successfully, 0 is returned. Otherwise 1.
189331 **
189332 ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
189333 ** on the iterator instead. That function does the same as this one, except
189334 ** that it deals with more complicated cases as well.
189335 */
189336 static int fts5MultiIterAdvanceRowid(
189337  Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
189338  int iChanged, /* Index of sub-iterator just advanced */
189339  Fts5SegIter **ppFirst
189340 ){
189341  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
189342 
189343  if( pNew->iRowid==pIter->iSwitchRowid
189344  || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
189345  ){
189346  int i;
189347  Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
189348  pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
189349  for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
189350  Fts5CResult *pRes = &pIter->aFirst[i];
189351 
189352  assert( pNew->pLeaf );
189353  assert( pRes->bTermEq==0 || pOther->pLeaf );
189354 
189355  if( pRes->bTermEq ){
189356  if( pNew->iRowid==pOther->iRowid ){
189357  return 1;
189358  }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
189359  pIter->iSwitchRowid = pOther->iRowid;
189360  pNew = pOther;
189361  }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
189362  pIter->iSwitchRowid = pOther->iRowid;
189363  }
189364  }
189365  pRes->iFirst = (u16)(pNew - pIter->aSeg);
189366  if( i==1 ) break;
189367 
189368  pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
189369  }
189370  }
189371 
189372  *ppFirst = pNew;
189373  return 0;
189374 }
189375 
189376 /*
189377 ** Set the pIter->bEof variable based on the state of the sub-iterators.
189378 */
189379 static void fts5MultiIterSetEof(Fts5Iter *pIter){
189380  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189381  pIter->base.bEof = pSeg->pLeaf==0;
189382  pIter->iSwitchRowid = pSeg->iRowid;
189383 }
189384 
189385 /*
189386 ** Move the iterator to the next entry.
189387 **
189388 ** If an error occurs, an error code is left in Fts5Index.rc. It is not
189389 ** considered an error if the iterator reaches EOF, or if it is already at
189390 ** EOF when this function is called.
189391 */
189392 static void fts5MultiIterNext(
189393  Fts5Index *p,
189394  Fts5Iter *pIter,
189395  int bFrom, /* True if argument iFrom is valid */
189396  i64 iFrom /* Advance at least as far as this */
189397 ){
189398  int bUseFrom = bFrom;
189399  assert( pIter->base.bEof==0 );
189400  while( p->rc==SQLITE_OK ){
189401  int iFirst = pIter->aFirst[1].iFirst;
189402  int bNewTerm = 0;
189403  Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
189404  assert( p->rc==SQLITE_OK );
189405  if( bUseFrom && pSeg->pDlidx ){
189406  fts5SegIterNextFrom(p, pSeg, iFrom);
189407  }else{
189408  pSeg->xNext(p, pSeg, &bNewTerm);
189409  }
189410 
189411  if( pSeg->pLeaf==0 || bNewTerm
189412  || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
189413  ){
189414  fts5MultiIterAdvanced(p, pIter, iFirst, 1);
189415  fts5MultiIterSetEof(pIter);
189416  pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
189417  if( pSeg->pLeaf==0 ) return;
189418  }
189419 
189420  fts5AssertMultiIterSetup(p, pIter);
189421  assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
189422  if( pIter->bSkipEmpty==0 || pSeg->nPos ){
189423  pIter->xSetOutputs(pIter, pSeg);
189424  return;
189425  }
189426  bUseFrom = 0;
189427  }
189428 }
189429 
189430 static void fts5MultiIterNext2(
189431  Fts5Index *p,
189432  Fts5Iter *pIter,
189433  int *pbNewTerm /* OUT: True if *might* be new term */
189434 ){
189435  assert( pIter->bSkipEmpty );
189436  if( p->rc==SQLITE_OK ){
189437  do {
189438  int iFirst = pIter->aFirst[1].iFirst;
189439  Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
189440  int bNewTerm = 0;
189441 
189442  assert( p->rc==SQLITE_OK );
189443  pSeg->xNext(p, pSeg, &bNewTerm);
189444  if( pSeg->pLeaf==0 || bNewTerm
189445  || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
189446  ){
189447  fts5MultiIterAdvanced(p, pIter, iFirst, 1);
189448  fts5MultiIterSetEof(pIter);
189449  *pbNewTerm = 1;
189450  }else{
189451  *pbNewTerm = 0;
189452  }
189453  fts5AssertMultiIterSetup(p, pIter);
189454 
189455  }while( fts5MultiIterIsEmpty(p, pIter) );
189456  }
189457 }
189458 
189459 static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
189460  UNUSED_PARAM2(pUnused1, pUnused2);
189461 }
189462 
189463 static Fts5Iter *fts5MultiIterAlloc(
189464  Fts5Index *p, /* FTS5 backend to iterate within */
189465  int nSeg
189466 ){
189467  Fts5Iter *pNew;
189468  int nSlot; /* Power of two >= nSeg */
189469 
189470  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
189471  pNew = fts5IdxMalloc(p,
189472  sizeof(Fts5Iter) + /* pNew */
189473  sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
189474  sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
189475  );
189476  if( pNew ){
189477  pNew->nSeg = nSlot;
189478  pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
189479  pNew->pIndex = p;
189480  pNew->xSetOutputs = fts5IterSetOutputs_Noop;
189481  }
189482  return pNew;
189483 }
189484 
189485 static void fts5PoslistCallback(
189486  Fts5Index *pUnused,
189487  void *pContext,
189488  const u8 *pChunk, int nChunk
189489 ){
189490  UNUSED_PARAM(pUnused);
189491  assert_nc( nChunk>=0 );
189492  if( nChunk>0 ){
189493  fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
189494  }
189495 }
189496 
189497 typedef struct PoslistCallbackCtx PoslistCallbackCtx;
189498 struct PoslistCallbackCtx {
189499  Fts5Buffer *pBuf; /* Append to this buffer */
189500  Fts5Colset *pColset; /* Restrict matches to this column */
189501  int eState; /* See above */
189502 };
189503 
189504 typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
189505 struct PoslistOffsetsCtx {
189506  Fts5Buffer *pBuf; /* Append to this buffer */
189507  Fts5Colset *pColset; /* Restrict matches to this column */
189508  int iRead;
189509  int iWrite;
189510 };
189511 
189512 /*
189513 ** TODO: Make this more efficient!
189514 */
189515 static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
189516  int i;
189517  for(i=0; i<pColset->nCol; i++){
189518  if( pColset->aiCol[i]==iCol ) return 1;
189519  }
189520  return 0;
189521 }
189522 
189523 static void fts5PoslistOffsetsCallback(
189524  Fts5Index *pUnused,
189525  void *pContext,
189526  const u8 *pChunk, int nChunk
189527 ){
189528  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
189529  UNUSED_PARAM(pUnused);
189530  assert_nc( nChunk>=0 );
189531  if( nChunk>0 ){
189532  int i = 0;
189533  while( i<nChunk ){
189534  int iVal;
189535  i += fts5GetVarint32(&pChunk[i], iVal);
189536  iVal += pCtx->iRead - 2;
189537  pCtx->iRead = iVal;
189538  if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
189539  fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
189540  pCtx->iWrite = iVal;
189541  }
189542  }
189543  }
189544 }
189545 
189546 static void fts5PoslistFilterCallback(
189547  Fts5Index *pUnused,
189548  void *pContext,
189549  const u8 *pChunk, int nChunk
189550 ){
189551  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
189552  UNUSED_PARAM(pUnused);
189553  assert_nc( nChunk>=0 );
189554  if( nChunk>0 ){
189555  /* Search through to find the first varint with value 1. This is the
189556  ** start of the next columns hits. */
189557  int i = 0;
189558  int iStart = 0;
189559 
189560  if( pCtx->eState==2 ){
189561  int iCol;
189562  fts5FastGetVarint32(pChunk, i, iCol);
189563  if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
189564  pCtx->eState = 1;
189565  fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
189566  }else{
189567  pCtx->eState = 0;
189568  }
189569  }
189570 
189571  do {
189572  while( i<nChunk && pChunk[i]!=0x01 ){
189573  while( pChunk[i] & 0x80 ) i++;
189574  i++;
189575  }
189576  if( pCtx->eState ){
189577  fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
189578  }
189579  if( i<nChunk ){
189580  int iCol;
189581  iStart = i;
189582  i++;
189583  if( i>=nChunk ){
189584  pCtx->eState = 2;
189585  }else{
189586  fts5FastGetVarint32(pChunk, i, iCol);
189587  pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
189588  if( pCtx->eState ){
189589  fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
189590  iStart = i;
189591  }
189592  }
189593  }
189594  }while( i<nChunk );
189595  }
189596 }
189597 
189598 static void fts5ChunkIterate(
189599  Fts5Index *p, /* Index object */
189600  Fts5SegIter *pSeg, /* Poslist of this iterator */
189601  void *pCtx, /* Context pointer for xChunk callback */
189602  void (*xChunk)(Fts5Index*, void*, const u8*, int)
189603 ){
189604  int nRem = pSeg->nPos; /* Number of bytes still to come */
189605  Fts5Data *pData = 0;
189606  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
189607  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
189608  int pgno = pSeg->iLeafPgno;
189609  int pgnoSave = 0;
189610 
189611  /* This function does notmwork with detail=none databases. */
189612  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
189613 
189614  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
189615  pgnoSave = pgno+1;
189616  }
189617 
189618  while( 1 ){
189619  xChunk(p, pCtx, pChunk, nChunk);
189620  nRem -= nChunk;
189621  fts5DataRelease(pData);
189622  if( nRem<=0 ){
189623  break;
189624  }else{
189625  pgno++;
189626  pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
189627  if( pData==0 ) break;
189628  pChunk = &pData->p[4];
189629  nChunk = MIN(nRem, pData->szLeaf - 4);
189630  if( pgno==pgnoSave ){
189631  assert( pSeg->pNextLeaf==0 );
189632  pSeg->pNextLeaf = pData;
189633  pData = 0;
189634  }
189635  }
189636  }
189637 }
189638 
189639 /*
189640 ** Iterator pIter currently points to a valid entry (not EOF). This
189641 ** function appends the position list data for the current entry to
189642 ** buffer pBuf. It does not make a copy of the position-list size
189643 ** field.
189644 */
189645 static void fts5SegiterPoslist(
189646  Fts5Index *p,
189647  Fts5SegIter *pSeg,
189648  Fts5Colset *pColset,
189649  Fts5Buffer *pBuf
189650 ){
189651  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
189652  if( pColset==0 ){
189653  fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
189654  }else{
189655  if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
189656  PoslistCallbackCtx sCtx;
189657  sCtx.pBuf = pBuf;
189658  sCtx.pColset = pColset;
189659  sCtx.eState = fts5IndexColsetTest(pColset, 0);
189660  assert( sCtx.eState==0 || sCtx.eState==1 );
189661  fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
189662  }else{
189663  PoslistOffsetsCtx sCtx;
189664  memset(&sCtx, 0, sizeof(sCtx));
189665  sCtx.pBuf = pBuf;
189666  sCtx.pColset = pColset;
189667  fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
189668  }
189669  }
189670  }
189671 }
189672 
189673 /*
189674 ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
189675 ** the position list contains entries for column iCol, then (*pa) is set
189676 ** to point to the sub-position-list for that column and the number of
189677 ** bytes in it returned. Or, if the argument position list does not
189678 ** contain any entries for column iCol, return 0.
189679 */
189680 static int fts5IndexExtractCol(
189681  const u8 **pa, /* IN/OUT: Pointer to poslist */
189682  int n, /* IN: Size of poslist in bytes */
189683  int iCol /* Column to extract from poslist */
189684 ){
189685  int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
189686  const u8 *p = *pa;
189687  const u8 *pEnd = &p[n]; /* One byte past end of position list */
189688 
189689  while( iCol>iCurrent ){
189690  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
189691  ** not part of a varint. Note that it is not possible for a negative
189692  ** or extremely large varint to occur within an uncorrupted position
189693  ** list. So the last byte of each varint may be assumed to have a clear
189694  ** 0x80 bit. */
189695  while( *p!=0x01 ){
189696  while( *p++ & 0x80 );
189697  if( p>=pEnd ) return 0;
189698  }
189699  *pa = p++;
189700  iCurrent = *p++;
189701  if( iCurrent & 0x80 ){
189702  p--;
189703  p += fts5GetVarint32(p, iCurrent);
189704  }
189705  }
189706  if( iCol!=iCurrent ) return 0;
189707 
189708  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
189709  ** not part of a varint */
189710  while( p<pEnd && *p!=0x01 ){
189711  while( *p++ & 0x80 );
189712  }
189713 
189714  return p - (*pa);
189715 }
189716 
189717 static int fts5IndexExtractColset (
189718  Fts5Colset *pColset, /* Colset to filter on */
189719  const u8 *pPos, int nPos, /* Position list */
189720  Fts5Buffer *pBuf /* Output buffer */
189721 ){
189722  int rc = SQLITE_OK;
189723  int i;
189724 
189725  fts5BufferZero(pBuf);
189726  for(i=0; i<pColset->nCol; i++){
189727  const u8 *pSub = pPos;
189728  int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
189729  if( nSub ){
189730  fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
189731  }
189732  }
189733  return rc;
189734 }
189735 
189736 /*
189737 ** xSetOutputs callback used by detail=none tables.
189738 */
189739 static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
189740  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
189741  pIter->base.iRowid = pSeg->iRowid;
189742  pIter->base.nData = pSeg->nPos;
189743 }
189744 
189745 /*
189746 ** xSetOutputs callback used by detail=full and detail=col tables when no
189747 ** column filters are specified.
189748 */
189749 static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
189750  pIter->base.iRowid = pSeg->iRowid;
189751  pIter->base.nData = pSeg->nPos;
189752 
189753  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
189754  assert( pIter->pColset==0 );
189755 
189756  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
189757  /* All data is stored on the current page. Populate the output
189758  ** variables to point into the body of the page object. */
189759  pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
189760  }else{
189761  /* The data is distributed over two or more pages. Copy it into the
189762  ** Fts5Iter.poslist buffer and then set the output pointer to point
189763  ** to this buffer. */
189764  fts5BufferZero(&pIter->poslist);
189765  fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
189766  pIter->base.pData = pIter->poslist.p;
189767  }
189768 }
189769 
189770 /*
189771 ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
189772 ** against no columns at all).
189773 */
189774 static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
189775  UNUSED_PARAM(pSeg);
189776  pIter->base.nData = 0;
189777 }
189778 
189779 /*
189780 ** xSetOutputs callback used by detail=col when there is a column filter
189781 ** and there are 100 or more columns. Also called as a fallback from
189782 ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
189783 */
189784 static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
189785  fts5BufferZero(&pIter->poslist);
189786  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
189787  pIter->base.iRowid = pSeg->iRowid;
189788  pIter->base.pData = pIter->poslist.p;
189789  pIter->base.nData = pIter->poslist.n;
189790 }
189791 
189792 /*
189793 ** xSetOutputs callback used when:
189794 **
189795 ** * detail=col,
189796 ** * there is a column filter, and
189797 ** * the table contains 100 or fewer columns.
189798 **
189799 ** The last point is to ensure all column numbers are stored as
189800 ** single-byte varints.
189801 */
189802 static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
189803 
189804  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
189805  assert( pIter->pColset );
189806 
189807  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
189808  fts5IterSetOutputs_Col(pIter, pSeg);
189809  }else{
189810  u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
189811  u8 *pEnd = (u8*)&a[pSeg->nPos];
189812  int iPrev = 0;
189813  int *aiCol = pIter->pColset->aiCol;
189814  int *aiColEnd = &aiCol[pIter->pColset->nCol];
189815 
189816  u8 *aOut = pIter->poslist.p;
189817  int iPrevOut = 0;
189818 
189819  pIter->base.iRowid = pSeg->iRowid;
189820 
189821  while( a<pEnd ){
189822  iPrev += (int)a++[0] - 2;
189823  while( *aiCol<iPrev ){
189824  aiCol++;
189825  if( aiCol==aiColEnd ) goto setoutputs_col_out;
189826  }
189827  if( *aiCol==iPrev ){
189828  *aOut++ = (u8)((iPrev - iPrevOut) + 2);
189829  iPrevOut = iPrev;
189830  }
189831  }
189832 
189833 setoutputs_col_out:
189834  pIter->base.pData = pIter->poslist.p;
189835  pIter->base.nData = aOut - pIter->poslist.p;
189836  }
189837 }
189838 
189839 /*
189840 ** xSetOutputs callback used by detail=full when there is a column filter.
189841 */
189842 static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
189843  Fts5Colset *pColset = pIter->pColset;
189844  pIter->base.iRowid = pSeg->iRowid;
189845 
189846  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
189847  assert( pColset );
189848 
189849  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
189850  /* All data is stored on the current page. Populate the output
189851  ** variables to point into the body of the page object. */
189852  const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
189853  if( pColset->nCol==1 ){
189854  pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
189855  pIter->base.pData = a;
189856  }else{
189857  fts5BufferZero(&pIter->poslist);
189858  fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
189859  pIter->base.pData = pIter->poslist.p;
189860  pIter->base.nData = pIter->poslist.n;
189861  }
189862  }else{
189863  /* The data is distributed over two or more pages. Copy it into the
189864  ** Fts5Iter.poslist buffer and then set the output pointer to point
189865  ** to this buffer. */
189866  fts5BufferZero(&pIter->poslist);
189867  fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
189868  pIter->base.pData = pIter->poslist.p;
189869  pIter->base.nData = pIter->poslist.n;
189870  }
189871 }
189872 
189873 static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
189874  if( *pRc==SQLITE_OK ){
189875  Fts5Config *pConfig = pIter->pIndex->pConfig;
189876  if( pConfig->eDetail==FTS5_DETAIL_NONE ){
189877  pIter->xSetOutputs = fts5IterSetOutputs_None;
189878  }
189879 
189880  else if( pIter->pColset==0 ){
189881  pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
189882  }
189883 
189884  else if( pIter->pColset->nCol==0 ){
189885  pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
189886  }
189887 
189888  else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
189889  pIter->xSetOutputs = fts5IterSetOutputs_Full;
189890  }
189891 
189892  else{
189893  assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
189894  if( pConfig->nCol<=100 ){
189895  pIter->xSetOutputs = fts5IterSetOutputs_Col100;
189896  sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
189897  }else{
189898  pIter->xSetOutputs = fts5IterSetOutputs_Col;
189899  }
189900  }
189901  }
189902 }
189903 
189904 
189905 /*
189906 ** Allocate a new Fts5Iter object.
189907 **
189908 ** The new object will be used to iterate through data in structure pStruct.
189909 ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
189910 ** is zero or greater, data from the first nSegment segments on level iLevel
189911 ** is merged.
189912 **
189913 ** The iterator initially points to the first term/rowid entry in the
189914 ** iterated data.
189915 */
189916 static void fts5MultiIterNew(
189917  Fts5Index *p, /* FTS5 backend to iterate within */
189918  Fts5Structure *pStruct, /* Structure of specific index */
189919  int flags, /* FTS5INDEX_QUERY_XXX flags */
189920  Fts5Colset *pColset, /* Colset to filter on (or NULL) */
189921  const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
189922  int iLevel, /* Level to iterate (-1 for all) */
189923  int nSegment, /* Number of segments to merge (iLevel>=0) */
189924  Fts5Iter **ppOut /* New object */
189925 ){
189926  int nSeg = 0; /* Number of segment-iters in use */
189927  int iIter = 0; /* */
189928  int iSeg; /* Used to iterate through segments */
189929  Fts5StructureLevel *pLvl;
189930  Fts5Iter *pNew;
189931 
189932  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
189933 
189934  /* Allocate space for the new multi-seg-iterator. */
189935  if( p->rc==SQLITE_OK ){
189936  if( iLevel<0 ){
189937  assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
189938  nSeg = pStruct->nSegment;
189939  nSeg += (p->pHash ? 1 : 0);
189940  }else{
189941  nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
189942  }
189943  }
189944  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
189945  if( pNew==0 ) return;
189946  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
189947  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
189948  pNew->pStruct = pStruct;
189949  pNew->pColset = pColset;
189950  fts5StructureRef(pStruct);
189951  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
189952  fts5IterSetOutputCb(&p->rc, pNew);
189953  }
189954 
189955  /* Initialize each of the component segment iterators. */
189956  if( p->rc==SQLITE_OK ){
189957  if( iLevel<0 ){
189958  Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
189959  if( p->pHash ){
189960  /* Add a segment iterator for the current contents of the hash table. */
189961  Fts5SegIter *pIter = &pNew->aSeg[iIter++];
189962  fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
189963  }
189964  for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
189965  for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
189966  Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
189967  Fts5SegIter *pIter = &pNew->aSeg[iIter++];
189968  if( pTerm==0 ){
189969  fts5SegIterInit(p, pSeg, pIter);
189970  }else{
189971  fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
189972  }
189973  }
189974  }
189975  }else{
189976  pLvl = &pStruct->aLevel[iLevel];
189977  for(iSeg=nSeg-1; iSeg>=0; iSeg--){
189978  fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
189979  }
189980  }
189981  assert( iIter==nSeg );
189982  }
189983 
189984  /* If the above was successful, each component iterators now points
189985  ** to the first entry in its segment. In this case initialize the
189986  ** aFirst[] array. Or, if an error has occurred, free the iterator
189987  ** object and set the output variable to NULL. */
189988  if( p->rc==SQLITE_OK ){
189989  for(iIter=pNew->nSeg-1; iIter>0; iIter--){
189990  int iEq;
189991  if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
189992  Fts5SegIter *pSeg = &pNew->aSeg[iEq];
189993  if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
189994  fts5MultiIterAdvanced(p, pNew, iEq, iIter);
189995  }
189996  }
189997  fts5MultiIterSetEof(pNew);
189998  fts5AssertMultiIterSetup(p, pNew);
189999 
190000  if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
190001  fts5MultiIterNext(p, pNew, 0, 0);
190002  }else if( pNew->base.bEof==0 ){
190003  Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
190004  pNew->xSetOutputs(pNew, pSeg);
190005  }
190006 
190007  }else{
190008  fts5MultiIterFree(pNew);
190009  *ppOut = 0;
190010  }
190011 }
190012 
190013 /*
190014 ** Create an Fts5Iter that iterates through the doclist provided
190015 ** as the second argument.
190016 */
190017 static void fts5MultiIterNew2(
190018  Fts5Index *p, /* FTS5 backend to iterate within */
190019  Fts5Data *pData, /* Doclist to iterate through */
190020  int bDesc, /* True for descending rowid order */
190021  Fts5Iter **ppOut /* New object */
190022 ){
190023  Fts5Iter *pNew;
190024  pNew = fts5MultiIterAlloc(p, 2);
190025  if( pNew ){
190026  Fts5SegIter *pIter = &pNew->aSeg[1];
190027 
190028  pIter->flags = FTS5_SEGITER_ONETERM;
190029  if( pData->szLeaf>0 ){
190030  pIter->pLeaf = pData;
190031  pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
190032  pIter->iEndofDoclist = pData->nn;
190033  pNew->aFirst[1].iFirst = 1;
190034  if( bDesc ){
190035  pNew->bRev = 1;
190036  pIter->flags |= FTS5_SEGITER_REVERSE;
190037  fts5SegIterReverseInitPage(p, pIter);
190038  }else{
190039  fts5SegIterLoadNPos(p, pIter);
190040  }
190041  pData = 0;
190042  }else{
190043  pNew->base.bEof = 1;
190044  }
190045  fts5SegIterSetNext(p, pIter);
190046 
190047  *ppOut = pNew;
190048  }
190049 
190050  fts5DataRelease(pData);
190051 }
190052 
190053 /*
190054 ** Return true if the iterator is at EOF or if an error has occurred.
190055 ** False otherwise.
190056 */
190057 static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
190058  assert( p->rc
190059  || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
190060  );
190061  return (p->rc || pIter->base.bEof);
190062 }
190063 
190064 /*
190065 ** Return the rowid of the entry that the iterator currently points
190066 ** to. If the iterator points to EOF when this function is called the
190067 ** results are undefined.
190068 */
190069 static i64 fts5MultiIterRowid(Fts5Iter *pIter){
190070  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
190071  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
190072 }
190073 
190074 /*
190075 ** Move the iterator to the next entry at or following iMatch.
190076 */
190077 static void fts5MultiIterNextFrom(
190078  Fts5Index *p,
190079  Fts5Iter *pIter,
190080  i64 iMatch
190081 ){
190082  while( 1 ){
190083  i64 iRowid;
190084  fts5MultiIterNext(p, pIter, 1, iMatch);
190085  if( fts5MultiIterEof(p, pIter) ) break;
190086  iRowid = fts5MultiIterRowid(pIter);
190087  if( pIter->bRev==0 && iRowid>=iMatch ) break;
190088  if( pIter->bRev!=0 && iRowid<=iMatch ) break;
190089  }
190090 }
190091 
190092 /*
190093 ** Return a pointer to a buffer containing the term associated with the
190094 ** entry that the iterator currently points to.
190095 */
190096 static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
190097  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
190098  *pn = p->term.n;
190099  return p->term.p;
190100 }
190101 
190102 /*
190103 ** Allocate a new segment-id for the structure pStruct. The new segment
190104 ** id must be between 1 and 65335 inclusive, and must not be used by
190105 ** any currently existing segment. If a free segment id cannot be found,
190106 ** SQLITE_FULL is returned.
190107 **
190108 ** If an error has already occurred, this function is a no-op. 0 is
190109 ** returned in this case.
190110 */
190111 static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
190112  int iSegid = 0;
190113 
190114  if( p->rc==SQLITE_OK ){
190115  if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
190116  p->rc = SQLITE_FULL;
190117  }else{
190118  /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
190119  ** array is 63 elements, or 252 bytes, in size. */
190120  u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
190121  int iLvl, iSeg;
190122  int i;
190123  u32 mask;
190124  memset(aUsed, 0, sizeof(aUsed));
190125  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190126  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
190127  int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
190128  if( iId<=FTS5_MAX_SEGMENT ){
190129  aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
190130  }
190131  }
190132  }
190133 
190134  for(i=0; aUsed[i]==0xFFFFFFFF; i++);
190135  mask = aUsed[i];
190136  for(iSegid=0; mask & (1 << iSegid); iSegid++);
190137  iSegid += 1 + i*32;
190138 
190139 #ifdef SQLITE_DEBUG
190140  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190141  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
190142  assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
190143  }
190144  }
190145  assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
190146 
190147  {
190148  sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
190149  if( p->rc==SQLITE_OK ){
190150  u8 aBlob[2] = {0xff, 0xff};
190151  sqlite3_bind_int(pIdxSelect, 1, iSegid);
190152  sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
190153  assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
190154  p->rc = sqlite3_reset(pIdxSelect);
190155  }
190156  }
190157 #endif
190158  }
190159  }
190160 
190161  return iSegid;
190162 }
190163 
190164 /*
190165 ** Discard all data currently cached in the hash-tables.
190166 */
190167 static void fts5IndexDiscardData(Fts5Index *p){
190168  assert( p->pHash || p->nPendingData==0 );
190169  if( p->pHash ){
190170  sqlite3Fts5HashClear(p->pHash);
190171  p->nPendingData = 0;
190172  }
190173 }
190174 
190175 /*
190176 ** Return the size of the prefix, in bytes, that buffer
190177 ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
190178 **
190179 ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
190180 ** than buffer (pOld/nOld).
190181 */
190182 static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
190183  int i;
190184  for(i=0; i<nOld; i++){
190185  if( pOld[i]!=pNew[i] ) break;
190186  }
190187  return i;
190188 }
190189 
190190 static void fts5WriteDlidxClear(
190191  Fts5Index *p,
190192  Fts5SegWriter *pWriter,
190193  int bFlush /* If true, write dlidx to disk */
190194 ){
190195  int i;
190196  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
190197  for(i=0; i<pWriter->nDlidx; i++){
190198  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
190199  if( pDlidx->buf.n==0 ) break;
190200  if( bFlush ){
190201  assert( pDlidx->pgno!=0 );
190202  fts5DataWrite(p,
190203  FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
190204  pDlidx->buf.p, pDlidx->buf.n
190205  );
190206  }
190207  sqlite3Fts5BufferZero(&pDlidx->buf);
190208  pDlidx->bPrevValid = 0;
190209  }
190210 }
190211 
190212 /*
190213 ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
190214 ** Any new array elements are zeroed before returning.
190215 */
190216 static int fts5WriteDlidxGrow(
190217  Fts5Index *p,
190218  Fts5SegWriter *pWriter,
190219  int nLvl
190220 ){
190221  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
190222  Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
190223  pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
190224  );
190225  if( aDlidx==0 ){
190226  p->rc = SQLITE_NOMEM;
190227  }else{
190228  int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
190229  memset(&aDlidx[pWriter->nDlidx], 0, nByte);
190230  pWriter->aDlidx = aDlidx;
190231  pWriter->nDlidx = nLvl;
190232  }
190233  }
190234  return p->rc;
190235 }
190236 
190237 /*
190238 ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
190239 ** enough, flush it to disk and return 1. Otherwise discard it and return
190240 ** zero.
190241 */
190242 static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
190243  int bFlag = 0;
190244 
190245  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
190246  ** to the database, also write the doclist-index to disk. */
190247  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
190248  bFlag = 1;
190249  }
190250  fts5WriteDlidxClear(p, pWriter, bFlag);
190251  pWriter->nEmpty = 0;
190252  return bFlag;
190253 }
190254 
190255 /*
190256 ** This function is called whenever processing of the doclist for the
190257 ** last term on leaf page (pWriter->iBtPage) is completed.
190258 **
190259 ** The doclist-index for that term is currently stored in-memory within the
190260 ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
190261 ** writes it out to disk. Or, if it is too small to bother with, discards
190262 ** it.
190263 **
190264 ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
190265 */
190266 static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
190267  int bFlag;
190268 
190269  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
190270  if( pWriter->iBtPage==0 ) return;
190271  bFlag = fts5WriteFlushDlidx(p, pWriter);
190272 
190273  if( p->rc==SQLITE_OK ){
190274  const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
190275  /* The following was already done in fts5WriteInit(): */
190276  /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
190277  sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
190278  sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
190279  sqlite3_step(p->pIdxWriter);
190280  p->rc = sqlite3_reset(p->pIdxWriter);
190281  }
190282  pWriter->iBtPage = 0;
190283 }
190284 
190285 /*
190286 ** This is called once for each leaf page except the first that contains
190287 ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
190288 ** is larger than all terms written to earlier leaves, and equal to or
190289 ** smaller than the first term on the new leaf.
190290 **
190291 ** If an error occurs, an error code is left in Fts5Index.rc. If an error
190292 ** has already occurred when this function is called, it is a no-op.
190293 */
190294 static void fts5WriteBtreeTerm(
190295  Fts5Index *p, /* FTS5 backend object */
190296  Fts5SegWriter *pWriter, /* Writer object */
190297  int nTerm, const u8 *pTerm /* First term on new page */
190298 ){
190299  fts5WriteFlushBtree(p, pWriter);
190300  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
190301  pWriter->iBtPage = pWriter->writer.pgno;
190302 }
190303 
190304 /*
190305 ** This function is called when flushing a leaf page that contains no
190306 ** terms at all to disk.
190307 */
190308 static void fts5WriteBtreeNoTerm(
190309  Fts5Index *p, /* FTS5 backend object */
190310  Fts5SegWriter *pWriter /* Writer object */
190311 ){
190312  /* If there were no rowids on the leaf page either and the doclist-index
190313  ** has already been started, append an 0x00 byte to it. */
190314  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
190315  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
190316  assert( pDlidx->bPrevValid );
190317  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
190318  }
190319 
190320  /* Increment the "number of sequential leaves without a term" counter. */
190321  pWriter->nEmpty++;
190322 }
190323 
190324 static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
190325  i64 iRowid;
190326  int iOff;
190327 
190328  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
190329  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
190330  return iRowid;
190331 }
190332 
190333 /*
190334 ** Rowid iRowid has just been appended to the current leaf page. It is the
190335 ** first on the page. This function appends an appropriate entry to the current
190336 ** doclist-index.
190337 */
190338 static void fts5WriteDlidxAppend(
190339  Fts5Index *p,
190340  Fts5SegWriter *pWriter,
190341  i64 iRowid
190342 ){
190343  int i;
190344  int bDone = 0;
190345 
190346  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
190347  i64 iVal;
190348  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
190349 
190350  if( pDlidx->buf.n>=p->pConfig->pgsz ){
190351  /* The current doclist-index page is full. Write it to disk and push
190352  ** a copy of iRowid (which will become the first rowid on the next
190353  ** doclist-index leaf page) up into the next level of the b-tree
190354  ** hierarchy. If the node being flushed is currently the root node,
190355  ** also push its first rowid upwards. */
190356  pDlidx->buf.p[0] = 0x01; /* Not the root node */
190357  fts5DataWrite(p,
190358  FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
190359  pDlidx->buf.p, pDlidx->buf.n
190360  );
190361  fts5WriteDlidxGrow(p, pWriter, i+2);
190362  pDlidx = &pWriter->aDlidx[i];
190363  if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
190364  i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
190365 
190366  /* This was the root node. Push its first rowid up to the new root. */
190367  pDlidx[1].pgno = pDlidx->pgno;
190368  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
190369  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
190370  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
190371  pDlidx[1].bPrevValid = 1;
190372  pDlidx[1].iPrev = iFirst;
190373  }
190374 
190375  sqlite3Fts5BufferZero(&pDlidx->buf);
190376  pDlidx->bPrevValid = 0;
190377  pDlidx->pgno++;
190378  }else{
190379  bDone = 1;
190380  }
190381 
190382  if( pDlidx->bPrevValid ){
190383  iVal = iRowid - pDlidx->iPrev;
190384  }else{
190385  i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
190386  assert( pDlidx->buf.n==0 );
190387  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
190388  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
190389  iVal = iRowid;
190390  }
190391 
190392  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
190393  pDlidx->bPrevValid = 1;
190394  pDlidx->iPrev = iRowid;
190395  }
190396 }
190397 
190398 static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
190399  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
190400  Fts5PageWriter *pPage = &pWriter->writer;
190401  i64 iRowid;
190402 
190403 static int nCall = 0;
190404 nCall++;
190405 
190406  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
190407 
190408  /* Set the szLeaf header field. */
190409  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
190410  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
190411 
190412  if( pWriter->bFirstTermInPage ){
190413  /* No term was written to this page. */
190414  assert( pPage->pgidx.n==0 );
190415  fts5WriteBtreeNoTerm(p, pWriter);
190416  }else{
190417  /* Append the pgidx to the page buffer. Set the szLeaf header field. */
190418  fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
190419  }
190420 
190421  /* Write the page out to disk */
190422  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
190423  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
190424 
190425  /* Initialize the next page. */
190426  fts5BufferZero(&pPage->buf);
190427  fts5BufferZero(&pPage->pgidx);
190428  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
190429  pPage->iPrevPgidx = 0;
190430  pPage->pgno++;
190431 
190432  /* Increase the leaves written counter */
190433  pWriter->nLeafWritten++;
190434 
190435  /* The new leaf holds no terms or rowids */
190436  pWriter->bFirstTermInPage = 1;
190437  pWriter->bFirstRowidInPage = 1;
190438 }
190439 
190440 /*
190441 ** Append term pTerm/nTerm to the segment being written by the writer passed
190442 ** as the second argument.
190443 **
190444 ** If an error occurs, set the Fts5Index.rc error code. If an error has
190445 ** already occurred, this function is a no-op.
190446 */
190447 static void fts5WriteAppendTerm(
190448  Fts5Index *p,
190449  Fts5SegWriter *pWriter,
190450  int nTerm, const u8 *pTerm
190451 ){
190452  int nPrefix; /* Bytes of prefix compression for term */
190453  Fts5PageWriter *pPage = &pWriter->writer;
190454  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
190455 
190456  assert( p->rc==SQLITE_OK );
190457  assert( pPage->buf.n>=4 );
190458  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
190459 
190460  /* If the current leaf page is full, flush it to disk. */
190461  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
190462  if( pPage->buf.n>4 ){
190463  fts5WriteFlushLeaf(p, pWriter);
190464  }
190465  fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
190466  }
190467 
190468  /* TODO1: Updating pgidx here. */
190469  pPgidx->n += sqlite3Fts5PutVarint(
190470  &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
190471  );
190472  pPage->iPrevPgidx = pPage->buf.n;
190473 #if 0
190474  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
190475  pPgidx->n += 2;
190476 #endif
190477 
190478  if( pWriter->bFirstTermInPage ){
190479  nPrefix = 0;
190480  if( pPage->pgno!=1 ){
190481  /* This is the first term on a leaf that is not the leftmost leaf in
190482  ** the segment b-tree. In this case it is necessary to add a term to
190483  ** the b-tree hierarchy that is (a) larger than the largest term
190484  ** already written to the segment and (b) smaller than or equal to
190485  ** this term. In other words, a prefix of (pTerm/nTerm) that is one
190486  ** byte longer than the longest prefix (pTerm/nTerm) shares with the
190487  ** previous term.
190488  **
190489  ** Usually, the previous term is available in pPage->term. The exception
190490  ** is if this is the first term written in an incremental-merge step.
190491  ** In this case the previous term is not available, so just write a
190492  ** copy of (pTerm/nTerm) into the parent node. This is slightly
190493  ** inefficient, but still correct. */
190494  int n = nTerm;
190495  if( pPage->term.n ){
190496  n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
190497  }
190498  fts5WriteBtreeTerm(p, pWriter, n, pTerm);
190499  pPage = &pWriter->writer;
190500  }
190501  }else{
190502  nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
190503  fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
190504  }
190505 
190506  /* Append the number of bytes of new data, then the term data itself
190507  ** to the page. */
190508  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
190509  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
190510 
190511  /* Update the Fts5PageWriter.term field. */
190512  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
190513  pWriter->bFirstTermInPage = 0;
190514 
190515  pWriter->bFirstRowidInPage = 0;
190516  pWriter->bFirstRowidInDoclist = 1;
190517 
190518  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
190519  pWriter->aDlidx[0].pgno = pPage->pgno;
190520 }
190521 
190522 /*
190523 ** Append a rowid and position-list size field to the writers output.
190524 */
190525 static void fts5WriteAppendRowid(
190526  Fts5Index *p,
190527  Fts5SegWriter *pWriter,
190528  i64 iRowid
190529 ){
190530  if( p->rc==SQLITE_OK ){
190531  Fts5PageWriter *pPage = &pWriter->writer;
190532 
190533  if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
190534  fts5WriteFlushLeaf(p, pWriter);
190535  }
190536 
190537  /* If this is to be the first rowid written to the page, set the
190538  ** rowid-pointer in the page-header. Also append a value to the dlidx
190539  ** buffer, in case a doclist-index is required. */
190540  if( pWriter->bFirstRowidInPage ){
190541  fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
190542  fts5WriteDlidxAppend(p, pWriter, iRowid);
190543  }
190544 
190545  /* Write the rowid. */
190546  if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
190547  fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
190548  }else{
190549  assert( p->rc || iRowid>pWriter->iPrevRowid );
190550  fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
190551  }
190552  pWriter->iPrevRowid = iRowid;
190553  pWriter->bFirstRowidInDoclist = 0;
190554  pWriter->bFirstRowidInPage = 0;
190555  }
190556 }
190557 
190558 static void fts5WriteAppendPoslistData(
190559  Fts5Index *p,
190560  Fts5SegWriter *pWriter,
190561  const u8 *aData,
190562  int nData
190563 ){
190564  Fts5PageWriter *pPage = &pWriter->writer;
190565  const u8 *a = aData;
190566  int n = nData;
190567 
190568  assert( p->pConfig->pgsz>0 );
190569  while( p->rc==SQLITE_OK
190570  && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
190571  ){
190572  int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
190573  int nCopy = 0;
190574  while( nCopy<nReq ){
190575  i64 dummy;
190576  nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
190577  }
190578  fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
190579  a += nCopy;
190580  n -= nCopy;
190581  fts5WriteFlushLeaf(p, pWriter);
190582  }
190583  if( n>0 ){
190584  fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
190585  }
190586 }
190587 
190588 /*
190589 ** Flush any data cached by the writer object to the database. Free any
190590 ** allocations associated with the writer.
190591 */
190592 static void fts5WriteFinish(
190593  Fts5Index *p,
190594  Fts5SegWriter *pWriter, /* Writer object */
190595  int *pnLeaf /* OUT: Number of leaf pages in b-tree */
190596 ){
190597  int i;
190598  Fts5PageWriter *pLeaf = &pWriter->writer;
190599  if( p->rc==SQLITE_OK ){
190600  assert( pLeaf->pgno>=1 );
190601  if( pLeaf->buf.n>4 ){
190602  fts5WriteFlushLeaf(p, pWriter);
190603  }
190604  *pnLeaf = pLeaf->pgno-1;
190605  if( pLeaf->pgno>1 ){
190606  fts5WriteFlushBtree(p, pWriter);
190607  }
190608  }
190609  fts5BufferFree(&pLeaf->term);
190610  fts5BufferFree(&pLeaf->buf);
190611  fts5BufferFree(&pLeaf->pgidx);
190612  fts5BufferFree(&pWriter->btterm);
190613 
190614  for(i=0; i<pWriter->nDlidx; i++){
190615  sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
190616  }
190617  sqlite3_free(pWriter->aDlidx);
190618 }
190619 
190620 static void fts5WriteInit(
190621  Fts5Index *p,
190622  Fts5SegWriter *pWriter,
190623  int iSegid
190624 ){
190625  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
190626 
190627  memset(pWriter, 0, sizeof(Fts5SegWriter));
190628  pWriter->iSegid = iSegid;
190629 
190630  fts5WriteDlidxGrow(p, pWriter, 1);
190631  pWriter->writer.pgno = 1;
190632  pWriter->bFirstTermInPage = 1;
190633  pWriter->iBtPage = 1;
190634 
190635  assert( pWriter->writer.buf.n==0 );
190636  assert( pWriter->writer.pgidx.n==0 );
190637 
190638  /* Grow the two buffers to pgsz + padding bytes in size. */
190639  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
190640  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
190641 
190642  if( p->pIdxWriter==0 ){
190643  Fts5Config *pConfig = p->pConfig;
190644  fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
190645  "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
190646  pConfig->zDb, pConfig->zName
190647  ));
190648  }
190649 
190650  if( p->rc==SQLITE_OK ){
190651  /* Initialize the 4-byte leaf-page header to 0x00. */
190652  memset(pWriter->writer.buf.p, 0, 4);
190653  pWriter->writer.buf.n = 4;
190654 
190655  /* Bind the current output segment id to the index-writer. This is an
190656  ** optimization over binding the same value over and over as rows are
190657  ** inserted into %_idx by the current writer. */
190658  sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
190659  }
190660 }
190661 
190662 /*
190663 ** Iterator pIter was used to iterate through the input segments of on an
190664 ** incremental merge operation. This function is called if the incremental
190665 ** merge step has finished but the input has not been completely exhausted.
190666 */
190667 static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
190668  int i;
190669  Fts5Buffer buf;
190670  memset(&buf, 0, sizeof(Fts5Buffer));
190671  for(i=0; i<pIter->nSeg; i++){
190672  Fts5SegIter *pSeg = &pIter->aSeg[i];
190673  if( pSeg->pSeg==0 ){
190674  /* no-op */
190675  }else if( pSeg->pLeaf==0 ){
190676  /* All keys from this input segment have been transfered to the output.
190677  ** Set both the first and last page-numbers to 0 to indicate that the
190678  ** segment is now empty. */
190679  pSeg->pSeg->pgnoLast = 0;
190680  pSeg->pSeg->pgnoFirst = 0;
190681  }else{
190682  int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
190683  i64 iLeafRowid;
190684  Fts5Data *pData;
190685  int iId = pSeg->pSeg->iSegid;
190686  u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
190687 
190688  iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
190689  pData = fts5DataRead(p, iLeafRowid);
190690  if( pData ){
190691  fts5BufferZero(&buf);
190692  fts5BufferGrow(&p->rc, &buf, pData->nn);
190693  fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
190694  fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
190695  fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
190696  fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
190697  if( p->rc==SQLITE_OK ){
190698  /* Set the szLeaf field */
190699  fts5PutU16(&buf.p[2], (u16)buf.n);
190700  }
190701 
190702  /* Set up the new page-index array */
190703  fts5BufferAppendVarint(&p->rc, &buf, 4);
190704  if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
190705  && pSeg->iEndofDoclist<pData->szLeaf
190706  ){
190707  int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
190708  fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
190709  fts5BufferAppendBlob(&p->rc, &buf,
190710  pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
190711  );
190712  }
190713 
190714  fts5DataRelease(pData);
190715  pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
190716  fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
190717  fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
190718  }
190719  }
190720  }
190721  fts5BufferFree(&buf);
190722 }
190723 
190724 static void fts5MergeChunkCallback(
190725  Fts5Index *p,
190726  void *pCtx,
190727  const u8 *pChunk, int nChunk
190728 ){
190729  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
190730  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
190731 }
190732 
190733 /*
190734 **
190735 */
190736 static void fts5IndexMergeLevel(
190737  Fts5Index *p, /* FTS5 backend object */
190738  Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
190739  int iLvl, /* Level to read input from */
190740  int *pnRem /* Write up to this many output leaves */
190741 ){
190742  Fts5Structure *pStruct = *ppStruct;
190743  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
190744  Fts5StructureLevel *pLvlOut;
190745  Fts5Iter *pIter = 0; /* Iterator to read input data */
190746  int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
190747  int nInput; /* Number of input segments */
190748  Fts5SegWriter writer; /* Writer object */
190749  Fts5StructureSegment *pSeg; /* Output segment */
190750  Fts5Buffer term;
190751  int bOldest; /* True if the output segment is the oldest */
190752  int eDetail = p->pConfig->eDetail;
190753  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
190754 
190755  assert( iLvl<pStruct->nLevel );
190756  assert( pLvl->nMerge<=pLvl->nSeg );
190757 
190758  memset(&writer, 0, sizeof(Fts5SegWriter));
190759  memset(&term, 0, sizeof(Fts5Buffer));
190760  if( pLvl->nMerge ){
190761  pLvlOut = &pStruct->aLevel[iLvl+1];
190762  assert( pLvlOut->nSeg>0 );
190763  nInput = pLvl->nMerge;
190764  pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
190765 
190766  fts5WriteInit(p, &writer, pSeg->iSegid);
190767  writer.writer.pgno = pSeg->pgnoLast+1;
190768  writer.iBtPage = 0;
190769  }else{
190770  int iSegid = fts5AllocateSegid(p, pStruct);
190771 
190772  /* Extend the Fts5Structure object as required to ensure the output
190773  ** segment exists. */
190774  if( iLvl==pStruct->nLevel-1 ){
190775  fts5StructureAddLevel(&p->rc, ppStruct);
190776  pStruct = *ppStruct;
190777  }
190778  fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
190779  if( p->rc ) return;
190780  pLvl = &pStruct->aLevel[iLvl];
190781  pLvlOut = &pStruct->aLevel[iLvl+1];
190782 
190783  fts5WriteInit(p, &writer, iSegid);
190784 
190785  /* Add the new segment to the output level */
190786  pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
190787  pLvlOut->nSeg++;
190788  pSeg->pgnoFirst = 1;
190789  pSeg->iSegid = iSegid;
190790  pStruct->nSegment++;
190791 
190792  /* Read input from all segments in the input level */
190793  nInput = pLvl->nSeg;
190794  }
190795  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
190796 
190797  assert( iLvl>=0 );
190798  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
190799  fts5MultiIterEof(p, pIter)==0;
190800  fts5MultiIterNext(p, pIter, 0, 0)
190801  ){
190802  Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
190803  int nPos; /* position-list size field value */
190804  int nTerm;
190805  const u8 *pTerm;
190806 
190807  /* Check for key annihilation. */
190808  if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
190809 
190810  pTerm = fts5MultiIterTerm(pIter, &nTerm);
190811  if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
190812  if( pnRem && writer.nLeafWritten>nRem ){
190813  break;
190814  }
190815 
190816  /* This is a new term. Append a term to the output segment. */
190817  fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
190818  fts5BufferSet(&p->rc, &term, nTerm, pTerm);
190819  }
190820 
190821  /* Append the rowid to the output */
190822  /* WRITEPOSLISTSIZE */
190823  fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
190824 
190825  if( eDetail==FTS5_DETAIL_NONE ){
190826  if( pSegIter->bDel ){
190827  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
190828  if( pSegIter->nPos>0 ){
190829  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
190830  }
190831  }
190832  }else{
190833  /* Append the position-list data to the output */
190834  nPos = pSegIter->nPos*2 + pSegIter->bDel;
190835  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
190836  fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
190837  }
190838  }
190839 
190840  /* Flush the last leaf page to disk. Set the output segment b-tree height
190841  ** and last leaf page number at the same time. */
190842  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
190843 
190844  if( fts5MultiIterEof(p, pIter) ){
190845  int i;
190846 
190847  /* Remove the redundant segments from the %_data table */
190848  for(i=0; i<nInput; i++){
190849  fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
190850  }
190851 
190852  /* Remove the redundant segments from the input level */
190853  if( pLvl->nSeg!=nInput ){
190854  int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
190855  memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
190856  }
190857  pStruct->nSegment -= nInput;
190858  pLvl->nSeg -= nInput;
190859  pLvl->nMerge = 0;
190860  if( pSeg->pgnoLast==0 ){
190861  pLvlOut->nSeg--;
190862  pStruct->nSegment--;
190863  }
190864  }else{
190865  assert( pSeg->pgnoLast>0 );
190866  fts5TrimSegments(p, pIter);
190867  pLvl->nMerge = nInput;
190868  }
190869 
190870  fts5MultiIterFree(pIter);
190871  fts5BufferFree(&term);
190872  if( pnRem ) *pnRem -= writer.nLeafWritten;
190873 }
190874 
190875 /*
190876 ** Do up to nPg pages of automerge work on the index.
190877 **
190878 ** Return true if any changes were actually made, or false otherwise.
190879 */
190880 static int fts5IndexMerge(
190881  Fts5Index *p, /* FTS5 backend object */
190882  Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
190883  int nPg, /* Pages of work to do */
190884  int nMin /* Minimum number of segments to merge */
190885 ){
190886  int nRem = nPg;
190887  int bRet = 0;
190888  Fts5Structure *pStruct = *ppStruct;
190889  while( nRem>0 && p->rc==SQLITE_OK ){
190890  int iLvl; /* To iterate through levels */
190891  int iBestLvl = 0; /* Level offering the most input segments */
190892  int nBest = 0; /* Number of input segments on best level */
190893 
190894  /* Set iBestLvl to the level to read input segments from. */
190895  assert( pStruct->nLevel>0 );
190896  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190897  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
190898  if( pLvl->nMerge ){
190899  if( pLvl->nMerge>nBest ){
190900  iBestLvl = iLvl;
190901  nBest = pLvl->nMerge;
190902  }
190903  break;
190904  }
190905  if( pLvl->nSeg>nBest ){
190906  nBest = pLvl->nSeg;
190907  iBestLvl = iLvl;
190908  }
190909  }
190910 
190911  /* If nBest is still 0, then the index must be empty. */
190912 #ifdef SQLITE_DEBUG
190913  for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
190914  assert( pStruct->aLevel[iLvl].nSeg==0 );
190915  }
190916 #endif
190917 
190918  if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
190919  break;
190920  }
190921  bRet = 1;
190922  fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
190923  if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
190924  fts5StructurePromote(p, iBestLvl+1, pStruct);
190925  }
190926  }
190927  *ppStruct = pStruct;
190928  return bRet;
190929 }
190930 
190931 /*
190932 ** A total of nLeaf leaf pages of data has just been flushed to a level-0
190933 ** segment. This function updates the write-counter accordingly and, if
190934 ** necessary, performs incremental merge work.
190935 **
190936 ** If an error occurs, set the Fts5Index.rc error code. If an error has
190937 ** already occurred, this function is a no-op.
190938 */
190939 static void fts5IndexAutomerge(
190940  Fts5Index *p, /* FTS5 backend object */
190941  Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
190942  int nLeaf /* Number of output leaves just written */
190943 ){
190944  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
190945  Fts5Structure *pStruct = *ppStruct;
190946  u64 nWrite; /* Initial value of write-counter */
190947  int nWork; /* Number of work-quanta to perform */
190948  int nRem; /* Number of leaf pages left to write */
190949 
190950  /* Update the write-counter. While doing so, set nWork. */
190951  nWrite = pStruct->nWriteCounter;
190952  nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
190953  pStruct->nWriteCounter += nLeaf;
190954  nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
190955 
190956  fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
190957  }
190958 }
190959 
190960 static void fts5IndexCrisismerge(
190961  Fts5Index *p, /* FTS5 backend object */
190962  Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
190963 ){
190964  const int nCrisis = p->pConfig->nCrisisMerge;
190965  Fts5Structure *pStruct = *ppStruct;
190966  int iLvl = 0;
190967 
190968  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
190969  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
190970  fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
190971  assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
190972  fts5StructurePromote(p, iLvl+1, pStruct);
190973  iLvl++;
190974  }
190975  *ppStruct = pStruct;
190976 }
190977 
190978 static int fts5IndexReturn(Fts5Index *p){
190979  int rc = p->rc;
190980  p->rc = SQLITE_OK;
190981  return rc;
190982 }
190983 
190984 typedef struct Fts5FlushCtx Fts5FlushCtx;
190985 struct Fts5FlushCtx {
190986  Fts5Index *pIdx;
190987  Fts5SegWriter writer;
190988 };
190989 
190990 /*
190991 ** Buffer aBuf[] contains a list of varints, all small enough to fit
190992 ** in a 32-bit integer. Return the size of the largest prefix of this
190993 ** list nMax bytes or less in size.
190994 */
190995 static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
190996  int ret;
190997  u32 dummy;
190998  ret = fts5GetVarint32(aBuf, dummy);
190999  if( ret<nMax ){
191000  while( 1 ){
191001  int i = fts5GetVarint32(&aBuf[ret], dummy);
191002  if( (ret + i) > nMax ) break;
191003  ret += i;
191004  }
191005  }
191006  return ret;
191007 }
191008 
191009 /*
191010 ** Flush the contents of in-memory hash table iHash to a new level-0
191011 ** segment on disk. Also update the corresponding structure record.
191012 **
191013 ** If an error occurs, set the Fts5Index.rc error code. If an error has
191014 ** already occurred, this function is a no-op.
191015 */
191016 static void fts5FlushOneHash(Fts5Index *p){
191017  Fts5Hash *pHash = p->pHash;
191018  Fts5Structure *pStruct;
191019  int iSegid;
191020  int pgnoLast = 0; /* Last leaf page number in segment */
191021 
191022  /* Obtain a reference to the index structure and allocate a new segment-id
191023  ** for the new level-0 segment. */
191024  pStruct = fts5StructureRead(p);
191025  iSegid = fts5AllocateSegid(p, pStruct);
191026  fts5StructureInvalidate(p);
191027 
191028  if( iSegid ){
191029  const int pgsz = p->pConfig->pgsz;
191030  int eDetail = p->pConfig->eDetail;
191031  Fts5StructureSegment *pSeg; /* New segment within pStruct */
191032  Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
191033  Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
191034 
191035  Fts5SegWriter writer;
191036  fts5WriteInit(p, &writer, iSegid);
191037 
191038  pBuf = &writer.writer.buf;
191039  pPgidx = &writer.writer.pgidx;
191040 
191041  /* fts5WriteInit() should have initialized the buffers to (most likely)
191042  ** the maximum space required. */
191043  assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
191044  assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
191045 
191046  /* Begin scanning through hash table entries. This loop runs once for each
191047  ** term/doclist currently stored within the hash table. */
191048  if( p->rc==SQLITE_OK ){
191049  p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
191050  }
191051  while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
191052  const char *zTerm; /* Buffer containing term */
191053  const u8 *pDoclist; /* Pointer to doclist for this term */
191054  int nDoclist; /* Size of doclist in bytes */
191055 
191056  /* Write the term for this entry to disk. */
191057  sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
191058  fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
191059 
191060  assert( writer.bFirstRowidInPage==0 );
191061  if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
191062  /* The entire doclist will fit on the current leaf. */
191063  fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
191064  }else{
191065  i64 iRowid = 0;
191066  i64 iDelta = 0;
191067  int iOff = 0;
191068 
191069  /* The entire doclist will not fit on this leaf. The following
191070  ** loop iterates through the poslists that make up the current
191071  ** doclist. */
191072  while( p->rc==SQLITE_OK && iOff<nDoclist ){
191073  iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
191074  iRowid += iDelta;
191075 
191076  if( writer.bFirstRowidInPage ){
191077  fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
191078  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
191079  writer.bFirstRowidInPage = 0;
191080  fts5WriteDlidxAppend(p, &writer, iRowid);
191081  }else{
191082  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
191083  }
191084  assert( pBuf->n<=pBuf->nSpace );
191085 
191086  if( eDetail==FTS5_DETAIL_NONE ){
191087  if( iOff<nDoclist && pDoclist[iOff]==0 ){
191088  pBuf->p[pBuf->n++] = 0;
191089  iOff++;
191090  if( iOff<nDoclist && pDoclist[iOff]==0 ){
191091  pBuf->p[pBuf->n++] = 0;
191092  iOff++;
191093  }
191094  }
191095  if( (pBuf->n + pPgidx->n)>=pgsz ){
191096  fts5WriteFlushLeaf(p, &writer);
191097  }
191098  }else{
191099  int bDummy;
191100  int nPos;
191101  int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
191102  nCopy += nPos;
191103  if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
191104  /* The entire poslist will fit on the current leaf. So copy
191105  ** it in one go. */
191106  fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
191107  }else{
191108  /* The entire poslist will not fit on this leaf. So it needs
191109  ** to be broken into sections. The only qualification being
191110  ** that each varint must be stored contiguously. */
191111  const u8 *pPoslist = &pDoclist[iOff];
191112  int iPos = 0;
191113  while( p->rc==SQLITE_OK ){
191114  int nSpace = pgsz - pBuf->n - pPgidx->n;
191115  int n = 0;
191116  if( (nCopy - iPos)<=nSpace ){
191117  n = nCopy - iPos;
191118  }else{
191119  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
191120  }
191121  assert( n>0 );
191122  fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
191123  iPos += n;
191124  if( (pBuf->n + pPgidx->n)>=pgsz ){
191125  fts5WriteFlushLeaf(p, &writer);
191126  }
191127  if( iPos>=nCopy ) break;
191128  }
191129  }
191130  iOff += nCopy;
191131  }
191132  }
191133  }
191134 
191135  /* TODO2: Doclist terminator written here. */
191136  /* pBuf->p[pBuf->n++] = '\0'; */
191137  assert( pBuf->n<=pBuf->nSpace );
191138  sqlite3Fts5HashScanNext(pHash);
191139  }
191140  sqlite3Fts5HashClear(pHash);
191141  fts5WriteFinish(p, &writer, &pgnoLast);
191142 
191143  /* Update the Fts5Structure. It is written back to the database by the
191144  ** fts5StructureRelease() call below. */
191145  if( pStruct->nLevel==0 ){
191146  fts5StructureAddLevel(&p->rc, &pStruct);
191147  }
191148  fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
191149  if( p->rc==SQLITE_OK ){
191150  pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
191151  pSeg->iSegid = iSegid;
191152  pSeg->pgnoFirst = 1;
191153  pSeg->pgnoLast = pgnoLast;
191154  pStruct->nSegment++;
191155  }
191156  fts5StructurePromote(p, 0, pStruct);
191157  }
191158 
191159  fts5IndexAutomerge(p, &pStruct, pgnoLast);
191160  fts5IndexCrisismerge(p, &pStruct);
191161  fts5StructureWrite(p, pStruct);
191162  fts5StructureRelease(pStruct);
191163 }
191164 
191165 /*
191166 ** Flush any data stored in the in-memory hash tables to the database.
191167 */
191168 static void fts5IndexFlush(Fts5Index *p){
191169  /* Unless it is empty, flush the hash table to disk */
191170  if( p->nPendingData ){
191171  assert( p->pHash );
191172  p->nPendingData = 0;
191173  fts5FlushOneHash(p);
191174  }
191175 }
191176 
191177 static Fts5Structure *fts5IndexOptimizeStruct(
191178  Fts5Index *p,
191179  Fts5Structure *pStruct
191180 ){
191181  Fts5Structure *pNew = 0;
191182  int nByte = sizeof(Fts5Structure);
191183  int nSeg = pStruct->nSegment;
191184  int i;
191185 
191186  /* Figure out if this structure requires optimization. A structure does
191187  ** not require optimization if either:
191188  **
191189  ** + it consists of fewer than two segments, or
191190  ** + all segments are on the same level, or
191191  ** + all segments except one are currently inputs to a merge operation.
191192  **
191193  ** In the first case, return NULL. In the second, increment the ref-count
191194  ** on *pStruct and return a copy of the pointer to it.
191195  */
191196  if( nSeg<2 ) return 0;
191197  for(i=0; i<pStruct->nLevel; i++){
191198  int nThis = pStruct->aLevel[i].nSeg;
191199  if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
191200  fts5StructureRef(pStruct);
191201  return pStruct;
191202  }
191203  assert( pStruct->aLevel[i].nMerge<=nThis );
191204  }
191205 
191206  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
191207  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
191208 
191209  if( pNew ){
191210  Fts5StructureLevel *pLvl;
191211  nByte = nSeg * sizeof(Fts5StructureSegment);
191212  pNew->nLevel = pStruct->nLevel+1;
191213  pNew->nRef = 1;
191214  pNew->nWriteCounter = pStruct->nWriteCounter;
191215  pLvl = &pNew->aLevel[pStruct->nLevel];
191216  pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
191217  if( pLvl->aSeg ){
191218  int iLvl, iSeg;
191219  int iSegOut = 0;
191220  /* Iterate through all segments, from oldest to newest. Add them to
191221  ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
191222  ** segment in the data structure. */
191223  for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
191224  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
191225  pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
191226  iSegOut++;
191227  }
191228  }
191229  pNew->nSegment = pLvl->nSeg = nSeg;
191230  }else{
191231  sqlite3_free(pNew);
191232  pNew = 0;
191233  }
191234  }
191235 
191236  return pNew;
191237 }
191238 
191239 static int sqlite3Fts5IndexOptimize(Fts5Index *p){
191240  Fts5Structure *pStruct;
191241  Fts5Structure *pNew = 0;
191242 
191243  assert( p->rc==SQLITE_OK );
191244  fts5IndexFlush(p);
191245  pStruct = fts5StructureRead(p);
191246  fts5StructureInvalidate(p);
191247 
191248  if( pStruct ){
191249  pNew = fts5IndexOptimizeStruct(p, pStruct);
191250  }
191251  fts5StructureRelease(pStruct);
191252 
191253  assert( pNew==0 || pNew->nSegment>0 );
191254  if( pNew ){
191255  int iLvl;
191256  for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
191257  while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
191258  int nRem = FTS5_OPT_WORK_UNIT;
191259  fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
191260  }
191261 
191262  fts5StructureWrite(p, pNew);
191263  fts5StructureRelease(pNew);
191264  }
191265 
191266  return fts5IndexReturn(p);
191267 }
191268 
191269 /*
191270 ** This is called to implement the special "VALUES('merge', $nMerge)"
191271 ** INSERT command.
191272 */
191273 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
191274  Fts5Structure *pStruct = fts5StructureRead(p);
191275  if( pStruct ){
191276  int nMin = p->pConfig->nUsermerge;
191277  fts5StructureInvalidate(p);
191278  if( nMerge<0 ){
191279  Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
191280  fts5StructureRelease(pStruct);
191281  pStruct = pNew;
191282  nMin = 2;
191283  nMerge = nMerge*-1;
191284  }
191285  if( pStruct && pStruct->nLevel ){
191286  if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
191287  fts5StructureWrite(p, pStruct);
191288  }
191289  }
191290  fts5StructureRelease(pStruct);
191291  }
191292  return fts5IndexReturn(p);
191293 }
191294 
191295 static void fts5AppendRowid(
191296  Fts5Index *p,
191297  i64 iDelta,
191298  Fts5Iter *pUnused,
191299  Fts5Buffer *pBuf
191300 ){
191301  UNUSED_PARAM(pUnused);
191302  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
191303 }
191304 
191305 static void fts5AppendPoslist(
191306  Fts5Index *p,
191307  i64 iDelta,
191308  Fts5Iter *pMulti,
191309  Fts5Buffer *pBuf
191310 ){
191311  int nData = pMulti->base.nData;
191312  assert( nData>0 );
191313  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
191314  fts5BufferSafeAppendVarint(pBuf, iDelta);
191315  fts5BufferSafeAppendVarint(pBuf, nData*2);
191316  fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
191317  }
191318 }
191319 
191320 
191321 static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
191322  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
191323 
191324  assert( pIter->aPoslist );
191325  if( p>=pIter->aEof ){
191326  pIter->aPoslist = 0;
191327  }else{
191328  i64 iDelta;
191329 
191330  p += fts5GetVarint(p, (u64*)&iDelta);
191331  pIter->iRowid += iDelta;
191332 
191333  /* Read position list size */
191334  if( p[0] & 0x80 ){
191335  int nPos;
191336  pIter->nSize = fts5GetVarint32(p, nPos);
191337  pIter->nPoslist = (nPos>>1);
191338  }else{
191339  pIter->nPoslist = ((int)(p[0])) >> 1;
191340  pIter->nSize = 1;
191341  }
191342 
191343  pIter->aPoslist = p;
191344  }
191345 }
191346 
191347 static void fts5DoclistIterInit(
191348  Fts5Buffer *pBuf,
191349  Fts5DoclistIter *pIter
191350 ){
191351  memset(pIter, 0, sizeof(*pIter));
191352  pIter->aPoslist = pBuf->p;
191353  pIter->aEof = &pBuf->p[pBuf->n];
191354  fts5DoclistIterNext(pIter);
191355 }
191356 
191357 #if 0
191358 /*
191359 ** Append a doclist to buffer pBuf.
191360 **
191361 ** This function assumes that space within the buffer has already been
191362 ** allocated.
191363 */
191364 static void fts5MergeAppendDocid(
191365  Fts5Buffer *pBuf, /* Buffer to write to */
191366  i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
191367  i64 iRowid /* Rowid to append */
191368 ){
191369  assert( pBuf->n!=0 || (*piLastRowid)==0 );
191370  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
191371  *piLastRowid = iRowid;
191372 }
191373 #endif
191374 
191375 #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
191376  assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
191377  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
191378  (iLastRowid) = (iRowid); \
191379 }
191380 
191381 /*
191382 ** Swap the contents of buffer *p1 with that of *p2.
191383 */
191384 static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
191385  Fts5Buffer tmp = *p1;
191386  *p1 = *p2;
191387  *p2 = tmp;
191388 }
191389 
191390 static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
191391  int i = *piOff;
191392  if( i>=pBuf->n ){
191393  *piOff = -1;
191394  }else{
191395  u64 iVal;
191396  *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
191397  *piRowid += iVal;
191398  }
191399 }
191400 
191401 /*
191402 ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
191403 ** In this case the buffers consist of a delta-encoded list of rowids only.
191404 */
191405 static void fts5MergeRowidLists(
191406  Fts5Index *p, /* FTS5 backend object */
191407  Fts5Buffer *p1, /* First list to merge */
191408  Fts5Buffer *p2 /* Second list to merge */
191409 ){
191410  int i1 = 0;
191411  int i2 = 0;
191412  i64 iRowid1 = 0;
191413  i64 iRowid2 = 0;
191414  i64 iOut = 0;
191415 
191416  Fts5Buffer out;
191417  memset(&out, 0, sizeof(out));
191418  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
191419  if( p->rc ) return;
191420 
191421  fts5NextRowid(p1, &i1, &iRowid1);
191422  fts5NextRowid(p2, &i2, &iRowid2);
191423  while( i1>=0 || i2>=0 ){
191424  if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
191425  assert( iOut==0 || iRowid1>iOut );
191426  fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
191427  iOut = iRowid1;
191428  fts5NextRowid(p1, &i1, &iRowid1);
191429  }else{
191430  assert( iOut==0 || iRowid2>iOut );
191431  fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
191432  iOut = iRowid2;
191433  if( i1>=0 && iRowid1==iRowid2 ){
191434  fts5NextRowid(p1, &i1, &iRowid1);
191435  }
191436  fts5NextRowid(p2, &i2, &iRowid2);
191437  }
191438  }
191439 
191440  fts5BufferSwap(&out, p1);
191441  fts5BufferFree(&out);
191442 }
191443 
191444 /*
191445 ** Buffers p1 and p2 contain doclists. This function merges the content
191446 ** of the two doclists together and sets buffer p1 to the result before
191447 ** returning.
191448 **
191449 ** If an error occurs, an error code is left in p->rc. If an error has
191450 ** already occurred, this function is a no-op.
191451 */
191452 static void fts5MergePrefixLists(
191453  Fts5Index *p, /* FTS5 backend object */
191454  Fts5Buffer *p1, /* First list to merge */
191455  Fts5Buffer *p2 /* Second list to merge */
191456 ){
191457  if( p2->n ){
191458  i64 iLastRowid = 0;
191459  Fts5DoclistIter i1;
191460  Fts5DoclistIter i2;
191461  Fts5Buffer out = {0, 0, 0};
191462  Fts5Buffer tmp = {0, 0, 0};
191463 
191464  if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
191465  fts5DoclistIterInit(p1, &i1);
191466  fts5DoclistIterInit(p2, &i2);
191467 
191468  while( 1 ){
191469  if( i1.iRowid<i2.iRowid ){
191470  /* Copy entry from i1 */
191471  fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
191472  fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
191473  fts5DoclistIterNext(&i1);
191474  if( i1.aPoslist==0 ) break;
191475  }
191476  else if( i2.iRowid!=i1.iRowid ){
191477  /* Copy entry from i2 */
191478  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
191479  fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
191480  fts5DoclistIterNext(&i2);
191481  if( i2.aPoslist==0 ) break;
191482  }
191483  else{
191484  /* Merge the two position lists. */
191485  i64 iPos1 = 0;
191486  i64 iPos2 = 0;
191487  int iOff1 = 0;
191488  int iOff2 = 0;
191489  u8 *a1 = &i1.aPoslist[i1.nSize];
191490  u8 *a2 = &i2.aPoslist[i2.nSize];
191491 
191492  i64 iPrev = 0;
191493  Fts5PoslistWriter writer;
191494  memset(&writer, 0, sizeof(writer));
191495 
191496  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
191497  fts5BufferZero(&tmp);
191498  sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
191499  if( p->rc ) break;
191500 
191501  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
191502  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
191503  assert( iPos1>=0 && iPos2>=0 );
191504 
191505  if( iPos1<iPos2 ){
191506  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
191507  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
191508  }else{
191509  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
191510  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
191511  }
191512 
191513  if( iPos1>=0 && iPos2>=0 ){
191514  while( 1 ){
191515  if( iPos1<iPos2 ){
191516  if( iPos1!=iPrev ){
191517  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
191518  }
191519  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
191520  if( iPos1<0 ) break;
191521  }else{
191522  assert( iPos2!=iPrev );
191523  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
191524  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
191525  if( iPos2<0 ) break;
191526  }
191527  }
191528  }
191529 
191530  if( iPos1>=0 ){
191531  if( iPos1!=iPrev ){
191532  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
191533  }
191534  fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
191535  }else{
191536  assert( iPos2>=0 && iPos2!=iPrev );
191537  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
191538  fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
191539  }
191540 
191541  /* WRITEPOSLISTSIZE */
191542  fts5BufferSafeAppendVarint(&out, tmp.n * 2);
191543  fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
191544  fts5DoclistIterNext(&i1);
191545  fts5DoclistIterNext(&i2);
191546  if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
191547  }
191548  }
191549 
191550  if( i1.aPoslist ){
191551  fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
191552  fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
191553  }
191554  else if( i2.aPoslist ){
191555  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
191556  fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
191557  }
191558 
191559  fts5BufferSet(&p->rc, p1, out.n, out.p);
191560  fts5BufferFree(&tmp);
191561  fts5BufferFree(&out);
191562  }
191563 }
191564 
191565 static void fts5SetupPrefixIter(
191566  Fts5Index *p, /* Index to read from */
191567  int bDesc, /* True for "ORDER BY rowid DESC" */
191568  const u8 *pToken, /* Buffer containing prefix to match */
191569  int nToken, /* Size of buffer pToken in bytes */
191570  Fts5Colset *pColset, /* Restrict matches to these columns */
191571  Fts5Iter **ppIter /* OUT: New iterator */
191572 ){
191573  Fts5Structure *pStruct;
191574  Fts5Buffer *aBuf;
191575  const int nBuf = 32;
191576 
191577  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
191578  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
191579  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
191580  xMerge = fts5MergeRowidLists;
191581  xAppend = fts5AppendRowid;
191582  }else{
191583  xMerge = fts5MergePrefixLists;
191584  xAppend = fts5AppendPoslist;
191585  }
191586 
191587  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
191588  pStruct = fts5StructureRead(p);
191589 
191590  if( aBuf && pStruct ){
191591  const int flags = FTS5INDEX_QUERY_SCAN
191592  | FTS5INDEX_QUERY_SKIPEMPTY
191593  | FTS5INDEX_QUERY_NOOUTPUT;
191594  int i;
191595  i64 iLastRowid = 0;
191596  Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
191597  Fts5Data *pData;
191598  Fts5Buffer doclist;
191599  int bNewTerm = 1;
191600 
191601  memset(&doclist, 0, sizeof(doclist));
191602  fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
191603  fts5IterSetOutputCb(&p->rc, p1);
191604  for( /* no-op */ ;
191605  fts5MultiIterEof(p, p1)==0;
191606  fts5MultiIterNext2(p, p1, &bNewTerm)
191607  ){
191608  Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
191609  int nTerm = pSeg->term.n;
191610  const u8 *pTerm = pSeg->term.p;
191611  p1->xSetOutputs(p1, pSeg);
191612 
191613  assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
191614  if( bNewTerm ){
191615  if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
191616  }
191617 
191618  if( p1->base.nData==0 ) continue;
191619 
191620  if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
191621  for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
191622  assert( i<nBuf );
191623  if( aBuf[i].n==0 ){
191624  fts5BufferSwap(&doclist, &aBuf[i]);
191625  fts5BufferZero(&doclist);
191626  }else{
191627  xMerge(p, &doclist, &aBuf[i]);
191628  fts5BufferZero(&aBuf[i]);
191629  }
191630  }
191631  iLastRowid = 0;
191632  }
191633 
191634  xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
191635  iLastRowid = p1->base.iRowid;
191636  }
191637 
191638  for(i=0; i<nBuf; i++){
191639  if( p->rc==SQLITE_OK ){
191640  xMerge(p, &doclist, &aBuf[i]);
191641  }
191642  fts5BufferFree(&aBuf[i]);
191643  }
191644  fts5MultiIterFree(p1);
191645 
191646  pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
191647  if( pData ){
191648  pData->p = (u8*)&pData[1];
191649  pData->nn = pData->szLeaf = doclist.n;
191650  memcpy(pData->p, doclist.p, doclist.n);
191651  fts5MultiIterNew2(p, pData, bDesc, ppIter);
191652  }
191653  fts5BufferFree(&doclist);
191654  }
191655 
191656  fts5StructureRelease(pStruct);
191657  sqlite3_free(aBuf);
191658 }
191659 
191660 
191661 /*
191662 ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
191663 ** to the document with rowid iRowid.
191664 */
191665 static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
191666  assert( p->rc==SQLITE_OK );
191667 
191668  /* Allocate the hash table if it has not already been allocated */
191669  if( p->pHash==0 ){
191670  p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
191671  }
191672 
191673  /* Flush the hash table to disk if required */
191674  if( iRowid<p->iWriteRowid
191675  || (iRowid==p->iWriteRowid && p->bDelete==0)
191676  || (p->nPendingData > p->pConfig->nHashSize)
191677  ){
191678  fts5IndexFlush(p);
191679  }
191680 
191681  p->iWriteRowid = iRowid;
191682  p->bDelete = bDelete;
191683  return fts5IndexReturn(p);
191684 }
191685 
191686 /*
191687 ** Commit data to disk.
191688 */
191689 static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
191690  assert( p->rc==SQLITE_OK );
191691  fts5IndexFlush(p);
191692  if( bCommit ) fts5CloseReader(p);
191693  return fts5IndexReturn(p);
191694 }
191695 
191696 /*
191697 ** Discard any data stored in the in-memory hash tables. Do not write it
191698 ** to the database. Additionally, assume that the contents of the %_data
191699 ** table may have changed on disk. So any in-memory caches of %_data
191700 ** records must be invalidated.
191701 */
191702 static int sqlite3Fts5IndexRollback(Fts5Index *p){
191703  fts5CloseReader(p);
191704  fts5IndexDiscardData(p);
191705  fts5StructureInvalidate(p);
191706  /* assert( p->rc==SQLITE_OK ); */
191707  return SQLITE_OK;
191708 }
191709 
191710 /*
191711 ** The %_data table is completely empty when this function is called. This
191712 ** function populates it with the initial structure objects for each index,
191713 ** and the initial version of the "averages" record (a zero-byte blob).
191714 */
191715 static int sqlite3Fts5IndexReinit(Fts5Index *p){
191716  Fts5Structure s;
191717  fts5StructureInvalidate(p);
191718  memset(&s, 0, sizeof(Fts5Structure));
191719  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
191720  fts5StructureWrite(p, &s);
191721  return fts5IndexReturn(p);
191722 }
191723 
191724 /*
191725 ** Open a new Fts5Index handle. If the bCreate argument is true, create
191726 ** and initialize the underlying %_data table.
191727 **
191728 ** If successful, set *pp to point to the new object and return SQLITE_OK.
191729 ** Otherwise, set *pp to NULL and return an SQLite error code.
191730 */
191731 static int sqlite3Fts5IndexOpen(
191732  Fts5Config *pConfig,
191733  int bCreate,
191734  Fts5Index **pp,
191735  char **pzErr
191736 ){
191737  int rc = SQLITE_OK;
191738  Fts5Index *p; /* New object */
191739 
191740  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
191741  if( rc==SQLITE_OK ){
191742  p->pConfig = pConfig;
191743  p->nWorkUnit = FTS5_WORK_UNIT;
191744  p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
191745  if( p->zDataTbl && bCreate ){
191746  rc = sqlite3Fts5CreateTable(
191747  pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
191748  );
191749  if( rc==SQLITE_OK ){
191750  rc = sqlite3Fts5CreateTable(pConfig, "idx",
191751  "segid, term, pgno, PRIMARY KEY(segid, term)",
191752  1, pzErr
191753  );
191754  }
191755  if( rc==SQLITE_OK ){
191756  rc = sqlite3Fts5IndexReinit(p);
191757  }
191758  }
191759  }
191760 
191761  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
191762  if( rc ){
191763  sqlite3Fts5IndexClose(p);
191764  *pp = 0;
191765  }
191766  return rc;
191767 }
191768 
191769 /*
191770 ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
191771 */
191772 static int sqlite3Fts5IndexClose(Fts5Index *p){
191773  int rc = SQLITE_OK;
191774  if( p ){
191775  assert( p->pReader==0 );
191776  fts5StructureInvalidate(p);
191777  sqlite3_finalize(p->pWriter);
191778  sqlite3_finalize(p->pDeleter);
191779  sqlite3_finalize(p->pIdxWriter);
191780  sqlite3_finalize(p->pIdxDeleter);
191781  sqlite3_finalize(p->pIdxSelect);
191782  sqlite3_finalize(p->pDataVersion);
191783  sqlite3Fts5HashFree(p->pHash);
191784  sqlite3_free(p->zDataTbl);
191785  sqlite3_free(p);
191786  }
191787  return rc;
191788 }
191789 
191790 /*
191791 ** Argument p points to a buffer containing utf-8 text that is n bytes in
191792 ** size. Return the number of bytes in the nChar character prefix of the
191793 ** buffer, or 0 if there are less than nChar characters in total.
191794 */
191795 static int sqlite3Fts5IndexCharlenToBytelen(
191796  const char *p,
191797  int nByte,
191798  int nChar
191799 ){
191800  int n = 0;
191801  int i;
191802  for(i=0; i<nChar; i++){
191803  if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
191804  if( (unsigned char)p[n++]>=0xc0 ){
191805  while( (p[n] & 0xc0)==0x80 ) n++;
191806  }
191807  }
191808  return n;
191809 }
191810 
191811 /*
191812 ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
191813 ** unicode characters in the string.
191814 */
191815 static int fts5IndexCharlen(const char *pIn, int nIn){
191816  int nChar = 0;
191817  int i = 0;
191818  while( i<nIn ){
191819  if( (unsigned char)pIn[i++]>=0xc0 ){
191820  while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
191821  }
191822  nChar++;
191823  }
191824  return nChar;
191825 }
191826 
191827 /*
191828 ** Insert or remove data to or from the index. Each time a document is
191829 ** added to or removed from the index, this function is called one or more
191830 ** times.
191831 **
191832 ** For an insert, it must be called once for each token in the new document.
191833 ** If the operation is a delete, it must be called (at least) once for each
191834 ** unique token in the document with an iCol value less than zero. The iPos
191835 ** argument is ignored for a delete.
191836 */
191837 static int sqlite3Fts5IndexWrite(
191838  Fts5Index *p, /* Index to write to */
191839  int iCol, /* Column token appears in (-ve -> delete) */
191840  int iPos, /* Position of token within column */
191841  const char *pToken, int nToken /* Token to add or remove to or from index */
191842 ){
191843  int i; /* Used to iterate through indexes */
191844  int rc = SQLITE_OK; /* Return code */
191845  Fts5Config *pConfig = p->pConfig;
191846 
191847  assert( p->rc==SQLITE_OK );
191848  assert( (iCol<0)==p->bDelete );
191849 
191850  /* Add the entry to the main terms index. */
191851  rc = sqlite3Fts5HashWrite(
191852  p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
191853  );
191854 
191855  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
191856  const int nChar = pConfig->aPrefix[i];
191857  int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
191858  if( nByte ){
191859  rc = sqlite3Fts5HashWrite(p->pHash,
191860  p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
191861  nByte
191862  );
191863  }
191864  }
191865 
191866  return rc;
191867 }
191868 
191869 /*
191870 ** Open a new iterator to iterate though all rowid that match the
191871 ** specified token or token prefix.
191872 */
191873 static int sqlite3Fts5IndexQuery(
191874  Fts5Index *p, /* FTS index to query */
191875  const char *pToken, int nToken, /* Token (or prefix) to query for */
191876  int flags, /* Mask of FTS5INDEX_QUERY_X flags */
191877  Fts5Colset *pColset, /* Match these columns only */
191878  Fts5IndexIter **ppIter /* OUT: New iterator object */
191879 ){
191880  Fts5Config *pConfig = p->pConfig;
191881  Fts5Iter *pRet = 0;
191882  Fts5Buffer buf = {0, 0, 0};
191883 
191884  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
191885  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
191886 
191887  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
191888  int iIdx = 0; /* Index to search */
191889  memcpy(&buf.p[1], pToken, nToken);
191890 
191891  /* Figure out which index to search and set iIdx accordingly. If this
191892  ** is a prefix query for which there is no prefix index, set iIdx to
191893  ** greater than pConfig->nPrefix to indicate that the query will be
191894  ** satisfied by scanning multiple terms in the main index.
191895  **
191896  ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
191897  ** prefix-query. Instead of using a prefix-index (if one exists),
191898  ** evaluate the prefix query using the main FTS index. This is used
191899  ** for internal sanity checking by the integrity-check in debug
191900  ** mode only. */
191901 #ifdef SQLITE_DEBUG
191902  if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
191903  assert( flags & FTS5INDEX_QUERY_PREFIX );
191904  iIdx = 1+pConfig->nPrefix;
191905  }else
191906 #endif
191907  if( flags & FTS5INDEX_QUERY_PREFIX ){
191908  int nChar = fts5IndexCharlen(pToken, nToken);
191909  for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
191910  if( pConfig->aPrefix[iIdx-1]==nChar ) break;
191911  }
191912  }
191913 
191914  if( iIdx<=pConfig->nPrefix ){
191915  /* Straight index lookup */
191916  Fts5Structure *pStruct = fts5StructureRead(p);
191917  buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
191918  if( pStruct ){
191919  fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
191920  pColset, buf.p, nToken+1, -1, 0, &pRet
191921  );
191922  fts5StructureRelease(pStruct);
191923  }
191924  }else{
191925  /* Scan multiple terms in the main index */
191926  int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
191927  buf.p[0] = FTS5_MAIN_PREFIX;
191928  fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
191929  assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
191930  fts5IterSetOutputCb(&p->rc, pRet);
191931  if( p->rc==SQLITE_OK ){
191932  Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
191933  if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
191934  }
191935  }
191936 
191937  if( p->rc ){
191938  sqlite3Fts5IterClose(&pRet->base);
191939  pRet = 0;
191940  fts5CloseReader(p);
191941  }
191942 
191943  *ppIter = &pRet->base;
191944  sqlite3Fts5BufferFree(&buf);
191945  }
191946  return fts5IndexReturn(p);
191947 }
191948 
191949 /*
191950 ** Return true if the iterator passed as the only argument is at EOF.
191951 */
191952 /*
191953 ** Move to the next matching rowid.
191954 */
191955 static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
191956  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
191957  assert( pIter->pIndex->rc==SQLITE_OK );
191958  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
191959  return fts5IndexReturn(pIter->pIndex);
191960 }
191961 
191962 /*
191963 ** Move to the next matching term/rowid. Used by the fts5vocab module.
191964 */
191965 static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
191966  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
191967  Fts5Index *p = pIter->pIndex;
191968 
191969  assert( pIter->pIndex->rc==SQLITE_OK );
191970 
191971  fts5MultiIterNext(p, pIter, 0, 0);
191972  if( p->rc==SQLITE_OK ){
191973  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
191974  if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
191975  fts5DataRelease(pSeg->pLeaf);
191976  pSeg->pLeaf = 0;
191977  pIter->base.bEof = 1;
191978  }
191979  }
191980 
191981  return fts5IndexReturn(pIter->pIndex);
191982 }
191983 
191984 /*
191985 ** Move to the next matching rowid that occurs at or after iMatch. The
191986 ** definition of "at or after" depends on whether this iterator iterates
191987 ** in ascending or descending rowid order.
191988 */
191989 static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
191990  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
191991  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
191992  return fts5IndexReturn(pIter->pIndex);
191993 }
191994 
191995 /*
191996 ** Return the current term.
191997 */
191998 static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
191999  int n;
192000  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
192001  *pn = n-1;
192002  return &z[1];
192003 }
192004 
192005 /*
192006 ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
192007 */
192008 static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
192009  if( pIndexIter ){
192010  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
192011  Fts5Index *pIndex = pIter->pIndex;
192012  fts5MultiIterFree(pIter);
192013  fts5CloseReader(pIndex);
192014  }
192015 }
192016 
192017 /*
192018 ** Read and decode the "averages" record from the database.
192019 **
192020 ** Parameter anSize must point to an array of size nCol, where nCol is
192021 ** the number of user defined columns in the FTS table.
192022 */
192023 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
192024  int nCol = p->pConfig->nCol;
192025  Fts5Data *pData;
192026 
192027  *pnRow = 0;
192028  memset(anSize, 0, sizeof(i64) * nCol);
192029  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
192030  if( p->rc==SQLITE_OK && pData->nn ){
192031  int i = 0;
192032  int iCol;
192033  i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
192034  for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
192035  i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
192036  }
192037  }
192038 
192039  fts5DataRelease(pData);
192040  return fts5IndexReturn(p);
192041 }
192042 
192043 /*
192044 ** Replace the current "averages" record with the contents of the buffer
192045 ** supplied as the second argument.
192046 */
192047 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
192048  assert( p->rc==SQLITE_OK );
192049  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
192050  return fts5IndexReturn(p);
192051 }
192052 
192053 /*
192054 ** Return the total number of blocks this module has read from the %_data
192055 ** table since it was created.
192056 */
192057 static int sqlite3Fts5IndexReads(Fts5Index *p){
192058  return p->nRead;
192059 }
192060 
192061 /*
192062 ** Set the 32-bit cookie value stored at the start of all structure
192063 ** records to the value passed as the second argument.
192064 **
192065 ** Return SQLITE_OK if successful, or an SQLite error code if an error
192066 ** occurs.
192067 */
192068 static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
192069  int rc; /* Return code */
192070  Fts5Config *pConfig = p->pConfig; /* Configuration object */
192071  u8 aCookie[4]; /* Binary representation of iNew */
192072  sqlite3_blob *pBlob = 0;
192073 
192074  assert( p->rc==SQLITE_OK );
192075  sqlite3Fts5Put32(aCookie, iNew);
192076 
192077  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
192078  "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
192079  );
192080  if( rc==SQLITE_OK ){
192081  sqlite3_blob_write(pBlob, aCookie, 4, 0);
192082  rc = sqlite3_blob_close(pBlob);
192083  }
192084 
192085  return rc;
192086 }
192087 
192088 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
192089  Fts5Structure *pStruct;
192090  pStruct = fts5StructureRead(p);
192091  fts5StructureRelease(pStruct);
192092  return fts5IndexReturn(p);
192093 }
192094 
192095 
192096 /*************************************************************************
192097 **************************************************************************
192098 ** Below this point is the implementation of the integrity-check
192099 ** functionality.
192100 */
192101 
192102 /*
192103 ** Return a simple checksum value based on the arguments.
192104 */
192105 static u64 sqlite3Fts5IndexEntryCksum(
192106  i64 iRowid,
192107  int iCol,
192108  int iPos,
192109  int iIdx,
192110  const char *pTerm,
192111  int nTerm
192112 ){
192113  int i;
192114  u64 ret = iRowid;
192115  ret += (ret<<3) + iCol;
192116  ret += (ret<<3) + iPos;
192117  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
192118  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
192119  return ret;
192120 }
192121 
192122 #ifdef SQLITE_DEBUG
192123 /*
192124 ** This function is purely an internal test. It does not contribute to
192125 ** FTS functionality, or even the integrity-check, in any way.
192126 **
192127 ** Instead, it tests that the same set of pgno/rowid combinations are
192128 ** visited regardless of whether the doclist-index identified by parameters
192129 ** iSegid/iLeaf is iterated in forwards or reverse order.
192130 */
192131 static void fts5TestDlidxReverse(
192132  Fts5Index *p,
192133  int iSegid, /* Segment id to load from */
192134  int iLeaf /* Load doclist-index for this leaf */
192135 ){
192136  Fts5DlidxIter *pDlidx = 0;
192137  u64 cksum1 = 13;
192138  u64 cksum2 = 13;
192139 
192140  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
192141  fts5DlidxIterEof(p, pDlidx)==0;
192142  fts5DlidxIterNext(p, pDlidx)
192143  ){
192144  i64 iRowid = fts5DlidxIterRowid(pDlidx);
192145  int pgno = fts5DlidxIterPgno(pDlidx);
192146  assert( pgno>iLeaf );
192147  cksum1 += iRowid + ((i64)pgno<<32);
192148  }
192149  fts5DlidxIterFree(pDlidx);
192150  pDlidx = 0;
192151 
192152  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
192153  fts5DlidxIterEof(p, pDlidx)==0;
192154  fts5DlidxIterPrev(p, pDlidx)
192155  ){
192156  i64 iRowid = fts5DlidxIterRowid(pDlidx);
192157  int pgno = fts5DlidxIterPgno(pDlidx);
192158  assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
192159  cksum2 += iRowid + ((i64)pgno<<32);
192160  }
192161  fts5DlidxIterFree(pDlidx);
192162  pDlidx = 0;
192163 
192164  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
192165 }
192166 
192167 static int fts5QueryCksum(
192168  Fts5Index *p, /* Fts5 index object */
192169  int iIdx,
192170  const char *z, /* Index key to query for */
192171  int n, /* Size of index key in bytes */
192172  int flags, /* Flags for Fts5IndexQuery */
192173  u64 *pCksum /* IN/OUT: Checksum value */
192174 ){
192175  int eDetail = p->pConfig->eDetail;
192176  u64 cksum = *pCksum;
192177  Fts5IndexIter *pIter = 0;
192178  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
192179 
192180  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
192181  i64 rowid = pIter->iRowid;
192182 
192183  if( eDetail==FTS5_DETAIL_NONE ){
192184  cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
192185  }else{
192186  Fts5PoslistReader sReader;
192187  for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
192188  sReader.bEof==0;
192189  sqlite3Fts5PoslistReaderNext(&sReader)
192190  ){
192191  int iCol = FTS5_POS2COLUMN(sReader.iPos);
192192  int iOff = FTS5_POS2OFFSET(sReader.iPos);
192193  cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
192194  }
192195  }
192196  if( rc==SQLITE_OK ){
192197  rc = sqlite3Fts5IterNext(pIter);
192198  }
192199  }
192200  sqlite3Fts5IterClose(pIter);
192201 
192202  *pCksum = cksum;
192203  return rc;
192204 }
192205 
192206 
192207 /*
192208 ** This function is also purely an internal test. It does not contribute to
192209 ** FTS functionality, or even the integrity-check, in any way.
192210 */
192211 static void fts5TestTerm(
192212  Fts5Index *p,
192213  Fts5Buffer *pPrev, /* Previous term */
192214  const char *z, int n, /* Possibly new term to test */
192215  u64 expected,
192216  u64 *pCksum
192217 ){
192218  int rc = p->rc;
192219  if( pPrev->n==0 ){
192220  fts5BufferSet(&rc, pPrev, n, (const u8*)z);
192221  }else
192222  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
192223  u64 cksum3 = *pCksum;
192224  const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
192225  int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
192226  int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
192227  int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
192228  u64 ck1 = 0;
192229  u64 ck2 = 0;
192230 
192231  /* Check that the results returned for ASC and DESC queries are
192232  ** the same. If not, call this corruption. */
192233  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
192234  if( rc==SQLITE_OK ){
192235  int f = flags|FTS5INDEX_QUERY_DESC;
192236  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
192237  }
192238  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
192239 
192240  /* If this is a prefix query, check that the results returned if the
192241  ** the index is disabled are the same. In both ASC and DESC order.
192242  **
192243  ** This check may only be performed if the hash table is empty. This
192244  ** is because the hash table only supports a single scan query at
192245  ** a time, and the multi-iter loop from which this function is called
192246  ** is already performing such a scan. */
192247  if( p->nPendingData==0 ){
192248  if( iIdx>0 && rc==SQLITE_OK ){
192249  int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
192250  ck2 = 0;
192251  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
192252  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
192253  }
192254  if( iIdx>0 && rc==SQLITE_OK ){
192255  int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
192256  ck2 = 0;
192257  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
192258  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
192259  }
192260  }
192261 
192262  cksum3 ^= ck1;
192263  fts5BufferSet(&rc, pPrev, n, (const u8*)z);
192264 
192265  if( rc==SQLITE_OK && cksum3!=expected ){
192266  rc = FTS5_CORRUPT;
192267  }
192268  *pCksum = cksum3;
192269  }
192270  p->rc = rc;
192271 }
192272 
192273 #else
192274 # define fts5TestDlidxReverse(x,y,z)
192275 # define fts5TestTerm(u,v,w,x,y,z)
192276 #endif
192277 
192278 /*
192279 ** Check that:
192280 **
192281 ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
192282 ** contain zero terms.
192283 ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
192284 ** contain zero rowids.
192285 */
192286 static void fts5IndexIntegrityCheckEmpty(
192287  Fts5Index *p,
192288  Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
192289  int iFirst,
192290  int iNoRowid,
192291  int iLast
192292 ){
192293  int i;
192294 
192295  /* Now check that the iter.nEmpty leaves following the current leaf
192296  ** (a) exist and (b) contain no terms. */
192297  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
192298  Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
192299  if( pLeaf ){
192300  if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
192301  if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
192302  }
192303  fts5DataRelease(pLeaf);
192304  }
192305 }
192306 
192307 static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
192308  int iTermOff = 0;
192309  int ii;
192310 
192311  Fts5Buffer buf1 = {0,0,0};
192312  Fts5Buffer buf2 = {0,0,0};
192313 
192314  ii = pLeaf->szLeaf;
192315  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
192316  int res;
192317  int iOff;
192318  int nIncr;
192319 
192320  ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
192321  iTermOff += nIncr;
192322  iOff = iTermOff;
192323 
192324  if( iOff>=pLeaf->szLeaf ){
192325  p->rc = FTS5_CORRUPT;
192326  }else if( iTermOff==nIncr ){
192327  int nByte;
192328  iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
192329  if( (iOff+nByte)>pLeaf->szLeaf ){
192330  p->rc = FTS5_CORRUPT;
192331  }else{
192332  fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
192333  }
192334  }else{
192335  int nKeep, nByte;
192336  iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
192337  iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
192338  if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
192339  p->rc = FTS5_CORRUPT;
192340  }else{
192341  buf1.n = nKeep;
192342  fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
192343  }
192344 
192345  if( p->rc==SQLITE_OK ){
192346  res = fts5BufferCompare(&buf1, &buf2);
192347  if( res<=0 ) p->rc = FTS5_CORRUPT;
192348  }
192349  }
192350  fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
192351  }
192352 
192353  fts5BufferFree(&buf1);
192354  fts5BufferFree(&buf2);
192355 }
192356 
192357 static void fts5IndexIntegrityCheckSegment(
192358  Fts5Index *p, /* FTS5 backend object */
192359  Fts5StructureSegment *pSeg /* Segment to check internal consistency */
192360 ){
192361  Fts5Config *pConfig = p->pConfig;
192362  sqlite3_stmt *pStmt = 0;
192363  int rc2;
192364  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
192365  int iDlidxPrevLeaf = pSeg->pgnoLast;
192366 
192367  if( pSeg->pgnoFirst==0 ) return;
192368 
192369  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
192370  "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
192371  pConfig->zDb, pConfig->zName, pSeg->iSegid
192372  ));
192373 
192374  /* Iterate through the b-tree hierarchy. */
192375  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
192376  i64 iRow; /* Rowid for this leaf */
192377  Fts5Data *pLeaf; /* Data for this leaf */
192378 
192379  int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
192380  const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
192381  int iIdxLeaf = sqlite3_column_int(pStmt, 2);
192382  int bIdxDlidx = sqlite3_column_int(pStmt, 3);
192383 
192384  /* If the leaf in question has already been trimmed from the segment,
192385  ** ignore this b-tree entry. Otherwise, load it into memory. */
192386  if( iIdxLeaf<pSeg->pgnoFirst ) continue;
192387  iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
192388  pLeaf = fts5DataRead(p, iRow);
192389  if( pLeaf==0 ) break;
192390 
192391  /* Check that the leaf contains at least one term, and that it is equal
192392  ** to or larger than the split-key in zIdxTerm. Also check that if there
192393  ** is also a rowid pointer within the leaf page header, it points to a
192394  ** location before the term. */
192395  if( pLeaf->nn<=pLeaf->szLeaf ){
192396  p->rc = FTS5_CORRUPT;
192397  }else{
192398  int iOff; /* Offset of first term on leaf */
192399  int iRowidOff; /* Offset of first rowid on leaf */
192400  int nTerm; /* Size of term on leaf in bytes */
192401  int res; /* Comparison of term and split-key */
192402 
192403  iOff = fts5LeafFirstTermOff(pLeaf);
192404  iRowidOff = fts5LeafFirstRowidOff(pLeaf);
192405  if( iRowidOff>=iOff ){
192406  p->rc = FTS5_CORRUPT;
192407  }else{
192408  iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
192409  res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
192410  if( res==0 ) res = nTerm - nIdxTerm;
192411  if( res<0 ) p->rc = FTS5_CORRUPT;
192412  }
192413 
192414  fts5IntegrityCheckPgidx(p, pLeaf);
192415  }
192416  fts5DataRelease(pLeaf);
192417  if( p->rc ) break;
192418 
192419  /* Now check that the iter.nEmpty leaves following the current leaf
192420  ** (a) exist and (b) contain no terms. */
192421  fts5IndexIntegrityCheckEmpty(
192422  p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
192423  );
192424  if( p->rc ) break;
192425 
192426  /* If there is a doclist-index, check that it looks right. */
192427  if( bIdxDlidx ){
192428  Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
192429  int iPrevLeaf = iIdxLeaf;
192430  int iSegid = pSeg->iSegid;
192431  int iPg = 0;
192432  i64 iKey;
192433 
192434  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
192435  fts5DlidxIterEof(p, pDlidx)==0;
192436  fts5DlidxIterNext(p, pDlidx)
192437  ){
192438 
192439  /* Check any rowid-less pages that occur before the current leaf. */
192440  for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
192441  iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
192442  pLeaf = fts5DataRead(p, iKey);
192443  if( pLeaf ){
192444  if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
192445  fts5DataRelease(pLeaf);
192446  }
192447  }
192448  iPrevLeaf = fts5DlidxIterPgno(pDlidx);
192449 
192450  /* Check that the leaf page indicated by the iterator really does
192451  ** contain the rowid suggested by the same. */
192452  iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
192453  pLeaf = fts5DataRead(p, iKey);
192454  if( pLeaf ){
192455  i64 iRowid;
192456  int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
192457  ASSERT_SZLEAF_OK(pLeaf);
192458  if( iRowidOff>=pLeaf->szLeaf ){
192459  p->rc = FTS5_CORRUPT;
192460  }else{
192461  fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
192462  if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
192463  }
192464  fts5DataRelease(pLeaf);
192465  }
192466  }
192467 
192468  iDlidxPrevLeaf = iPg;
192469  fts5DlidxIterFree(pDlidx);
192470  fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
192471  }else{
192472  iDlidxPrevLeaf = pSeg->pgnoLast;
192473  /* TODO: Check there is no doclist index */
192474  }
192475 
192476  iIdxPrevLeaf = iIdxLeaf;
192477  }
192478 
192479  rc2 = sqlite3_finalize(pStmt);
192480  if( p->rc==SQLITE_OK ) p->rc = rc2;
192481 
192482  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
192483 #if 0
192484  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
192485  p->rc = FTS5_CORRUPT;
192486  }
192487 #endif
192488 }
192489 
192490 
192491 /*
192492 ** Run internal checks to ensure that the FTS index (a) is internally
192493 ** consistent and (b) contains entries for which the XOR of the checksums
192494 ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
192495 **
192496 ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
192497 ** checksum does not match. Return SQLITE_OK if all checks pass without
192498 ** error, or some other SQLite error code if another error (e.g. OOM)
192499 ** occurs.
192500 */
192501 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
192502  int eDetail = p->pConfig->eDetail;
192503  u64 cksum2 = 0; /* Checksum based on contents of indexes */
192504  Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
192505  Fts5Iter *pIter; /* Used to iterate through entire index */
192506  Fts5Structure *pStruct; /* Index structure */
192507 
192508 #ifdef SQLITE_DEBUG
192509  /* Used by extra internal tests only run if NDEBUG is not defined */
192510  u64 cksum3 = 0; /* Checksum based on contents of indexes */
192511  Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
192512 #endif
192513  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
192514 
192515  /* Load the FTS index structure */
192516  pStruct = fts5StructureRead(p);
192517 
192518  /* Check that the internal nodes of each segment match the leaves */
192519  if( pStruct ){
192520  int iLvl, iSeg;
192521  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
192522  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
192523  Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
192524  fts5IndexIntegrityCheckSegment(p, pSeg);
192525  }
192526  }
192527  }
192528 
192529  /* The cksum argument passed to this function is a checksum calculated
192530  ** based on all expected entries in the FTS index (including prefix index
192531  ** entries). This block checks that a checksum calculated based on the
192532  ** actual contents of FTS index is identical.
192533  **
192534  ** Two versions of the same checksum are calculated. The first (stack
192535  ** variable cksum2) based on entries extracted from the full-text index
192536  ** while doing a linear scan of each individual index in turn.
192537  **
192538  ** As each term visited by the linear scans, a separate query for the
192539  ** same term is performed. cksum3 is calculated based on the entries
192540  ** extracted by these queries.
192541  */
192542  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
192543  fts5MultiIterEof(p, pIter)==0;
192544  fts5MultiIterNext(p, pIter, 0, 0)
192545  ){
192546  int n; /* Size of term in bytes */
192547  i64 iPos = 0; /* Position read from poslist */
192548  int iOff = 0; /* Offset within poslist */
192549  i64 iRowid = fts5MultiIterRowid(pIter);
192550  char *z = (char*)fts5MultiIterTerm(pIter, &n);
192551 
192552  /* If this is a new term, query for it. Update cksum3 with the results. */
192553  fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
192554 
192555  if( eDetail==FTS5_DETAIL_NONE ){
192556  if( 0==fts5MultiIterIsEmpty(p, pIter) ){
192557  cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
192558  }
192559  }else{
192560  poslist.n = 0;
192561  fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
192562  while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
192563  int iCol = FTS5_POS2COLUMN(iPos);
192564  int iTokOff = FTS5_POS2OFFSET(iPos);
192565  cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
192566  }
192567  }
192568  }
192569  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
192570 
192571  fts5MultiIterFree(pIter);
192572  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
192573 
192574  fts5StructureRelease(pStruct);
192575 #ifdef SQLITE_DEBUG
192576  fts5BufferFree(&term);
192577 #endif
192578  fts5BufferFree(&poslist);
192579  return fts5IndexReturn(p);
192580 }
192581 
192582 /*************************************************************************
192583 **************************************************************************
192584 ** Below this point is the implementation of the fts5_decode() scalar
192585 ** function only.
192586 */
192587 
192588 /*
192589 ** Decode a segment-data rowid from the %_data table. This function is
192590 ** the opposite of macro FTS5_SEGMENT_ROWID().
192591 */
192592 static void fts5DecodeRowid(
192593  i64 iRowid, /* Rowid from %_data table */
192594  int *piSegid, /* OUT: Segment id */
192595  int *pbDlidx, /* OUT: Dlidx flag */
192596  int *piHeight, /* OUT: Height */
192597  int *piPgno /* OUT: Page number */
192598 ){
192599  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
192600  iRowid >>= FTS5_DATA_PAGE_B;
192601 
192602  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
192603  iRowid >>= FTS5_DATA_HEIGHT_B;
192604 
192605  *pbDlidx = (int)(iRowid & 0x0001);
192606  iRowid >>= FTS5_DATA_DLI_B;
192607 
192608  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
192609 }
192610 
192611 static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
192612  int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
192613  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
192614 
192615  if( iSegid==0 ){
192616  if( iKey==FTS5_AVERAGES_ROWID ){
192617  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
192618  }else{
192619  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
192620  }
192621  }
192622  else{
192623  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
192624  bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
192625  );
192626  }
192627 }
192628 
192629 static void fts5DebugStructure(
192630  int *pRc, /* IN/OUT: error code */
192631  Fts5Buffer *pBuf,
192632  Fts5Structure *p
192633 ){
192634  int iLvl, iSeg; /* Iterate through levels, segments */
192635 
192636  for(iLvl=0; iLvl<p->nLevel; iLvl++){
192637  Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
192638  sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
192639  " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
192640  );
192641  for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
192642  Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
192643  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
192644  pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
192645  );
192646  }
192647  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
192648  }
192649 }
192650 
192651 /*
192652 ** This is part of the fts5_decode() debugging aid.
192653 **
192654 ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
192655 ** function appends a human-readable representation of the same object
192656 ** to the buffer passed as the second argument.
192657 */
192658 static void fts5DecodeStructure(
192659  int *pRc, /* IN/OUT: error code */
192660  Fts5Buffer *pBuf,
192661  const u8 *pBlob, int nBlob
192662 ){
192663  int rc; /* Return code */
192664  Fts5Structure *p = 0; /* Decoded structure object */
192665 
192666  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
192667  if( rc!=SQLITE_OK ){
192668  *pRc = rc;
192669  return;
192670  }
192671 
192672  fts5DebugStructure(pRc, pBuf, p);
192673  fts5StructureRelease(p);
192674 }
192675 
192676 /*
192677 ** This is part of the fts5_decode() debugging aid.
192678 **
192679 ** Arguments pBlob/nBlob contain an "averages" record. This function
192680 ** appends a human-readable representation of record to the buffer passed
192681 ** as the second argument.
192682 */
192683 static void fts5DecodeAverages(
192684  int *pRc, /* IN/OUT: error code */
192685  Fts5Buffer *pBuf,
192686  const u8 *pBlob, int nBlob
192687 ){
192688  int i = 0;
192689  const char *zSpace = "";
192690 
192691  while( i<nBlob ){
192692  u64 iVal;
192693  i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
192694  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
192695  zSpace = " ";
192696  }
192697 }
192698 
192699 /*
192700 ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
192701 ** each varint and append its string representation to buffer pBuf. Return
192702 ** after either the input buffer is exhausted or a 0 value is read.
192703 **
192704 ** The return value is the number of bytes read from the input buffer.
192705 */
192706 static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
192707  int iOff = 0;
192708  while( iOff<n ){
192709  int iVal;
192710  iOff += fts5GetVarint32(&a[iOff], iVal);
192711  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
192712  }
192713  return iOff;
192714 }
192715 
192716 /*
192717 ** The start of buffer (a/n) contains the start of a doclist. The doclist
192718 ** may or may not finish within the buffer. This function appends a text
192719 ** representation of the part of the doclist that is present to buffer
192720 ** pBuf.
192721 **
192722 ** The return value is the number of bytes read from the input buffer.
192723 */
192724 static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
192725  i64 iDocid = 0;
192726  int iOff = 0;
192727 
192728  if( n>0 ){
192729  iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
192730  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
192731  }
192732  while( iOff<n ){
192733  int nPos;
192734  int bDel;
192735  iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
192736  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
192737  iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
192738  if( iOff<n ){
192739  i64 iDelta;
192740  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
192741  iDocid += iDelta;
192742  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
192743  }
192744  }
192745 
192746  return iOff;
192747 }
192748 
192749 /*
192750 ** This function is part of the fts5_decode() debugging function. It is
192751 ** only ever used with detail=none tables.
192752 **
192753 ** Buffer (pData/nData) contains a doclist in the format used by detail=none
192754 ** tables. This function appends a human-readable version of that list to
192755 ** buffer pBuf.
192756 **
192757 ** If *pRc is other than SQLITE_OK when this function is called, it is a
192758 ** no-op. If an OOM or other error occurs within this function, *pRc is
192759 ** set to an SQLite error code before returning. The final state of buffer
192760 ** pBuf is undefined in this case.
192761 */
192762 static void fts5DecodeRowidList(
192763  int *pRc, /* IN/OUT: Error code */
192764  Fts5Buffer *pBuf, /* Buffer to append text to */
192765  const u8 *pData, int nData /* Data to decode list-of-rowids from */
192766 ){
192767  int i = 0;
192768  i64 iRowid = 0;
192769 
192770  while( i<nData ){
192771  const char *zApp = "";
192772  u64 iVal;
192773  i += sqlite3Fts5GetVarint(&pData[i], &iVal);
192774  iRowid += iVal;
192775 
192776  if( i<nData && pData[i]==0x00 ){
192777  i++;
192778  if( i<nData && pData[i]==0x00 ){
192779  i++;
192780  zApp = "+";
192781  }else{
192782  zApp = "*";
192783  }
192784  }
192785 
192786  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
192787  }
192788 }
192789 
192790 /*
192791 ** The implementation of user-defined scalar function fts5_decode().
192792 */
192793 static void fts5DecodeFunction(
192794  sqlite3_context *pCtx, /* Function call context */
192795  int nArg, /* Number of args (always 2) */
192796  sqlite3_value **apVal /* Function arguments */
192797 ){
192798  i64 iRowid; /* Rowid for record being decoded */
192799  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
192800  const u8 *aBlob; int n; /* Record to decode */
192801  u8 *a = 0;
192802  Fts5Buffer s; /* Build up text to return here */
192803  int rc = SQLITE_OK; /* Return code */
192804  int nSpace = 0;
192805  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
192806 
192807  assert( nArg==2 );
192808  UNUSED_PARAM(nArg);
192809  memset(&s, 0, sizeof(Fts5Buffer));
192810  iRowid = sqlite3_value_int64(apVal[0]);
192811 
192812  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
192813  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
192814  ** buffer overreads even if the record is corrupt. */
192815  n = sqlite3_value_bytes(apVal[1]);
192816  aBlob = sqlite3_value_blob(apVal[1]);
192817  nSpace = n + FTS5_DATA_ZERO_PADDING;
192818  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
192819  if( a==0 ) goto decode_out;
192820  memcpy(a, aBlob, n);
192821 
192822 
192823  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
192824 
192825  fts5DebugRowid(&rc, &s, iRowid);
192826  if( bDlidx ){
192827  Fts5Data dlidx;
192828  Fts5DlidxLvl lvl;
192829 
192830  dlidx.p = a;
192831  dlidx.nn = n;
192832 
192833  memset(&lvl, 0, sizeof(Fts5DlidxLvl));
192834  lvl.pData = &dlidx;
192835  lvl.iLeafPgno = iPgno;
192836 
192837  for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
192838  sqlite3Fts5BufferAppendPrintf(&rc, &s,
192839  " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
192840  );
192841  }
192842  }else if( iSegid==0 ){
192843  if( iRowid==FTS5_AVERAGES_ROWID ){
192844  fts5DecodeAverages(&rc, &s, a, n);
192845  }else{
192846  fts5DecodeStructure(&rc, &s, a, n);
192847  }
192848  }else if( eDetailNone ){
192849  Fts5Buffer term; /* Current term read from page */
192850  int szLeaf;
192851  int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
192852  int iTermOff;
192853  int nKeep = 0;
192854  int iOff;
192855 
192856  memset(&term, 0, sizeof(Fts5Buffer));
192857 
192858  /* Decode any entries that occur before the first term. */
192859  if( szLeaf<n ){
192860  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
192861  }else{
192862  iTermOff = szLeaf;
192863  }
192864  fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
192865 
192866  iOff = iTermOff;
192867  while( iOff<szLeaf ){
192868  int nAppend;
192869 
192870  /* Read the term data for the next term*/
192871  iOff += fts5GetVarint32(&a[iOff], nAppend);
192872  term.n = nKeep;
192873  fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
192874  sqlite3Fts5BufferAppendPrintf(
192875  &rc, &s, " term=%.*s", term.n, (const char*)term.p
192876  );
192877  iOff += nAppend;
192878 
192879  /* Figure out where the doclist for this term ends */
192880  if( iPgidxOff<n ){
192881  int nIncr;
192882  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
192883  iTermOff += nIncr;
192884  }else{
192885  iTermOff = szLeaf;
192886  }
192887 
192888  fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
192889  iOff = iTermOff;
192890  if( iOff<szLeaf ){
192891  iOff += fts5GetVarint32(&a[iOff], nKeep);
192892  }
192893  }
192894 
192895  fts5BufferFree(&term);
192896  }else{
192897  Fts5Buffer term; /* Current term read from page */
192898  int szLeaf; /* Offset of pgidx in a[] */
192899  int iPgidxOff;
192900  int iPgidxPrev = 0; /* Previous value read from pgidx */
192901  int iTermOff = 0;
192902  int iRowidOff = 0;
192903  int iOff;
192904  int nDoclist;
192905 
192906  memset(&term, 0, sizeof(Fts5Buffer));
192907 
192908  if( n<4 ){
192909  sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
192910  goto decode_out;
192911  }else{
192912  iRowidOff = fts5GetU16(&a[0]);
192913  iPgidxOff = szLeaf = fts5GetU16(&a[2]);
192914  if( iPgidxOff<n ){
192915  fts5GetVarint32(&a[iPgidxOff], iTermOff);
192916  }
192917  }
192918 
192919  /* Decode the position list tail at the start of the page */
192920  if( iRowidOff!=0 ){
192921  iOff = iRowidOff;
192922  }else if( iTermOff!=0 ){
192923  iOff = iTermOff;
192924  }else{
192925  iOff = szLeaf;
192926  }
192927  fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
192928 
192929  /* Decode any more doclist data that appears on the page before the
192930  ** first term. */
192931  nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
192932  fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
192933 
192934  while( iPgidxOff<n ){
192935  int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
192936  int nByte; /* Bytes of data */
192937  int iEnd;
192938 
192939  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
192940  iPgidxPrev += nByte;
192941  iOff = iPgidxPrev;
192942 
192943  if( iPgidxOff<n ){
192944  fts5GetVarint32(&a[iPgidxOff], nByte);
192945  iEnd = iPgidxPrev + nByte;
192946  }else{
192947  iEnd = szLeaf;
192948  }
192949 
192950  if( bFirst==0 ){
192951  iOff += fts5GetVarint32(&a[iOff], nByte);
192952  term.n = nByte;
192953  }
192954  iOff += fts5GetVarint32(&a[iOff], nByte);
192955  fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
192956  iOff += nByte;
192957 
192958  sqlite3Fts5BufferAppendPrintf(
192959  &rc, &s, " term=%.*s", term.n, (const char*)term.p
192960  );
192961  iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
192962  }
192963 
192964  fts5BufferFree(&term);
192965  }
192966 
192967  decode_out:
192968  sqlite3_free(a);
192969  if( rc==SQLITE_OK ){
192970  sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
192971  }else{
192972  sqlite3_result_error_code(pCtx, rc);
192973  }
192974  fts5BufferFree(&s);
192975 }
192976 
192977 /*
192978 ** The implementation of user-defined scalar function fts5_rowid().
192979 */
192980 static void fts5RowidFunction(
192981  sqlite3_context *pCtx, /* Function call context */
192982  int nArg, /* Number of args (always 2) */
192983  sqlite3_value **apVal /* Function arguments */
192984 ){
192985  const char *zArg;
192986  if( nArg==0 ){
192987  sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
192988  }else{
192989  zArg = (const char*)sqlite3_value_text(apVal[0]);
192990  if( 0==sqlite3_stricmp(zArg, "segment") ){
192991  i64 iRowid;
192992  int segid, pgno;
192993  if( nArg!=3 ){
192994  sqlite3_result_error(pCtx,
192995  "should be: fts5_rowid('segment', segid, pgno))", -1
192996  );
192997  }else{
192998  segid = sqlite3_value_int(apVal[1]);
192999  pgno = sqlite3_value_int(apVal[2]);
193000  iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
193001  sqlite3_result_int64(pCtx, iRowid);
193002  }
193003  }else{
193004  sqlite3_result_error(pCtx,
193005  "first arg to fts5_rowid() must be 'segment'" , -1
193006  );
193007  }
193008  }
193009 }
193010 
193011 /*
193012 ** This is called as part of registering the FTS5 module with database
193013 ** connection db. It registers several user-defined scalar functions useful
193014 ** with FTS5.
193015 **
193016 ** If successful, SQLITE_OK is returned. If an error occurs, some other
193017 ** SQLite error code is returned instead.
193018 */
193019 static int sqlite3Fts5IndexInit(sqlite3 *db){
193020  int rc = sqlite3_create_function(
193021  db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
193022  );
193023 
193024  if( rc==SQLITE_OK ){
193026  db, "fts5_decode_none", 2,
193027  SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
193028  );
193029  }
193030 
193031  if( rc==SQLITE_OK ){
193033  db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
193034  );
193035  }
193036  return rc;
193037 }
193038 
193039 
193040 static int sqlite3Fts5IndexReset(Fts5Index *p){
193041  assert( p->pStruct==0 || p->iStructVersion!=0 );
193042  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
193043  fts5StructureInvalidate(p);
193044  }
193045  return fts5IndexReturn(p);
193046 }
193047 
193048 /*
193049 ** 2014 Jun 09
193050 **
193051 ** The author disclaims copyright to this source code. In place of
193052 ** a legal notice, here is a blessing:
193053 **
193054 ** May you do good and not evil.
193055 ** May you find forgiveness for yourself and forgive others.
193056 ** May you share freely, never taking more than you give.
193057 **
193058 ******************************************************************************
193059 **
193060 ** This is an SQLite module implementing full-text search.
193061 */
193062 
193063 
193064 /* #include "fts5Int.h" */
193065 
193066 /*
193067 ** This variable is set to false when running tests for which the on disk
193068 ** structures should not be corrupt. Otherwise, true. If it is false, extra
193069 ** assert() conditions in the fts5 code are activated - conditions that are
193070 ** only true if it is guaranteed that the fts5 database is not corrupt.
193071 */
193072 SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
193073 
193074 
193075 typedef struct Fts5Auxdata Fts5Auxdata;
193076 typedef struct Fts5Auxiliary Fts5Auxiliary;
193077 typedef struct Fts5Cursor Fts5Cursor;
193078 typedef struct Fts5Sorter Fts5Sorter;
193079 typedef struct Fts5Table Fts5Table;
193080 typedef struct Fts5TokenizerModule Fts5TokenizerModule;
193081 
193082 /*
193083 ** NOTES ON TRANSACTIONS:
193084 **
193085 ** SQLite invokes the following virtual table methods as transactions are
193086 ** opened and closed by the user:
193087 **
193088 ** xBegin(): Start of a new transaction.
193089 ** xSync(): Initial part of two-phase commit.
193090 ** xCommit(): Final part of two-phase commit.
193091 ** xRollback(): Rollback the transaction.
193092 **
193093 ** Anything that is required as part of a commit that may fail is performed
193094 ** in the xSync() callback. Current versions of SQLite ignore any errors
193095 ** returned by xCommit().
193096 **
193097 ** And as sub-transactions are opened/closed:
193098 **
193099 ** xSavepoint(int S): Open savepoint S.
193100 ** xRelease(int S): Commit and close savepoint S.
193101 ** xRollbackTo(int S): Rollback to start of savepoint S.
193102 **
193103 ** During a write-transaction the fts5_index.c module may cache some data
193104 ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
193105 ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
193106 ** is called.
193107 **
193108 ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
193109 ** structure is used to record the current transaction state. This information
193110 ** is not required, but it is used in the assert() statements executed by
193111 ** function fts5CheckTransactionState() (see below).
193112 */
193113 struct Fts5TransactionState {
193114  int eState; /* 0==closed, 1==open, 2==synced */
193115  int iSavepoint; /* Number of open savepoints (0 -> none) */
193116 };
193117 
193118 /*
193119 ** A single object of this type is allocated when the FTS5 module is
193120 ** registered with a database handle. It is used to store pointers to
193121 ** all registered FTS5 extensions - tokenizers and auxiliary functions.
193122 */
193123 struct Fts5Global {
193124  fts5_api api; /* User visible part of object (see fts5.h) */
193125  sqlite3 *db; /* Associated database connection */
193126  i64 iNextId; /* Used to allocate unique cursor ids */
193127  Fts5Auxiliary *pAux; /* First in list of all aux. functions */
193128  Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
193129  Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
193130  Fts5Cursor *pCsr; /* First in list of all open cursors */
193131 };
193132 
193133 /*
193134 ** Each auxiliary function registered with the FTS5 module is represented
193135 ** by an object of the following type. All such objects are stored as part
193136 ** of the Fts5Global.pAux list.
193137 */
193138 struct Fts5Auxiliary {
193139  Fts5Global *pGlobal; /* Global context for this function */
193140  char *zFunc; /* Function name (nul-terminated) */
193141  void *pUserData; /* User-data pointer */
193142  fts5_extension_function xFunc; /* Callback function */
193143  void (*xDestroy)(void*); /* Destructor function */
193144  Fts5Auxiliary *pNext; /* Next registered auxiliary function */
193145 };
193146 
193147 /*
193148 ** Each tokenizer module registered with the FTS5 module is represented
193149 ** by an object of the following type. All such objects are stored as part
193150 ** of the Fts5Global.pTok list.
193151 */
193152 struct Fts5TokenizerModule {
193153  char *zName; /* Name of tokenizer */
193154  void *pUserData; /* User pointer passed to xCreate() */
193155  fts5_tokenizer x; /* Tokenizer functions */
193156  void (*xDestroy)(void*); /* Destructor function */
193157  Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
193158 };
193159 
193160 /*
193161 ** Virtual-table object.
193162 */
193163 struct Fts5Table {
193164  sqlite3_vtab base; /* Base class used by SQLite core */
193165  Fts5Config *pConfig; /* Virtual table configuration */
193166  Fts5Index *pIndex; /* Full-text index */
193167  Fts5Storage *pStorage; /* Document store */
193168  Fts5Global *pGlobal; /* Global (connection wide) data */
193169  Fts5Cursor *pSortCsr; /* Sort data from this cursor */
193170 #ifdef SQLITE_DEBUG
193171  struct Fts5TransactionState ts;
193172 #endif
193173 };
193174 
193175 struct Fts5MatchPhrase {
193176  Fts5Buffer *pPoslist; /* Pointer to current poslist */
193177  int nTerm; /* Size of phrase in terms */
193178 };
193179 
193180 /*
193181 ** pStmt:
193182 ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
193183 **
193184 ** aIdx[]:
193185 ** There is one entry in the aIdx[] array for each phrase in the query,
193186 ** the value of which is the offset within aPoslist[] following the last
193187 ** byte of the position list for the corresponding phrase.
193188 */
193189 struct Fts5Sorter {
193190  sqlite3_stmt *pStmt;
193191  i64 iRowid; /* Current rowid */
193192  const u8 *aPoslist; /* Position lists for current row */
193193  int nIdx; /* Number of entries in aIdx[] */
193194  int aIdx[1]; /* Offsets into aPoslist for current row */
193195 };
193196 
193197 
193198 /*
193199 ** Virtual-table cursor object.
193200 **
193201 ** iSpecial:
193202 ** If this is a 'special' query (refer to function fts5SpecialMatch()),
193203 ** then this variable contains the result of the query.
193204 **
193205 ** iFirstRowid, iLastRowid:
193206 ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
193207 ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
193208 ** limit of rowids to return, and iLastRowid the upper. In other words, the
193209 ** WHERE clause in the user's query might have been:
193210 **
193211 ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
193212 **
193213 ** If the cursor iterates in descending order of rowid, iFirstRowid
193214 ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
193215 ** the lower.
193216 */
193217 struct Fts5Cursor {
193218  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
193219  Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
193220  int *aColumnSize; /* Values for xColumnSize() */
193221  i64 iCsrId; /* Cursor id */
193222 
193223  /* Zero from this point onwards on cursor reset */
193224  int ePlan; /* FTS5_PLAN_XXX value */
193225  int bDesc; /* True for "ORDER BY rowid DESC" queries */
193226  i64 iFirstRowid; /* Return no rowids earlier than this */
193227  i64 iLastRowid; /* Return no rowids later than this */
193228  sqlite3_stmt *pStmt; /* Statement used to read %_content */
193229  Fts5Expr *pExpr; /* Expression for MATCH queries */
193230  Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
193231  int csrflags; /* Mask of cursor flags (see below) */
193232  i64 iSpecial; /* Result of special query */
193233 
193234  /* "rank" function. Populated on demand from vtab.xColumn(). */
193235  char *zRank; /* Custom rank function */
193236  char *zRankArgs; /* Custom rank function args */
193237  Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
193238  int nRankArg; /* Number of trailing arguments for rank() */
193239  sqlite3_value **apRankArg; /* Array of trailing arguments */
193240  sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
193241 
193242  /* Auxiliary data storage */
193243  Fts5Auxiliary *pAux; /* Currently executing extension function */
193244  Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
193245 
193246  /* Cache used by auxiliary functions xInst() and xInstCount() */
193247  Fts5PoslistReader *aInstIter; /* One for each phrase */
193248  int nInstAlloc; /* Size of aInst[] array (entries / 3) */
193249  int nInstCount; /* Number of phrase instances */
193250  int *aInst; /* 3 integers per phrase instance */
193251 };
193252 
193253 /*
193254 ** Bits that make up the "idxNum" parameter passed indirectly by
193255 ** xBestIndex() to xFilter().
193256 */
193257 #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
193258 #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
193259 #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
193260 #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
193261 #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
193262 
193263 #define FTS5_BI_ORDER_RANK 0x0020
193264 #define FTS5_BI_ORDER_ROWID 0x0040
193265 #define FTS5_BI_ORDER_DESC 0x0080
193266 
193267 /*
193268 ** Values for Fts5Cursor.csrflags
193269 */
193270 #define FTS5CSR_EOF 0x01
193271 #define FTS5CSR_REQUIRE_CONTENT 0x02
193272 #define FTS5CSR_REQUIRE_DOCSIZE 0x04
193273 #define FTS5CSR_REQUIRE_INST 0x08
193274 #define FTS5CSR_FREE_ZRANK 0x10
193275 #define FTS5CSR_REQUIRE_RESEEK 0x20
193276 #define FTS5CSR_REQUIRE_POSLIST 0x40
193277 
193278 #define BitFlagAllTest(x,y) (((x) & (y))==(y))
193279 #define BitFlagTest(x,y) (((x) & (y))!=0)
193280 
193281 
193282 /*
193283 ** Macros to Set(), Clear() and Test() cursor flags.
193284 */
193285 #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
193286 #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
193287 #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
193288 
193289 struct Fts5Auxdata {
193290  Fts5Auxiliary *pAux; /* Extension to which this belongs */
193291  void *pPtr; /* Pointer value */
193292  void(*xDelete)(void*); /* Destructor */
193293  Fts5Auxdata *pNext; /* Next object in linked list */
193294 };
193295 
193296 #ifdef SQLITE_DEBUG
193297 #define FTS5_BEGIN 1
193298 #define FTS5_SYNC 2
193299 #define FTS5_COMMIT 3
193300 #define FTS5_ROLLBACK 4
193301 #define FTS5_SAVEPOINT 5
193302 #define FTS5_RELEASE 6
193303 #define FTS5_ROLLBACKTO 7
193304 static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
193305  switch( op ){
193306  case FTS5_BEGIN:
193307  assert( p->ts.eState==0 );
193308  p->ts.eState = 1;
193309  p->ts.iSavepoint = -1;
193310  break;
193311 
193312  case FTS5_SYNC:
193313  assert( p->ts.eState==1 );
193314  p->ts.eState = 2;
193315  break;
193316 
193317  case FTS5_COMMIT:
193318  assert( p->ts.eState==2 );
193319  p->ts.eState = 0;
193320  break;
193321 
193322  case FTS5_ROLLBACK:
193323  assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
193324  p->ts.eState = 0;
193325  break;
193326 
193327  case FTS5_SAVEPOINT:
193328  assert( p->ts.eState==1 );
193329  assert( iSavepoint>=0 );
193330  assert( iSavepoint>p->ts.iSavepoint );
193331  p->ts.iSavepoint = iSavepoint;
193332  break;
193333 
193334  case FTS5_RELEASE:
193335  assert( p->ts.eState==1 );
193336  assert( iSavepoint>=0 );
193337  assert( iSavepoint<=p->ts.iSavepoint );
193338  p->ts.iSavepoint = iSavepoint-1;
193339  break;
193340 
193341  case FTS5_ROLLBACKTO:
193342  assert( p->ts.eState==1 );
193343  assert( iSavepoint>=0 );
193344  assert( iSavepoint<=p->ts.iSavepoint );
193345  p->ts.iSavepoint = iSavepoint;
193346  break;
193347  }
193348 }
193349 #else
193350 # define fts5CheckTransactionState(x,y,z)
193351 #endif
193352 
193353 /*
193354 ** Return true if pTab is a contentless table.
193355 */
193356 static int fts5IsContentless(Fts5Table *pTab){
193357  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
193358 }
193359 
193360 /*
193361 ** Delete a virtual table handle allocated by fts5InitVtab().
193362 */
193363 static void fts5FreeVtab(Fts5Table *pTab){
193364  if( pTab ){
193365  sqlite3Fts5IndexClose(pTab->pIndex);
193366  sqlite3Fts5StorageClose(pTab->pStorage);
193367  sqlite3Fts5ConfigFree(pTab->pConfig);
193368  sqlite3_free(pTab);
193369  }
193370 }
193371 
193372 /*
193373 ** The xDisconnect() virtual table method.
193374 */
193375 static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
193376  fts5FreeVtab((Fts5Table*)pVtab);
193377  return SQLITE_OK;
193378 }
193379 
193380 /*
193381 ** The xDestroy() virtual table method.
193382 */
193383 static int fts5DestroyMethod(sqlite3_vtab *pVtab){
193384  Fts5Table *pTab = (Fts5Table*)pVtab;
193385  int rc = sqlite3Fts5DropAll(pTab->pConfig);
193386  if( rc==SQLITE_OK ){
193387  fts5FreeVtab((Fts5Table*)pVtab);
193388  }
193389  return rc;
193390 }
193391 
193392 /*
193393 ** This function is the implementation of both the xConnect and xCreate
193394 ** methods of the FTS3 virtual table.
193395 **
193396 ** The argv[] array contains the following:
193397 **
193398 ** argv[0] -> module name ("fts5")
193399 ** argv[1] -> database name
193400 ** argv[2] -> table name
193401 ** argv[...] -> "column name" and other module argument fields.
193402 */
193403 static int fts5InitVtab(
193404  int bCreate, /* True for xCreate, false for xConnect */
193405  sqlite3 *db, /* The SQLite database connection */
193406  void *pAux, /* Hash table containing tokenizers */
193407  int argc, /* Number of elements in argv array */
193408  const char * const *argv, /* xCreate/xConnect argument array */
193409  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
193410  char **pzErr /* Write any error message here */
193411 ){
193412  Fts5Global *pGlobal = (Fts5Global*)pAux;
193413  const char **azConfig = (const char**)argv;
193414  int rc = SQLITE_OK; /* Return code */
193415  Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
193416  Fts5Table *pTab = 0; /* New virtual table object */
193417 
193418  /* Allocate the new vtab object and parse the configuration */
193419  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
193420  if( rc==SQLITE_OK ){
193421  rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
193422  assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
193423  }
193424  if( rc==SQLITE_OK ){
193425  pTab->pConfig = pConfig;
193426  pTab->pGlobal = pGlobal;
193427  }
193428 
193429  /* Open the index sub-system */
193430  if( rc==SQLITE_OK ){
193431  rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
193432  }
193433 
193434  /* Open the storage sub-system */
193435  if( rc==SQLITE_OK ){
193436  rc = sqlite3Fts5StorageOpen(
193437  pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
193438  );
193439  }
193440 
193441  /* Call sqlite3_declare_vtab() */
193442  if( rc==SQLITE_OK ){
193443  rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
193444  }
193445 
193446  /* Load the initial configuration */
193447  if( rc==SQLITE_OK ){
193448  assert( pConfig->pzErrmsg==0 );
193449  pConfig->pzErrmsg = pzErr;
193450  rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
193451  sqlite3Fts5IndexRollback(pTab->pIndex);
193452  pConfig->pzErrmsg = 0;
193453  }
193454 
193455  if( rc!=SQLITE_OK ){
193456  fts5FreeVtab(pTab);
193457  pTab = 0;
193458  }else if( bCreate ){
193459  fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
193460  }
193461  *ppVTab = (sqlite3_vtab*)pTab;
193462  return rc;
193463 }
193464 
193465 /*
193466 ** The xConnect() and xCreate() methods for the virtual table. All the
193467 ** work is done in function fts5InitVtab().
193468 */
193469 static int fts5ConnectMethod(
193470  sqlite3 *db, /* Database connection */
193471  void *pAux, /* Pointer to tokenizer hash table */
193472  int argc, /* Number of elements in argv array */
193473  const char * const *argv, /* xCreate/xConnect argument array */
193474  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
193475  char **pzErr /* OUT: sqlite3_malloc'd error message */
193476 ){
193477  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
193478 }
193479 static int fts5CreateMethod(
193480  sqlite3 *db, /* Database connection */
193481  void *pAux, /* Pointer to tokenizer hash table */
193482  int argc, /* Number of elements in argv array */
193483  const char * const *argv, /* xCreate/xConnect argument array */
193484  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
193485  char **pzErr /* OUT: sqlite3_malloc'd error message */
193486 ){
193487  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
193488 }
193489 
193490 /*
193491 ** The different query plans.
193492 */
193493 #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
193494 #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
193495 #define FTS5_PLAN_SPECIAL 3 /* An internal query */
193496 #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
193497 #define FTS5_PLAN_SCAN 5 /* No usable constraint */
193498 #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
193499 
193500 /*
193501 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
193502 ** extension is currently being used by a version of SQLite too old to
193503 ** support index-info flags. In that case this function is a no-op.
193504 */
193505 static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
193506 #if SQLITE_VERSION_NUMBER>=3008012
193507 #ifndef SQLITE_CORE
193508  if( sqlite3_libversion_number()>=3008012 )
193509 #endif
193510  {
193511  pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
193512  }
193513 #endif
193514 }
193515 
193516 /*
193517 ** Implementation of the xBestIndex method for FTS5 tables. Within the
193518 ** WHERE constraint, it searches for the following:
193519 **
193520 ** 1. A MATCH constraint against the special column.
193521 ** 2. A MATCH constraint against the "rank" column.
193522 ** 3. An == constraint against the rowid column.
193523 ** 4. A < or <= constraint against the rowid column.
193524 ** 5. A > or >= constraint against the rowid column.
193525 **
193526 ** Within the ORDER BY, either:
193527 **
193528 ** 5. ORDER BY rank [ASC|DESC]
193529 ** 6. ORDER BY rowid [ASC|DESC]
193530 **
193531 ** Costs are assigned as follows:
193532 **
193533 ** a) If an unusable MATCH operator is present in the WHERE clause, the
193534 ** cost is unconditionally set to 1e50 (a really big number).
193535 **
193536 ** a) If a MATCH operator is present, the cost depends on the other
193537 ** constraints also present. As follows:
193538 **
193539 ** * No other constraints: cost=1000.0
193540 ** * One rowid range constraint: cost=750.0
193541 ** * Both rowid range constraints: cost=500.0
193542 ** * An == rowid constraint: cost=100.0
193543 **
193544 ** b) Otherwise, if there is no MATCH:
193545 **
193546 ** * No other constraints: cost=1000000.0
193547 ** * One rowid range constraint: cost=750000.0
193548 ** * Both rowid range constraints: cost=250000.0
193549 ** * An == rowid constraint: cost=10.0
193550 **
193551 ** Costs are not modified by the ORDER BY clause.
193552 */
193553 static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
193554  Fts5Table *pTab = (Fts5Table*)pVTab;
193555  Fts5Config *pConfig = pTab->pConfig;
193556  int idxFlags = 0; /* Parameter passed through to xFilter() */
193557  int bHasMatch;
193558  int iNext;
193559  int i;
193560 
193561  struct Constraint {
193562  int op; /* Mask against sqlite3_index_constraint.op */
193563  int fts5op; /* FTS5 mask for idxFlags */
193564  int iCol; /* 0==rowid, 1==tbl, 2==rank */
193565  int omit; /* True to omit this if found */
193566  int iConsIndex; /* Index in pInfo->aConstraint[] */
193567  } aConstraint[] = {
193569  FTS5_BI_MATCH, 1, 1, -1},
193571  FTS5_BI_RANK, 2, 1, -1},
193572  {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
193574  FTS5_BI_ROWID_LE, 0, 0, -1},
193576  FTS5_BI_ROWID_GE, 0, 0, -1},
193577  };
193578 
193579  int aColMap[3];
193580  aColMap[0] = -1;
193581  aColMap[1] = pConfig->nCol;
193582  aColMap[2] = pConfig->nCol+1;
193583 
193584  /* Set idxFlags flags for all WHERE clause terms that will be used. */
193585  for(i=0; i<pInfo->nConstraint; i++){
193586  struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
193587  int j;
193588  for(j=0; j<ArraySize(aConstraint); j++){
193589  struct Constraint *pC = &aConstraint[j];
193590  if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
193591  if( p->usable ){
193592  pC->iConsIndex = i;
193593  idxFlags |= pC->fts5op;
193594  }else if( j==0 ){
193595  /* As there exists an unusable MATCH constraint this is an
193596  ** unusable plan. Set a prohibitively high cost. */
193597  pInfo->estimatedCost = 1e50;
193598  return SQLITE_OK;
193599  }
193600  }
193601  }
193602  }
193603 
193604  /* Set idxFlags flags for the ORDER BY clause */
193605  if( pInfo->nOrderBy==1 ){
193606  int iSort = pInfo->aOrderBy[0].iColumn;
193607  if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
193608  idxFlags |= FTS5_BI_ORDER_RANK;
193609  }else if( iSort==-1 ){
193610  idxFlags |= FTS5_BI_ORDER_ROWID;
193611  }
193612  if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
193613  pInfo->orderByConsumed = 1;
193614  if( pInfo->aOrderBy[0].desc ){
193615  idxFlags |= FTS5_BI_ORDER_DESC;
193616  }
193617  }
193618  }
193619 
193620  /* Calculate the estimated cost based on the flags set in idxFlags. */
193621  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
193622  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
193623  pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
193624  if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
193625  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
193626  pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
193627  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
193628  pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
193629  }else{
193630  pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
193631  }
193632 
193633  /* Assign argvIndex values to each constraint in use. */
193634  iNext = 1;
193635  for(i=0; i<ArraySize(aConstraint); i++){
193636  struct Constraint *pC = &aConstraint[i];
193637  if( pC->iConsIndex>=0 ){
193638  pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
193639  pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
193640  }
193641  }
193642 
193643  pInfo->idxNum = idxFlags;
193644  return SQLITE_OK;
193645 }
193646 
193647 static int fts5NewTransaction(Fts5Table *pTab){
193648  Fts5Cursor *pCsr;
193649  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
193650  if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
193651  }
193652  return sqlite3Fts5StorageReset(pTab->pStorage);
193653 }
193654 
193655 /*
193656 ** Implementation of xOpen method.
193657 */
193658 static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
193659  Fts5Table *pTab = (Fts5Table*)pVTab;
193660  Fts5Config *pConfig = pTab->pConfig;
193661  Fts5Cursor *pCsr = 0; /* New cursor object */
193662  int nByte; /* Bytes of space to allocate */
193663  int rc; /* Return code */
193664 
193665  rc = fts5NewTransaction(pTab);
193666  if( rc==SQLITE_OK ){
193667  nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
193668  pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
193669  if( pCsr ){
193670  Fts5Global *pGlobal = pTab->pGlobal;
193671  memset(pCsr, 0, nByte);
193672  pCsr->aColumnSize = (int*)&pCsr[1];
193673  pCsr->pNext = pGlobal->pCsr;
193674  pGlobal->pCsr = pCsr;
193675  pCsr->iCsrId = ++pGlobal->iNextId;
193676  }else{
193677  rc = SQLITE_NOMEM;
193678  }
193679  }
193680  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
193681  return rc;
193682 }
193683 
193684 static int fts5StmtType(Fts5Cursor *pCsr){
193685  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
193686  return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
193687  }
193688  return FTS5_STMT_LOOKUP;
193689 }
193690 
193691 /*
193692 ** This function is called after the cursor passed as the only argument
193693 ** is moved to point at a different row. It clears all cached data
193694 ** specific to the previous row stored by the cursor object.
193695 */
193696 static void fts5CsrNewrow(Fts5Cursor *pCsr){
193697  CsrFlagSet(pCsr,
193698  FTS5CSR_REQUIRE_CONTENT
193699  | FTS5CSR_REQUIRE_DOCSIZE
193700  | FTS5CSR_REQUIRE_INST
193701  | FTS5CSR_REQUIRE_POSLIST
193702  );
193703 }
193704 
193705 static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
193706  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193707  Fts5Auxdata *pData;
193708  Fts5Auxdata *pNext;
193709 
193710  sqlite3_free(pCsr->aInstIter);
193711  sqlite3_free(pCsr->aInst);
193712  if( pCsr->pStmt ){
193713  int eStmt = fts5StmtType(pCsr);
193714  sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
193715  }
193716  if( pCsr->pSorter ){
193717  Fts5Sorter *pSorter = pCsr->pSorter;
193718  sqlite3_finalize(pSorter->pStmt);
193719  sqlite3_free(pSorter);
193720  }
193721 
193722  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
193723  sqlite3Fts5ExprFree(pCsr->pExpr);
193724  }
193725 
193726  for(pData=pCsr->pAuxdata; pData; pData=pNext){
193727  pNext = pData->pNext;
193728  if( pData->xDelete ) pData->xDelete(pData->pPtr);
193729  sqlite3_free(pData);
193730  }
193731 
193732  sqlite3_finalize(pCsr->pRankArgStmt);
193733  sqlite3_free(pCsr->apRankArg);
193734 
193735  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
193736  sqlite3_free(pCsr->zRank);
193737  sqlite3_free(pCsr->zRankArgs);
193738  }
193739 
193740  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
193741 }
193742 
193743 
193744 /*
193745 ** Close the cursor. For additional information see the documentation
193746 ** on the xClose method of the virtual table interface.
193747 */
193748 static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
193749  if( pCursor ){
193750  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
193751  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
193752  Fts5Cursor **pp;
193753 
193754  fts5FreeCursorComponents(pCsr);
193755  /* Remove the cursor from the Fts5Global.pCsr list */
193756  for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
193757  *pp = pCsr->pNext;
193758 
193759  sqlite3_free(pCsr);
193760  }
193761  return SQLITE_OK;
193762 }
193763 
193764 static int fts5SorterNext(Fts5Cursor *pCsr){
193765  Fts5Sorter *pSorter = pCsr->pSorter;
193766  int rc;
193767 
193768  rc = sqlite3_step(pSorter->pStmt);
193769  if( rc==SQLITE_DONE ){
193770  rc = SQLITE_OK;
193771  CsrFlagSet(pCsr, FTS5CSR_EOF);
193772  }else if( rc==SQLITE_ROW ){
193773  const u8 *a;
193774  const u8 *aBlob;
193775  int nBlob;
193776  int i;
193777  int iOff = 0;
193778  rc = SQLITE_OK;
193779 
193780  pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
193781  nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
193782  aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
193783 
193784  /* nBlob==0 in detail=none mode. */
193785  if( nBlob>0 ){
193786  for(i=0; i<(pSorter->nIdx-1); i++){
193787  int iVal;
193788  a += fts5GetVarint32(a, iVal);
193789  iOff += iVal;
193790  pSorter->aIdx[i] = iOff;
193791  }
193792  pSorter->aIdx[i] = &aBlob[nBlob] - a;
193793  pSorter->aPoslist = a;
193794  }
193795 
193796  fts5CsrNewrow(pCsr);
193797  }
193798 
193799  return rc;
193800 }
193801 
193802 
193803 /*
193804 ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
193805 ** open on table pTab.
193806 */
193807 static void fts5TripCursors(Fts5Table *pTab){
193808  Fts5Cursor *pCsr;
193809  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
193810  if( pCsr->ePlan==FTS5_PLAN_MATCH
193811  && pCsr->base.pVtab==(sqlite3_vtab*)pTab
193812  ){
193813  CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
193814  }
193815  }
193816 }
193817 
193818 /*
193819 ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
193820 ** argument, close and reopen all Fts5IndexIter iterators that the cursor
193821 ** is using. Then attempt to move the cursor to a rowid equal to or laster
193822 ** (in the cursors sort order - ASC or DESC) than the current rowid.
193823 **
193824 ** If the new rowid is not equal to the old, set output parameter *pbSkip
193825 ** to 1 before returning. Otherwise, leave it unchanged.
193826 **
193827 ** Return SQLITE_OK if successful or if no reseek was required, or an
193828 ** error code if an error occurred.
193829 */
193830 static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
193831  int rc = SQLITE_OK;
193832  assert( *pbSkip==0 );
193833  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
193834  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193835  int bDesc = pCsr->bDesc;
193836  i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
193837 
193838  rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
193839  if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
193840  *pbSkip = 1;
193841  }
193842 
193843  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
193844  fts5CsrNewrow(pCsr);
193845  if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
193846  CsrFlagSet(pCsr, FTS5CSR_EOF);
193847  *pbSkip = 1;
193848  }
193849  }
193850  return rc;
193851 }
193852 
193853 
193854 /*
193855 ** Advance the cursor to the next row in the table that matches the
193856 ** search criteria.
193857 **
193858 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
193859 ** even if we reach end-of-file. The fts5EofMethod() will be called
193860 ** subsequently to determine whether or not an EOF was hit.
193861 */
193862 static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
193863  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
193864  int rc;
193865 
193866  assert( (pCsr->ePlan<3)==
193867  (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
193868  );
193869  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
193870 
193871  if( pCsr->ePlan<3 ){
193872  int bSkip = 0;
193873  if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
193874  rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
193875  CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
193876  fts5CsrNewrow(pCsr);
193877  }else{
193878  switch( pCsr->ePlan ){
193879  case FTS5_PLAN_SPECIAL: {
193880  CsrFlagSet(pCsr, FTS5CSR_EOF);
193881  rc = SQLITE_OK;
193882  break;
193883  }
193884 
193885  case FTS5_PLAN_SORTED_MATCH: {
193886  rc = fts5SorterNext(pCsr);
193887  break;
193888  }
193889 
193890  default:
193891  rc = sqlite3_step(pCsr->pStmt);
193892  if( rc!=SQLITE_ROW ){
193893  CsrFlagSet(pCsr, FTS5CSR_EOF);
193894  rc = sqlite3_reset(pCsr->pStmt);
193895  }else{
193896  rc = SQLITE_OK;
193897  }
193898  break;
193899  }
193900  }
193901 
193902  return rc;
193903 }
193904 
193905 
193906 static int fts5PrepareStatement(
193907  sqlite3_stmt **ppStmt,
193908  Fts5Config *pConfig,
193909  const char *zFmt,
193910  ...
193911 ){
193912  sqlite3_stmt *pRet = 0;
193913  int rc;
193914  char *zSql;
193915  va_list ap;
193916 
193917  va_start(ap, zFmt);
193918  zSql = sqlite3_vmprintf(zFmt, ap);
193919  if( zSql==0 ){
193920  rc = SQLITE_NOMEM;
193921  }else{
193922  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
193923  if( rc!=SQLITE_OK ){
193924  *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
193925  }
193926  sqlite3_free(zSql);
193927  }
193928 
193929  va_end(ap);
193930  *ppStmt = pRet;
193931  return rc;
193932 }
193933 
193934 static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
193935  Fts5Config *pConfig = pTab->pConfig;
193936  Fts5Sorter *pSorter;
193937  int nPhrase;
193938  int nByte;
193939  int rc;
193940  const char *zRank = pCsr->zRank;
193941  const char *zRankArgs = pCsr->zRankArgs;
193942 
193943  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193944  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
193945  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
193946  if( pSorter==0 ) return SQLITE_NOMEM;
193947  memset(pSorter, 0, nByte);
193948  pSorter->nIdx = nPhrase;
193949 
193950  /* TODO: It would be better to have some system for reusing statement
193951  ** handles here, rather than preparing a new one for each query. But that
193952  ** is not possible as SQLite reference counts the virtual table objects.
193953  ** And since the statement required here reads from this very virtual
193954  ** table, saving it creates a circular reference.
193955  **
193956  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
193957  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
193958  "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
193959  pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
193960  (zRankArgs ? ", " : ""),
193961  (zRankArgs ? zRankArgs : ""),
193962  bDesc ? "DESC" : "ASC"
193963  );
193964 
193965  pCsr->pSorter = pSorter;
193966  if( rc==SQLITE_OK ){
193967  assert( pTab->pSortCsr==0 );
193968  pTab->pSortCsr = pCsr;
193969  rc = fts5SorterNext(pCsr);
193970  pTab->pSortCsr = 0;
193971  }
193972 
193973  if( rc!=SQLITE_OK ){
193974  sqlite3_finalize(pSorter->pStmt);
193975  sqlite3_free(pSorter);
193976  pCsr->pSorter = 0;
193977  }
193978 
193979  return rc;
193980 }
193981 
193982 static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
193983  int rc;
193984  Fts5Expr *pExpr = pCsr->pExpr;
193985  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
193986  if( sqlite3Fts5ExprEof(pExpr) ){
193987  CsrFlagSet(pCsr, FTS5CSR_EOF);
193988  }
193989  fts5CsrNewrow(pCsr);
193990  return rc;
193991 }
193992 
193993 /*
193994 ** Process a "special" query. A special query is identified as one with a
193995 ** MATCH expression that begins with a '*' character. The remainder of
193996 ** the text passed to the MATCH operator are used as the special query
193997 ** parameters.
193998 */
193999 static int fts5SpecialMatch(
194000  Fts5Table *pTab,
194001  Fts5Cursor *pCsr,
194002  const char *zQuery
194003 ){
194004  int rc = SQLITE_OK; /* Return code */
194005  const char *z = zQuery; /* Special query text */
194006  int n; /* Number of bytes in text at z */
194007 
194008  while( z[0]==' ' ) z++;
194009  for(n=0; z[n] && z[n]!=' '; n++);
194010 
194011  assert( pTab->base.zErrMsg==0 );
194012  pCsr->ePlan = FTS5_PLAN_SPECIAL;
194013 
194014  if( 0==sqlite3_strnicmp("reads", z, n) ){
194015  pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
194016  }
194017  else if( 0==sqlite3_strnicmp("id", z, n) ){
194018  pCsr->iSpecial = pCsr->iCsrId;
194019  }
194020  else{
194021  /* An unrecognized directive. Return an error message. */
194022  pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
194023  rc = SQLITE_ERROR;
194024  }
194025 
194026  return rc;
194027 }
194028 
194029 /*
194030 ** Search for an auxiliary function named zName that can be used with table
194031 ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
194032 ** structure. Otherwise, if no such function exists, return NULL.
194033 */
194034 static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
194035  Fts5Auxiliary *pAux;
194036 
194037  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
194038  if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
194039  }
194040 
194041  /* No function of the specified name was found. Return 0. */
194042  return 0;
194043 }
194044 
194045 
194046 static int fts5FindRankFunction(Fts5Cursor *pCsr){
194047  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194048  Fts5Config *pConfig = pTab->pConfig;
194049  int rc = SQLITE_OK;
194050  Fts5Auxiliary *pAux = 0;
194051  const char *zRank = pCsr->zRank;
194052  const char *zRankArgs = pCsr->zRankArgs;
194053 
194054  if( zRankArgs ){
194055  char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
194056  if( zSql ){
194057  sqlite3_stmt *pStmt = 0;
194058  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
194059  sqlite3_free(zSql);
194060  assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
194061  if( rc==SQLITE_OK ){
194062  if( SQLITE_ROW==sqlite3_step(pStmt) ){
194063  int nByte;
194064  pCsr->nRankArg = sqlite3_column_count(pStmt);
194065  nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
194066  pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
194067  if( rc==SQLITE_OK ){
194068  int i;
194069  for(i=0; i<pCsr->nRankArg; i++){
194070  pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
194071  }
194072  }
194073  pCsr->pRankArgStmt = pStmt;
194074  }else{
194075  rc = sqlite3_finalize(pStmt);
194076  assert( rc!=SQLITE_OK );
194077  }
194078  }
194079  }
194080  }
194081 
194082  if( rc==SQLITE_OK ){
194083  pAux = fts5FindAuxiliary(pTab, zRank);
194084  if( pAux==0 ){
194085  assert( pTab->base.zErrMsg==0 );
194086  pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
194087  rc = SQLITE_ERROR;
194088  }
194089  }
194090 
194091  pCsr->pRank = pAux;
194092  return rc;
194093 }
194094 
194095 
194096 static int fts5CursorParseRank(
194097  Fts5Config *pConfig,
194098  Fts5Cursor *pCsr,
194099  sqlite3_value *pRank
194100 ){
194101  int rc = SQLITE_OK;
194102  if( pRank ){
194103  const char *z = (const char*)sqlite3_value_text(pRank);
194104  char *zRank = 0;
194105  char *zRankArgs = 0;
194106 
194107  if( z==0 ){
194108  if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
194109  }else{
194110  rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
194111  }
194112  if( rc==SQLITE_OK ){
194113  pCsr->zRank = zRank;
194114  pCsr->zRankArgs = zRankArgs;
194115  CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
194116  }else if( rc==SQLITE_ERROR ){
194117  pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
194118  "parse error in rank function: %s", z
194119  );
194120  }
194121  }else{
194122  if( pConfig->zRank ){
194123  pCsr->zRank = (char*)pConfig->zRank;
194124  pCsr->zRankArgs = (char*)pConfig->zRankArgs;
194125  }else{
194126  pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
194127  pCsr->zRankArgs = 0;
194128  }
194129  }
194130  return rc;
194131 }
194132 
194133 static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
194134  if( pVal ){
194135  int eType = sqlite3_value_numeric_type(pVal);
194136  if( eType==SQLITE_INTEGER ){
194137  return sqlite3_value_int64(pVal);
194138  }
194139  }
194140  return iDefault;
194141 }
194142 
194143 /*
194144 ** This is the xFilter interface for the virtual table. See
194145 ** the virtual table xFilter method documentation for additional
194146 ** information.
194147 **
194148 ** There are three possible query strategies:
194149 **
194150 ** 1. Full-text search using a MATCH operator.
194151 ** 2. A by-rowid lookup.
194152 ** 3. A full-table scan.
194153 */
194154 static int fts5FilterMethod(
194155  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
194156  int idxNum, /* Strategy index */
194157  const char *zUnused, /* Unused */
194158  int nVal, /* Number of elements in apVal */
194159  sqlite3_value **apVal /* Arguments for the indexing scheme */
194160 ){
194161  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
194162  Fts5Config *pConfig = pTab->pConfig;
194163  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
194164  int rc = SQLITE_OK; /* Error code */
194165  int iVal = 0; /* Counter for apVal[] */
194166  int bDesc; /* True if ORDER BY [rank|rowid] DESC */
194167  int bOrderByRank; /* True if ORDER BY rank */
194168  sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
194169  sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
194170  sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
194171  sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
194172  sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
194173  char **pzErrmsg = pConfig->pzErrmsg;
194174 
194175  UNUSED_PARAM(zUnused);
194176  UNUSED_PARAM(nVal);
194177 
194178  if( pCsr->ePlan ){
194179  fts5FreeCursorComponents(pCsr);
194180  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
194181  }
194182 
194183  assert( pCsr->pStmt==0 );
194184  assert( pCsr->pExpr==0 );
194185  assert( pCsr->csrflags==0 );
194186  assert( pCsr->pRank==0 );
194187  assert( pCsr->zRank==0 );
194188  assert( pCsr->zRankArgs==0 );
194189 
194190  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
194191  pConfig->pzErrmsg = &pTab->base.zErrMsg;
194192 
194193  /* Decode the arguments passed through to this function.
194194  **
194195  ** Note: The following set of if(...) statements must be in the same
194196  ** order as the corresponding entries in the struct at the top of
194197  ** fts5BestIndexMethod(). */
194198  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
194199  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
194200  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
194201  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
194202  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
194203  assert( iVal==nVal );
194204  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
194205  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
194206 
194207  /* Set the cursor upper and lower rowid limits. Only some strategies
194208  ** actually use them. This is ok, as the xBestIndex() method leaves the
194209  ** sqlite3_index_constraint.omit flag clear for range constraints
194210  ** on the rowid field. */
194211  if( pRowidEq ){
194212  pRowidLe = pRowidGe = pRowidEq;
194213  }
194214  if( bDesc ){
194215  pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
194216  pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
194217  }else{
194218  pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
194219  pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
194220  }
194221 
194222  if( pTab->pSortCsr ){
194223  /* If pSortCsr is non-NULL, then this call is being made as part of
194224  ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
194225  ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
194226  ** return results to the user for this query. The current cursor
194227  ** (pCursor) is used to execute the query issued by function
194228  ** fts5CursorFirstSorted() above. */
194229  assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
194230  assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
194231  assert( pCsr->iLastRowid==LARGEST_INT64 );
194232  assert( pCsr->iFirstRowid==SMALLEST_INT64 );
194233  pCsr->ePlan = FTS5_PLAN_SOURCE;
194234  pCsr->pExpr = pTab->pSortCsr->pExpr;
194235  rc = fts5CursorFirst(pTab, pCsr, bDesc);
194236  }else if( pMatch ){
194237  const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
194238  if( zExpr==0 ) zExpr = "";
194239 
194240  rc = fts5CursorParseRank(pConfig, pCsr, pRank);
194241  if( rc==SQLITE_OK ){
194242  if( zExpr[0]=='*' ){
194243  /* The user has issued a query of the form "MATCH '*...'". This
194244  ** indicates that the MATCH expression is not a full text query,
194245  ** but a request for an internal parameter. */
194246  rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
194247  }else{
194248  char **pzErr = &pTab->base.zErrMsg;
194249  rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
194250  if( rc==SQLITE_OK ){
194251  if( bOrderByRank ){
194252  pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
194253  rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
194254  }else{
194255  pCsr->ePlan = FTS5_PLAN_MATCH;
194256  rc = fts5CursorFirst(pTab, pCsr, bDesc);
194257  }
194258  }
194259  }
194260  }
194261  }else if( pConfig->zContent==0 ){
194262  *pConfig->pzErrmsg = sqlite3_mprintf(
194263  "%s: table does not support scanning", pConfig->zName
194264  );
194265  rc = SQLITE_ERROR;
194266  }else{
194267  /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
194268  ** by rowid (ePlan==FTS5_PLAN_ROWID). */
194269  pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
194270  rc = sqlite3Fts5StorageStmt(
194271  pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
194272  );
194273  if( rc==SQLITE_OK ){
194274  if( pCsr->ePlan==FTS5_PLAN_ROWID ){
194275  sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
194276  }else{
194277  sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
194278  sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
194279  }
194280  rc = fts5NextMethod(pCursor);
194281  }
194282  }
194283 
194284  pConfig->pzErrmsg = pzErrmsg;
194285  return rc;
194286 }
194287 
194288 /*
194289 ** This is the xEof method of the virtual table. SQLite calls this
194290 ** routine to find out if it has reached the end of a result set.
194291 */
194292 static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
194293  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
194294  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
194295 }
194296 
194297 /*
194298 ** Return the rowid that the cursor currently points to.
194299 */
194300 static i64 fts5CursorRowid(Fts5Cursor *pCsr){
194301  assert( pCsr->ePlan==FTS5_PLAN_MATCH
194302  || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
194303  || pCsr->ePlan==FTS5_PLAN_SOURCE
194304  );
194305  if( pCsr->pSorter ){
194306  return pCsr->pSorter->iRowid;
194307  }else{
194308  return sqlite3Fts5ExprRowid(pCsr->pExpr);
194309  }
194310 }
194311 
194312 /*
194313 ** This is the xRowid method. The SQLite core calls this routine to
194314 ** retrieve the rowid for the current row of the result set. fts5
194315 ** exposes %_content.rowid as the rowid for the virtual table. The
194316 ** rowid should be written to *pRowid.
194317 */
194318 static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
194319  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
194320  int ePlan = pCsr->ePlan;
194321 
194322  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
194323  switch( ePlan ){
194324  case FTS5_PLAN_SPECIAL:
194325  *pRowid = 0;
194326  break;
194327 
194328  case FTS5_PLAN_SOURCE:
194329  case FTS5_PLAN_MATCH:
194330  case FTS5_PLAN_SORTED_MATCH:
194331  *pRowid = fts5CursorRowid(pCsr);
194332  break;
194333 
194334  default:
194335  *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
194336  break;
194337  }
194338 
194339  return SQLITE_OK;
194340 }
194341 
194342 /*
194343 ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
194344 ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
194345 **
194346 ** If argument bErrormsg is true and an error occurs, an error message may
194347 ** be left in sqlite3_vtab.zErrMsg.
194348 */
194349 static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
194350  int rc = SQLITE_OK;
194351 
194352  /* If the cursor does not yet have a statement handle, obtain one now. */
194353  if( pCsr->pStmt==0 ){
194354  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194355  int eStmt = fts5StmtType(pCsr);
194356  rc = sqlite3Fts5StorageStmt(
194357  pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
194358  );
194359  assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
194360  assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
194361  }
194362 
194363  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
194364  assert( pCsr->pExpr );
194365  sqlite3_reset(pCsr->pStmt);
194366  sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
194367  rc = sqlite3_step(pCsr->pStmt);
194368  if( rc==SQLITE_ROW ){
194369  rc = SQLITE_OK;
194370  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
194371  }else{
194372  rc = sqlite3_reset(pCsr->pStmt);
194373  if( rc==SQLITE_OK ){
194374  rc = FTS5_CORRUPT;
194375  }
194376  }
194377  }
194378  return rc;
194379 }
194380 
194381 static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
194382  va_list ap; /* ... printf arguments */
194383  va_start(ap, zFormat);
194384  assert( p->base.zErrMsg==0 );
194385  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
194386  va_end(ap);
194387 }
194388 
194389 /*
194390 ** This function is called to handle an FTS INSERT command. In other words,
194391 ** an INSERT statement of the form:
194392 **
194393 ** INSERT INTO fts(fts) VALUES($pCmd)
194394 ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
194395 **
194396 ** Argument pVal is the value assigned to column "fts" by the INSERT
194397 ** statement. This function returns SQLITE_OK if successful, or an SQLite
194398 ** error code if an error occurs.
194399 **
194400 ** The commands implemented by this function are documented in the "Special
194401 ** INSERT Directives" section of the documentation. It should be updated if
194402 ** more commands are added to this function.
194403 */
194404 static int fts5SpecialInsert(
194405  Fts5Table *pTab, /* Fts5 table object */
194406  const char *zCmd, /* Text inserted into table-name column */
194407  sqlite3_value *pVal /* Value inserted into rank column */
194408 ){
194409  Fts5Config *pConfig = pTab->pConfig;
194410  int rc = SQLITE_OK;
194411  int bError = 0;
194412 
194413  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
194414  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194415  fts5SetVtabError(pTab,
194416  "'delete-all' may only be used with a "
194417  "contentless or external content fts5 table"
194418  );
194419  rc = SQLITE_ERROR;
194420  }else{
194421  rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
194422  }
194423  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
194424  if( pConfig->eContent==FTS5_CONTENT_NONE ){
194425  fts5SetVtabError(pTab,
194426  "'rebuild' may not be used with a contentless fts5 table"
194427  );
194428  rc = SQLITE_ERROR;
194429  }else{
194430  rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
194431  }
194432  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
194433  rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
194434  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
194435  int nMerge = sqlite3_value_int(pVal);
194436  rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
194437  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
194438  rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
194439 #ifdef SQLITE_DEBUG
194440  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
194441  pConfig->bPrefixIndex = sqlite3_value_int(pVal);
194442 #endif
194443  }else{
194444  rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
194445  if( rc==SQLITE_OK ){
194446  rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
194447  }
194448  if( rc==SQLITE_OK ){
194449  if( bError ){
194450  rc = SQLITE_ERROR;
194451  }else{
194452  rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
194453  }
194454  }
194455  }
194456  return rc;
194457 }
194458 
194459 static int fts5SpecialDelete(
194460  Fts5Table *pTab,
194461  sqlite3_value **apVal
194462 ){
194463  int rc = SQLITE_OK;
194464  int eType1 = sqlite3_value_type(apVal[1]);
194465  if( eType1==SQLITE_INTEGER ){
194466  sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
194467  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
194468  }
194469  return rc;
194470 }
194471 
194472 static void fts5StorageInsert(
194473  int *pRc,
194474  Fts5Table *pTab,
194475  sqlite3_value **apVal,
194476  i64 *piRowid
194477 ){
194478  int rc = *pRc;
194479  if( rc==SQLITE_OK ){
194480  rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
194481  }
194482  if( rc==SQLITE_OK ){
194483  rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
194484  }
194485  *pRc = rc;
194486 }
194487 
194488 /*
194489 ** This function is the implementation of the xUpdate callback used by
194490 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
194491 ** inserted, updated or deleted.
194492 **
194493 ** A delete specifies a single argument - the rowid of the row to remove.
194494 **
194495 ** Update and insert operations pass:
194496 **
194497 ** 1. The "old" rowid, or NULL.
194498 ** 2. The "new" rowid.
194499 ** 3. Values for each of the nCol matchable columns.
194500 ** 4. Values for the two hidden columns (<tablename> and "rank").
194501 */
194502 static int fts5UpdateMethod(
194503  sqlite3_vtab *pVtab, /* Virtual table handle */
194504  int nArg, /* Size of argument array */
194505  sqlite3_value **apVal, /* Array of arguments */
194506  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
194507 ){
194508  Fts5Table *pTab = (Fts5Table*)pVtab;
194509  Fts5Config *pConfig = pTab->pConfig;
194510  int eType0; /* value_type() of apVal[0] */
194511  int rc = SQLITE_OK; /* Return code */
194512 
194513  /* A transaction must be open when this is called. */
194514  assert( pTab->ts.eState==1 );
194515 
194516  assert( pVtab->zErrMsg==0 );
194517  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
194518  assert( nArg==1
194519  || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
194520  || sqlite3_value_type(apVal[1])==SQLITE_NULL
194521  );
194522  assert( pTab->pConfig->pzErrmsg==0 );
194523  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
194524 
194525  /* Put any active cursors into REQUIRE_SEEK state. */
194526  fts5TripCursors(pTab);
194527 
194528  eType0 = sqlite3_value_type(apVal[0]);
194529  if( eType0==SQLITE_NULL
194530  && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
194531  ){
194532  /* A "special" INSERT op. These are handled separately. */
194533  const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
194534  if( pConfig->eContent!=FTS5_CONTENT_NORMAL
194535  && 0==sqlite3_stricmp("delete", z)
194536  ){
194537  rc = fts5SpecialDelete(pTab, apVal);
194538  }else{
194539  rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
194540  }
194541  }else{
194542  /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
194543  ** any conflict on the rowid value must be detected before any
194544  ** modifications are made to the database file. There are 4 cases:
194545  **
194546  ** 1) DELETE
194547  ** 2) UPDATE (rowid not modified)
194548  ** 3) UPDATE (rowid modified)
194549  ** 4) INSERT
194550  **
194551  ** Cases 3 and 4 may violate the rowid constraint.
194552  */
194553  int eConflict = SQLITE_ABORT;
194554  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194555  eConflict = sqlite3_vtab_on_conflict(pConfig->db);
194556  }
194557 
194558  assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
194559  assert( nArg!=1 || eType0==SQLITE_INTEGER );
194560 
194561  /* Filter out attempts to run UPDATE or DELETE on contentless tables.
194562  ** This is not suported. */
194563  if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
194564  pTab->base.zErrMsg = sqlite3_mprintf(
194565  "cannot %s contentless fts5 table: %s",
194566  (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
194567  );
194568  rc = SQLITE_ERROR;
194569  }
194570 
194571  /* DELETE */
194572  else if( nArg==1 ){
194573  i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
194574  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
194575  }
194576 
194577  /* INSERT */
194578  else if( eType0!=SQLITE_INTEGER ){
194579  /* If this is a REPLACE, first remove the current entry (if any) */
194580  if( eConflict==SQLITE_REPLACE
194581  && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
194582  ){
194583  i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
194584  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
194585  }
194586  fts5StorageInsert(&rc, pTab, apVal, pRowid);
194587  }
194588 
194589  /* UPDATE */
194590  else{
194591  i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
194592  i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
194593  if( iOld!=iNew ){
194594  if( eConflict==SQLITE_REPLACE ){
194595  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
194596  if( rc==SQLITE_OK ){
194597  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
194598  }
194599  fts5StorageInsert(&rc, pTab, apVal, pRowid);
194600  }else{
194601  rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
194602  if( rc==SQLITE_OK ){
194603  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
194604  }
194605  if( rc==SQLITE_OK ){
194606  rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
194607  }
194608  }
194609  }else{
194610  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
194611  fts5StorageInsert(&rc, pTab, apVal, pRowid);
194612  }
194613  }
194614  }
194615 
194616  pTab->pConfig->pzErrmsg = 0;
194617  return rc;
194618 }
194619 
194620 /*
194621 ** Implementation of xSync() method.
194622 */
194623 static int fts5SyncMethod(sqlite3_vtab *pVtab){
194624  int rc;
194625  Fts5Table *pTab = (Fts5Table*)pVtab;
194626  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
194627  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
194628  fts5TripCursors(pTab);
194629  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
194630  pTab->pConfig->pzErrmsg = 0;
194631  return rc;
194632 }
194633 
194634 /*
194635 ** Implementation of xBegin() method.
194636 */
194637 static int fts5BeginMethod(sqlite3_vtab *pVtab){
194638  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
194639  fts5NewTransaction((Fts5Table*)pVtab);
194640  return SQLITE_OK;
194641 }
194642 
194643 /*
194644 ** Implementation of xCommit() method. This is a no-op. The contents of
194645 ** the pending-terms hash-table have already been flushed into the database
194646 ** by fts5SyncMethod().
194647 */
194648 static int fts5CommitMethod(sqlite3_vtab *pVtab){
194649  UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
194650  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
194651  return SQLITE_OK;
194652 }
194653 
194654 /*
194655 ** Implementation of xRollback(). Discard the contents of the pending-terms
194656 ** hash-table. Any changes made to the database are reverted by SQLite.
194657 */
194658 static int fts5RollbackMethod(sqlite3_vtab *pVtab){
194659  int rc;
194660  Fts5Table *pTab = (Fts5Table*)pVtab;
194661  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
194662  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
194663  return rc;
194664 }
194665 
194666 static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
194667 
194668 static void *fts5ApiUserData(Fts5Context *pCtx){
194669  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194670  return pCsr->pAux->pUserData;
194671 }
194672 
194673 static int fts5ApiColumnCount(Fts5Context *pCtx){
194674  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194675  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
194676 }
194677 
194678 static int fts5ApiColumnTotalSize(
194679  Fts5Context *pCtx,
194680  int iCol,
194681  sqlite3_int64 *pnToken
194682 ){
194683  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194684  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194685  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
194686 }
194687 
194688 static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
194689  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194690  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194691  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
194692 }
194693 
194694 static int fts5ApiTokenize(
194695  Fts5Context *pCtx,
194696  const char *pText, int nText,
194697  void *pUserData,
194698  int (*xToken)(void*, int, const char*, int, int, int)
194699 ){
194700  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194701  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194702  return sqlite3Fts5Tokenize(
194703  pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
194704  );
194705 }
194706 
194707 static int fts5ApiPhraseCount(Fts5Context *pCtx){
194708  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194709  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
194710 }
194711 
194712 static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
194713  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194714  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
194715 }
194716 
194717 static int fts5ApiColumnText(
194718  Fts5Context *pCtx,
194719  int iCol,
194720  const char **pz,
194721  int *pn
194722 ){
194723  int rc = SQLITE_OK;
194724  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194725  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
194726  *pz = 0;
194727  *pn = 0;
194728  }else{
194729  rc = fts5SeekCursor(pCsr, 0);
194730  if( rc==SQLITE_OK ){
194731  *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
194732  *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
194733  }
194734  }
194735  return rc;
194736 }
194737 
194738 static int fts5CsrPoslist(
194739  Fts5Cursor *pCsr,
194740  int iPhrase,
194741  const u8 **pa,
194742  int *pn
194743 ){
194744  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
194745  int rc = SQLITE_OK;
194746  int bLive = (pCsr->pSorter==0);
194747 
194748  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
194749 
194750  if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
194751  Fts5PoslistPopulator *aPopulator;
194752  int i;
194753  aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
194754  if( aPopulator==0 ) rc = SQLITE_NOMEM;
194755  for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
194756  int n; const char *z;
194757  rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
194758  if( rc==SQLITE_OK ){
194759  rc = sqlite3Fts5ExprPopulatePoslists(
194760  pConfig, pCsr->pExpr, aPopulator, i, z, n
194761  );
194762  }
194763  }
194764  sqlite3_free(aPopulator);
194765 
194766  if( pCsr->pSorter ){
194767  sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
194768  }
194769  }
194770  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
194771  }
194772 
194773  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
194774  Fts5Sorter *pSorter = pCsr->pSorter;
194775  int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
194776  *pn = pSorter->aIdx[iPhrase] - i1;
194777  *pa = &pSorter->aPoslist[i1];
194778  }else{
194779  *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
194780  }
194781 
194782  return rc;
194783 }
194784 
194785 /*
194786 ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
194787 ** correctly for the current view. Return SQLITE_OK if successful, or an
194788 ** SQLite error code otherwise.
194789 */
194790 static int fts5CacheInstArray(Fts5Cursor *pCsr){
194791  int rc = SQLITE_OK;
194792  Fts5PoslistReader *aIter; /* One iterator for each phrase */
194793  int nIter; /* Number of iterators/phrases */
194794 
194795  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
194796  if( pCsr->aInstIter==0 ){
194797  int nByte = sizeof(Fts5PoslistReader) * nIter;
194798  pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
194799  }
194800  aIter = pCsr->aInstIter;
194801 
194802  if( aIter ){
194803  int nInst = 0; /* Number instances seen so far */
194804  int i;
194805 
194806  /* Initialize all iterators */
194807  for(i=0; i<nIter && rc==SQLITE_OK; i++){
194808  const u8 *a;
194809  int n;
194810  rc = fts5CsrPoslist(pCsr, i, &a, &n);
194811  if( rc==SQLITE_OK ){
194812  sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
194813  }
194814  }
194815 
194816  if( rc==SQLITE_OK ){
194817  while( 1 ){
194818  int *aInst;
194819  int iBest = -1;
194820  for(i=0; i<nIter; i++){
194821  if( (aIter[i].bEof==0)
194822  && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
194823  ){
194824  iBest = i;
194825  }
194826  }
194827  if( iBest<0 ) break;
194828 
194829  nInst++;
194830  if( nInst>=pCsr->nInstAlloc ){
194831  pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
194832  aInst = (int*)sqlite3_realloc(
194833  pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
194834  );
194835  if( aInst ){
194836  pCsr->aInst = aInst;
194837  }else{
194838  rc = SQLITE_NOMEM;
194839  break;
194840  }
194841  }
194842 
194843  aInst = &pCsr->aInst[3 * (nInst-1)];
194844  aInst[0] = iBest;
194845  aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
194846  aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
194847  sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
194848  }
194849  }
194850 
194851  pCsr->nInstCount = nInst;
194852  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
194853  }
194854  return rc;
194855 }
194856 
194857 static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
194858  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194859  int rc = SQLITE_OK;
194860  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
194861  || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
194862  *pnInst = pCsr->nInstCount;
194863  }
194864  return rc;
194865 }
194866 
194867 static int fts5ApiInst(
194868  Fts5Context *pCtx,
194869  int iIdx,
194870  int *piPhrase,
194871  int *piCol,
194872  int *piOff
194873 ){
194874  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194875  int rc = SQLITE_OK;
194876  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
194877  || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
194878  ){
194879  if( iIdx<0 || iIdx>=pCsr->nInstCount ){
194880  rc = SQLITE_RANGE;
194881 #if 0
194882  }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
194883  *piPhrase = pCsr->aInst[iIdx*3];
194884  *piCol = pCsr->aInst[iIdx*3 + 2];
194885  *piOff = -1;
194886 #endif
194887  }else{
194888  *piPhrase = pCsr->aInst[iIdx*3];
194889  *piCol = pCsr->aInst[iIdx*3 + 1];
194890  *piOff = pCsr->aInst[iIdx*3 + 2];
194891  }
194892  }
194893  return rc;
194894 }
194895 
194896 static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
194897  return fts5CursorRowid((Fts5Cursor*)pCtx);
194898 }
194899 
194900 static int fts5ColumnSizeCb(
194901  void *pContext, /* Pointer to int */
194902  int tflags,
194903  const char *pUnused, /* Buffer containing token */
194904  int nUnused, /* Size of token in bytes */
194905  int iUnused1, /* Start offset of token */
194906  int iUnused2 /* End offset of token */
194907 ){
194908  int *pCnt = (int*)pContext;
194909  UNUSED_PARAM2(pUnused, nUnused);
194910  UNUSED_PARAM2(iUnused1, iUnused2);
194911  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
194912  (*pCnt)++;
194913  }
194914  return SQLITE_OK;
194915 }
194916 
194917 static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
194918  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194919  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
194920  Fts5Config *pConfig = pTab->pConfig;
194921  int rc = SQLITE_OK;
194922 
194923  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
194924  if( pConfig->bColumnsize ){
194925  i64 iRowid = fts5CursorRowid(pCsr);
194926  rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
194927  }else if( pConfig->zContent==0 ){
194928  int i;
194929  for(i=0; i<pConfig->nCol; i++){
194930  if( pConfig->abUnindexed[i]==0 ){
194931  pCsr->aColumnSize[i] = -1;
194932  }
194933  }
194934  }else{
194935  int i;
194936  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
194937  if( pConfig->abUnindexed[i]==0 ){
194938  const char *z; int n;
194939  void *p = (void*)(&pCsr->aColumnSize[i]);
194940  pCsr->aColumnSize[i] = 0;
194941  rc = fts5ApiColumnText(pCtx, i, &z, &n);
194942  if( rc==SQLITE_OK ){
194943  rc = sqlite3Fts5Tokenize(
194944  pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
194945  );
194946  }
194947  }
194948  }
194949  }
194950  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
194951  }
194952  if( iCol<0 ){
194953  int i;
194954  *pnToken = 0;
194955  for(i=0; i<pConfig->nCol; i++){
194956  *pnToken += pCsr->aColumnSize[i];
194957  }
194958  }else if( iCol<pConfig->nCol ){
194959  *pnToken = pCsr->aColumnSize[iCol];
194960  }else{
194961  *pnToken = 0;
194962  rc = SQLITE_RANGE;
194963  }
194964  return rc;
194965 }
194966 
194967 /*
194968 ** Implementation of the xSetAuxdata() method.
194969 */
194970 static int fts5ApiSetAuxdata(
194971  Fts5Context *pCtx, /* Fts5 context */
194972  void *pPtr, /* Pointer to save as auxdata */
194973  void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
194974 ){
194975  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
194976  Fts5Auxdata *pData;
194977 
194978  /* Search through the cursors list of Fts5Auxdata objects for one that
194979  ** corresponds to the currently executing auxiliary function. */
194980  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
194981  if( pData->pAux==pCsr->pAux ) break;
194982  }
194983 
194984  if( pData ){
194985  if( pData->xDelete ){
194986  pData->xDelete(pData->pPtr);
194987  }
194988  }else{
194989  int rc = SQLITE_OK;
194990  pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
194991  if( pData==0 ){
194992  if( xDelete ) xDelete(pPtr);
194993  return rc;
194994  }
194995  pData->pAux = pCsr->pAux;
194996  pData->pNext = pCsr->pAuxdata;
194997  pCsr->pAuxdata = pData;
194998  }
194999 
195000  pData->xDelete = xDelete;
195001  pData->pPtr = pPtr;
195002  return SQLITE_OK;
195003 }
195004 
195005 static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
195006  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195007  Fts5Auxdata *pData;
195008  void *pRet = 0;
195009 
195010  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
195011  if( pData->pAux==pCsr->pAux ) break;
195012  }
195013 
195014  if( pData ){
195015  pRet = pData->pPtr;
195016  if( bClear ){
195017  pData->pPtr = 0;
195018  pData->xDelete = 0;
195019  }
195020  }
195021 
195022  return pRet;
195023 }
195024 
195025 static void fts5ApiPhraseNext(
195026  Fts5Context *pUnused,
195027  Fts5PhraseIter *pIter,
195028  int *piCol, int *piOff
195029 ){
195030  UNUSED_PARAM(pUnused);
195031  if( pIter->a>=pIter->b ){
195032  *piCol = -1;
195033  *piOff = -1;
195034  }else{
195035  int iVal;
195036  pIter->a += fts5GetVarint32(pIter->a, iVal);
195037  if( iVal==1 ){
195038  pIter->a += fts5GetVarint32(pIter->a, iVal);
195039  *piCol = iVal;
195040  *piOff = 0;
195041  pIter->a += fts5GetVarint32(pIter->a, iVal);
195042  }
195043  *piOff += (iVal-2);
195044  }
195045 }
195046 
195047 static int fts5ApiPhraseFirst(
195048  Fts5Context *pCtx,
195049  int iPhrase,
195050  Fts5PhraseIter *pIter,
195051  int *piCol, int *piOff
195052 ){
195053  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195054  int n;
195055  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
195056  if( rc==SQLITE_OK ){
195057  pIter->b = &pIter->a[n];
195058  *piCol = 0;
195059  *piOff = 0;
195060  fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
195061  }
195062  return rc;
195063 }
195064 
195065 static void fts5ApiPhraseNextColumn(
195066  Fts5Context *pCtx,
195067  Fts5PhraseIter *pIter,
195068  int *piCol
195069 ){
195070  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195071  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
195072 
195073  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195074  if( pIter->a>=pIter->b ){
195075  *piCol = -1;
195076  }else{
195077  int iIncr;
195078  pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
195079  *piCol += (iIncr-2);
195080  }
195081  }else{
195082  while( 1 ){
195083  int dummy;
195084  if( pIter->a>=pIter->b ){
195085  *piCol = -1;
195086  return;
195087  }
195088  if( pIter->a[0]==0x01 ) break;
195089  pIter->a += fts5GetVarint32(pIter->a, dummy);
195090  }
195091  pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
195092  }
195093 }
195094 
195095 static int fts5ApiPhraseFirstColumn(
195096  Fts5Context *pCtx,
195097  int iPhrase,
195098  Fts5PhraseIter *pIter,
195099  int *piCol
195100 ){
195101  int rc = SQLITE_OK;
195102  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195103  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
195104 
195105  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195106  Fts5Sorter *pSorter = pCsr->pSorter;
195107  int n;
195108  if( pSorter ){
195109  int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
195110  n = pSorter->aIdx[iPhrase] - i1;
195111  pIter->a = &pSorter->aPoslist[i1];
195112  }else{
195113  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
195114  }
195115  if( rc==SQLITE_OK ){
195116  pIter->b = &pIter->a[n];
195117  *piCol = 0;
195118  fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
195119  }
195120  }else{
195121  int n;
195122  rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
195123  if( rc==SQLITE_OK ){
195124  pIter->b = &pIter->a[n];
195125  if( n<=0 ){
195126  *piCol = -1;
195127  }else if( pIter->a[0]==0x01 ){
195128  pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
195129  }else{
195130  *piCol = 0;
195131  }
195132  }
195133  }
195134 
195135  return rc;
195136 }
195137 
195138 
195139 static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
195140  int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
195141 );
195142 
195143 static const Fts5ExtensionApi sFts5Api = {
195144  2, /* iVersion */
195145  fts5ApiUserData,
195146  fts5ApiColumnCount,
195147  fts5ApiRowCount,
195148  fts5ApiColumnTotalSize,
195149  fts5ApiTokenize,
195150  fts5ApiPhraseCount,
195151  fts5ApiPhraseSize,
195152  fts5ApiInstCount,
195153  fts5ApiInst,
195154  fts5ApiRowid,
195155  fts5ApiColumnText,
195156  fts5ApiColumnSize,
195157  fts5ApiQueryPhrase,
195158  fts5ApiSetAuxdata,
195159  fts5ApiGetAuxdata,
195160  fts5ApiPhraseFirst,
195161  fts5ApiPhraseNext,
195162  fts5ApiPhraseFirstColumn,
195163  fts5ApiPhraseNextColumn,
195164 };
195165 
195166 /*
195167 ** Implementation of API function xQueryPhrase().
195168 */
195169 static int fts5ApiQueryPhrase(
195170  Fts5Context *pCtx,
195171  int iPhrase,
195172  void *pUserData,
195173  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
195174 ){
195175  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
195176  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
195177  int rc;
195178  Fts5Cursor *pNew = 0;
195179 
195180  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
195181  if( rc==SQLITE_OK ){
195182  pNew->ePlan = FTS5_PLAN_MATCH;
195183  pNew->iFirstRowid = SMALLEST_INT64;
195184  pNew->iLastRowid = LARGEST_INT64;
195185  pNew->base.pVtab = (sqlite3_vtab*)pTab;
195186  rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
195187  }
195188 
195189  if( rc==SQLITE_OK ){
195190  for(rc = fts5CursorFirst(pTab, pNew, 0);
195191  rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
195192  rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
195193  ){
195194  rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
195195  if( rc!=SQLITE_OK ){
195196  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195197  break;
195198  }
195199  }
195200  }
195201 
195202  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
195203  return rc;
195204 }
195205 
195206 static void fts5ApiInvoke(
195207  Fts5Auxiliary *pAux,
195208  Fts5Cursor *pCsr,
195209  sqlite3_context *context,
195210  int argc,
195211  sqlite3_value **argv
195212 ){
195213  assert( pCsr->pAux==0 );
195214  pCsr->pAux = pAux;
195215  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
195216  pCsr->pAux = 0;
195217 }
195218 
195219 static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
195220  Fts5Cursor *pCsr;
195221  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
195222  if( pCsr->iCsrId==iCsrId ) break;
195223  }
195224  return pCsr;
195225 }
195226 
195227 static void fts5ApiCallback(
195228  sqlite3_context *context,
195229  int argc,
195230  sqlite3_value **argv
195231 ){
195232 
195233  Fts5Auxiliary *pAux;
195234  Fts5Cursor *pCsr;
195235  i64 iCsrId;
195236 
195237  assert( argc>=1 );
195238  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
195239  iCsrId = sqlite3_value_int64(argv[0]);
195240 
195241  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
195242  if( pCsr==0 ){
195243  char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
195244  sqlite3_result_error(context, zErr, -1);
195245  sqlite3_free(zErr);
195246  }else{
195247  fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
195248  }
195249 }
195250 
195251 
195252 /*
195253 ** Given cursor id iId, return a pointer to the corresponding Fts5Index
195254 ** object. Or NULL If the cursor id does not exist.
195255 **
195256 ** If successful, set *ppConfig to point to the associated config object
195257 ** before returning.
195258 */
195259 static Fts5Index *sqlite3Fts5IndexFromCsrid(
195260  Fts5Global *pGlobal, /* FTS5 global context for db handle */
195261  i64 iCsrId, /* Id of cursor to find */
195262  Fts5Config **ppConfig /* OUT: Configuration object */
195263 ){
195264  Fts5Cursor *pCsr;
195265  Fts5Table *pTab;
195266 
195267  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
195268  pTab = (Fts5Table*)pCsr->base.pVtab;
195269  *ppConfig = pTab->pConfig;
195270 
195271  return pTab->pIndex;
195272 }
195273 
195274 /*
195275 ** Return a "position-list blob" corresponding to the current position of
195276 ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
195277 ** the current position-list for each phrase in the query associated with
195278 ** cursor pCsr.
195279 **
195280 ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
195281 ** the number of phrases in the query. Following the varints are the
195282 ** concatenated position lists for each phrase, in order.
195283 **
195284 ** The first varint (if it exists) contains the size of the position list
195285 ** for phrase 0. The second (same disclaimer) contains the size of position
195286 ** list 1. And so on. There is no size field for the final position list,
195287 ** as it can be derived from the total size of the blob.
195288 */
195289 static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
195290  int i;
195291  int rc = SQLITE_OK;
195292  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
195293  Fts5Buffer val;
195294 
195295  memset(&val, 0, sizeof(Fts5Buffer));
195296  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
195297  case FTS5_DETAIL_FULL:
195298 
195299  /* Append the varints */
195300  for(i=0; i<(nPhrase-1); i++){
195301  const u8 *dummy;
195302  int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
195303  sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
195304  }
195305 
195306  /* Append the position lists */
195307  for(i=0; i<nPhrase; i++){
195308  const u8 *pPoslist;
195309  int nPoslist;
195310  nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
195311  sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
195312  }
195313  break;
195314 
195315  case FTS5_DETAIL_COLUMNS:
195316 
195317  /* Append the varints */
195318  for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
195319  const u8 *dummy;
195320  int nByte;
195321  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
195322  sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
195323  }
195324 
195325  /* Append the position lists */
195326  for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
195327  const u8 *pPoslist;
195328  int nPoslist;
195329  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
195330  sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
195331  }
195332  break;
195333 
195334  default:
195335  break;
195336  }
195337 
195338  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
195339  return rc;
195340 }
195341 
195342 /*
195343 ** This is the xColumn method, called by SQLite to request a value from
195344 ** the row that the supplied cursor currently points to.
195345 */
195346 static int fts5ColumnMethod(
195347  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
195348  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
195349  int iCol /* Index of column to read value from */
195350 ){
195351  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
195352  Fts5Config *pConfig = pTab->pConfig;
195353  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
195354  int rc = SQLITE_OK;
195355 
195356  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
195357 
195358  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
195359  if( iCol==pConfig->nCol ){
195360  sqlite3_result_int64(pCtx, pCsr->iSpecial);
195361  }
195362  }else
195363 
195364  if( iCol==pConfig->nCol ){
195365  /* User is requesting the value of the special column with the same name
195366  ** as the table. Return the cursor integer id number. This value is only
195367  ** useful in that it may be passed as the first argument to an FTS5
195368  ** auxiliary function. */
195369  sqlite3_result_int64(pCtx, pCsr->iCsrId);
195370  }else if( iCol==pConfig->nCol+1 ){
195371 
195372  /* The value of the "rank" column. */
195373  if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
195374  fts5PoslistBlob(pCtx, pCsr);
195375  }else if(
195376  pCsr->ePlan==FTS5_PLAN_MATCH
195377  || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
195378  ){
195379  if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
195380  fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
195381  }
195382  }
195383  }else if( !fts5IsContentless(pTab) ){
195384  rc = fts5SeekCursor(pCsr, 1);
195385  if( rc==SQLITE_OK ){
195386  sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
195387  }
195388  }
195389  return rc;
195390 }
195391 
195392 
195393 /*
195394 ** This routine implements the xFindFunction method for the FTS3
195395 ** virtual table.
195396 */
195397 static int fts5FindFunctionMethod(
195398  sqlite3_vtab *pVtab, /* Virtual table handle */
195399  int nUnused, /* Number of SQL function arguments */
195400  const char *zName, /* Name of SQL function */
195401  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
195402  void **ppArg /* OUT: User data for *pxFunc */
195403 ){
195404  Fts5Table *pTab = (Fts5Table*)pVtab;
195405  Fts5Auxiliary *pAux;
195406 
195407  UNUSED_PARAM(nUnused);
195408  pAux = fts5FindAuxiliary(pTab, zName);
195409  if( pAux ){
195410  *pxFunc = fts5ApiCallback;
195411  *ppArg = (void*)pAux;
195412  return 1;
195413  }
195414 
195415  /* No function of the specified name was found. Return 0. */
195416  return 0;
195417 }
195418 
195419 /*
195420 ** Implementation of FTS5 xRename method. Rename an fts5 table.
195421 */
195422 static int fts5RenameMethod(
195423  sqlite3_vtab *pVtab, /* Virtual table handle */
195424  const char *zName /* New name of table */
195425 ){
195426  Fts5Table *pTab = (Fts5Table*)pVtab;
195427  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
195428 }
195429 
195430 /*
195431 ** The xSavepoint() method.
195432 **
195433 ** Flush the contents of the pending-terms table to disk.
195434 */
195435 static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
195436  Fts5Table *pTab = (Fts5Table*)pVtab;
195437  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
195438  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
195439  fts5TripCursors(pTab);
195440  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
195441 }
195442 
195443 /*
195444 ** The xRelease() method.
195445 **
195446 ** This is a no-op.
195447 */
195448 static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
195449  Fts5Table *pTab = (Fts5Table*)pVtab;
195450  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
195451  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
195452  fts5TripCursors(pTab);
195453  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
195454 }
195455 
195456 /*
195457 ** The xRollbackTo() method.
195458 **
195459 ** Discard the contents of the pending terms table.
195460 */
195461 static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
195462  Fts5Table *pTab = (Fts5Table*)pVtab;
195463  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
195464  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
195465  fts5TripCursors(pTab);
195466  return sqlite3Fts5StorageRollback(pTab->pStorage);
195467 }
195468 
195469 /*
195470 ** Register a new auxiliary function with global context pGlobal.
195471 */
195472 static int fts5CreateAux(
195473  fts5_api *pApi, /* Global context (one per db handle) */
195474  const char *zName, /* Name of new function */
195475  void *pUserData, /* User data for aux. function */
195476  fts5_extension_function xFunc, /* Aux. function implementation */
195477  void(*xDestroy)(void*) /* Destructor for pUserData */
195478 ){
195479  Fts5Global *pGlobal = (Fts5Global*)pApi;
195480  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
195481  if( rc==SQLITE_OK ){
195482  Fts5Auxiliary *pAux;
195483  int nName; /* Size of zName in bytes, including \0 */
195484  int nByte; /* Bytes of space to allocate */
195485 
195486  nName = (int)strlen(zName) + 1;
195487  nByte = sizeof(Fts5Auxiliary) + nName;
195488  pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
195489  if( pAux ){
195490  memset(pAux, 0, nByte);
195491  pAux->zFunc = (char*)&pAux[1];
195492  memcpy(pAux->zFunc, zName, nName);
195493  pAux->pGlobal = pGlobal;
195494  pAux->pUserData = pUserData;
195495  pAux->xFunc = xFunc;
195496  pAux->xDestroy = xDestroy;
195497  pAux->pNext = pGlobal->pAux;
195498  pGlobal->pAux = pAux;
195499  }else{
195500  rc = SQLITE_NOMEM;
195501  }
195502  }
195503 
195504  return rc;
195505 }
195506 
195507 /*
195508 ** Register a new tokenizer. This is the implementation of the
195509 ** fts5_api.xCreateTokenizer() method.
195510 */
195511 static int fts5CreateTokenizer(
195512  fts5_api *pApi, /* Global context (one per db handle) */
195513  const char *zName, /* Name of new function */
195514  void *pUserData, /* User data for aux. function */
195515  fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
195516  void(*xDestroy)(void*) /* Destructor for pUserData */
195517 ){
195518  Fts5Global *pGlobal = (Fts5Global*)pApi;
195519  Fts5TokenizerModule *pNew;
195520  int nName; /* Size of zName and its \0 terminator */
195521  int nByte; /* Bytes of space to allocate */
195522  int rc = SQLITE_OK;
195523 
195524  nName = (int)strlen(zName) + 1;
195525  nByte = sizeof(Fts5TokenizerModule) + nName;
195526  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
195527  if( pNew ){
195528  memset(pNew, 0, nByte);
195529  pNew->zName = (char*)&pNew[1];
195530  memcpy(pNew->zName, zName, nName);
195531  pNew->pUserData = pUserData;
195532  pNew->x = *pTokenizer;
195533  pNew->xDestroy = xDestroy;
195534  pNew->pNext = pGlobal->pTok;
195535  pGlobal->pTok = pNew;
195536  if( pNew->pNext==0 ){
195537  pGlobal->pDfltTok = pNew;
195538  }
195539  }else{
195540  rc = SQLITE_NOMEM;
195541  }
195542 
195543  return rc;
195544 }
195545 
195546 static Fts5TokenizerModule *fts5LocateTokenizer(
195547  Fts5Global *pGlobal,
195548  const char *zName
195549 ){
195550  Fts5TokenizerModule *pMod = 0;
195551 
195552  if( zName==0 ){
195553  pMod = pGlobal->pDfltTok;
195554  }else{
195555  for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
195556  if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
195557  }
195558  }
195559 
195560  return pMod;
195561 }
195562 
195563 /*
195564 ** Find a tokenizer. This is the implementation of the
195565 ** fts5_api.xFindTokenizer() method.
195566 */
195567 static int fts5FindTokenizer(
195568  fts5_api *pApi, /* Global context (one per db handle) */
195569  const char *zName, /* Name of new function */
195570  void **ppUserData,
195571  fts5_tokenizer *pTokenizer /* Populate this object */
195572 ){
195573  int rc = SQLITE_OK;
195574  Fts5TokenizerModule *pMod;
195575 
195576  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
195577  if( pMod ){
195578  *pTokenizer = pMod->x;
195579  *ppUserData = pMod->pUserData;
195580  }else{
195581  memset(pTokenizer, 0, sizeof(fts5_tokenizer));
195582  rc = SQLITE_ERROR;
195583  }
195584 
195585  return rc;
195586 }
195587 
195588 static int sqlite3Fts5GetTokenizer(
195589  Fts5Global *pGlobal,
195590  const char **azArg,
195591  int nArg,
195592  Fts5Tokenizer **ppTok,
195593  fts5_tokenizer **ppTokApi,
195594  char **pzErr
195595 ){
195596  Fts5TokenizerModule *pMod;
195597  int rc = SQLITE_OK;
195598 
195599  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
195600  if( pMod==0 ){
195601  assert( nArg>0 );
195602  rc = SQLITE_ERROR;
195603  *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
195604  }else{
195605  rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
195606  *ppTokApi = &pMod->x;
195607  if( rc!=SQLITE_OK && pzErr ){
195608  *pzErr = sqlite3_mprintf("error in tokenizer constructor");
195609  }
195610  }
195611 
195612  if( rc!=SQLITE_OK ){
195613  *ppTokApi = 0;
195614  *ppTok = 0;
195615  }
195616 
195617  return rc;
195618 }
195619 
195620 static void fts5ModuleDestroy(void *pCtx){
195621  Fts5TokenizerModule *pTok, *pNextTok;
195622  Fts5Auxiliary *pAux, *pNextAux;
195623  Fts5Global *pGlobal = (Fts5Global*)pCtx;
195624 
195625  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
195626  pNextAux = pAux->pNext;
195627  if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
195628  sqlite3_free(pAux);
195629  }
195630 
195631  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
195632  pNextTok = pTok->pNext;
195633  if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
195634  sqlite3_free(pTok);
195635  }
195636 
195637  sqlite3_free(pGlobal);
195638 }
195639 
195640 static void fts5Fts5Func(
195641  sqlite3_context *pCtx, /* Function call context */
195642  int nArg, /* Number of args */
195643  sqlite3_value **apUnused /* Function arguments */
195644 ){
195645  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
195646  char buf[8];
195647  UNUSED_PARAM2(nArg, apUnused);
195648  assert( nArg==0 );
195649  assert( sizeof(buf)>=sizeof(pGlobal) );
195650  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
195651  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
195652 }
195653 
195654 /*
195655 ** Implementation of fts5_source_id() function.
195656 */
195657 static void fts5SourceIdFunc(
195658  sqlite3_context *pCtx, /* Function call context */
195659  int nArg, /* Number of args */
195660  sqlite3_value **apUnused /* Function arguments */
195661 ){
195662  assert( nArg==0 );
195663  UNUSED_PARAM2(nArg, apUnused);
195664  sqlite3_result_text(pCtx, "fts5: 2016-11-28 19:13:37 bbd85d235f7037c6a033a9690534391ffeacecc8", -1, SQLITE_TRANSIENT);
195665 }
195666 
195667 static int fts5Init(sqlite3 *db){
195668  static const sqlite3_module fts5Mod = {
195669  /* iVersion */ 2,
195670  /* xCreate */ fts5CreateMethod,
195671  /* xConnect */ fts5ConnectMethod,
195672  /* xBestIndex */ fts5BestIndexMethod,
195673  /* xDisconnect */ fts5DisconnectMethod,
195674  /* xDestroy */ fts5DestroyMethod,
195675  /* xOpen */ fts5OpenMethod,
195676  /* xClose */ fts5CloseMethod,
195677  /* xFilter */ fts5FilterMethod,
195678  /* xNext */ fts5NextMethod,
195679  /* xEof */ fts5EofMethod,
195680  /* xColumn */ fts5ColumnMethod,
195681  /* xRowid */ fts5RowidMethod,
195682  /* xUpdate */ fts5UpdateMethod,
195683  /* xBegin */ fts5BeginMethod,
195684  /* xSync */ fts5SyncMethod,
195685  /* xCommit */ fts5CommitMethod,
195686  /* xRollback */ fts5RollbackMethod,
195687  /* xFindFunction */ fts5FindFunctionMethod,
195688  /* xRename */ fts5RenameMethod,
195689  /* xSavepoint */ fts5SavepointMethod,
195690  /* xRelease */ fts5ReleaseMethod,
195691  /* xRollbackTo */ fts5RollbackToMethod,
195692  };
195693 
195694  int rc;
195695  Fts5Global *pGlobal = 0;
195696 
195697  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
195698  if( pGlobal==0 ){
195699  rc = SQLITE_NOMEM;
195700  }else{
195701  void *p = (void*)pGlobal;
195702  memset(pGlobal, 0, sizeof(Fts5Global));
195703  pGlobal->db = db;
195704  pGlobal->api.iVersion = 2;
195705  pGlobal->api.xCreateFunction = fts5CreateAux;
195706  pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
195707  pGlobal->api.xFindTokenizer = fts5FindTokenizer;
195708  rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
195709  if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
195710  if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
195711  if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
195712  if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
195713  if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
195714  if( rc==SQLITE_OK ){
195716  db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
195717  );
195718  }
195719  if( rc==SQLITE_OK ){
195721  db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
195722  );
195723  }
195724  }
195725 
195726  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
195727  ** fts5_test_mi.c is compiled and linked into the executable. And call
195728  ** its entry point to enable the matchinfo() demo. */
195729 #ifdef SQLITE_FTS5_ENABLE_TEST_MI
195730  if( rc==SQLITE_OK ){
195731  extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
195732  rc = sqlite3Fts5TestRegisterMatchinfo(db);
195733  }
195734 #endif
195735 
195736  return rc;
195737 }
195738 
195739 /*
195740 ** The following functions are used to register the module with SQLite. If
195741 ** this module is being built as part of the SQLite core (SQLITE_CORE is
195742 ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
195743 **
195744 ** Or, if this module is being built as a loadable extension,
195745 ** sqlite3Fts5Init() is omitted and the two standard entry points
195746 ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
195747 */
195748 #ifndef SQLITE_CORE
195749 #ifdef _WIN32
195750 __declspec(dllexport)
195751 #endif
195752 SQLITE_API int sqlite3_fts_init(
195753  sqlite3 *db,
195754  char **pzErrMsg,
195755  const sqlite3_api_routines *pApi
195756 ){
195757  SQLITE_EXTENSION_INIT2(pApi);
195758  (void)pzErrMsg; /* Unused parameter */
195759  return fts5Init(db);
195760 }
195761 
195762 #ifdef _WIN32
195763 __declspec(dllexport)
195764 #endif
195765 SQLITE_API int sqlite3_fts5_init(
195766  sqlite3 *db,
195767  char **pzErrMsg,
195768  const sqlite3_api_routines *pApi
195769 ){
195770  SQLITE_EXTENSION_INIT2(pApi);
195771  (void)pzErrMsg; /* Unused parameter */
195772  return fts5Init(db);
195773 }
195774 #else
195775 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
195776  return fts5Init(db);
195777 }
195778 #endif
195779 
195780 /*
195781 ** 2014 May 31
195782 **
195783 ** The author disclaims copyright to this source code. In place of
195784 ** a legal notice, here is a blessing:
195785 **
195786 ** May you do good and not evil.
195787 ** May you find forgiveness for yourself and forgive others.
195788 ** May you share freely, never taking more than you give.
195789 **
195790 ******************************************************************************
195791 **
195792 */
195793 
195794 
195795 
195796 /* #include "fts5Int.h" */
195797 
195798 struct Fts5Storage {
195799  Fts5Config *pConfig;
195800  Fts5Index *pIndex;
195801  int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
195802  i64 nTotalRow; /* Total number of rows in FTS table */
195803  i64 *aTotalSize; /* Total sizes of each column */
195804  sqlite3_stmt *aStmt[11];
195805 };
195806 
195807 
195808 #if FTS5_STMT_SCAN_ASC!=0
195809 # error "FTS5_STMT_SCAN_ASC mismatch"
195810 #endif
195811 #if FTS5_STMT_SCAN_DESC!=1
195812 # error "FTS5_STMT_SCAN_DESC mismatch"
195813 #endif
195814 #if FTS5_STMT_LOOKUP!=2
195815 # error "FTS5_STMT_LOOKUP mismatch"
195816 #endif
195817 
195818 #define FTS5_STMT_INSERT_CONTENT 3
195819 #define FTS5_STMT_REPLACE_CONTENT 4
195820 #define FTS5_STMT_DELETE_CONTENT 5
195821 #define FTS5_STMT_REPLACE_DOCSIZE 6
195822 #define FTS5_STMT_DELETE_DOCSIZE 7
195823 #define FTS5_STMT_LOOKUP_DOCSIZE 8
195824 #define FTS5_STMT_REPLACE_CONFIG 9
195825 #define FTS5_STMT_SCAN 10
195826 
195827 /*
195828 ** Prepare the two insert statements - Fts5Storage.pInsertContent and
195829 ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
195830 ** Return SQLITE_OK if successful, or an SQLite error code if an error
195831 ** occurs.
195832 */
195833 static int fts5StorageGetStmt(
195834  Fts5Storage *p, /* Storage handle */
195835  int eStmt, /* FTS5_STMT_XXX constant */
195836  sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
195837  char **pzErrMsg /* OUT: Error message (if any) */
195838 ){
195839  int rc = SQLITE_OK;
195840 
195841  /* If there is no %_docsize table, there should be no requests for
195842  ** statements to operate on it. */
195843  assert( p->pConfig->bColumnsize || (
195844  eStmt!=FTS5_STMT_REPLACE_DOCSIZE
195845  && eStmt!=FTS5_STMT_DELETE_DOCSIZE
195846  && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
195847  ));
195848 
195849  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
195850  if( p->aStmt[eStmt]==0 ){
195851  const char *azStmt[] = {
195852  "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
195853  "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
195854  "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
195855 
195856  "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
195857  "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
195858  "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
195859  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
195860  "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
195861 
195862  "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
195863 
195864  "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
195865  "SELECT %s FROM %s AS T", /* SCAN */
195866  };
195867  Fts5Config *pC = p->pConfig;
195868  char *zSql = 0;
195869 
195870  switch( eStmt ){
195871  case FTS5_STMT_SCAN:
195872  zSql = sqlite3_mprintf(azStmt[eStmt],
195873  pC->zContentExprlist, pC->zContent
195874  );
195875  break;
195876 
195877  case FTS5_STMT_SCAN_ASC:
195878  case FTS5_STMT_SCAN_DESC:
195879  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
195880  pC->zContent, pC->zContentRowid, pC->zContentRowid,
195881  pC->zContentRowid
195882  );
195883  break;
195884 
195885  case FTS5_STMT_LOOKUP:
195886  zSql = sqlite3_mprintf(azStmt[eStmt],
195887  pC->zContentExprlist, pC->zContent, pC->zContentRowid
195888  );
195889  break;
195890 
195891  case FTS5_STMT_INSERT_CONTENT:
195892  case FTS5_STMT_REPLACE_CONTENT: {
195893  int nCol = pC->nCol + 1;
195894  char *zBind;
195895  int i;
195896 
195897  zBind = sqlite3_malloc(1 + nCol*2);
195898  if( zBind ){
195899  for(i=0; i<nCol; i++){
195900  zBind[i*2] = '?';
195901  zBind[i*2 + 1] = ',';
195902  }
195903  zBind[i*2-1] = '\0';
195904  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
195905  sqlite3_free(zBind);
195906  }
195907  break;
195908  }
195909 
195910  default:
195911  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
195912  break;
195913  }
195914 
195915  if( zSql==0 ){
195916  rc = SQLITE_NOMEM;
195917  }else{
195918  rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
195919  sqlite3_free(zSql);
195920  if( rc!=SQLITE_OK && pzErrMsg ){
195921  *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
195922  }
195923  }
195924  }
195925 
195926  *ppStmt = p->aStmt[eStmt];
195927  sqlite3_reset(*ppStmt);
195928  return rc;
195929 }
195930 
195931 
195932 static int fts5ExecPrintf(
195933  sqlite3 *db,
195934  char **pzErr,
195935  const char *zFormat,
195936  ...
195937 ){
195938  int rc;
195939  va_list ap; /* ... printf arguments */
195940  char *zSql;
195941 
195942  va_start(ap, zFormat);
195943  zSql = sqlite3_vmprintf(zFormat, ap);
195944 
195945  if( zSql==0 ){
195946  rc = SQLITE_NOMEM;
195947  }else{
195948  rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
195949  sqlite3_free(zSql);
195950  }
195951 
195952  va_end(ap);
195953  return rc;
195954 }
195955 
195956 /*
195957 ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
195958 ** code otherwise.
195959 */
195960 static int sqlite3Fts5DropAll(Fts5Config *pConfig){
195961  int rc = fts5ExecPrintf(pConfig->db, 0,
195962  "DROP TABLE IF EXISTS %Q.'%q_data';"
195963  "DROP TABLE IF EXISTS %Q.'%q_idx';"
195964  "DROP TABLE IF EXISTS %Q.'%q_config';",
195965  pConfig->zDb, pConfig->zName,
195966  pConfig->zDb, pConfig->zName,
195967  pConfig->zDb, pConfig->zName
195968  );
195969  if( rc==SQLITE_OK && pConfig->bColumnsize ){
195970  rc = fts5ExecPrintf(pConfig->db, 0,
195971  "DROP TABLE IF EXISTS %Q.'%q_docsize';",
195972  pConfig->zDb, pConfig->zName
195973  );
195974  }
195975  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
195976  rc = fts5ExecPrintf(pConfig->db, 0,
195977  "DROP TABLE IF EXISTS %Q.'%q_content';",
195978  pConfig->zDb, pConfig->zName
195979  );
195980  }
195981  return rc;
195982 }
195983 
195984 static void fts5StorageRenameOne(
195985  Fts5Config *pConfig, /* Current FTS5 configuration */
195986  int *pRc, /* IN/OUT: Error code */
195987  const char *zTail, /* Tail of table name e.g. "data", "config" */
195988  const char *zName /* New name of FTS5 table */
195989 ){
195990  if( *pRc==SQLITE_OK ){
195991  *pRc = fts5ExecPrintf(pConfig->db, 0,
195992  "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
195993  pConfig->zDb, pConfig->zName, zTail, zName, zTail
195994  );
195995  }
195996 }
195997 
195998 static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
195999  Fts5Config *pConfig = pStorage->pConfig;
196000  int rc = sqlite3Fts5StorageSync(pStorage, 1);
196001 
196002  fts5StorageRenameOne(pConfig, &rc, "data", zName);
196003  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
196004  fts5StorageRenameOne(pConfig, &rc, "config", zName);
196005  if( pConfig->bColumnsize ){
196006  fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
196007  }
196008  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
196009  fts5StorageRenameOne(pConfig, &rc, "content", zName);
196010  }
196011  return rc;
196012 }
196013 
196014 /*
196015 ** Create the shadow table named zPost, with definition zDefn. Return
196016 ** SQLITE_OK if successful, or an SQLite error code otherwise.
196017 */
196018 static int sqlite3Fts5CreateTable(
196019  Fts5Config *pConfig, /* FTS5 configuration */
196020  const char *zPost, /* Shadow table to create (e.g. "content") */
196021  const char *zDefn, /* Columns etc. for shadow table */
196022  int bWithout, /* True for without rowid */
196023  char **pzErr /* OUT: Error message */
196024 ){
196025  int rc;
196026  char *zErr = 0;
196027 
196028  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
196029  pConfig->zDb, pConfig->zName, zPost, zDefn,
196030 #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
196031  bWithout?" WITHOUT ROWID":
196032 #endif
196033  ""
196034  );
196035  if( zErr ){
196036  *pzErr = sqlite3_mprintf(
196037  "fts5: error creating shadow table %q_%s: %s",
196038  pConfig->zName, zPost, zErr
196039  );
196040  sqlite3_free(zErr);
196041  }
196042 
196043  return rc;
196044 }
196045 
196046 /*
196047 ** Open a new Fts5Index handle. If the bCreate argument is true, create
196048 ** and initialize the underlying tables
196049 **
196050 ** If successful, set *pp to point to the new object and return SQLITE_OK.
196051 ** Otherwise, set *pp to NULL and return an SQLite error code.
196052 */
196053 static int sqlite3Fts5StorageOpen(
196054  Fts5Config *pConfig,
196055  Fts5Index *pIndex,
196056  int bCreate,
196057  Fts5Storage **pp,
196058  char **pzErr /* OUT: Error message */
196059 ){
196060  int rc = SQLITE_OK;
196061  Fts5Storage *p; /* New object */
196062  int nByte; /* Bytes of space to allocate */
196063 
196064  nByte = sizeof(Fts5Storage) /* Fts5Storage object */
196065  + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
196066  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
196067  if( !p ) return SQLITE_NOMEM;
196068 
196069  memset(p, 0, nByte);
196070  p->aTotalSize = (i64*)&p[1];
196071  p->pConfig = pConfig;
196072  p->pIndex = pIndex;
196073 
196074  if( bCreate ){
196075  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
196076  int nDefn = 32 + pConfig->nCol*10;
196077  char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
196078  if( zDefn==0 ){
196079  rc = SQLITE_NOMEM;
196080  }else{
196081  int i;
196082  int iOff;
196083  sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
196084  iOff = (int)strlen(zDefn);
196085  for(i=0; i<pConfig->nCol; i++){
196086  sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
196087  iOff += (int)strlen(&zDefn[iOff]);
196088  }
196089  rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
196090  }
196091  sqlite3_free(zDefn);
196092  }
196093 
196094  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196095  rc = sqlite3Fts5CreateTable(
196096  pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
196097  );
196098  }
196099  if( rc==SQLITE_OK ){
196100  rc = sqlite3Fts5CreateTable(
196101  pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
196102  );
196103  }
196104  if( rc==SQLITE_OK ){
196105  rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
196106  }
196107  }
196108 
196109  if( rc ){
196110  sqlite3Fts5StorageClose(p);
196111  *pp = 0;
196112  }
196113  return rc;
196114 }
196115 
196116 /*
196117 ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
196118 */
196119 static int sqlite3Fts5StorageClose(Fts5Storage *p){
196120  int rc = SQLITE_OK;
196121  if( p ){
196122  int i;
196123 
196124  /* Finalize all SQL statements */
196125  for(i=0; i<ArraySize(p->aStmt); i++){
196126  sqlite3_finalize(p->aStmt[i]);
196127  }
196128 
196129  sqlite3_free(p);
196130  }
196131  return rc;
196132 }
196133 
196134 typedef struct Fts5InsertCtx Fts5InsertCtx;
196135 struct Fts5InsertCtx {
196136  Fts5Storage *pStorage;
196137  int iCol;
196138  int szCol; /* Size of column value in tokens */
196139 };
196140 
196141 /*
196142 ** Tokenization callback used when inserting tokens into the FTS index.
196143 */
196144 static int fts5StorageInsertCallback(
196145  void *pContext, /* Pointer to Fts5InsertCtx object */
196146  int tflags,
196147  const char *pToken, /* Buffer containing token */
196148  int nToken, /* Size of token in bytes */
196149  int iUnused1, /* Start offset of token */
196150  int iUnused2 /* End offset of token */
196151 ){
196152  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
196153  Fts5Index *pIdx = pCtx->pStorage->pIndex;
196154  UNUSED_PARAM2(iUnused1, iUnused2);
196155  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
196156  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
196157  pCtx->szCol++;
196158  }
196159  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
196160 }
196161 
196162 /*
196163 ** If a row with rowid iDel is present in the %_content table, add the
196164 ** delete-markers to the FTS index necessary to delete it. Do not actually
196165 ** remove the %_content row at this time though.
196166 */
196167 static int fts5StorageDeleteFromIndex(
196168  Fts5Storage *p,
196169  i64 iDel,
196170  sqlite3_value **apVal
196171 ){
196172  Fts5Config *pConfig = p->pConfig;
196173  sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
196174  int rc; /* Return code */
196175  int rc2; /* sqlite3_reset() return code */
196176  int iCol;
196177  Fts5InsertCtx ctx;
196178 
196179  if( apVal==0 ){
196180  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
196181  if( rc!=SQLITE_OK ) return rc;
196182  sqlite3_bind_int64(pSeek, 1, iDel);
196183  if( sqlite3_step(pSeek)!=SQLITE_ROW ){
196184  return sqlite3_reset(pSeek);
196185  }
196186  }
196187 
196188  ctx.pStorage = p;
196189  ctx.iCol = -1;
196190  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
196191  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
196192  if( pConfig->abUnindexed[iCol-1]==0 ){
196193  const char *zText;
196194  int nText;
196195  if( pSeek ){
196196  zText = (const char*)sqlite3_column_text(pSeek, iCol);
196197  nText = sqlite3_column_bytes(pSeek, iCol);
196198  }else{
196199  zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
196200  nText = sqlite3_value_bytes(apVal[iCol-1]);
196201  }
196202  ctx.szCol = 0;
196203  rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
196204  zText, nText, (void*)&ctx, fts5StorageInsertCallback
196205  );
196206  p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
196207  }
196208  }
196209  p->nTotalRow--;
196210 
196211  rc2 = sqlite3_reset(pSeek);
196212  if( rc==SQLITE_OK ) rc = rc2;
196213  return rc;
196214 }
196215 
196216 
196217 /*
196218 ** Insert a record into the %_docsize table. Specifically, do:
196219 **
196220 ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
196221 **
196222 ** If there is no %_docsize table (as happens if the columnsize=0 option
196223 ** is specified when the FTS5 table is created), this function is a no-op.
196224 */
196225 static int fts5StorageInsertDocsize(
196226  Fts5Storage *p, /* Storage module to write to */
196227  i64 iRowid, /* id value */
196228  Fts5Buffer *pBuf /* sz value */
196229 ){
196230  int rc = SQLITE_OK;
196231  if( p->pConfig->bColumnsize ){
196232  sqlite3_stmt *pReplace = 0;
196233  rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
196234  if( rc==SQLITE_OK ){
196235  sqlite3_bind_int64(pReplace, 1, iRowid);
196236  sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
196237  sqlite3_step(pReplace);
196238  rc = sqlite3_reset(pReplace);
196239  }
196240  }
196241  return rc;
196242 }
196243 
196244 /*
196245 ** Load the contents of the "averages" record from disk into the
196246 ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
196247 ** argument bCache is true, set the p->bTotalsValid flag to indicate
196248 ** that the contents of aTotalSize[] and nTotalRow are valid until
196249 ** further notice.
196250 **
196251 ** Return SQLITE_OK if successful, or an SQLite error code if an error
196252 ** occurs.
196253 */
196254 static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
196255  int rc = SQLITE_OK;
196256  if( p->bTotalsValid==0 ){
196257  rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
196258  p->bTotalsValid = bCache;
196259  }
196260  return rc;
196261 }
196262 
196263 /*
196264 ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
196265 ** variables in the "averages" record on disk.
196266 **
196267 ** Return SQLITE_OK if successful, or an SQLite error code if an error
196268 ** occurs.
196269 */
196270 static int fts5StorageSaveTotals(Fts5Storage *p){
196271  int nCol = p->pConfig->nCol;
196272  int i;
196273  Fts5Buffer buf;
196274  int rc = SQLITE_OK;
196275  memset(&buf, 0, sizeof(buf));
196276 
196277  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
196278  for(i=0; i<nCol; i++){
196279  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
196280  }
196281  if( rc==SQLITE_OK ){
196282  rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
196283  }
196284  sqlite3_free(buf.p);
196285 
196286  return rc;
196287 }
196288 
196289 /*
196290 ** Remove a row from the FTS table.
196291 */
196292 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
196293  Fts5Config *pConfig = p->pConfig;
196294  int rc;
196295  sqlite3_stmt *pDel = 0;
196296 
196297  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
196298  rc = fts5StorageLoadTotals(p, 1);
196299 
196300  /* Delete the index records */
196301  if( rc==SQLITE_OK ){
196302  rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
196303  }
196304 
196305  /* Delete the %_docsize record */
196306  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196307  rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
196308  if( rc==SQLITE_OK ){
196309  sqlite3_bind_int64(pDel, 1, iDel);
196310  sqlite3_step(pDel);
196311  rc = sqlite3_reset(pDel);
196312  }
196313  }
196314 
196315  /* Delete the %_content record */
196316  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
196317  if( rc==SQLITE_OK ){
196318  rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
196319  }
196320  if( rc==SQLITE_OK ){
196321  sqlite3_bind_int64(pDel, 1, iDel);
196322  sqlite3_step(pDel);
196323  rc = sqlite3_reset(pDel);
196324  }
196325  }
196326 
196327  /* Write the averages record */
196328  if( rc==SQLITE_OK ){
196329  rc = fts5StorageSaveTotals(p);
196330  }
196331 
196332  return rc;
196333 }
196334 
196335 /*
196336 ** Delete all entries in the FTS5 index.
196337 */
196338 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
196339  Fts5Config *pConfig = p->pConfig;
196340  int rc;
196341 
196342  /* Delete the contents of the %_data and %_docsize tables. */
196343  rc = fts5ExecPrintf(pConfig->db, 0,
196344  "DELETE FROM %Q.'%q_data';"
196345  "DELETE FROM %Q.'%q_idx';",
196346  pConfig->zDb, pConfig->zName,
196347  pConfig->zDb, pConfig->zName
196348  );
196349  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196350  rc = fts5ExecPrintf(pConfig->db, 0,
196351  "DELETE FROM %Q.'%q_docsize';",
196352  pConfig->zDb, pConfig->zName
196353  );
196354  }
196355 
196356  /* Reinitialize the %_data table. This call creates the initial structure
196357  ** and averages records. */
196358  if( rc==SQLITE_OK ){
196359  rc = sqlite3Fts5IndexReinit(p->pIndex);
196360  }
196361  if( rc==SQLITE_OK ){
196362  rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
196363  }
196364  return rc;
196365 }
196366 
196367 static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
196368  Fts5Buffer buf = {0,0,0};
196369  Fts5Config *pConfig = p->pConfig;
196370  sqlite3_stmt *pScan = 0;
196371  Fts5InsertCtx ctx;
196372  int rc;
196373 
196374  memset(&ctx, 0, sizeof(Fts5InsertCtx));
196375  ctx.pStorage = p;
196376  rc = sqlite3Fts5StorageDeleteAll(p);
196377  if( rc==SQLITE_OK ){
196378  rc = fts5StorageLoadTotals(p, 1);
196379  }
196380 
196381  if( rc==SQLITE_OK ){
196382  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
196383  }
196384 
196385  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
196386  i64 iRowid = sqlite3_column_int64(pScan, 0);
196387 
196388  sqlite3Fts5BufferZero(&buf);
196389  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
196390  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
196391  ctx.szCol = 0;
196392  if( pConfig->abUnindexed[ctx.iCol]==0 ){
196393  rc = sqlite3Fts5Tokenize(pConfig,
196395  (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
196396  sqlite3_column_bytes(pScan, ctx.iCol+1),
196397  (void*)&ctx,
196398  fts5StorageInsertCallback
196399  );
196400  }
196401  sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
196402  p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
196403  }
196404  p->nTotalRow++;
196405 
196406  if( rc==SQLITE_OK ){
196407  rc = fts5StorageInsertDocsize(p, iRowid, &buf);
196408  }
196409  }
196410  sqlite3_free(buf.p);
196411 
196412  /* Write the averages record */
196413  if( rc==SQLITE_OK ){
196414  rc = fts5StorageSaveTotals(p);
196415  }
196416  return rc;
196417 }
196418 
196419 static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
196420  return sqlite3Fts5IndexOptimize(p->pIndex);
196421 }
196422 
196423 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
196424  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
196425 }
196426 
196427 static int sqlite3Fts5StorageReset(Fts5Storage *p){
196428  return sqlite3Fts5IndexReset(p->pIndex);
196429 }
196430 
196431 /*
196432 ** Allocate a new rowid. This is used for "external content" tables when
196433 ** a NULL value is inserted into the rowid column. The new rowid is allocated
196434 ** by inserting a dummy row into the %_docsize table. The dummy will be
196435 ** overwritten later.
196436 **
196437 ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
196438 ** this case the user is required to provide a rowid explicitly.
196439 */
196440 static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
196441  int rc = SQLITE_MISMATCH;
196442  if( p->pConfig->bColumnsize ){
196443  sqlite3_stmt *pReplace = 0;
196444  rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
196445  if( rc==SQLITE_OK ){
196446  sqlite3_bind_null(pReplace, 1);
196447  sqlite3_bind_null(pReplace, 2);
196448  sqlite3_step(pReplace);
196449  rc = sqlite3_reset(pReplace);
196450  }
196451  if( rc==SQLITE_OK ){
196452  *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
196453  }
196454  }
196455  return rc;
196456 }
196457 
196458 /*
196459 ** Insert a new row into the FTS content table.
196460 */
196461 static int sqlite3Fts5StorageContentInsert(
196462  Fts5Storage *p,
196463  sqlite3_value **apVal,
196464  i64 *piRowid
196465 ){
196466  Fts5Config *pConfig = p->pConfig;
196467  int rc = SQLITE_OK;
196468 
196469  /* Insert the new row into the %_content table. */
196470  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
196471  if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
196472  *piRowid = sqlite3_value_int64(apVal[1]);
196473  }else{
196474  rc = fts5StorageNewRowid(p, piRowid);
196475  }
196476  }else{
196477  sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
196478  int i; /* Counter variable */
196479  rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
196480  for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
196481  rc = sqlite3_bind_value(pInsert, i, apVal[i]);
196482  }
196483  if( rc==SQLITE_OK ){
196484  sqlite3_step(pInsert);
196485  rc = sqlite3_reset(pInsert);
196486  }
196487  *piRowid = sqlite3_last_insert_rowid(pConfig->db);
196488  }
196489 
196490  return rc;
196491 }
196492 
196493 /*
196494 ** Insert new entries into the FTS index and %_docsize table.
196495 */
196496 static int sqlite3Fts5StorageIndexInsert(
196497  Fts5Storage *p,
196498  sqlite3_value **apVal,
196499  i64 iRowid
196500 ){
196501  Fts5Config *pConfig = p->pConfig;
196502  int rc = SQLITE_OK; /* Return code */
196503  Fts5InsertCtx ctx; /* Tokenization callback context object */
196504  Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
196505 
196506  memset(&buf, 0, sizeof(Fts5Buffer));
196507  ctx.pStorage = p;
196508  rc = fts5StorageLoadTotals(p, 1);
196509 
196510  if( rc==SQLITE_OK ){
196511  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
196512  }
196513  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
196514  ctx.szCol = 0;
196515  if( pConfig->abUnindexed[ctx.iCol]==0 ){
196516  rc = sqlite3Fts5Tokenize(pConfig,
196518  (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
196519  sqlite3_value_bytes(apVal[ctx.iCol+2]),
196520  (void*)&ctx,
196521  fts5StorageInsertCallback
196522  );
196523  }
196524  sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
196525  p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
196526  }
196527  p->nTotalRow++;
196528 
196529  /* Write the %_docsize record */
196530  if( rc==SQLITE_OK ){
196531  rc = fts5StorageInsertDocsize(p, iRowid, &buf);
196532  }
196533  sqlite3_free(buf.p);
196534 
196535  /* Write the averages record */
196536  if( rc==SQLITE_OK ){
196537  rc = fts5StorageSaveTotals(p);
196538  }
196539 
196540  return rc;
196541 }
196542 
196543 static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
196544  Fts5Config *pConfig = p->pConfig;
196545  char *zSql;
196546  int rc;
196547 
196548  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
196549  pConfig->zDb, pConfig->zName, zSuffix
196550  );
196551  if( zSql==0 ){
196552  rc = SQLITE_NOMEM;
196553  }else{
196554  sqlite3_stmt *pCnt = 0;
196555  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
196556  if( rc==SQLITE_OK ){
196557  if( SQLITE_ROW==sqlite3_step(pCnt) ){
196558  *pnRow = sqlite3_column_int64(pCnt, 0);
196559  }
196560  rc = sqlite3_finalize(pCnt);
196561  }
196562  }
196563 
196564  sqlite3_free(zSql);
196565  return rc;
196566 }
196567 
196568 /*
196569 ** Context object used by sqlite3Fts5StorageIntegrity().
196570 */
196571 typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
196572 struct Fts5IntegrityCtx {
196573  i64 iRowid;
196574  int iCol;
196575  int szCol;
196576  u64 cksum;
196577  Fts5Termset *pTermset;
196578  Fts5Config *pConfig;
196579 };
196580 
196581 
196582 /*
196583 ** Tokenization callback used by integrity check.
196584 */
196585 static int fts5StorageIntegrityCallback(
196586  void *pContext, /* Pointer to Fts5IntegrityCtx object */
196587  int tflags,
196588  const char *pToken, /* Buffer containing token */
196589  int nToken, /* Size of token in bytes */
196590  int iUnused1, /* Start offset of token */
196591  int iUnused2 /* End offset of token */
196592 ){
196593  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
196594  Fts5Termset *pTermset = pCtx->pTermset;
196595  int bPresent;
196596  int ii;
196597  int rc = SQLITE_OK;
196598  int iPos;
196599  int iCol;
196600 
196601  UNUSED_PARAM2(iUnused1, iUnused2);
196602  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
196603 
196604  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
196605  pCtx->szCol++;
196606  }
196607 
196608  switch( pCtx->pConfig->eDetail ){
196609  case FTS5_DETAIL_FULL:
196610  iPos = pCtx->szCol-1;
196611  iCol = pCtx->iCol;
196612  break;
196613 
196614  case FTS5_DETAIL_COLUMNS:
196615  iPos = pCtx->iCol;
196616  iCol = 0;
196617  break;
196618 
196619  default:
196620  assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
196621  iPos = 0;
196622  iCol = 0;
196623  break;
196624  }
196625 
196626  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
196627  if( rc==SQLITE_OK && bPresent==0 ){
196628  pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
196629  pCtx->iRowid, iCol, iPos, 0, pToken, nToken
196630  );
196631  }
196632 
196633  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
196634  const int nChar = pCtx->pConfig->aPrefix[ii];
196635  int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
196636  if( nByte ){
196637  rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
196638  if( bPresent==0 ){
196639  pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
196640  pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
196641  );
196642  }
196643  }
196644  }
196645 
196646  return rc;
196647 }
196648 
196649 /*
196650 ** Check that the contents of the FTS index match that of the %_content
196651 ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
196652 ** some other SQLite error code if an error occurs while attempting to
196653 ** determine this.
196654 */
196655 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
196656  Fts5Config *pConfig = p->pConfig;
196657  int rc; /* Return code */
196658  int *aColSize; /* Array of size pConfig->nCol */
196659  i64 *aTotalSize; /* Array of size pConfig->nCol */
196660  Fts5IntegrityCtx ctx;
196661  sqlite3_stmt *pScan;
196662 
196663  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
196664  ctx.pConfig = p->pConfig;
196665  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
196666  if( !aTotalSize ) return SQLITE_NOMEM;
196667  aColSize = (int*)&aTotalSize[pConfig->nCol];
196668  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
196669 
196670  /* Generate the expected index checksum based on the contents of the
196671  ** %_content table. This block stores the checksum in ctx.cksum. */
196672  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
196673  if( rc==SQLITE_OK ){
196674  int rc2;
196675  while( SQLITE_ROW==sqlite3_step(pScan) ){
196676  int i;
196677  ctx.iRowid = sqlite3_column_int64(pScan, 0);
196678  ctx.szCol = 0;
196679  if( pConfig->bColumnsize ){
196680  rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
196681  }
196682  if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
196683  rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
196684  }
196685  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
196686  if( pConfig->abUnindexed[i] ) continue;
196687  ctx.iCol = i;
196688  ctx.szCol = 0;
196689  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
196690  rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
196691  }
196692  if( rc==SQLITE_OK ){
196693  rc = sqlite3Fts5Tokenize(pConfig,
196695  (const char*)sqlite3_column_text(pScan, i+1),
196696  sqlite3_column_bytes(pScan, i+1),
196697  (void*)&ctx,
196698  fts5StorageIntegrityCallback
196699  );
196700  }
196701  if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
196702  rc = FTS5_CORRUPT;
196703  }
196704  aTotalSize[i] += ctx.szCol;
196705  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
196706  sqlite3Fts5TermsetFree(ctx.pTermset);
196707  ctx.pTermset = 0;
196708  }
196709  }
196710  sqlite3Fts5TermsetFree(ctx.pTermset);
196711  ctx.pTermset = 0;
196712 
196713  if( rc!=SQLITE_OK ) break;
196714  }
196715  rc2 = sqlite3_reset(pScan);
196716  if( rc==SQLITE_OK ) rc = rc2;
196717  }
196718 
196719  /* Test that the "totals" (sometimes called "averages") record looks Ok */
196720  if( rc==SQLITE_OK ){
196721  int i;
196722  rc = fts5StorageLoadTotals(p, 0);
196723  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
196724  if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
196725  }
196726  }
196727 
196728  /* Check that the %_docsize and %_content tables contain the expected
196729  ** number of rows. */
196730  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
196731  i64 nRow = 0;
196732  rc = fts5StorageCount(p, "content", &nRow);
196733  if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
196734  }
196735  if( rc==SQLITE_OK && pConfig->bColumnsize ){
196736  i64 nRow = 0;
196737  rc = fts5StorageCount(p, "docsize", &nRow);
196738  if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
196739  }
196740 
196741  /* Pass the expected checksum down to the FTS index module. It will
196742  ** verify, amongst other things, that it matches the checksum generated by
196743  ** inspecting the index itself. */
196744  if( rc==SQLITE_OK ){
196745  rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
196746  }
196747 
196748  sqlite3_free(aTotalSize);
196749  return rc;
196750 }
196751 
196752 /*
196753 ** Obtain an SQLite statement handle that may be used to read data from the
196754 ** %_content table.
196755 */
196756 static int sqlite3Fts5StorageStmt(
196757  Fts5Storage *p,
196758  int eStmt,
196759  sqlite3_stmt **pp,
196760  char **pzErrMsg
196761 ){
196762  int rc;
196763  assert( eStmt==FTS5_STMT_SCAN_ASC
196764  || eStmt==FTS5_STMT_SCAN_DESC
196765  || eStmt==FTS5_STMT_LOOKUP
196766  );
196767  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
196768  if( rc==SQLITE_OK ){
196769  assert( p->aStmt[eStmt]==*pp );
196770  p->aStmt[eStmt] = 0;
196771  }
196772  return rc;
196773 }
196774 
196775 /*
196776 ** Release an SQLite statement handle obtained via an earlier call to
196777 ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
196778 ** must match that passed to the sqlite3Fts5StorageStmt() call.
196779 */
196780 static void sqlite3Fts5StorageStmtRelease(
196781  Fts5Storage *p,
196782  int eStmt,
196783  sqlite3_stmt *pStmt
196784 ){
196785  assert( eStmt==FTS5_STMT_SCAN_ASC
196786  || eStmt==FTS5_STMT_SCAN_DESC
196787  || eStmt==FTS5_STMT_LOOKUP
196788  );
196789  if( p->aStmt[eStmt]==0 ){
196790  sqlite3_reset(pStmt);
196791  p->aStmt[eStmt] = pStmt;
196792  }else{
196793  sqlite3_finalize(pStmt);
196794  }
196795 }
196796 
196797 static int fts5StorageDecodeSizeArray(
196798  int *aCol, int nCol, /* Array to populate */
196799  const u8 *aBlob, int nBlob /* Record to read varints from */
196800 ){
196801  int i;
196802  int iOff = 0;
196803  for(i=0; i<nCol; i++){
196804  if( iOff>=nBlob ) return 1;
196805  iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
196806  }
196807  return (iOff!=nBlob);
196808 }
196809 
196810 /*
196811 ** Argument aCol points to an array of integers containing one entry for
196812 ** each table column. This function reads the %_docsize record for the
196813 ** specified rowid and populates aCol[] with the results.
196814 **
196815 ** An SQLite error code is returned if an error occurs, or SQLITE_OK
196816 ** otherwise.
196817 */
196818 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
196819  int nCol = p->pConfig->nCol; /* Number of user columns in table */
196820  sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
196821  int rc; /* Return Code */
196822 
196823  assert( p->pConfig->bColumnsize );
196824  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
196825  if( rc==SQLITE_OK ){
196826  int bCorrupt = 1;
196827  sqlite3_bind_int64(pLookup, 1, iRowid);
196828  if( SQLITE_ROW==sqlite3_step(pLookup) ){
196829  const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
196830  int nBlob = sqlite3_column_bytes(pLookup, 0);
196831  if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
196832  bCorrupt = 0;
196833  }
196834  }
196835  rc = sqlite3_reset(pLookup);
196836  if( bCorrupt && rc==SQLITE_OK ){
196837  rc = FTS5_CORRUPT;
196838  }
196839  }
196840 
196841  return rc;
196842 }
196843 
196844 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
196845  int rc = fts5StorageLoadTotals(p, 0);
196846  if( rc==SQLITE_OK ){
196847  *pnToken = 0;
196848  if( iCol<0 ){
196849  int i;
196850  for(i=0; i<p->pConfig->nCol; i++){
196851  *pnToken += p->aTotalSize[i];
196852  }
196853  }else if( iCol<p->pConfig->nCol ){
196854  *pnToken = p->aTotalSize[iCol];
196855  }else{
196856  rc = SQLITE_RANGE;
196857  }
196858  }
196859  return rc;
196860 }
196861 
196862 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
196863  int rc = fts5StorageLoadTotals(p, 0);
196864  if( rc==SQLITE_OK ){
196865  *pnRow = p->nTotalRow;
196866  }
196867  return rc;
196868 }
196869 
196870 /*
196871 ** Flush any data currently held in-memory to disk.
196872 */
196873 static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
196874  if( bCommit && p->bTotalsValid ){
196875  int rc = fts5StorageSaveTotals(p);
196876  p->bTotalsValid = 0;
196877  if( rc!=SQLITE_OK ) return rc;
196878  }
196879  return sqlite3Fts5IndexSync(p->pIndex, bCommit);
196880 }
196881 
196882 static int sqlite3Fts5StorageRollback(Fts5Storage *p){
196883  p->bTotalsValid = 0;
196884  return sqlite3Fts5IndexRollback(p->pIndex);
196885 }
196886 
196887 static int sqlite3Fts5StorageConfigValue(
196888  Fts5Storage *p,
196889  const char *z,
196890  sqlite3_value *pVal,
196891  int iVal
196892 ){
196893  sqlite3_stmt *pReplace = 0;
196894  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
196895  if( rc==SQLITE_OK ){
196896  sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
196897  if( pVal ){
196898  sqlite3_bind_value(pReplace, 2, pVal);
196899  }else{
196900  sqlite3_bind_int(pReplace, 2, iVal);
196901  }
196902  sqlite3_step(pReplace);
196903  rc = sqlite3_reset(pReplace);
196904  }
196905  if( rc==SQLITE_OK && pVal ){
196906  int iNew = p->pConfig->iCookie + 1;
196907  rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
196908  if( rc==SQLITE_OK ){
196909  p->pConfig->iCookie = iNew;
196910  }
196911  }
196912  return rc;
196913 }
196914 
196915 /*
196916 ** 2014 May 31
196917 **
196918 ** The author disclaims copyright to this source code. In place of
196919 ** a legal notice, here is a blessing:
196920 **
196921 ** May you do good and not evil.
196922 ** May you find forgiveness for yourself and forgive others.
196923 ** May you share freely, never taking more than you give.
196924 **
196925 ******************************************************************************
196926 */
196927 
196928 
196929 /* #include "fts5Int.h" */
196930 
196931 /**************************************************************************
196932 ** Start of ascii tokenizer implementation.
196933 */
196934 
196935 /*
196936 ** For tokenizers with no "unicode" modifier, the set of token characters
196937 ** is the same as the set of ASCII range alphanumeric characters.
196938 */
196939 static unsigned char aAsciiTokenChar[128] = {
196940  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
196941  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
196942  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
196943  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
196944  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
196945  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
196946  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
196947  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
196948 };
196949 
196950 typedef struct AsciiTokenizer AsciiTokenizer;
196951 struct AsciiTokenizer {
196952  unsigned char aTokenChar[128];
196953 };
196954 
196955 static void fts5AsciiAddExceptions(
196956  AsciiTokenizer *p,
196957  const char *zArg,
196958  int bTokenChars
196959 ){
196960  int i;
196961  for(i=0; zArg[i]; i++){
196962  if( (zArg[i] & 0x80)==0 ){
196963  p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
196964  }
196965  }
196966 }
196967 
196968 /*
196969 ** Delete a "ascii" tokenizer.
196970 */
196971 static void fts5AsciiDelete(Fts5Tokenizer *p){
196972  sqlite3_free(p);
196973 }
196974 
196975 /*
196976 ** Create an "ascii" tokenizer.
196977 */
196978 static int fts5AsciiCreate(
196979  void *pUnused,
196980  const char **azArg, int nArg,
196981  Fts5Tokenizer **ppOut
196982 ){
196983  int rc = SQLITE_OK;
196984  AsciiTokenizer *p = 0;
196985  UNUSED_PARAM(pUnused);
196986  if( nArg%2 ){
196987  rc = SQLITE_ERROR;
196988  }else{
196989  p = sqlite3_malloc(sizeof(AsciiTokenizer));
196990  if( p==0 ){
196991  rc = SQLITE_NOMEM;
196992  }else{
196993  int i;
196994  memset(p, 0, sizeof(AsciiTokenizer));
196995  memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
196996  for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
196997  const char *zArg = azArg[i+1];
196998  if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
196999  fts5AsciiAddExceptions(p, zArg, 1);
197000  }else
197001  if( 0==sqlite3_stricmp(azArg[i], "separators") ){
197002  fts5AsciiAddExceptions(p, zArg, 0);
197003  }else{
197004  rc = SQLITE_ERROR;
197005  }
197006  }
197007  if( rc!=SQLITE_OK ){
197008  fts5AsciiDelete((Fts5Tokenizer*)p);
197009  p = 0;
197010  }
197011  }
197012  }
197013 
197014  *ppOut = (Fts5Tokenizer*)p;
197015  return rc;
197016 }
197017 
197018 
197019 static void asciiFold(char *aOut, const char *aIn, int nByte){
197020  int i;
197021  for(i=0; i<nByte; i++){
197022  char c = aIn[i];
197023  if( c>='A' && c<='Z' ) c += 32;
197024  aOut[i] = c;
197025  }
197026 }
197027 
197028 /*
197029 ** Tokenize some text using the ascii tokenizer.
197030 */
197031 static int fts5AsciiTokenize(
197032  Fts5Tokenizer *pTokenizer,
197033  void *pCtx,
197034  int iUnused,
197035  const char *pText, int nText,
197036  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
197037 ){
197038  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
197039  int rc = SQLITE_OK;
197040  int ie;
197041  int is = 0;
197042 
197043  char aFold[64];
197044  int nFold = sizeof(aFold);
197045  char *pFold = aFold;
197046  unsigned char *a = p->aTokenChar;
197047 
197048  UNUSED_PARAM(iUnused);
197049 
197050  while( is<nText && rc==SQLITE_OK ){
197051  int nByte;
197052 
197053  /* Skip any leading divider characters. */
197054  while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
197055  is++;
197056  }
197057  if( is==nText ) break;
197058 
197059  /* Count the token characters */
197060  ie = is+1;
197061  while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
197062  ie++;
197063  }
197064 
197065  /* Fold to lower case */
197066  nByte = ie-is;
197067  if( nByte>nFold ){
197068  if( pFold!=aFold ) sqlite3_free(pFold);
197069  pFold = sqlite3_malloc(nByte*2);
197070  if( pFold==0 ){
197071  rc = SQLITE_NOMEM;
197072  break;
197073  }
197074  nFold = nByte*2;
197075  }
197076  asciiFold(pFold, &pText[is], nByte);
197077 
197078  /* Invoke the token callback */
197079  rc = xToken(pCtx, 0, pFold, nByte, is, ie);
197080  is = ie+1;
197081  }
197082 
197083  if( pFold!=aFold ) sqlite3_free(pFold);
197084  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
197085  return rc;
197086 }
197087 
197088 /**************************************************************************
197089 ** Start of unicode61 tokenizer implementation.
197090 */
197091 
197092 
197093 /*
197094 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
197095 ** from the sqlite3 source file utf.c. If this file is compiled as part
197096 ** of the amalgamation, they are not required.
197097 */
197098 #ifndef SQLITE_AMALGAMATION
197099 
197100 static const unsigned char sqlite3Utf8Trans1[] = {
197101  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
197102  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
197103  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
197104  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
197105  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
197106  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
197107  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
197108  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
197109 };
197110 
197111 #define READ_UTF8(zIn, zTerm, c) \
197112  c = *(zIn++); \
197113  if( c>=0xc0 ){ \
197114  c = sqlite3Utf8Trans1[c-0xc0]; \
197115  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
197116  c = (c<<6) + (0x3f & *(zIn++)); \
197117  } \
197118  if( c<0x80 \
197119  || (c&0xFFFFF800)==0xD800 \
197120  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
197121  }
197122 
197123 
197124 #define WRITE_UTF8(zOut, c) { \
197125  if( c<0x00080 ){ \
197126  *zOut++ = (unsigned char)(c&0xFF); \
197127  } \
197128  else if( c<0x00800 ){ \
197129  *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
197130  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
197131  } \
197132  else if( c<0x10000 ){ \
197133  *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
197134  *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
197135  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
197136  }else{ \
197137  *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
197138  *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
197139  *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
197140  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
197141  } \
197142 }
197143 
197144 #endif /* ifndef SQLITE_AMALGAMATION */
197145 
197146 typedef struct Unicode61Tokenizer Unicode61Tokenizer;
197147 struct Unicode61Tokenizer {
197148  unsigned char aTokenChar[128]; /* ASCII range token characters */
197149  char *aFold; /* Buffer to fold text into */
197150  int nFold; /* Size of aFold[] in bytes */
197151  int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
197152  int nException;
197153  int *aiException;
197154 };
197155 
197156 static int fts5UnicodeAddExceptions(
197157  Unicode61Tokenizer *p, /* Tokenizer object */
197158  const char *z, /* Characters to treat as exceptions */
197159  int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
197160 ){
197161  int rc = SQLITE_OK;
197162  int n = (int)strlen(z);
197163  int *aNew;
197164 
197165  if( n>0 ){
197166  aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
197167  if( aNew ){
197168  int nNew = p->nException;
197169  const unsigned char *zCsr = (const unsigned char*)z;
197170  const unsigned char *zTerm = (const unsigned char*)&z[n];
197171  while( zCsr<zTerm ){
197172  int iCode;
197173  int bToken;
197174  READ_UTF8(zCsr, zTerm, iCode);
197175  if( iCode<128 ){
197176  p->aTokenChar[iCode] = (unsigned char)bTokenChars;
197177  }else{
197178  bToken = sqlite3Fts5UnicodeIsalnum(iCode);
197179  assert( (bToken==0 || bToken==1) );
197180  assert( (bTokenChars==0 || bTokenChars==1) );
197181  if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
197182  int i;
197183  for(i=0; i<nNew; i++){
197184  if( aNew[i]>iCode ) break;
197185  }
197186  memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
197187  aNew[i] = iCode;
197188  nNew++;
197189  }
197190  }
197191  }
197192  p->aiException = aNew;
197193  p->nException = nNew;
197194  }else{
197195  rc = SQLITE_NOMEM;
197196  }
197197  }
197198 
197199  return rc;
197200 }
197201 
197202 /*
197203 ** Return true if the p->aiException[] array contains the value iCode.
197204 */
197205 static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
197206  if( p->nException>0 ){
197207  int *a = p->aiException;
197208  int iLo = 0;
197209  int iHi = p->nException-1;
197210 
197211  while( iHi>=iLo ){
197212  int iTest = (iHi + iLo) / 2;
197213  if( iCode==a[iTest] ){
197214  return 1;
197215  }else if( iCode>a[iTest] ){
197216  iLo = iTest+1;
197217  }else{
197218  iHi = iTest-1;
197219  }
197220  }
197221  }
197222 
197223  return 0;
197224 }
197225 
197226 /*
197227 ** Delete a "unicode61" tokenizer.
197228 */
197229 static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
197230  if( pTok ){
197231  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
197232  sqlite3_free(p->aiException);
197233  sqlite3_free(p->aFold);
197234  sqlite3_free(p);
197235  }
197236  return;
197237 }
197238 
197239 /*
197240 ** Create a "unicode61" tokenizer.
197241 */
197242 static int fts5UnicodeCreate(
197243  void *pUnused,
197244  const char **azArg, int nArg,
197245  Fts5Tokenizer **ppOut
197246 ){
197247  int rc = SQLITE_OK; /* Return code */
197248  Unicode61Tokenizer *p = 0; /* New tokenizer object */
197249 
197250  UNUSED_PARAM(pUnused);
197251 
197252  if( nArg%2 ){
197253  rc = SQLITE_ERROR;
197254  }else{
197255  p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
197256  if( p ){
197257  int i;
197258  memset(p, 0, sizeof(Unicode61Tokenizer));
197259  memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
197260  p->bRemoveDiacritic = 1;
197261  p->nFold = 64;
197262  p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
197263  if( p->aFold==0 ){
197264  rc = SQLITE_NOMEM;
197265  }
197266  for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
197267  const char *zArg = azArg[i+1];
197268  if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
197269  if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
197270  rc = SQLITE_ERROR;
197271  }
197272  p->bRemoveDiacritic = (zArg[0]=='1');
197273  }else
197274  if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
197275  rc = fts5UnicodeAddExceptions(p, zArg, 1);
197276  }else
197277  if( 0==sqlite3_stricmp(azArg[i], "separators") ){
197278  rc = fts5UnicodeAddExceptions(p, zArg, 0);
197279  }else{
197280  rc = SQLITE_ERROR;
197281  }
197282  }
197283  }else{
197284  rc = SQLITE_NOMEM;
197285  }
197286  if( rc!=SQLITE_OK ){
197287  fts5UnicodeDelete((Fts5Tokenizer*)p);
197288  p = 0;
197289  }
197290  *ppOut = (Fts5Tokenizer*)p;
197291  }
197292  return rc;
197293 }
197294 
197295 /*
197296 ** Return true if, for the purposes of tokenizing with the tokenizer
197297 ** passed as the first argument, codepoint iCode is considered a token
197298 ** character (not a separator).
197299 */
197300 static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
197301  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
197302  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
197303 }
197304 
197305 static int fts5UnicodeTokenize(
197306  Fts5Tokenizer *pTokenizer,
197307  void *pCtx,
197308  int iUnused,
197309  const char *pText, int nText,
197310  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
197311 ){
197312  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
197313  int rc = SQLITE_OK;
197314  unsigned char *a = p->aTokenChar;
197315 
197316  unsigned char *zTerm = (unsigned char*)&pText[nText];
197317  unsigned char *zCsr = (unsigned char *)pText;
197318 
197319  /* Output buffer */
197320  char *aFold = p->aFold;
197321  int nFold = p->nFold;
197322  const char *pEnd = &aFold[nFold-6];
197323 
197324  UNUSED_PARAM(iUnused);
197325 
197326  /* Each iteration of this loop gobbles up a contiguous run of separators,
197327  ** then the next token. */
197328  while( rc==SQLITE_OK ){
197329  int iCode; /* non-ASCII codepoint read from input */
197330  char *zOut = aFold;
197331  int is;
197332  int ie;
197333 
197334  /* Skip any separator characters. */
197335  while( 1 ){
197336  if( zCsr>=zTerm ) goto tokenize_done;
197337  if( *zCsr & 0x80 ) {
197338  /* A character outside of the ascii range. Skip past it if it is
197339  ** a separator character. Or break out of the loop if it is not. */
197340  is = zCsr - (unsigned char*)pText;
197341  READ_UTF8(zCsr, zTerm, iCode);
197342  if( fts5UnicodeIsAlnum(p, iCode) ){
197343  goto non_ascii_tokenchar;
197344  }
197345  }else{
197346  if( a[*zCsr] ){
197347  is = zCsr - (unsigned char*)pText;
197348  goto ascii_tokenchar;
197349  }
197350  zCsr++;
197351  }
197352  }
197353 
197354  /* Run through the tokenchars. Fold them into the output buffer along
197355  ** the way. */
197356  while( zCsr<zTerm ){
197357 
197358  /* Grow the output buffer so that there is sufficient space to fit the
197359  ** largest possible utf-8 character. */
197360  if( zOut>pEnd ){
197361  aFold = sqlite3_malloc(nFold*2);
197362  if( aFold==0 ){
197363  rc = SQLITE_NOMEM;
197364  goto tokenize_done;
197365  }
197366  zOut = &aFold[zOut - p->aFold];
197367  memcpy(aFold, p->aFold, nFold);
197368  sqlite3_free(p->aFold);
197369  p->aFold = aFold;
197370  p->nFold = nFold = nFold*2;
197371  pEnd = &aFold[nFold-6];
197372  }
197373 
197374  if( *zCsr & 0x80 ){
197375  /* An non-ascii-range character. Fold it into the output buffer if
197376  ** it is a token character, or break out of the loop if it is not. */
197377  READ_UTF8(zCsr, zTerm, iCode);
197378  if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
197379  non_ascii_tokenchar:
197380  iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
197381  if( iCode ) WRITE_UTF8(zOut, iCode);
197382  }else{
197383  break;
197384  }
197385  }else if( a[*zCsr]==0 ){
197386  /* An ascii-range separator character. End of token. */
197387  break;
197388  }else{
197389  ascii_tokenchar:
197390  if( *zCsr>='A' && *zCsr<='Z' ){
197391  *zOut++ = *zCsr + 32;
197392  }else{
197393  *zOut++ = *zCsr;
197394  }
197395  zCsr++;
197396  }
197397  ie = zCsr - (unsigned char*)pText;
197398  }
197399 
197400  /* Invoke the token callback */
197401  rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
197402  }
197403 
197404  tokenize_done:
197405  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
197406  return rc;
197407 }
197408 
197409 /**************************************************************************
197410 ** Start of porter stemmer implementation.
197411 */
197412 
197413 /* Any tokens larger than this (in bytes) are passed through without
197414 ** stemming. */
197415 #define FTS5_PORTER_MAX_TOKEN 64
197416 
197417 typedef struct PorterTokenizer PorterTokenizer;
197418 struct PorterTokenizer {
197419  fts5_tokenizer tokenizer; /* Parent tokenizer module */
197420  Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
197421  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
197422 };
197423 
197424 /*
197425 ** Delete a "porter" tokenizer.
197426 */
197427 static void fts5PorterDelete(Fts5Tokenizer *pTok){
197428  if( pTok ){
197429  PorterTokenizer *p = (PorterTokenizer*)pTok;
197430  if( p->pTokenizer ){
197431  p->tokenizer.xDelete(p->pTokenizer);
197432  }
197433  sqlite3_free(p);
197434  }
197435 }
197436 
197437 /*
197438 ** Create a "porter" tokenizer.
197439 */
197440 static int fts5PorterCreate(
197441  void *pCtx,
197442  const char **azArg, int nArg,
197443  Fts5Tokenizer **ppOut
197444 ){
197445  fts5_api *pApi = (fts5_api*)pCtx;
197446  int rc = SQLITE_OK;
197447  PorterTokenizer *pRet;
197448  void *pUserdata = 0;
197449  const char *zBase = "unicode61";
197450 
197451  if( nArg>0 ){
197452  zBase = azArg[0];
197453  }
197454 
197455  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
197456  if( pRet ){
197457  memset(pRet, 0, sizeof(PorterTokenizer));
197458  rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
197459  }else{
197460  rc = SQLITE_NOMEM;
197461  }
197462  if( rc==SQLITE_OK ){
197463  int nArg2 = (nArg>0 ? nArg-1 : 0);
197464  const char **azArg2 = (nArg2 ? &azArg[1] : 0);
197465  rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
197466  }
197467 
197468  if( rc!=SQLITE_OK ){
197469  fts5PorterDelete((Fts5Tokenizer*)pRet);
197470  pRet = 0;
197471  }
197472  *ppOut = (Fts5Tokenizer*)pRet;
197473  return rc;
197474 }
197475 
197476 typedef struct PorterContext PorterContext;
197477 struct PorterContext {
197478  void *pCtx;
197479  int (*xToken)(void*, int, const char*, int, int, int);
197480  char *aBuf;
197481 };
197482 
197483 typedef struct PorterRule PorterRule;
197484 struct PorterRule {
197485  const char *zSuffix;
197486  int nSuffix;
197487  int (*xCond)(char *zStem, int nStem);
197488  const char *zOutput;
197489  int nOutput;
197490 };
197491 
197492 #if 0
197493 static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
197494  int ret = -1;
197495  int nBuf = *pnBuf;
197496  PorterRule *p;
197497 
197498  for(p=aRule; p->zSuffix; p++){
197499  assert( strlen(p->zSuffix)==p->nSuffix );
197500  assert( strlen(p->zOutput)==p->nOutput );
197501  if( nBuf<p->nSuffix ) continue;
197502  if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
197503  }
197504 
197505  if( p->zSuffix ){
197506  int nStem = nBuf - p->nSuffix;
197507  if( p->xCond==0 || p->xCond(aBuf, nStem) ){
197508  memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
197509  *pnBuf = nStem + p->nOutput;
197510  ret = p - aRule;
197511  }
197512  }
197513 
197514  return ret;
197515 }
197516 #endif
197517 
197518 static int fts5PorterIsVowel(char c, int bYIsVowel){
197519  return (
197520  c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
197521  );
197522 }
197523 
197524 static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
197525  int i;
197526  int bCons = bPrevCons;
197527 
197528  /* Scan for a vowel */
197529  for(i=0; i<nStem; i++){
197530  if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
197531  }
197532 
197533  /* Scan for a consonent */
197534  for(i++; i<nStem; i++){
197535  if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
197536  }
197537  return 0;
197538 }
197539 
197540 /* porter rule condition: (m > 0) */
197541 static int fts5Porter_MGt0(char *zStem, int nStem){
197542  return !!fts5PorterGobbleVC(zStem, nStem, 0);
197543 }
197544 
197545 /* porter rule condition: (m > 1) */
197546 static int fts5Porter_MGt1(char *zStem, int nStem){
197547  int n;
197548  n = fts5PorterGobbleVC(zStem, nStem, 0);
197549  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
197550  return 1;
197551  }
197552  return 0;
197553 }
197554 
197555 /* porter rule condition: (m = 1) */
197556 static int fts5Porter_MEq1(char *zStem, int nStem){
197557  int n;
197558  n = fts5PorterGobbleVC(zStem, nStem, 0);
197559  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
197560  return 1;
197561  }
197562  return 0;
197563 }
197564 
197565 /* porter rule condition: (*o) */
197566 static int fts5Porter_Ostar(char *zStem, int nStem){
197567  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
197568  return 0;
197569  }else{
197570  int i;
197571  int mask = 0;
197572  int bCons = 0;
197573  for(i=0; i<nStem; i++){
197574  bCons = !fts5PorterIsVowel(zStem[i], bCons);
197575  assert( bCons==0 || bCons==1 );
197576  mask = (mask << 1) + bCons;
197577  }
197578  return ((mask & 0x0007)==0x0005);
197579  }
197580 }
197581 
197582 /* porter rule condition: (m > 1 and (*S or *T)) */
197583 static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
197584  assert( nStem>0 );
197585  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
197586  && fts5Porter_MGt1(zStem, nStem);
197587 }
197588 
197589 /* porter rule condition: (*v*) */
197590 static int fts5Porter_Vowel(char *zStem, int nStem){
197591  int i;
197592  for(i=0; i<nStem; i++){
197593  if( fts5PorterIsVowel(zStem[i], i>0) ){
197594  return 1;
197595  }
197596  }
197597  return 0;
197598 }
197599 
197600 
197601 /**************************************************************************
197602 ***************************************************************************
197603 ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
197604 */
197605 
197606 static int fts5PorterStep4(char *aBuf, int *pnBuf){
197607  int ret = 0;
197608  int nBuf = *pnBuf;
197609  switch( aBuf[nBuf-2] ){
197610 
197611  case 'a':
197612  if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
197613  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197614  *pnBuf = nBuf - 2;
197615  }
197616  }
197617  break;
197618 
197619  case 'c':
197620  if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
197621  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197622  *pnBuf = nBuf - 4;
197623  }
197624  }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
197625  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197626  *pnBuf = nBuf - 4;
197627  }
197628  }
197629  break;
197630 
197631  case 'e':
197632  if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
197633  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197634  *pnBuf = nBuf - 2;
197635  }
197636  }
197637  break;
197638 
197639  case 'i':
197640  if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
197641  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197642  *pnBuf = nBuf - 2;
197643  }
197644  }
197645  break;
197646 
197647  case 'l':
197648  if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
197649  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197650  *pnBuf = nBuf - 4;
197651  }
197652  }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
197653  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197654  *pnBuf = nBuf - 4;
197655  }
197656  }
197657  break;
197658 
197659  case 'n':
197660  if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
197661  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197662  *pnBuf = nBuf - 3;
197663  }
197664  }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
197665  if( fts5Porter_MGt1(aBuf, nBuf-5) ){
197666  *pnBuf = nBuf - 5;
197667  }
197668  }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
197669  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
197670  *pnBuf = nBuf - 4;
197671  }
197672  }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
197673  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197674  *pnBuf = nBuf - 3;
197675  }
197676  }
197677  break;
197678 
197679  case 'o':
197680  if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
197681  if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
197682  *pnBuf = nBuf - 3;
197683  }
197684  }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
197685  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
197686  *pnBuf = nBuf - 2;
197687  }
197688  }
197689  break;
197690 
197691  case 's':
197692  if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
197693  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197694  *pnBuf = nBuf - 3;
197695  }
197696  }
197697  break;
197698 
197699  case 't':
197700  if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
197701  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197702  *pnBuf = nBuf - 3;
197703  }
197704  }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
197705  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197706  *pnBuf = nBuf - 3;
197707  }
197708  }
197709  break;
197710 
197711  case 'u':
197712  if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
197713  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197714  *pnBuf = nBuf - 3;
197715  }
197716  }
197717  break;
197718 
197719  case 'v':
197720  if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
197721  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197722  *pnBuf = nBuf - 3;
197723  }
197724  }
197725  break;
197726 
197727  case 'z':
197728  if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
197729  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
197730  *pnBuf = nBuf - 3;
197731  }
197732  }
197733  break;
197734 
197735  }
197736  return ret;
197737 }
197738 
197739 
197740 static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
197741  int ret = 0;
197742  int nBuf = *pnBuf;
197743  switch( aBuf[nBuf-2] ){
197744 
197745  case 'a':
197746  if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
197747  memcpy(&aBuf[nBuf-2], "ate", 3);
197748  *pnBuf = nBuf - 2 + 3;
197749  ret = 1;
197750  }
197751  break;
197752 
197753  case 'b':
197754  if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
197755  memcpy(&aBuf[nBuf-2], "ble", 3);
197756  *pnBuf = nBuf - 2 + 3;
197757  ret = 1;
197758  }
197759  break;
197760 
197761  case 'i':
197762  if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
197763  memcpy(&aBuf[nBuf-2], "ize", 3);
197764  *pnBuf = nBuf - 2 + 3;
197765  ret = 1;
197766  }
197767  break;
197768 
197769  }
197770  return ret;
197771 }
197772 
197773 
197774 static int fts5PorterStep2(char *aBuf, int *pnBuf){
197775  int ret = 0;
197776  int nBuf = *pnBuf;
197777  switch( aBuf[nBuf-2] ){
197778 
197779  case 'a':
197780  if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
197781  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197782  memcpy(&aBuf[nBuf-7], "ate", 3);
197783  *pnBuf = nBuf - 7 + 3;
197784  }
197785  }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
197786  if( fts5Porter_MGt0(aBuf, nBuf-6) ){
197787  memcpy(&aBuf[nBuf-6], "tion", 4);
197788  *pnBuf = nBuf - 6 + 4;
197789  }
197790  }
197791  break;
197792 
197793  case 'c':
197794  if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
197795  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197796  memcpy(&aBuf[nBuf-4], "ence", 4);
197797  *pnBuf = nBuf - 4 + 4;
197798  }
197799  }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
197800  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197801  memcpy(&aBuf[nBuf-4], "ance", 4);
197802  *pnBuf = nBuf - 4 + 4;
197803  }
197804  }
197805  break;
197806 
197807  case 'e':
197808  if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
197809  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197810  memcpy(&aBuf[nBuf-4], "ize", 3);
197811  *pnBuf = nBuf - 4 + 3;
197812  }
197813  }
197814  break;
197815 
197816  case 'g':
197817  if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
197818  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197819  memcpy(&aBuf[nBuf-4], "log", 3);
197820  *pnBuf = nBuf - 4 + 3;
197821  }
197822  }
197823  break;
197824 
197825  case 'l':
197826  if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
197827  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197828  memcpy(&aBuf[nBuf-3], "ble", 3);
197829  *pnBuf = nBuf - 3 + 3;
197830  }
197831  }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
197832  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197833  memcpy(&aBuf[nBuf-4], "al", 2);
197834  *pnBuf = nBuf - 4 + 2;
197835  }
197836  }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
197837  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197838  memcpy(&aBuf[nBuf-5], "ent", 3);
197839  *pnBuf = nBuf - 5 + 3;
197840  }
197841  }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
197842  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197843  memcpy(&aBuf[nBuf-3], "e", 1);
197844  *pnBuf = nBuf - 3 + 1;
197845  }
197846  }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
197847  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197848  memcpy(&aBuf[nBuf-5], "ous", 3);
197849  *pnBuf = nBuf - 5 + 3;
197850  }
197851  }
197852  break;
197853 
197854  case 'o':
197855  if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
197856  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197857  memcpy(&aBuf[nBuf-7], "ize", 3);
197858  *pnBuf = nBuf - 7 + 3;
197859  }
197860  }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
197861  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197862  memcpy(&aBuf[nBuf-5], "ate", 3);
197863  *pnBuf = nBuf - 5 + 3;
197864  }
197865  }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
197866  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197867  memcpy(&aBuf[nBuf-4], "ate", 3);
197868  *pnBuf = nBuf - 4 + 3;
197869  }
197870  }
197871  break;
197872 
197873  case 's':
197874  if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
197875  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197876  memcpy(&aBuf[nBuf-5], "al", 2);
197877  *pnBuf = nBuf - 5 + 2;
197878  }
197879  }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
197880  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197881  memcpy(&aBuf[nBuf-7], "ive", 3);
197882  *pnBuf = nBuf - 7 + 3;
197883  }
197884  }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
197885  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197886  memcpy(&aBuf[nBuf-7], "ful", 3);
197887  *pnBuf = nBuf - 7 + 3;
197888  }
197889  }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
197890  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
197891  memcpy(&aBuf[nBuf-7], "ous", 3);
197892  *pnBuf = nBuf - 7 + 3;
197893  }
197894  }
197895  break;
197896 
197897  case 't':
197898  if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
197899  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197900  memcpy(&aBuf[nBuf-5], "al", 2);
197901  *pnBuf = nBuf - 5 + 2;
197902  }
197903  }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
197904  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197905  memcpy(&aBuf[nBuf-5], "ive", 3);
197906  *pnBuf = nBuf - 5 + 3;
197907  }
197908  }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
197909  if( fts5Porter_MGt0(aBuf, nBuf-6) ){
197910  memcpy(&aBuf[nBuf-6], "ble", 3);
197911  *pnBuf = nBuf - 6 + 3;
197912  }
197913  }
197914  break;
197915 
197916  }
197917  return ret;
197918 }
197919 
197920 
197921 static int fts5PorterStep3(char *aBuf, int *pnBuf){
197922  int ret = 0;
197923  int nBuf = *pnBuf;
197924  switch( aBuf[nBuf-2] ){
197925 
197926  case 'a':
197927  if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
197928  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197929  memcpy(&aBuf[nBuf-4], "ic", 2);
197930  *pnBuf = nBuf - 4 + 2;
197931  }
197932  }
197933  break;
197934 
197935  case 's':
197936  if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
197937  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
197938  *pnBuf = nBuf - 4;
197939  }
197940  }
197941  break;
197942 
197943  case 't':
197944  if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
197945  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197946  memcpy(&aBuf[nBuf-5], "ic", 2);
197947  *pnBuf = nBuf - 5 + 2;
197948  }
197949  }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
197950  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197951  memcpy(&aBuf[nBuf-5], "ic", 2);
197952  *pnBuf = nBuf - 5 + 2;
197953  }
197954  }
197955  break;
197956 
197957  case 'u':
197958  if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
197959  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197960  *pnBuf = nBuf - 3;
197961  }
197962  }
197963  break;
197964 
197965  case 'v':
197966  if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
197967  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197968  *pnBuf = nBuf - 5;
197969  }
197970  }
197971  break;
197972 
197973  case 'z':
197974  if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
197975  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
197976  memcpy(&aBuf[nBuf-5], "al", 2);
197977  *pnBuf = nBuf - 5 + 2;
197978  }
197979  }
197980  break;
197981 
197982  }
197983  return ret;
197984 }
197985 
197986 
197987 static int fts5PorterStep1B(char *aBuf, int *pnBuf){
197988  int ret = 0;
197989  int nBuf = *pnBuf;
197990  switch( aBuf[nBuf-2] ){
197991 
197992  case 'e':
197993  if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
197994  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
197995  memcpy(&aBuf[nBuf-3], "ee", 2);
197996  *pnBuf = nBuf - 3 + 2;
197997  }
197998  }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
197999  if( fts5Porter_Vowel(aBuf, nBuf-2) ){
198000  *pnBuf = nBuf - 2;
198001  ret = 1;
198002  }
198003  }
198004  break;
198005 
198006  case 'n':
198007  if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
198008  if( fts5Porter_Vowel(aBuf, nBuf-3) ){
198009  *pnBuf = nBuf - 3;
198010  ret = 1;
198011  }
198012  }
198013  break;
198014 
198015  }
198016  return ret;
198017 }
198018 
198019 /*
198020 ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
198021 ***************************************************************************
198022 **************************************************************************/
198023 
198024 static void fts5PorterStep1A(char *aBuf, int *pnBuf){
198025  int nBuf = *pnBuf;
198026  if( aBuf[nBuf-1]=='s' ){
198027  if( aBuf[nBuf-2]=='e' ){
198028  if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
198029  || (nBuf>3 && aBuf[nBuf-3]=='i' )
198030  ){
198031  *pnBuf = nBuf-2;
198032  }else{
198033  *pnBuf = nBuf-1;
198034  }
198035  }
198036  else if( aBuf[nBuf-2]!='s' ){
198037  *pnBuf = nBuf-1;
198038  }
198039  }
198040 }
198041 
198042 static int fts5PorterCb(
198043  void *pCtx,
198044  int tflags,
198045  const char *pToken,
198046  int nToken,
198047  int iStart,
198048  int iEnd
198049 ){
198050  PorterContext *p = (PorterContext*)pCtx;
198051 
198052  char *aBuf;
198053  int nBuf;
198054 
198055  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
198056  aBuf = p->aBuf;
198057  nBuf = nToken;
198058  memcpy(aBuf, pToken, nBuf);
198059 
198060  /* Step 1. */
198061  fts5PorterStep1A(aBuf, &nBuf);
198062  if( fts5PorterStep1B(aBuf, &nBuf) ){
198063  if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
198064  char c = aBuf[nBuf-1];
198065  if( fts5PorterIsVowel(c, 0)==0
198066  && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
198067  ){
198068  nBuf--;
198069  }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
198070  aBuf[nBuf++] = 'e';
198071  }
198072  }
198073  }
198074 
198075  /* Step 1C. */
198076  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
198077  aBuf[nBuf-1] = 'i';
198078  }
198079 
198080  /* Steps 2 through 4. */
198081  fts5PorterStep2(aBuf, &nBuf);
198082  fts5PorterStep3(aBuf, &nBuf);
198083  fts5PorterStep4(aBuf, &nBuf);
198084 
198085  /* Step 5a. */
198086  assert( nBuf>0 );
198087  if( aBuf[nBuf-1]=='e' ){
198088  if( fts5Porter_MGt1(aBuf, nBuf-1)
198089  || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
198090  ){
198091  nBuf--;
198092  }
198093  }
198094 
198095  /* Step 5b. */
198096  if( nBuf>1 && aBuf[nBuf-1]=='l'
198097  && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
198098  ){
198099  nBuf--;
198100  }
198101 
198102  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
198103 
198104  pass_through:
198105  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
198106 }
198107 
198108 /*
198109 ** Tokenize using the porter tokenizer.
198110 */
198111 static int fts5PorterTokenize(
198112  Fts5Tokenizer *pTokenizer,
198113  void *pCtx,
198114  int flags,
198115  const char *pText, int nText,
198116  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
198117 ){
198118  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
198119  PorterContext sCtx;
198120  sCtx.xToken = xToken;
198121  sCtx.pCtx = pCtx;
198122  sCtx.aBuf = p->aBuf;
198123  return p->tokenizer.xTokenize(
198124  p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
198125  );
198126 }
198127 
198128 /*
198129 ** Register all built-in tokenizers with FTS5.
198130 */
198131 static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
198132  struct BuiltinTokenizer {
198133  const char *zName;
198134  fts5_tokenizer x;
198135  } aBuiltin[] = {
198136  { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
198137  { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
198138  { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
198139  };
198140 
198141  int rc = SQLITE_OK; /* Return code */
198142  int i; /* To iterate through builtin functions */
198143 
198144  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
198145  rc = pApi->xCreateTokenizer(pApi,
198146  aBuiltin[i].zName,
198147  (void*)pApi,
198148  &aBuiltin[i].x,
198149  0
198150  );
198151  }
198152 
198153  return rc;
198154 }
198155 
198156 
198157 
198158 /*
198159 ** 2012 May 25
198160 **
198161 ** The author disclaims copyright to this source code. In place of
198162 ** a legal notice, here is a blessing:
198163 **
198164 ** May you do good and not evil.
198165 ** May you find forgiveness for yourself and forgive others.
198166 ** May you share freely, never taking more than you give.
198167 **
198168 ******************************************************************************
198169 */
198170 
198171 /*
198172 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
198173 */
198174 
198175 
198176 /* #include <assert.h> */
198177 
198178 /*
198179 ** Return true if the argument corresponds to a unicode codepoint
198180 ** classified as either a letter or a number. Otherwise false.
198181 **
198182 ** The results are undefined if the value passed to this function
198183 ** is less than zero.
198184 */
198185 static int sqlite3Fts5UnicodeIsalnum(int c){
198186  /* Each unsigned integer in the following array corresponds to a contiguous
198187  ** range of unicode codepoints that are not either letters or numbers (i.e.
198188  ** codepoints for which this function should return 0).
198189  **
198190  ** The most significant 22 bits in each 32-bit value contain the first
198191  ** codepoint in the range. The least significant 10 bits are used to store
198192  ** the size of the range (always at least 1). In other words, the value
198193  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
198194  ** C. It is not possible to represent a range larger than 1023 codepoints
198195  ** using this format.
198196  */
198197  static const unsigned int aEntry[] = {
198198  0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
198199  0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
198200  0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
198201  0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
198202  0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
198203  0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
198204  0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
198205  0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
198206  0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
198207  0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
198208  0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
198209  0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
198210  0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
198211  0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
198212  0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
198213  0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
198214  0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
198215  0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
198216  0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
198217  0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
198218  0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
198219  0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
198220  0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
198221  0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
198222  0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
198223  0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
198224  0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
198225  0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
198226  0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
198227  0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
198228  0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
198229  0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
198230  0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
198231  0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
198232  0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
198233  0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
198234  0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
198235  0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
198236  0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
198237  0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
198238  0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
198239  0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
198240  0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
198241  0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
198242  0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
198243  0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
198244  0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
198245  0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
198246  0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
198247  0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
198248  0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
198249  0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
198250  0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
198251  0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
198252  0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
198253  0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
198254  0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
198255  0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
198256  0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
198257  0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
198258  0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
198259  0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
198260  0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
198261  0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
198262  0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
198263  0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
198264  0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
198265  0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
198266  0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
198267  0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
198268  0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
198269  0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
198270  0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
198271  0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
198272  0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
198273  0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
198274  0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
198275  0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
198276  0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
198277  0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
198278  0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
198279  0x380400F0,
198280  };
198281  static const unsigned int aAscii[4] = {
198282  0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
198283  };
198284 
198285  if( (unsigned int)c<128 ){
198286  return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
198287  }else if( (unsigned int)c<(1<<22) ){
198288  unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
198289  int iRes = 0;
198290  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
198291  int iLo = 0;
198292  while( iHi>=iLo ){
198293  int iTest = (iHi + iLo) / 2;
198294  if( key >= aEntry[iTest] ){
198295  iRes = iTest;
198296  iLo = iTest+1;
198297  }else{
198298  iHi = iTest-1;
198299  }
198300  }
198301  assert( aEntry[0]<key );
198302  assert( key>=aEntry[iRes] );
198303  return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
198304  }
198305  return 1;
198306 }
198307 
198308 
198309 /*
198310 ** If the argument is a codepoint corresponding to a lowercase letter
198311 ** in the ASCII range with a diacritic added, return the codepoint
198312 ** of the ASCII letter only. For example, if passed 235 - "LATIN
198313 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
198314 ** E"). The resuls of passing a codepoint that corresponds to an
198315 ** uppercase letter are undefined.
198316 */
198317 static int fts5_remove_diacritic(int c){
198318  unsigned short aDia[] = {
198319  0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
198320  2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
198321  2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
198322  2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
198323  3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
198324  3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
198325  4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
198326  6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
198327  61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
198328  61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
198329  62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
198330  62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
198331  62924, 63050, 63082, 63274, 63390,
198332  };
198333  char aChar[] = {
198334  '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
198335  'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
198336  's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
198337  'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
198338  'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
198339  '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
198340  'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
198341  'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
198342  'e', 'i', 'o', 'u', 'y',
198343  };
198344 
198345  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
198346  int iRes = 0;
198347  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
198348  int iLo = 0;
198349  while( iHi>=iLo ){
198350  int iTest = (iHi + iLo) / 2;
198351  if( key >= aDia[iTest] ){
198352  iRes = iTest;
198353  iLo = iTest+1;
198354  }else{
198355  iHi = iTest-1;
198356  }
198357  }
198358  assert( key>=aDia[iRes] );
198359  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
198360 }
198361 
198362 
198363 /*
198364 ** Return true if the argument interpreted as a unicode codepoint
198365 ** is a diacritical modifier character.
198366 */
198367 static int sqlite3Fts5UnicodeIsdiacritic(int c){
198368  unsigned int mask0 = 0x08029FDF;
198369  unsigned int mask1 = 0x000361F8;
198370  if( c<768 || c>817 ) return 0;
198371  return (c < 768+32) ?
198372  (mask0 & (1 << (c-768))) :
198373  (mask1 & (1 << (c-768-32)));
198374 }
198375 
198376 
198377 /*
198378 ** Interpret the argument as a unicode codepoint. If the codepoint
198379 ** is an upper case character that has a lower case equivalent,
198380 ** return the codepoint corresponding to the lower case version.
198381 ** Otherwise, return a copy of the argument.
198382 **
198383 ** The results are undefined if the value passed to this function
198384 ** is less than zero.
198385 */
198386 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
198387  /* Each entry in the following array defines a rule for folding a range
198388  ** of codepoints to lower case. The rule applies to a range of nRange
198389  ** codepoints starting at codepoint iCode.
198390  **
198391  ** If the least significant bit in flags is clear, then the rule applies
198392  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
198393  ** need to be folded). Or, if it is set, then the rule only applies to
198394  ** every second codepoint in the range, starting with codepoint C.
198395  **
198396  ** The 7 most significant bits in flags are an index into the aiOff[]
198397  ** array. If a specific codepoint C does require folding, then its lower
198398  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
198399  **
198400  ** The contents of this array are generated by parsing the CaseFolding.txt
198401  ** file distributed as part of the "Unicode Character Database". See
198402  ** http://www.unicode.org for details.
198403  */
198404  static const struct TableEntry {
198405  unsigned short iCode;
198406  unsigned char flags;
198407  unsigned char nRange;
198408  } aEntry[] = {
198409  {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
198410  {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
198411  {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
198412  {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
198413  {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
198414  {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
198415  {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
198416  {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
198417  {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
198418  {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
198419  {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
198420  {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
198421  {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
198422  {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
198423  {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
198424  {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
198425  {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
198426  {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
198427  {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
198428  {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
198429  {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
198430  {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
198431  {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
198432  {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
198433  {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
198434  {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
198435  {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
198436  {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
198437  {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
198438  {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
198439  {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
198440  {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
198441  {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
198442  {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
198443  {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
198444  {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
198445  {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
198446  {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
198447  {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
198448  {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
198449  {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
198450  {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
198451  {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
198452  {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
198453  {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
198454  {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
198455  {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
198456  {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
198457  {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
198458  {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
198459  {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
198460  {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
198461  {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
198462  {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
198463  {65313, 14, 26},
198464  };
198465  static const unsigned short aiOff[] = {
198466  1, 2, 8, 15, 16, 26, 28, 32,
198467  37, 38, 40, 48, 63, 64, 69, 71,
198468  79, 80, 116, 202, 203, 205, 206, 207,
198469  209, 210, 211, 213, 214, 217, 218, 219,
198470  775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
198471  54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
198472  57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
198473  65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
198474  65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
198475  65514, 65521, 65527, 65528, 65529,
198476  };
198477 
198478  int ret = c;
198479 
198480  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
198481 
198482  if( c<128 ){
198483  if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
198484  }else if( c<65536 ){
198485  const struct TableEntry *p;
198486  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
198487  int iLo = 0;
198488  int iRes = -1;
198489 
198490  assert( c>aEntry[0].iCode );
198491  while( iHi>=iLo ){
198492  int iTest = (iHi + iLo) / 2;
198493  int cmp = (c - aEntry[iTest].iCode);
198494  if( cmp>=0 ){
198495  iRes = iTest;
198496  iLo = iTest+1;
198497  }else{
198498  iHi = iTest-1;
198499  }
198500  }
198501 
198502  assert( iRes>=0 && c>=aEntry[iRes].iCode );
198503  p = &aEntry[iRes];
198504  if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
198505  ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
198506  assert( ret>0 );
198507  }
198508 
198509  if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
198510  }
198511 
198512  else if( c>=66560 && c<66600 ){
198513  ret = c + 40;
198514  }
198515 
198516  return ret;
198517 }
198518 
198519 /*
198520 ** 2015 May 30
198521 **
198522 ** The author disclaims copyright to this source code. In place of
198523 ** a legal notice, here is a blessing:
198524 **
198525 ** May you do good and not evil.
198526 ** May you find forgiveness for yourself and forgive others.
198527 ** May you share freely, never taking more than you give.
198528 **
198529 ******************************************************************************
198530 **
198531 ** Routines for varint serialization and deserialization.
198532 */
198533 
198534 
198535 /* #include "fts5Int.h" */
198536 
198537 /*
198538 ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
198539 ** Except, this version does handle the single byte case that the core
198540 ** version depends on being handled before its function is called.
198541 */
198542 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
198543  u32 a,b;
198544 
198545  /* The 1-byte case. Overwhelmingly the most common. */
198546  a = *p;
198547  /* a: p0 (unmasked) */
198548  if (!(a&0x80))
198549  {
198550  /* Values between 0 and 127 */
198551  *v = a;
198552  return 1;
198553  }
198554 
198555  /* The 2-byte case */
198556  p++;
198557  b = *p;
198558  /* b: p1 (unmasked) */
198559  if (!(b&0x80))
198560  {
198561  /* Values between 128 and 16383 */
198562  a &= 0x7f;
198563  a = a<<7;
198564  *v = a | b;
198565  return 2;
198566  }
198567 
198568  /* The 3-byte case */
198569  p++;
198570  a = a<<14;
198571  a |= *p;
198572  /* a: p0<<14 | p2 (unmasked) */
198573  if (!(a&0x80))
198574  {
198575  /* Values between 16384 and 2097151 */
198576  a &= (0x7f<<14)|(0x7f);
198577  b &= 0x7f;
198578  b = b<<7;
198579  *v = a | b;
198580  return 3;
198581  }
198582 
198583  /* A 32-bit varint is used to store size information in btrees.
198584  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
198585  ** A 3-byte varint is sufficient, for example, to record the size
198586  ** of a 1048569-byte BLOB or string.
198587  **
198588  ** We only unroll the first 1-, 2-, and 3- byte cases. The very
198589  ** rare larger cases can be handled by the slower 64-bit varint
198590  ** routine.
198591  */
198592  {
198593  u64 v64;
198594  u8 n;
198595  p -= 2;
198596  n = sqlite3Fts5GetVarint(p, &v64);
198597  *v = (u32)v64;
198598  assert( n>3 && n<=9 );
198599  return n;
198600  }
198601 }
198602 
198603 
198604 /*
198605 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
198606 ** are defined here rather than simply putting the constant expressions
198607 ** inline in order to work around bugs in the RVT compiler.
198608 **
198609 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
198610 **
198611 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
198612 */
198613 #define SLOT_2_0 0x001fc07f
198614 #define SLOT_4_2_0 0xf01fc07f
198615 
198616 /*
198617 ** Read a 64-bit variable-length integer from memory starting at p[0].
198618 ** Return the number of bytes read. The value is stored in *v.
198619 */
198620 static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
198621  u32 a,b,s;
198622 
198623  a = *p;
198624  /* a: p0 (unmasked) */
198625  if (!(a&0x80))
198626  {
198627  *v = a;
198628  return 1;
198629  }
198630 
198631  p++;
198632  b = *p;
198633  /* b: p1 (unmasked) */
198634  if (!(b&0x80))
198635  {
198636  a &= 0x7f;
198637  a = a<<7;
198638  a |= b;
198639  *v = a;
198640  return 2;
198641  }
198642 
198643  /* Verify that constants are precomputed correctly */
198644  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
198645  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
198646 
198647  p++;
198648  a = a<<14;
198649  a |= *p;
198650  /* a: p0<<14 | p2 (unmasked) */
198651  if (!(a&0x80))
198652  {
198653  a &= SLOT_2_0;
198654  b &= 0x7f;
198655  b = b<<7;
198656  a |= b;
198657  *v = a;
198658  return 3;
198659  }
198660 
198661  /* CSE1 from below */
198662  a &= SLOT_2_0;
198663  p++;
198664  b = b<<14;
198665  b |= *p;
198666  /* b: p1<<14 | p3 (unmasked) */
198667  if (!(b&0x80))
198668  {
198669  b &= SLOT_2_0;
198670  /* moved CSE1 up */
198671  /* a &= (0x7f<<14)|(0x7f); */
198672  a = a<<7;
198673  a |= b;
198674  *v = a;
198675  return 4;
198676  }
198677 
198678  /* a: p0<<14 | p2 (masked) */
198679  /* b: p1<<14 | p3 (unmasked) */
198680  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
198681  /* moved CSE1 up */
198682  /* a &= (0x7f<<14)|(0x7f); */
198683  b &= SLOT_2_0;
198684  s = a;
198685  /* s: p0<<14 | p2 (masked) */
198686 
198687  p++;
198688  a = a<<14;
198689  a |= *p;
198690  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
198691  if (!(a&0x80))
198692  {
198693  /* we can skip these cause they were (effectively) done above in calc'ing s */
198694  /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
198695  /* b &= (0x7f<<14)|(0x7f); */
198696  b = b<<7;
198697  a |= b;
198698  s = s>>18;
198699  *v = ((u64)s)<<32 | a;
198700  return 5;
198701  }
198702 
198703  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
198704  s = s<<7;
198705  s |= b;
198706  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
198707 
198708  p++;
198709  b = b<<14;
198710  b |= *p;
198711  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
198712  if (!(b&0x80))
198713  {
198714  /* we can skip this cause it was (effectively) done above in calc'ing s */
198715  /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
198716  a &= SLOT_2_0;
198717  a = a<<7;
198718  a |= b;
198719  s = s>>18;
198720  *v = ((u64)s)<<32 | a;
198721  return 6;
198722  }
198723 
198724  p++;
198725  a = a<<14;
198726  a |= *p;
198727  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
198728  if (!(a&0x80))
198729  {
198730  a &= SLOT_4_2_0;
198731  b &= SLOT_2_0;
198732  b = b<<7;
198733  a |= b;
198734  s = s>>11;
198735  *v = ((u64)s)<<32 | a;
198736  return 7;
198737  }
198738 
198739  /* CSE2 from below */
198740  a &= SLOT_2_0;
198741  p++;
198742  b = b<<14;
198743  b |= *p;
198744  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
198745  if (!(b&0x80))
198746  {
198747  b &= SLOT_4_2_0;
198748  /* moved CSE2 up */
198749  /* a &= (0x7f<<14)|(0x7f); */
198750  a = a<<7;
198751  a |= b;
198752  s = s>>4;
198753  *v = ((u64)s)<<32 | a;
198754  return 8;
198755  }
198756 
198757  p++;
198758  a = a<<15;
198759  a |= *p;
198760  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
198761 
198762  /* moved CSE2 up */
198763  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
198764  b &= SLOT_2_0;
198765  b = b<<8;
198766  a |= b;
198767 
198768  s = s<<4;
198769  b = p[-4];
198770  b &= 0x7f;
198771  b = b>>3;
198772  s |= b;
198773 
198774  *v = ((u64)s)<<32 | a;
198775 
198776  return 9;
198777 }
198778 
198779 /*
198780 ** The variable-length integer encoding is as follows:
198781 **
198782 ** KEY:
198783 ** A = 0xxxxxxx 7 bits of data and one flag bit
198784 ** B = 1xxxxxxx 7 bits of data and one flag bit
198785 ** C = xxxxxxxx 8 bits of data
198786 **
198787 ** 7 bits - A
198788 ** 14 bits - BA
198789 ** 21 bits - BBA
198790 ** 28 bits - BBBA
198791 ** 35 bits - BBBBA
198792 ** 42 bits - BBBBBA
198793 ** 49 bits - BBBBBBA
198794 ** 56 bits - BBBBBBBA
198795 ** 64 bits - BBBBBBBBC
198796 */
198797 
198798 #ifdef SQLITE_NOINLINE
198799 # define FTS5_NOINLINE SQLITE_NOINLINE
198800 #else
198801 # define FTS5_NOINLINE
198802 #endif
198803 
198804 /*
198805 ** Write a 64-bit variable-length integer to memory starting at p[0].
198806 ** The length of data write will be between 1 and 9 bytes. The number
198807 ** of bytes written is returned.
198808 **
198809 ** A variable-length integer consists of the lower 7 bits of each byte
198810 ** for all bytes that have the 8th bit set and one byte with the 8th
198811 ** bit clear. Except, if we get to the 9th byte, it stores the full
198812 ** 8 bits and is the last byte.
198813 */
198814 static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
198815  int i, j, n;
198816  u8 buf[10];
198817  if( v & (((u64)0xff000000)<<32) ){
198818  p[8] = (u8)v;
198819  v >>= 8;
198820  for(i=7; i>=0; i--){
198821  p[i] = (u8)((v & 0x7f) | 0x80);
198822  v >>= 7;
198823  }
198824  return 9;
198825  }
198826  n = 0;
198827  do{
198828  buf[n++] = (u8)((v & 0x7f) | 0x80);
198829  v >>= 7;
198830  }while( v!=0 );
198831  buf[0] &= 0x7f;
198832  assert( n<=9 );
198833  for(i=0, j=n-1; j>=0; j--, i++){
198834  p[i] = buf[j];
198835  }
198836  return n;
198837 }
198838 
198839 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
198840  if( v<=0x7f ){
198841  p[0] = v&0x7f;
198842  return 1;
198843  }
198844  if( v<=0x3fff ){
198845  p[0] = ((v>>7)&0x7f)|0x80;
198846  p[1] = v&0x7f;
198847  return 2;
198848  }
198849  return fts5PutVarint64(p,v);
198850 }
198851 
198852 
198853 static int sqlite3Fts5GetVarintLen(u32 iVal){
198854 #if 0
198855  if( iVal<(1 << 7 ) ) return 1;
198856 #endif
198857  assert( iVal>=(1 << 7) );
198858  if( iVal<(1 << 14) ) return 2;
198859  if( iVal<(1 << 21) ) return 3;
198860  if( iVal<(1 << 28) ) return 4;
198861  return 5;
198862 }
198863 
198864 
198865 /*
198866 ** 2015 May 08
198867 **
198868 ** The author disclaims copyright to this source code. In place of
198869 ** a legal notice, here is a blessing:
198870 **
198871 ** May you do good and not evil.
198872 ** May you find forgiveness for yourself and forgive others.
198873 ** May you share freely, never taking more than you give.
198874 **
198875 ******************************************************************************
198876 **
198877 ** This is an SQLite virtual table module implementing direct access to an
198878 ** existing FTS5 index. The module may create several different types of
198879 ** tables:
198880 **
198881 ** col:
198882 ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
198883 **
198884 ** One row for each term/column combination. The value of $doc is set to
198885 ** the number of fts5 rows that contain at least one instance of term
198886 ** $term within column $col. Field $cnt is set to the total number of
198887 ** instances of term $term in column $col (in any row of the fts5 table).
198888 **
198889 ** row:
198890 ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
198891 **
198892 ** One row for each term in the database. The value of $doc is set to
198893 ** the number of fts5 rows that contain at least one instance of term
198894 ** $term. Field $cnt is set to the total number of instances of term
198895 ** $term in the database.
198896 */
198897 
198898 
198899 /* #include "fts5Int.h" */
198900 
198901 
198902 typedef struct Fts5VocabTable Fts5VocabTable;
198903 typedef struct Fts5VocabCursor Fts5VocabCursor;
198904 
198905 struct Fts5VocabTable {
198906  sqlite3_vtab base;
198907  char *zFts5Tbl; /* Name of fts5 table */
198908  char *zFts5Db; /* Db containing fts5 table */
198909  sqlite3 *db; /* Database handle */
198910  Fts5Global *pGlobal; /* FTS5 global object for this database */
198911  int eType; /* FTS5_VOCAB_COL or ROW */
198912 };
198913 
198914 struct Fts5VocabCursor {
198915  sqlite3_vtab_cursor base;
198916  sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
198917  Fts5Index *pIndex; /* Associated FTS5 index */
198918 
198919  int bEof; /* True if this cursor is at EOF */
198920  Fts5IndexIter *pIter; /* Term/rowid iterator object */
198921 
198922  int nLeTerm; /* Size of zLeTerm in bytes */
198923  char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
198924 
198925  /* These are used by 'col' tables only */
198926  Fts5Config *pConfig; /* Fts5 table configuration */
198927  int iCol;
198928  i64 *aCnt;
198929  i64 *aDoc;
198930 
198931  /* Output values used by 'row' and 'col' tables */
198932  i64 rowid; /* This table's current rowid value */
198933  Fts5Buffer term; /* Current value of 'term' column */
198934 };
198935 
198936 #define FTS5_VOCAB_COL 0
198937 #define FTS5_VOCAB_ROW 1
198938 
198939 #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
198940 #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
198941 
198942 /*
198943 ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
198944 */
198945 #define FTS5_VOCAB_TERM_EQ 0x01
198946 #define FTS5_VOCAB_TERM_GE 0x02
198947 #define FTS5_VOCAB_TERM_LE 0x04
198948 
198949 
198950 /*
198951 ** Translate a string containing an fts5vocab table type to an
198952 ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
198953 ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
198954 ** and return SQLITE_ERROR.
198955 */
198956 static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
198957  int rc = SQLITE_OK;
198958  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
198959  if( rc==SQLITE_OK ){
198960  sqlite3Fts5Dequote(zCopy);
198961  if( sqlite3_stricmp(zCopy, "col")==0 ){
198962  *peType = FTS5_VOCAB_COL;
198963  }else
198964 
198965  if( sqlite3_stricmp(zCopy, "row")==0 ){
198966  *peType = FTS5_VOCAB_ROW;
198967  }else
198968  {
198969  *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
198970  rc = SQLITE_ERROR;
198971  }
198972  sqlite3_free(zCopy);
198973  }
198974 
198975  return rc;
198976 }
198977 
198978 
198979 /*
198980 ** The xDisconnect() virtual table method.
198981 */
198982 static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
198983  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
198984  sqlite3_free(pTab);
198985  return SQLITE_OK;
198986 }
198987 
198988 /*
198989 ** The xDestroy() virtual table method.
198990 */
198991 static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
198992  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
198993  sqlite3_free(pTab);
198994  return SQLITE_OK;
198995 }
198996 
198997 /*
198998 ** This function is the implementation of both the xConnect and xCreate
198999 ** methods of the FTS3 virtual table.
199000 **
199001 ** The argv[] array contains the following:
199002 **
199003 ** argv[0] -> module name ("fts5vocab")
199004 ** argv[1] -> database name
199005 ** argv[2] -> table name
199006 **
199007 ** then:
199008 **
199009 ** argv[3] -> name of fts5 table
199010 ** argv[4] -> type of fts5vocab table
199011 **
199012 ** or, for tables in the TEMP schema only.
199013 **
199014 ** argv[3] -> name of fts5 tables database
199015 ** argv[4] -> name of fts5 table
199016 ** argv[5] -> type of fts5vocab table
199017 */
199018 static int fts5VocabInitVtab(
199019  sqlite3 *db, /* The SQLite database connection */
199020  void *pAux, /* Pointer to Fts5Global object */
199021  int argc, /* Number of elements in argv array */
199022  const char * const *argv, /* xCreate/xConnect argument array */
199023  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
199024  char **pzErr /* Write any error message here */
199025 ){
199026  const char *azSchema[] = {
199027  "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
199028  "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
199029  };
199030 
199031  Fts5VocabTable *pRet = 0;
199032  int rc = SQLITE_OK; /* Return code */
199033  int bDb;
199034 
199035  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
199036 
199037  if( argc!=5 && bDb==0 ){
199038  *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
199039  rc = SQLITE_ERROR;
199040  }else{
199041  int nByte; /* Bytes of space to allocate */
199042  const char *zDb = bDb ? argv[3] : argv[1];
199043  const char *zTab = bDb ? argv[4] : argv[3];
199044  const char *zType = bDb ? argv[5] : argv[4];
199045  int nDb = (int)strlen(zDb)+1;
199046  int nTab = (int)strlen(zTab)+1;
199047  int eType = 0;
199048 
199049  rc = fts5VocabTableType(zType, pzErr, &eType);
199050  if( rc==SQLITE_OK ){
199051  assert( eType>=0 && eType<ArraySize(azSchema) );
199052  rc = sqlite3_declare_vtab(db, azSchema[eType]);
199053  }
199054 
199055  nByte = sizeof(Fts5VocabTable) + nDb + nTab;
199056  pRet = sqlite3Fts5MallocZero(&rc, nByte);
199057  if( pRet ){
199058  pRet->pGlobal = (Fts5Global*)pAux;
199059  pRet->eType = eType;
199060  pRet->db = db;
199061  pRet->zFts5Tbl = (char*)&pRet[1];
199062  pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
199063  memcpy(pRet->zFts5Tbl, zTab, nTab);
199064  memcpy(pRet->zFts5Db, zDb, nDb);
199065  sqlite3Fts5Dequote(pRet->zFts5Tbl);
199066  sqlite3Fts5Dequote(pRet->zFts5Db);
199067  }
199068  }
199069 
199070  *ppVTab = (sqlite3_vtab*)pRet;
199071  return rc;
199072 }
199073 
199074 
199075 /*
199076 ** The xConnect() and xCreate() methods for the virtual table. All the
199077 ** work is done in function fts5VocabInitVtab().
199078 */
199079 static int fts5VocabConnectMethod(
199080  sqlite3 *db, /* Database connection */
199081  void *pAux, /* Pointer to tokenizer hash table */
199082  int argc, /* Number of elements in argv array */
199083  const char * const *argv, /* xCreate/xConnect argument array */
199084  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
199085  char **pzErr /* OUT: sqlite3_malloc'd error message */
199086 ){
199087  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
199088 }
199089 static int fts5VocabCreateMethod(
199090  sqlite3 *db, /* Database connection */
199091  void *pAux, /* Pointer to tokenizer hash table */
199092  int argc, /* Number of elements in argv array */
199093  const char * const *argv, /* xCreate/xConnect argument array */
199094  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
199095  char **pzErr /* OUT: sqlite3_malloc'd error message */
199096 ){
199097  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
199098 }
199099 
199100 /*
199101 ** Implementation of the xBestIndex method.
199102 */
199103 static int fts5VocabBestIndexMethod(
199104  sqlite3_vtab *pUnused,
199105  sqlite3_index_info *pInfo
199106 ){
199107  int i;
199108  int iTermEq = -1;
199109  int iTermGe = -1;
199110  int iTermLe = -1;
199111  int idxNum = 0;
199112  int nArg = 0;
199113 
199114  UNUSED_PARAM(pUnused);
199115 
199116  for(i=0; i<pInfo->nConstraint; i++){
199117  struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
199118  if( p->usable==0 ) continue;
199119  if( p->iColumn==0 ){ /* term column */
199120  if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
199121  if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
199122  if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
199123  if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
199124  if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
199125  }
199126  }
199127 
199128  if( iTermEq>=0 ){
199129  idxNum |= FTS5_VOCAB_TERM_EQ;
199130  pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
199131  pInfo->estimatedCost = 100;
199132  }else{
199133  pInfo->estimatedCost = 1000000;
199134  if( iTermGe>=0 ){
199135  idxNum |= FTS5_VOCAB_TERM_GE;
199136  pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
199137  pInfo->estimatedCost = pInfo->estimatedCost / 2;
199138  }
199139  if( iTermLe>=0 ){
199140  idxNum |= FTS5_VOCAB_TERM_LE;
199141  pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
199142  pInfo->estimatedCost = pInfo->estimatedCost / 2;
199143  }
199144  }
199145 
199146  /* This virtual table always delivers results in ascending order of
199147  ** the "term" column (column 0). So if the user has requested this
199148  ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
199149  ** sqlite3_index_info.orderByConsumed flag to tell the core the results
199150  ** are already in sorted order. */
199151  if( pInfo->nOrderBy==1
199152  && pInfo->aOrderBy[0].iColumn==0
199153  && pInfo->aOrderBy[0].desc==0
199154  ){
199155  pInfo->orderByConsumed = 1;
199156  }
199157 
199158  pInfo->idxNum = idxNum;
199159  return SQLITE_OK;
199160 }
199161 
199162 /*
199163 ** Implementation of xOpen method.
199164 */
199165 static int fts5VocabOpenMethod(
199166  sqlite3_vtab *pVTab,
199167  sqlite3_vtab_cursor **ppCsr
199168 ){
199169  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
199170  Fts5Index *pIndex = 0;
199171  Fts5Config *pConfig = 0;
199172  Fts5VocabCursor *pCsr = 0;
199173  int rc = SQLITE_OK;
199174  sqlite3_stmt *pStmt = 0;
199175  char *zSql = 0;
199176 
199177  zSql = sqlite3Fts5Mprintf(&rc,
199178  "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
199179  pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
199180  );
199181  if( zSql ){
199182  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
199183  }
199184  sqlite3_free(zSql);
199185  assert( rc==SQLITE_OK || pStmt==0 );
199186  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
199187 
199188  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
199189  i64 iId = sqlite3_column_int64(pStmt, 0);
199190  pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
199191  }
199192 
199193  if( rc==SQLITE_OK && pIndex==0 ){
199194  rc = sqlite3_finalize(pStmt);
199195  pStmt = 0;
199196  if( rc==SQLITE_OK ){
199197  pVTab->zErrMsg = sqlite3_mprintf(
199198  "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
199199  );
199200  rc = SQLITE_ERROR;
199201  }
199202  }
199203 
199204  if( rc==SQLITE_OK ){
199205  int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
199206  pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
199207  }
199208 
199209  if( pCsr ){
199210  pCsr->pIndex = pIndex;
199211  pCsr->pStmt = pStmt;
199212  pCsr->pConfig = pConfig;
199213  pCsr->aCnt = (i64*)&pCsr[1];
199214  pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
199215  }else{
199216  sqlite3_finalize(pStmt);
199217  }
199218 
199219  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
199220  return rc;
199221 }
199222 
199223 static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
199224  pCsr->rowid = 0;
199225  sqlite3Fts5IterClose(pCsr->pIter);
199226  pCsr->pIter = 0;
199227  sqlite3_free(pCsr->zLeTerm);
199228  pCsr->nLeTerm = -1;
199229  pCsr->zLeTerm = 0;
199230 }
199231 
199232 /*
199233 ** Close the cursor. For additional information see the documentation
199234 ** on the xClose method of the virtual table interface.
199235 */
199236 static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
199237  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199238  fts5VocabResetCursor(pCsr);
199239  sqlite3Fts5BufferFree(&pCsr->term);
199240  sqlite3_finalize(pCsr->pStmt);
199241  sqlite3_free(pCsr);
199242  return SQLITE_OK;
199243 }
199244 
199245 
199246 /*
199247 ** Advance the cursor to the next row in the table.
199248 */
199249 static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
199250  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199251  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
199252  int rc = SQLITE_OK;
199253  int nCol = pCsr->pConfig->nCol;
199254 
199255  pCsr->rowid++;
199256 
199257  if( pTab->eType==FTS5_VOCAB_COL ){
199258  for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
199259  if( pCsr->aDoc[pCsr->iCol] ) break;
199260  }
199261  }
199262 
199263  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
199264  if( sqlite3Fts5IterEof(pCsr->pIter) ){
199265  pCsr->bEof = 1;
199266  }else{
199267  const char *zTerm;
199268  int nTerm;
199269 
199270  zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
199271  if( pCsr->nLeTerm>=0 ){
199272  int nCmp = MIN(nTerm, pCsr->nLeTerm);
199273  int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
199274  if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
199275  pCsr->bEof = 1;
199276  return SQLITE_OK;
199277  }
199278  }
199279 
199280  sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
199281  memset(pCsr->aCnt, 0, nCol * sizeof(i64));
199282  memset(pCsr->aDoc, 0, nCol * sizeof(i64));
199283  pCsr->iCol = 0;
199284 
199285  assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
199286  while( rc==SQLITE_OK ){
199287  const u8 *pPos; int nPos; /* Position list */
199288  i64 iPos = 0; /* 64-bit position read from poslist */
199289  int iOff = 0; /* Current offset within position list */
199290 
199291  pPos = pCsr->pIter->pData;
199292  nPos = pCsr->pIter->nData;
199293  switch( pCsr->pConfig->eDetail ){
199294  case FTS5_DETAIL_FULL:
199295  pPos = pCsr->pIter->pData;
199296  nPos = pCsr->pIter->nData;
199297  if( pTab->eType==FTS5_VOCAB_ROW ){
199298  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
199299  pCsr->aCnt[0]++;
199300  }
199301  pCsr->aDoc[0]++;
199302  }else{
199303  int iCol = -1;
199304  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
199305  int ii = FTS5_POS2COLUMN(iPos);
199306  pCsr->aCnt[ii]++;
199307  if( iCol!=ii ){
199308  if( ii>=nCol ){
199309  rc = FTS5_CORRUPT;
199310  break;
199311  }
199312  pCsr->aDoc[ii]++;
199313  iCol = ii;
199314  }
199315  }
199316  }
199317  break;
199318 
199319  case FTS5_DETAIL_COLUMNS:
199320  if( pTab->eType==FTS5_VOCAB_ROW ){
199321  pCsr->aDoc[0]++;
199322  }else{
199323  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
199324  assert_nc( iPos>=0 && iPos<nCol );
199325  if( iPos>=nCol ){
199326  rc = FTS5_CORRUPT;
199327  break;
199328  }
199329  pCsr->aDoc[iPos]++;
199330  }
199331  }
199332  break;
199333 
199334  default:
199335  assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
199336  pCsr->aDoc[0]++;
199337  break;
199338  }
199339 
199340  if( rc==SQLITE_OK ){
199341  rc = sqlite3Fts5IterNextScan(pCsr->pIter);
199342  }
199343 
199344  if( rc==SQLITE_OK ){
199345  zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
199346  if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
199347  break;
199348  }
199349  if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
199350  }
199351  }
199352  }
199353  }
199354 
199355  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
199356  while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
199357  assert( pCsr->iCol<pCsr->pConfig->nCol );
199358  }
199359  return rc;
199360 }
199361 
199362 /*
199363 ** This is the xFilter implementation for the virtual table.
199364 */
199365 static int fts5VocabFilterMethod(
199366  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
199367  int idxNum, /* Strategy index */
199368  const char *zUnused, /* Unused */
199369  int nUnused, /* Number of elements in apVal */
199370  sqlite3_value **apVal /* Arguments for the indexing scheme */
199371 ){
199372  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199373  int rc = SQLITE_OK;
199374 
199375  int iVal = 0;
199376  int f = FTS5INDEX_QUERY_SCAN;
199377  const char *zTerm = 0;
199378  int nTerm = 0;
199379 
199380  sqlite3_value *pEq = 0;
199381  sqlite3_value *pGe = 0;
199382  sqlite3_value *pLe = 0;
199383 
199384  UNUSED_PARAM2(zUnused, nUnused);
199385 
199386  fts5VocabResetCursor(pCsr);
199387  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
199388  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
199389  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
199390 
199391  if( pEq ){
199392  zTerm = (const char *)sqlite3_value_text(pEq);
199393  nTerm = sqlite3_value_bytes(pEq);
199394  f = 0;
199395  }else{
199396  if( pGe ){
199397  zTerm = (const char *)sqlite3_value_text(pGe);
199398  nTerm = sqlite3_value_bytes(pGe);
199399  }
199400  if( pLe ){
199401  const char *zCopy = (const char *)sqlite3_value_text(pLe);
199402  pCsr->nLeTerm = sqlite3_value_bytes(pLe);
199403  pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
199404  if( pCsr->zLeTerm==0 ){
199405  rc = SQLITE_NOMEM;
199406  }else{
199407  memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
199408  }
199409  }
199410  }
199411 
199412 
199413  if( rc==SQLITE_OK ){
199414  rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
199415  }
199416  if( rc==SQLITE_OK ){
199417  rc = fts5VocabNextMethod(pCursor);
199418  }
199419 
199420  return rc;
199421 }
199422 
199423 /*
199424 ** This is the xEof method of the virtual table. SQLite calls this
199425 ** routine to find out if it has reached the end of a result set.
199426 */
199427 static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
199428  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199429  return pCsr->bEof;
199430 }
199431 
199432 static int fts5VocabColumnMethod(
199433  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
199434  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
199435  int iCol /* Index of column to read value from */
199436 ){
199437  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199438  int eDetail = pCsr->pConfig->eDetail;
199439  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
199440  i64 iVal = 0;
199441 
199442  if( iCol==0 ){
199444  pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
199445  );
199446  }else if( eType==FTS5_VOCAB_COL ){
199447  assert( iCol==1 || iCol==2 || iCol==3 );
199448  if( iCol==1 ){
199449  if( eDetail!=FTS5_DETAIL_NONE ){
199450  const char *z = pCsr->pConfig->azCol[pCsr->iCol];
199451  sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
199452  }
199453  }else if( iCol==2 ){
199454  iVal = pCsr->aDoc[pCsr->iCol];
199455  }else{
199456  iVal = pCsr->aCnt[pCsr->iCol];
199457  }
199458  }else{
199459  assert( iCol==1 || iCol==2 );
199460  if( iCol==1 ){
199461  iVal = pCsr->aDoc[0];
199462  }else{
199463  iVal = pCsr->aCnt[0];
199464  }
199465  }
199466 
199467  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
199468  return SQLITE_OK;
199469 }
199470 
199471 /*
199472 ** This is the xRowid method. The SQLite core calls this routine to
199473 ** retrieve the rowid for the current row of the result set. The
199474 ** rowid should be written to *pRowid.
199475 */
199476 static int fts5VocabRowidMethod(
199477  sqlite3_vtab_cursor *pCursor,
199478  sqlite_int64 *pRowid
199479 ){
199480  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
199481  *pRowid = pCsr->rowid;
199482  return SQLITE_OK;
199483 }
199484 
199485 static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
199486  static const sqlite3_module fts5Vocab = {
199487  /* iVersion */ 2,
199488  /* xCreate */ fts5VocabCreateMethod,
199489  /* xConnect */ fts5VocabConnectMethod,
199490  /* xBestIndex */ fts5VocabBestIndexMethod,
199491  /* xDisconnect */ fts5VocabDisconnectMethod,
199492  /* xDestroy */ fts5VocabDestroyMethod,
199493  /* xOpen */ fts5VocabOpenMethod,
199494  /* xClose */ fts5VocabCloseMethod,
199495  /* xFilter */ fts5VocabFilterMethod,
199496  /* xNext */ fts5VocabNextMethod,
199497  /* xEof */ fts5VocabEofMethod,
199498  /* xColumn */ fts5VocabColumnMethod,
199499  /* xRowid */ fts5VocabRowidMethod,
199500  /* xUpdate */ 0,
199501  /* xBegin */ 0,
199502  /* xSync */ 0,
199503  /* xCommit */ 0,
199504  /* xRollback */ 0,
199505  /* xFindFunction */ 0,
199506  /* xRename */ 0,
199507  /* xSavepoint */ 0,
199508  /* xRelease */ 0,
199509  /* xRollbackTo */ 0,
199510  };
199511  void *p = (void*)pGlobal;
199512 
199513  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
199514 }
199515 
199516 
199517 
199518 
199519 
199520 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
199521 
199522 /************** End of fts5.c ************************************************/
static int selectExpander(Walker *pWalker, Select *p)
Definition: sqlite3.c:118610
#define TK_UPDATE
Definition: sqlite3.c:11401
sqlite3_file * pFd
Definition: sqlite3.c:56617
static void destroyRootPage(Parse *pParse, int iTable, int iDb)
Definition: sqlite3.c:100612
SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *, Mem *)
Definition: sqlite3.c:69587
SQLITE_PRIVATE void sqlite3StatusHighwater(int, int)
Definition: sqlite3.c:18335
int nChunkSize
Definition: sqlite3.c:87670
int nOBSat
Definition: sqlite3.c:114441
#define pcache1
Definition: sqlite3.c:44670
#define ISAUTOVACUUM
Definition: sqlite3.c:57904
#define SQLITE_SYNC_MASK
Definition: sqlite3.c:46265
AggInfo * pAggInfo
Definition: sqlite3.c:15240
static u16 operatorMask(int op)
Definition: sqlite3.c:126534
#define SQLITE_MAX_ATTACHED
Definition: sqlite3.c:10773
u32 minFrame
Definition: sqlite3.c:54230
SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *)
Definition: sqlite3.c:118289
void * pTraceArg
Definition: sqlite3.c:13949
static int unixSectorSize(sqlite3_file *NotUsed)
Definition: sqlite3.c:33249
#define TK_AUTOINCR
Definition: sqlite3.c:11397
static const char * unixNextSystemCall(sqlite3_vfs *p, const char *zName)
Definition: sqlite3.c:29971
SQLITE_PRIVATE void sqlite3BeginTrigger(Parse *, Token *, Token *, int, int, IdList *, SrcList *, Expr *, int, int)
Definition: sqlite3.c:120348
#define EXTRA_SIZE
Definition: sqlite3.c:57558
SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *)
Definition: sqlite3.c:90413
static int pushDownWhereTerms(sqlite3 *db, Select *pSubq, Expr *pWhere, int iCursor)
Definition: sqlite3.c:118168
static void cacheEntryClear(Parse *pParse, int i)
Definition: sqlite3.c:92697
const Token * pName
Definition: sqlite3.c:15784
SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *)
Definition: sqlite3.c:69327
SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse *, Table *, int, int, int, int *, int, int, int)
Definition: sqlite3.c:109036
#define OPFLG_IN1
Definition: sqlite3.c:12731
SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *, Table *)
Definition: sqlite3.c:98860
int(* xFindTokenizer)(fts5_api *pApi, const char *zName, void **ppContext, fts5_tokenizer *pTokenizer)
Definition: sqlite3.c:10604
#define OP_Expire
Definition: sqlite3.c:12712
#define SQLITE_INDEX_SCAN_UNIQUE
Definition: sqlite3.c:6224
void * pAux
Definition: sqlite3.c:17975
#define PTRMAP_PAGENO(pBt, pgno)
Definition: sqlite3.c:57847
#define osOpen
SQLITE_API const unsigned char * sqlite3_value_text(sqlite3_value *)
Definition: sqlite3.c:75318
#define sqlite3Isalpha(x)
Definition: sqlite3.c:16033
d
#define SQLITE_MUTEX_STATIC_MASTER
Definition: sqlite3.c:6879
static int pagerOpentemp(Pager *pPager, sqlite3_file *pFile, int vfsFlags)
Definition: sqlite3.c:49940
#define EP_IntValue
Definition: sqlite3.c:14965
u8 sharable
Definition: sqlite3.c:57603
#define UNIXFILE_RDONLY
Definition: sqlite3.c:29454
static int vdbeCompareMemString(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl, u8 *prcErr)
Definition: sqlite3.c:74167
SQLITE_PRIVATE int sqlite3BtreeCursor(Btree *, int iTable, int wrFlag, struct KeyInfo *, BtCursor *pCursor)
Definition: sqlite3.c:62401
void(* xDlClose)(sqlite3_vfs *, void *)
Definition: sqlite3.c:1501
#define YY_MAX_REDUCE
Definition: sqlite3.c:133127
#define SQLITE_CANTOPEN_FULLPATH
Definition: sqlite3.c:758
int(* xClose)(sqlite3_file *)
Definition: sqlite3.c:1007
SQLITE_API int sqlite3_bind_text(sqlite3_stmt *, int, const char *, int, void(*)(void *))
Definition: sqlite3.c:76481
#define SQLITE_TRACE_LEGACY
Definition: sqlite3.c:13893
#define OPFLAG_SAVEPOSITION
Definition: sqlite3.c:15679
static void fkScanChildren(Parse *pParse, SrcList *pSrc, Table *pTab, Index *pIdx, FKey *pFKey, int *aiCol, int regData, int nIncr)
Definition: sqlite3.c:106505
SQLITE_PRIVATE int sqlite3RunVacuum(char **, sqlite3 *, int)
Definition: sqlite3.c:122315
u8 * apOvfl[5]
Definition: sqlite3.c:57541
#define SQLITE_READONLY
Definition: sqlite3.c:683
static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem)
Definition: sqlite3.c:77569
#define CODEC2(P, D, N, X, E, O)
Definition: sqlite3.c:46785
#define SQLITE_ABORT
Definition: sqlite3.c:679
#define COLNAME_TABLE
Definition: sqlite3.c:12534
#define FLAG_INTERN
Definition: sqlite3.c:24773
SQLITE_PRIVATE struct Pager * sqlite3BtreePager(Btree *)
Definition: sqlite3.c:67052
int nFunc
Definition: sqlite3.c:14824
static int robust_ftruncate(int h, sqlite3_int64 sz)
Definition: sqlite3.c:30161
struct WherePath WherePath
Definition: sqlite3.c:123848
static int parseDateOrTime(sqlite3_context *context, const char *zDate, DateTime *p)
Definition: sqlite3.c:18924
#define TK_AFTER
Definition: sqlite3.c:11350
Select * pSelect
Definition: sqlite3.c:15763
Expr * pLimit
Definition: sqlite3.c:132870
int aiCurOnePass[2]
Definition: sqlite3.c:124224
FuncDef * pNext
Definition: sqlite3.c:14140
SQLITE_API int sqlite3_open16(const void *filename, sqlite3 **ppDb)
Definition: sqlite3.c:140956
#define IsPowerOfTwo(X)
Definition: sqlite3.c:11906
static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock)
Definition: sqlite3.c:31133
#define CC_RP
Definition: sqlite3.c:136616
char * zJournal
Definition: sqlite3.c:47053
#define SQLITE_SHM_UNLOCK
Definition: sqlite3.c:1571
#define OpenCounter(X)
Definition: sqlite3.c:29661
static void unixShmBarrier(sqlite3_file *fd)
Definition: sqlite3.c:34016
SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *, int)
Definition: sqlite3.c:69428
SQLITE_PRIVATE IdList * sqlite3IdListAppend(sqlite3 *, IdList *, Token *)
Definition: sqlite3.c:101877
char * zBase
Definition: sqlite3.c:15793
#define IN_INDEX_NOOP
Definition: sqlite3.c:16813
static const FuncDef statPushFuncdef
Definition: sqlite3.c:96337
SQLITE_API double sqlite3_column_double(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76142
static void sqlite3MallocAlarm(int nByte)
Definition: sqlite3.c:24093
int errMask
Definition: sqlite3.c:13914
#define PAGER_MAX_PGNO
Definition: sqlite3.c:47164
#define PAGER_INCR(v)
Definition: sqlite3.c:47095
int walkerDepth
Definition: sqlite3.c:15909
#define SQLITE_FUNC_LENGTH
Definition: sqlite3.c:14188
#define unlikely(X)
Definition: sqlite3.c:11187
#define TK_AGG_COLUMN
Definition: sqlite3.c:11445
#define SQLITE_FUNC_SLOCHNG
Definition: sqlite3.c:14195
ExprList * pGroupBy
Definition: sqlite3.c:15296
static void insertElement(Hash *pH, struct _ht *pEntry, HashElem *pNew)
Definition: sqlite3.c:28802
u32 selFlags
Definition: sqlite3.c:15288
SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *)
Definition: sqlite3.c:98350
u32 aWalData[WAL_SAVEPOINT_NDATA]
Definition: sqlite3.c:46818
SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *)
Definition: sqlite3.c:56172
etByte charset
Definition: sqlite3.c:24765
#define SQLITE_LOCKED
Definition: sqlite3.c:681
static void verifyDbFile(unixFile *pFile)
Definition: sqlite3.c:30741
SQLITE_API const void * sqlite3_value_blob(sqlite3_value *)
Definition: sqlite3.c:75286
static int btreeSetHasContent(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:58802
static void parserDoubleLinkSelect(Parse *pParse, Select *p)
Definition: sqlite3.c:132900
#define PTF_INTKEY
Definition: sqlite3.c:57505
static int copyPayload(void *pPayload, void *pBuf, int nByte, int eOp, DbPage *pDbPage)
Definition: sqlite3.c:62635
Btree * pBt
Definition: sqlite3.c:13738
static int memjrnlCreateFile(MemJournal *p)
Definition: sqlite3.c:87751
SQLITE_PRIVATE const char * sqlite3BtreeGetJournalname(Btree *)
Definition: sqlite3.c:67693
#define SF_MinMaxAgg
Definition: sqlite3.c:15327
#define SQLITE_DBSTATUS_CACHE_HIT
Definition: sqlite3.c:7259
Select * pSelect
Definition: sqlite3.c:15949
BtShared * pNext
Definition: sqlite3.c:57693
u32 pageSize
Definition: sqlite3.c:57683
SQLITE_PRIVATE void sqlite3Put4byte(u8 *, u32)
u64 Bitmask
Definition: sqlite3.c:15099
static void spanUnaryPrefix(ExprSpan *pOut, Parse *pParse, int op, ExprSpan *pOperand, Token *pPreOp)
Definition: sqlite3.c:133000
u8 eCreate
Definition: sqlite3.c:43628
SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix)
Definition: sqlite3.c:60896
SQLITE_API int sqlite3_table_column_metadata(sqlite3 *db, const char *zDbName, const char *zTableName, const char *zColumnName, char const **pzDataType, char const **pzCollSeq, int *pNotNull, int *pPrimaryKey, int *pAutoinc)
Definition: sqlite3.c:141182
#define OP_Init
Definition: sqlite3.c:12633
static int pager_truncate(Pager *pPager, Pgno nPage)
Definition: sqlite3.c:48931
#define SWAP(TYPE, A, B)
Definition: sqlite3.c:11581
#define SQLITE_MAX_PAGE_SIZE
Definition: sqlite3.c:10798
SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *, double)
Definition: sqlite3.c:69467
#define WHERE_COLUMN_IN
Definition: sqlite3.c:124343
Trigger * pNewTrigger
Definition: sqlite3.c:15612
#define SQLITE_READ
Definition: sqlite3.c:3036
#define WAL_HEAPMEMORY_MODE
Definition: sqlite3.c:54247
u8 printfFlags
Definition: sqlite3.c:15799
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *)
Definition: sqlite3.c:19993
Pgno dbOrigSize
Definition: sqlite3.c:47019
static void setStrAccumError(StrAccum *p, u8 eError)
Definition: sqlite3.c:24848
#define put32bits(A, B)
Definition: sqlite3.c:47438
static SQLITE_WSD struct sqlite3StatType sqlite3Stat
With * yy285
Definition: sqlite3.c:133108
#define UNIXFILE_DELETE
Definition: sqlite3.c:29462
#define VdbeCoverage(v)
Definition: sqlite3.c:12899
#define SQLITE_DROP_VTABLE
Definition: sqlite3.c:3046
#define OP_Function
Definition: sqlite3.c:12652
static int pagerUnlockDb(Pager *pPager, int eLock)
Definition: sqlite3.c:47460
#define PragTyp_FOREIGN_KEY_CHECK
Definition: sqlite3.c:111124
MergeEngine * pMerger
Definition: sqlite3.c:85165
#define etDYNSTRING
Definition: sqlite3.c:24735
SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *, int)
Definition: sqlite3.c:19841
static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode)
Definition: sqlite3.c:87112
Pgno nPage
Definition: sqlite3.c:57925
#define MEM_Str
Definition: sqlite3.c:17916
#define TF_NoVisibleRowid
Definition: sqlite3.c:14483
struct RowSetEntry * pLast
Definition: sqlite3.c:45826
SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id)
Definition: sqlite3.c:19891
sqlite3_mem_methods m
Definition: sqlite3.c:15837
static void sqlite3SkipAccumulatorLoad(sqlite3_context *context)
Definition: sqlite3.c:104152
FuncDef * pFunc
Definition: sqlite3.c:17995
#define OP_And
Definition: sqlite3.c:12590
struct SrcList::SrcList_item::@7 fg
static int isLookaside(sqlite3 *db, void *p)
Definition: sqlite3.c:24280
#define OP_ResetSorter
Definition: sqlite3.c:12695
int n
Definition: sqlite3.c:17883
u8 padToSectorBoundary
Definition: sqlite3.c:54228
Bitvec * pInJournal
Definition: sqlite3.c:47026
#define TK_COMMA
Definition: sqlite3.c:11317
#define SQLITE_LoadExtFunc
Definition: sqlite3.c:14067
#define WRC_Abort
Definition: sqlite3.c:15937
static const char * explainIndexColumnName(Index *pIdx, int i)
Definition: sqlite3.c:124369
static int moveToRoot(BtCursor *pCur)
Definition: sqlite3.c:63086
u32 aReadMark[WAL_NREADER]
Definition: sqlite3.c:54163
StrAccum errMsg
Definition: sqlite3.c:57931
#define NC_IdxExpr
Definition: sqlite3.c:15260
Schema * pTabSchema
Definition: sqlite3.c:15706
SrcList * pSrcList
Definition: sqlite3.c:15238
SorterList list
Definition: sqlite3.c:85142
#define WAL_RETRY
Definition: sqlite3.c:55907
#define BTREE_FORDELETE
Definition: sqlite3.c:12244
#define O_NOFOLLOW
Definition: sqlite3.c:29680
SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *)
Definition: sqlite3.c:58234
SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *)
Definition: sqlite3.c:111033
struct WhereLoop * pWLoop
Definition: sqlite3.c:123898
#define OP_ShiftRight
Definition: sqlite3.c:12608
#define wsdHooks
Definition: sqlite3.c:20212
struct SorterRecord SorterRecord
Definition: sqlite3.c:85005
SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *)
Definition: sqlite3.c:53504
#define EP_xIsSelect
Definition: sqlite3.c:14966
SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *, int)
Definition: sqlite3.c:19849
static int pager_playback(Pager *pPager, int isHot)
Definition: sqlite3.c:49074
Bitmask indexable
Definition: sqlite3.c:124145
void * pKey
Definition: sqlite3.c:57761
#define TK_VACUUM
Definition: sqlite3.c:11380
SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *)
Definition: sqlite3.c:98834
SQLITE_API int sqlite3_busy_handler(sqlite3 *, int(*)(void *, int), void *)
Definition: sqlite3.c:139348
#define DFUNCTION(zName, nArg, iArg, bNC, xFunc)
Definition: sqlite3.c:14238
static int unixShmUnmap(sqlite3_file *fd, int deleteFlag)
Definition: sqlite3.c:34032
static SQLITE_WSD struct sqlite3PrngType sqlite3Prng
static const unsigned char sqlite3Utf8Trans1[]
Definition: sqlite3.c:26791
SQLITE_API int sqlite3_value_int(sqlite3_value *)
Definition: sqlite3.c:75308
#define SQLITE_CONFIG_GETMUTEX
Definition: sqlite3.c:2138
static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut)
Definition: sqlite3.c:85422
static int vdbeRecordCompareString(int nKey1, const void *pKey1, UnpackedRecord *pPKey2)
Definition: sqlite3.c:74720
static int accessPayload(BtCursor *pCur, u32 offset, u32 amt, unsigned char *pBuf, int eOp)
Definition: sqlite3.c:62686
static void pcache1Cachesize(sqlite3_pcache *p, int nMax)
Definition: sqlite3.c:45250
SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *)
Definition: sqlite3.c:127860
#define NC_MinMaxAgg
Definition: sqlite3.c:15262
Select * pSelect
Definition: sqlite3.c:14924
SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe *, int, int, int, int, const u8 *, int)
Definition: sqlite3.c:70754
int nTab
Definition: sqlite3.c:15533
#define MEMCELLSIZE
Definition: sqlite3.c:17901
#define IsUniqueIndex(X)
Definition: sqlite3.c:14749
unixShmNode * pShmNode
Definition: sqlite3.c:30467
#define TK_FLOAT
Definition: sqlite3.c:11423
#define VdbeBranchTaken(I, M)
Definition: sqlite3.c:77355
#define COLFLAG_HASTYPE
Definition: sqlite3.c:14310
union Mem::MemValue u
#define OP_IdxGE
Definition: sqlite3.c:12623
ExprList * pGroupBy
Definition: sqlite3.c:14805
int(* xRead)(sqlite3_file *, void *, int iAmt, sqlite3_int64 iOfst)
Definition: sqlite3.c:1008
const char ** azColl
Definition: sqlite3.c:14714
static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit)
Definition: sqlite3.c:45584
#define SQLITE_BIGENDIAN
Definition: sqlite3.c:11758
#define sqlite3_column_table_name16
Definition: sqlite3.c:110314
union WhereLoop::@15 u
#define MEMDB
Definition: sqlite3.c:47148
#define UINT8_TYPE
Definition: sqlite3.c:11625
static int checkTreePage(IntegrityCk *pCheck, int iPage, i64 *piMinKey, i64 maxKey)
Definition: sqlite3.c:67297
static int dupedExprSize(Expr *p, int flags)
Definition: sqlite3.c:90866
ExprList * pList
Definition: sqlite3.c:14923
#define SQLITE_EXPERIMENTAL
Definition: sqlite3.c:344
int busyTimeout
Definition: sqlite3.c:13999
SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse *, ExprList *, int, int, int)
Definition: sqlite3.c:99575
int eFWErr
Definition: sqlite3.c:85257
SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db)
Definition: sqlite3.c:123459
#define WHERE_TOP_LIMIT
Definition: sqlite3.c:124346
static void transferParseError(Parse *pTo, Parse *pFrom)
Definition: sqlite3.c:121041
char * zText
Definition: sqlite3.c:15794
#define BTCURSOR_MAX_DEPTH
Definition: sqlite3.c:57733
#define WHERE_ONEPASS_MULTIROW
Definition: sqlite3.c:15193
static int robust_open(const char *z, int f, mode_t m)
Definition: sqlite3.c:30012
u8 suppressErr
Definition: sqlite3.c:13924
#define PTRMAP_OVERFLOW2
Definition: sqlite3.c:57885
#define WHERE_ORDERBY_MIN
Definition: sqlite3.c:15190
static int exprIdxCover(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:94358
#define swapMixedEndianFloat(X)
Definition: sqlite3.c:73743
struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]
Definition: sqlite3.c:45814
BtShared * pBt
Definition: sqlite3.c:57756
int(* xSectorSize)(sqlite3_file *)
Definition: sqlite3.c:1017
char * zMalloc
Definition: sqlite3.c:17886
#define OP_IfNotZero
Definition: sqlite3.c:12629
Definition: sqlite3.c:54210
#define SQLITE_DBCONFIG_ENABLE_TRIGGER
Definition: sqlite3.c:2255
static void changes(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:104658
#define OP_RowSetTest
Definition: sqlite3.c:12625
#define DB_SchemaLoaded
Definition: sqlite3.c:13794
#define WO_OR
Definition: sqlite3.c:124328
static int checkColumnOverlap(IdList *pIdList, ExprList *pEList)
Definition: sqlite3.c:120868
static int pageFreeArray(MemPage *pPg, int iFirst, int nCell, CellArray *pCArray)
Definition: sqlite3.c:64804
#define JT_NATURAL
Definition: sqlite3.c:15175
#define SQLITE_NULLEQ
Definition: sqlite3.c:14376
SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal)
Definition: sqlite3.c:56396
#define ADDR(X)
Definition: sqlite3.c:12552
PgHdr1 * pLruPrev
Definition: sqlite3.c:44559
#define SQLITE_STMTSTATUS_AUTOINDEX
Definition: sqlite3.c:7332
#define VdbeFrameMem(p)
Definition: sqlite3.c:17864
#define TK_RESTRICT
Definition: sqlite3.c:11377
int nChildCsr
Definition: sqlite3.c:17859
#define EP_Subquery
Definition: sqlite3.c:14976
static void explainAppendTerm(StrAccum *pStr, Index *pIdx, int nTerm, int iTerm, int bAnd, const char *zOp)
Definition: sqlite3.c:124384
static int sqlite3Step(Vdbe *p)
Definition: sqlite3.c:75637
#define TRACE(X)
Definition: sqlite3.c:58275
static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2)
Definition: sqlite3.c:74216
struct WalWriter WalWriter
#define MAX_SECTOR_SIZE
Definition: sqlite3.c:46794
PgHdr1 lru
Definition: sqlite3.c:44590
#define SQLITE_FULL
Definition: sqlite3.c:688
#define TK_PRIMARY
Definition: sqlite3.c:11393
#define SQLITE_OPEN_MAIN_JOURNAL
Definition: sqlite3.c:800
#define osFcntl
#define FUNC_PERFECT_MATCH
Definition: sqlite3.c:102978
static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p)
Definition: sqlite3.c:126418
#define EP_CanBeNull
Definition: sqlite3.c:14975
#define PragTyp_STATS
Definition: sqlite3.c:111140
SQLITE_PRIVATE void * sqlite3PagerTempSpace(Pager *)
Definition: sqlite3.c:50088
#define SQLITE_IOERR_MMAP
Definition: sqlite3.c:748
Expr * pDflt
Definition: sqlite3.c:14298
yDbMask cookieMask
Definition: sqlite3.c:15546
void * pArg
Definition: sqlite3.c:11875
static void trimFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105355
#define PAGERID(p)
Definition: sqlite3.c:46496
#define OP_ResetCount
Definition: sqlite3.c:12680
#define SQLITE_QueryOnly
Definition: sqlite3.c:14070
unsigned int htsize
Definition: sqlite3.c:11234
tRowcnt * anEq
Definition: sqlite3.c:14765
u8 notNull
Definition: sqlite3.c:14300
static int whereLoopResize(sqlite3 *, WhereLoop *, int)
Definition: sqlite3.c:129623
#define FOUR_BYTE_INT(x)
Definition: sqlite3.c:73802
static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc)
Definition: sqlite3.c:70457
#define YY_SHIFT_MIN
Definition: sqlite3.c:133523
char ** azVar
Definition: sqlite3.c:18058
yDbMask btreeMask
Definition: sqlite3.c:18078
static int vtabCallConstructor(sqlite3 *db, Table *pTab, Module *pMod, int(*xConstruct)(sqlite3 *, void *, int, const char *const *, sqlite3_vtab **, char **), char **pzErr)
Definition: sqlite3.c:123037
int iCur
Definition: sqlite3.c:94350
LogEst nRowLogEst
Definition: sqlite3.c:14448
sqlite_uint64 u64
Definition: sqlite3.c:11639
u8 memDb
Definition: sqlite3.c:46999
SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *)
Definition: sqlite3.c:71906
SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void)
Definition: sqlite3.c:141174
static int sqlite3MemInit(void *NotUsed)
Definition: sqlite3.c:20547
#define SQLITE_STATUS_PAGECACHE_SIZE
Definition: sqlite3.c:7121
#define PAGER_LOCKINGMODE_NORMAL
Definition: sqlite3.c:12984
#define OP_PrevIfOpen
Definition: sqlite3.c:12566
char * table
Definition: sqlite3.c:15699
#define SETBIT(V, I)
Definition: sqlite3.c:43467
SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *)
Definition: sqlite3.c:92936
SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *, SrcList *)
Definition: sqlite3.c:102062
SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *)
Definition: sqlite3.c:43441
static void vfsUnlink(sqlite3_vfs *pVfs)
Definition: sqlite3.c:20099
SQLITE_API char * sqlite3_temp_directory
Definition: sqlite3.c:5454
SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList *, WhereClause *)
Definition: sqlite3.c:127775
u32 aSalt[2]
Definition: sqlite3.c:54098
SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char *, int, int, int, void(*)(DbPage *))
Definition: sqlite3.c:50935
#define TKFLG_MASK
Definition: sqlite3.c:11457
static PgHdr1 * pcache1AllocPage(PCache1 *pCache, int benignMalloc)
Definition: sqlite3.c:44854
#define SQLITE_MAX_VARIABLE_NUMBER
Definition: sqlite3.c:10781
SQLITE_PRIVATE void sqlite3AlterFunctions(void)
Definition: sqlite3.c:94982
#define SQLITE_FUNC_TYPEOF
Definition: sqlite3.c:14189
SQLITE_PRIVATE void sqlite3PagerRef(DbPage *)
Definition: sqlite3.c:50455
SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *)
Definition: sqlite3.c:105759
SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *)
Definition: sqlite3.c:102263
#define SQLITE_DEFAULT_MEMSTATUS
Definition: sqlite3.c:10973
static int btreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int bias, int *pRes)
Definition: sqlite3.c:59000
static int unixFileSize(sqlite3_file *id, i64 *pSize)
Definition: sqlite3.c:33030
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs)
Definition: sqlite3.c:71022
Select * pSelect
Definition: sqlite3.c:14439
#define SQLITE_TEXT
Definition: sqlite3.c:4394
#define SQLITE_PTR_TO_INT(X)
Definition: sqlite3.c:10901
Pgno pgnoRoot
Definition: sqlite3.c:17775
u16 omitMask
Definition: sqlite3.c:123941
static void decodeIntArray(char *zIntArray, int nOut, tRowcnt *aOut, LogEst *aLog, Index *pIndex)
Definition: sqlite3.c:96980
#define SQLITE_TOOBIG
Definition: sqlite3.c:693
#define TK_RSHIFT
Definition: sqlite3.c:11337
SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte)
Definition: sqlite3.c:27122
u8 curIntKey
Definition: sqlite3.c:57774
SQLITE_PRIVATE sqlite3_mutex * sqlite3Pcache1Mutex(void)
Definition: sqlite3.c:45650
u8 notUsed1
Definition: sqlite3.c:12435
static int SQLITE_NOINLINE saveCursorsOnList(BtCursor *, Pgno, BtCursor *)
Definition: sqlite3.c:58963
u32 expmask
Definition: sqlite3.c:18086
#define OP_BitOr
Definition: sqlite3.c:12606
static int unixSetSystemCall(sqlite3_vfs *pNotUsed, const char *zName, sqlite3_syscall_ptr pNewFunc)
Definition: sqlite3.c:29909
#define MEM_Real
Definition: sqlite3.c:17918
SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *, u8 flags)
Definition: sqlite3.c:66353
#define SQLITE_LIMIT_ATTACHED
Definition: sqlite3.c:3680
#define SQLITE_MAX_DEFAULT_PAGE_SIZE
Definition: sqlite3.c:10820
#define SQLITE_RANGE
Definition: sqlite3.c:700
#define BTALLOC_EXACT
Definition: sqlite3.c:58293
SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *)
Definition: sqlite3.c:56376
static int identLength(const char *z)
Definition: sqlite3.c:99772
#define isMalloced(X)
Definition: sqlite3.c:15807
#define SQLITE_IOERR_TRUNCATE
Definition: sqlite3.c:730
#define osPwrite
#define sqlite3Isquote(x)
Definition: sqlite3.c:16037
#define SQLITE_CORRUPT
Definition: sqlite3.c:686
int(* xCurrentTime)(sqlite3_vfs *, double *)
Definition: sqlite3.c:1504
#define CURSOR_FAULT
Definition: sqlite3.c:57825
#define SRT_Table
Definition: sqlite3.c:15416
int nByte
Definition: sqlite3.c:84361
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_count(sqlite3 *)
#define OP_NotNull
Definition: sqlite3.c:12597
static void freePage(MemPage *pPage, int *pRC)
Definition: sqlite3.c:64219
VdbeFrame * pParent
Definition: sqlite3.c:17846
static struct RowSetEntry * rowSetNDeepTree(struct RowSetEntry **ppList, int iDepth)
Definition: sqlite3.c:46050
#define osPread64
#define DbMaskAllZero(M)
Definition: sqlite3.c:15495
sqlite3 * db
Definition: sqlite3.c:18029
static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg)
Definition: sqlite3.c:92824
SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse *, Token *, Token *, Token *, int)
Definition: sqlite3.c:122864
#define P4_TABLE
Definition: sqlite3.c:12518
SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *, int *pRes)
Definition: sqlite3.c:63627
WhereClause * pWC
Definition: sqlite3.c:124057
#define CC_ID
Definition: sqlite3.c:136600
struct WhereLevel::@13::@14 in
sqlite3_file * pFd
Definition: sqlite3.c:85263
#define THREE_BYTE_INT(x)
Definition: sqlite3.c:73800
AggInfo * pAggInfo
Definition: sqlite3.c:14948
static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint)
Definition: sqlite3.c:52937
#define MEM_TypeMask
Definition: sqlite3.c:17925
static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p)
Definition: sqlite3.c:34273
#define MUTEX_LOGIC(X)
Definition: sqlite3.c:13692
tRowcnt * anDLt
Definition: sqlite3.c:14767
#define columnType(A, B, C, D, E, F)
Definition: sqlite3.c:115724
#define wsdPrng
SQLITE_API int sqlite3_bind_int(sqlite3_stmt *, int, int)
Definition: sqlite3.c:76459
ExprList * pDistinctSet
Definition: sqlite3.c:124222
u8 eLock
Definition: sqlite3.c:47011
#define SQLITE_FILE_HEADER
Definition: sqlite3.c:57498
#define SQLITE_MUTEX_STATIC_VFS3
Definition: sqlite3.c:6892
#define COLUMN_MASK(x)
Definition: sqlite3.c:107014
SQLITE_PRIVATE void sqlite3ParserFree(void *, void(*)(void *))
Definition: sqlite3.c:134477
Index * pIdx
Definition: sqlite3.c:94349
int orconf
Definition: sqlite3.c:15476
#define OP_NotFound
Definition: sqlite3.c:12592
#define WHERE_LOOP_XFER_SZ
Definition: sqlite3.c:123949
static void total_changes(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:104672
#define TK_ORDER
Definition: sqlite3.c:11417
#define SQLITE_FCNTL_BUSYHANDLER
Definition: sqlite3.c:1284
#define STAT_GET_NLT
Definition: sqlite3.c:96351
Select * yy243
Definition: sqlite3.c:133106
bft explain
Definition: sqlite3.c:18071
#define BTALLOC_LE
Definition: sqlite3.c:58294
PmaReader * pReader
Definition: sqlite3.c:85164
#define OP_Not
Definition: sqlite3.c:12581
#define OP_Real
Definition: sqlite3.c:12694
static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr)
Definition: sqlite3.c:84389
#define SQLITE_CONFIG_GETPCACHE2
Definition: sqlite3.c:2146
#define SQLITE3_MUTEX_INITIALIZER
Definition: sqlite3.c:22858
u8 walSyncFlags
Definition: sqlite3.c:46994
#define TK_DOT
Definition: sqlite3.c:11413
#define TERM_VIRTUAL
Definition: sqlite3.c:124079
int szSpill
Definition: sqlite3.c:43624
int(* xBegin)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:6078
ExprList * pOrderBy
Definition: sqlite3.c:124221
static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew)
Definition: sqlite3.c:129031
u32 uTemp
Definition: sqlite3.c:17888
Table * pTable
Definition: sqlite3.c:14709
#define MEM_RowSet
Definition: sqlite3.c:17921
SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int, int *)
Definition: sqlite3.c:43501
int szMalloc
Definition: sqlite3.c:17887
SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int)
Definition: sqlite3.c:24697
SQLITE_PRIVATE const void * sqlite3BtreePayloadFetch(BtCursor *, u32 *pAmt)
Definition: sqlite3.c:62987
SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor *, const BtreePayload *pPayload, int bias, int seekResult)
Definition: sqlite3.c:66186
static void pcache1Destroy(sqlite3_pcache *p)
Definition: sqlite3.c:45599
int anStat[3]
Definition: sqlite3.c:13830
void(* xFinalize)(sqlite3_context *)
Definition: sqlite3.c:14142
#define PragFlag_NeedSchema
Definition: sqlite3.c:111154
static void btreeParseCellPtrIndex(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:59410
SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *, int)
Definition: sqlite3.c:90323
Mem * aColName
Definition: sqlite3.c:18053
int iField
Definition: sqlite3.c:124065
#define WALTRACE(X)
Definition: sqlite3.c:54037
SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *, Table *)
Definition: sqlite3.c:98933
static int vdbeIncrPopulate(IncrMerger *pIncr)
Definition: sqlite3.c:86719
struct sqlite3_index_info::sqlite3_index_constraint * aConstraint
#define CC_BANG
Definition: sqlite3.c:136613
BtLock * pLock
Definition: sqlite3.c:57694
u8 checkSchema
Definition: sqlite3.c:15521
u8 tempFile
Definition: sqlite3.c:46996
SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *, int addr)
Definition: sqlite3.c:71253
#define SQLITE_DBSTATUS_CACHE_WRITE
Definition: sqlite3.c:7261
int szExtra
Definition: sqlite3.c:43626
void * pUpdateArg
Definition: sqlite3.c:13956
#define TK_BITNOT
Definition: sqlite3.c:11345
static void vdbePmaWriterInit(sqlite3_file *pFd, PmaWriter *p, int nBuf, i64 iStart)
Definition: sqlite3.c:86300
#define READ_UTF16BE(zIn, TERM, c)
Definition: sqlite3.c:26857
YYMINORTYPE minor
Definition: sqlite3.c:133797
#define PragTyp_BUSY_TIMEOUT
Definition: sqlite3.c:111114
#define EP_Resolved
Definition: sqlite3.c:14957
SQLITE_PRIVATE Expr * sqlite3Expr(sqlite3 *, int, const char *)
Definition: sqlite3.c:90500
#define SQLITE_UTF16BE
Definition: sqlite3.c:4758
static int writeMasterJournal(Pager *pPager, const char *zMaster)
Definition: sqlite3.c:47992
SQLITE_PRIVATE PgHdr * sqlite3PcacheFetchFinish(PCache *, Pgno, sqlite3_pcache_page *pPage)
Definition: sqlite3.c:44059
int addrFirst
Definition: sqlite3.c:123878
static int getTempStore(const char *z)
Definition: sqlite3.c:111654
struct SrcList::SrcList_item a[1]
static void moveToParent(BtCursor *pCur)
Definition: sqlite3.c:63049
#define SF_Recursive
Definition: sqlite3.c:15328
SQLITE_PRIVATE int sqlite3FaultSim(int)
Definition: sqlite3.c:27318
i64 nStmtDefImmCons
Definition: sqlite3.c:18045
With * pWith
Definition: sqlite3.c:15303
bft runOnlyOnce
Definition: sqlite3.c:18073
static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p)
Definition: sqlite3.c:24341
SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64)
Definition: sqlite3.c:53526
BtLock * pNext
Definition: sqlite3.c:57571
SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *, ExprList *, int)
Definition: sqlite3.c:94288
KeyInfo * pKeyInfo
Definition: sqlite3.c:17785
SQLITE_PRIVATE ExprList * sqlite3ExprListAppendVector(Parse *, ExprList *, IdList *, Expr *)
Definition: sqlite3.c:91220
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *, int(*)(void *), void *)
Definition: sqlite3.c:49979
#define TK_INITIALLY
Definition: sqlite3.c:11367
#define OP_IdxLT
Definition: sqlite3.c:12622
#define SQLITE_TEMP_FILE_PREFIX
Definition: sqlite3.c:13473
SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *, const char *z, int n, int)
Definition: sqlite3.c:70535
int bUnderPressure
Definition: sqlite3.c:44662
int(* xMutexTry)(sqlite3_mutex *)
Definition: sqlite3.c:6827
#define SQLITE_DEFAULT_SECTOR_SIZE
Definition: sqlite3.c:13448
sqlite3 * pSrcDb
Definition: sqlite3.c:67987
static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut)
Definition: sqlite3.c:35505
union sqlite3::@1 u1
sqlite3_rtree_dbl rScore
Definition: sqlite3.c:8748
#define SQLITE_LoadExtension
Definition: sqlite3.c:14066
SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table *)
Definition: sqlite3.c:107338
SQLITE_API sqlite3_stmt * sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt)
Definition: sqlite3.c:76698
SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *)
Definition: sqlite3.c:56274
static void returnSingleText(Vdbe *v, const char *zLabel, const char *zValue)
Definition: sqlite3.c:111736
#define WHERE_DISTINCTBY
Definition: sqlite3.c:15198
#define SQLITE_DROP_INDEX
Definition: sqlite3.c:3026
static int rebuildPage(MemPage *pPg, int nCell, u8 **apCell, u16 *szCell)
Definition: sqlite3.c:64689
#define JT_ERROR
Definition: sqlite3.c:15179
static void computeHMS(DateTime *p)
Definition: sqlite3.c:18973
static int yy_find_reduce_action(int stateno, YYCODETYPE iLookAhead)
Definition: sqlite3.c:134569
SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int)
Definition: sqlite3.c:123532
#define SQLITE_FUNC_LIKE
Definition: sqlite3.c:14184
FileChunk * pNext
Definition: sqlite3.c:87640
#define P4_SUBPROGRAM
Definition: sqlite3.c:12516
u8 mTrace
Definition: sqlite3.c:13927
#define SF_Values
Definition: sqlite3.c:15324
static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur)
Definition: sqlite3.c:62497
u8 * aDataEnd
Definition: sqlite3.c:57544
Bitvec * pInSavepoint
Definition: sqlite3.c:46814
SQLITE_API void sqlite3_result_error(sqlite3_context *, const char *, int)
Definition: sqlite3.c:75470
#define SQLITE_NullCallback
Definition: sqlite3.c:14051
Expr * pOffset
Definition: sqlite3.c:15302
#define assertParentIndex(x, y, z)
Definition: sqlite3.c:63038
static void pushOntoSorter(Parse *pParse, SortCtx *pSort, Select *pSelect, int regData, int regOrigData, int nData, int nPrefixReg)
Definition: sqlite3.c:114893
#define P4_DYNAMIC
Definition: sqlite3.c:12502
SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt)
Definition: sqlite3.c:75214
SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *, int, int *)
Definition: sqlite3.c:66740
SQLITE_API int sqlite3_wal_checkpoint_v2(sqlite3 *db, const char *zDb, int eMode, int *pnLog, int *pnCkpt)
Definition: sqlite3.c:139915
i16 ynVar
Definition: sqlite3.c:14838
#define PragTyp_FLAG
Definition: sqlite3.c:111113
#define SQLITE_DBSTATUS_LOOKASIDE_HIT
Definition: sqlite3.c:7256
#define SQLITE_FUNC_HASH_SZ
Definition: sqlite3.c:13846
u8 childPtrSize
Definition: sqlite3.c:57530
SQLITE_PRIVATE sqlite3_value * sqlite3ValueNew(sqlite3 *)
Definition: sqlite3.c:69833
PgHdr * pDirty
Definition: sqlite3.c:43620
static int vdbeUnbind(Vdbe *p, int i)
Definition: sqlite3.c:76345
#define READ_UTF16LE(zIn, TERM, c)
Definition: sqlite3.c:26847
int(* xColumn)(sqlite3_vtab_cursor *, sqlite3_context *, int)
Definition: sqlite3.c:6075
int nExtension
Definition: sqlite3.c:13946
SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *, int, int, int *, int *)
Definition: sqlite3.c:139996
char * zCanonicalName
Definition: sqlite3.c:30232
int isPCacheInit
Definition: sqlite3.c:15860
static char * whereForeignKeys(Parse *pParse, Table *pTab)
Definition: sqlite3.c:95029
u16 nKeyCol
Definition: sqlite3.c:14719
static void compileoptiongetFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105058
IdList * pColumns
Definition: sqlite3.c:15703
static void updateRangeAffinityStr(Expr *pRight, int n, char *zAff)
Definition: sqlite3.c:124704
#define CURTYPE_BTREE
Definition: sqlite3.c:17746
#define SQLITE_CREATE_TRIGGER
Definition: sqlite3.c:3023
static volatile WalCkptInfo * walCkptInfo(Wal *pWal)
Definition: sqlite3.c:54364
int(* xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor)
Definition: sqlite3.c:6069
#define SQLITE_NOMEM
Definition: sqlite3.c:682
Parse * pParse
Definition: sqlite3.c:15779
#define PAGER_JOURNALMODE_TRUNCATE
Definition: sqlite3.c:12998
static void unixShmPurge(unixFile *pFd)
Definition: sqlite3.c:33557
WhereClause * pWC
Definition: sqlite3.c:124198
static int btreeGetPage(BtShared *pBt, Pgno pgno, MemPage **ppPage, int flags)
Definition: sqlite3.c:60171
#define PTF_LEAFDATA
Definition: sqlite3.c:57507
#define PragTyp_HEXKEY
Definition: sqlite3.c:111149
SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *)
Definition: sqlite3.c:70867
#define TF_Virtual
Definition: sqlite3.c:14481
SQLITE_PRIVATE With * sqlite3WithAdd(Parse *, With *, Token *, ExprList *, Select *)
Definition: sqlite3.c:102663
SQLITE_PRIVATE int sqlite3ParseUri(const char *, const char *, unsigned int *, sqlite3_vfs **, char **, char **)
Definition: sqlite3.c:140377
#define VdbeCoverageIf(v, x)
Definition: sqlite3.c:12900
SQLITE_PRIVATE void * sqlite3DbRealloc(sqlite3 *, void *, u64)
Definition: sqlite3.c:24554
int nVtabLock
Definition: sqlite3.c:15601
#define SQLITE_MAGIC_OPEN
Definition: sqlite3.c:14119
#define WAL_NORMAL_MODE
Definition: sqlite3.c:54245
i64 iReadOff
Definition: sqlite3.c:85193
#define BTREE_DATA_VERSION
Definition: sqlite3.c:12173
union WhereTerm::@18 u
SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs *, sqlite3_file *, const char *, int, i64, Wal **)
Definition: sqlite3.c:55062
Pgno mxPgno
Definition: sqlite3.c:47050
#define assertTruncateConstraint(pPager)
Definition: sqlite3.c:50245
sqlite3_file * fd
Definition: sqlite3.c:47027
#define SQLITE_API
Definition: sqlite3.c:312
SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe *, Parse *)
Definition: sqlite3.c:72356
char affinity
Definition: sqlite3.c:14301
static struct RowSetEntry * rowSetListToTree(struct RowSetEntry *pList)
Definition: sqlite3.c:46086
#define IS_BIG_INT(X)
Definition: sqlite3.c:11177
static SorterRecord * vdbeSorterMerge(SortSubtask *pTask, SorterRecord *p1, SorterRecord *p2)
Definition: sqlite3.c:86188
static void walChecksumBytes(int nativeCksum, u8 *a, int nByte, const u32 *aIn, u32 *aOut)
Definition: sqlite3.c:54398
#define OP_RowSetRead
Definition: sqlite3.c:12624
bft usesStmtJournal
Definition: sqlite3.c:18074
u16 aiOvfl[5]
Definition: sqlite3.c:57539
SQLITE_PRIVATE void sqlite3RowidConstraint(Parse *, int, Table *)
Definition: sqlite3.c:102477
Btree * pNext
Definition: sqlite3.c:57609
SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *, u32)
Definition: sqlite3.c:43294
#define INT8_TYPE
Definition: sqlite3.c:11632
#define OP_NotExists
Definition: sqlite3.c:12595
void(* xDelUser)(void *)
Definition: sqlite3.c:8738
static void * allocSpace(struct ReusableSpace *p, void *pBuf, int nByte)
Definition: sqlite3.c:72280
SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *, Select *)
Definition: sqlite3.c:88102
#define SQLITE_DEFAULT_AUTOVACUUM
Definition: sqlite3.c:12049
void *(* xDlOpen)(sqlite3_vfs *, const char *zFilename)
Definition: sqlite3.c:1498
Token sNameToken
Definition: sqlite3.c:15585
#define PragTyp_WAL_AUTOCHECKPOINT
Definition: sqlite3.c:111146
int nChildMem
Definition: sqlite3.c:17858
unsigned isResized
Definition: sqlite3.c:14725
SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *, int)
Definition: sqlite3.c:102336
#define OP_IdxRowid
Definition: sqlite3.c:12691
u8 max1bytePayload
Definition: sqlite3.c:57531
SQLITE_PRIVATE sqlite3_mutex * sqlite3MallocMutex(void)
Definition: sqlite3.c:23956
struct SrcCount * pSrcCount
Definition: sqlite3.c:15916
int(* xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, void(**pxFunc)(sqlite3_context *, int, sqlite3_value **), void **ppArg)
Definition: sqlite3.c:6082
Parse * pToplevel
Definition: sqlite3.c:15559
#define SRVAL(p)
Definition: sqlite3.c:85298
SQLITE_API void * sqlite3_get_auxdata(sqlite3_context *, int N)
Definition: sqlite3.c:75924
static void setJoinExpr(Expr *p, int iTable)
Definition: sqlite3.c:114762
LogEst truthProb
Definition: sqlite3.c:124058
int(* xFileControl)(sqlite3_file *, int op, void *pArg)
Definition: sqlite3.c:1016
static void computeYMD(DateTime *p)
Definition: sqlite3.c:18947
SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *, i64 *)
Definition: sqlite3.c:46118
#define BTS_PAGESIZE_FIXED
Definition: sqlite3.c:57704
SQLITE_PRIVATE void sqlite3CreateIndex(Parse *, Token *, Token *, SrcList *, ExprList *, int, Token *, Expr *, int, int, u8)
Definition: sqlite3.c:101178
SrcList * pSrc
Definition: sqlite3.c:15294
static int sqlite3LockAndPrepare(sqlite3 *db, const char *zSql, int nBytes, int saveSqlFlag, Vdbe *pOld, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:114197
Vdbe * pReprepare
Definition: sqlite3.c:15609
#define BTREE_OMIT_JOURNAL
Definition: sqlite3.c:12080
tRowcnt nPSample
Definition: sqlite3.c:95846
SQLITE_API void * sqlite3_realloc(void *, int)
Definition: sqlite3.c:24431
#define SQLITE_NOTICE_RECOVER_ROLLBACK
Definition: sqlite3.c:777
unixInodeInfo * pInode
Definition: sqlite3.c:33413
#define PAGER_JOURNALMODE_QUERY
Definition: sqlite3.c:12994
#define SQLITE_TESTCTRL_ISKEYWORD
Definition: sqlite3.c:6983
#define TK_USING
Definition: sqlite3.c:11416
#define OP_Sort
Definition: sqlite3.c:12618
#define TK_ABORT
Definition: sqlite3.c:11348
VTable * pVtab
Definition: sqlite3.c:12450
SQLITE_PRIVATE void sqlite3AddColumn(Parse *, Token *, Token *)
Definition: sqlite3.c:99336
#define sqlite3_column_table_name
Definition: sqlite3.c:110313
#define CC_KYWD
Definition: sqlite3.c:136599
#define OE_SetNull
Definition: sqlite3.c:14598
struct AggInfo::AggInfo_func * aFunc
SQLITE_API int sqlite3_value_bytes16(sqlite3_value *)
Definition: sqlite3.c:75302
static int vdbePmaReadBlob(PmaReader *p, int nByte, u8 **ppOut)
Definition: sqlite3.c:85328
SQLITE_API void sqlite3_result_text16le(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:75546
sqlite3_vtab * pVtab
Definition: sqlite3.c:6327
static int databaseIsUnmoved(Pager *pPager)
Definition: sqlite3.c:51228
static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS)
Definition: sqlite3.c:127182
#define OP_Cast
Definition: sqlite3.c:12655
#define SQLITE_TRACE_PROFILE
Definition: sqlite3.c:3142
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *, int, const char *)
Definition: sqlite3.c:98749
unsigned bft
Definition: sqlite3.c:18009
SQLITE_PRIVATE void sqlite3Parser(void *, int, Token, Parse *)
#define SQLITE_SCANSTAT_NLOOP
Definition: sqlite3.c:8308
SrcList * pSrcList
Definition: sqlite3.c:15915
NameContext * pNC
Definition: sqlite3.c:15912
#define TK_EXPLAIN
Definition: sqlite3.c:11293
static void walEncodeFrame(Wal *pWal, u32 iPage, u32 nTruncate, u8 *aData, u8 *aFrame)
Definition: sqlite3.c:54473
u8 isAnchor
Definition: sqlite3.c:44555
SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int)
Definition: sqlite3.c:19898
#define OP_Remainder
Definition: sqlite3.c:12613
#define TK_RELEASE
Definition: sqlite3.c:11305
struct ScratchFreeslot ScratchFreeslot
SQLITE_API const char * sqlite3_uri_parameter(const char *zFilename, const char *zParam)
Definition: sqlite3.c:141723
#define UNKNOWN_LOCK
Definition: sqlite3.c:46772
#define IfNotOmitAV(expr)
Definition: sqlite3.c:58303
Vdbe * v
Definition: sqlite3.c:17845
SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum *, const char *, va_list)
Definition: sqlite3.c:24883
SQLITE_PRIVATE LogEst sqlite3LogEst(u64)
Definition: sqlite3.c:28672
static int pager_wait_on_lock(Pager *pPager, int locktype)
Definition: sqlite3.c:50195
LogEst * aiRowLogEst
Definition: sqlite3.c:14708
#define OP_AggFinal
Definition: sqlite3.c:12711
static int pthreadMutexInit(void)
Definition: sqlite3.c:22902
sqlite3_int64 sqlite3StatValueType
Definition: sqlite3.c:18244
#define OP_OffsetLimit
Definition: sqlite3.c:12708
#define BTREE_AUXDELETE
Definition: sqlite3.c:12274
#define OP_Found
Definition: sqlite3.c:12593
f
SQLITE_PRIVATE int sqlite3PendingByte
Definition: sqlite3.c:17197
static void ctimeFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:19633
Parse * pParse
Definition: sqlite3.c:15237
SQLITE_PRIVATE char * sqlite3Utf16to8(sqlite3 *, const void *, int, u8)
Definition: sqlite3.c:27176
int addrCrTab
Definition: sqlite3.c:15561
static int readsTable(Parse *p, int iDb, Table *pTab)
Definition: sqlite3.c:107543
static void removeElementGivenHash(Hash *pH, HashElem *elem, unsigned int h)
Definition: sqlite3.c:28910
SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor *)
Definition: sqlite3.c:72457
#define SQLITE_LOCKED_SHAREDCACHE
Definition: sqlite3.c:753
static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags)
Definition: sqlite3.c:126442
static int whereLoopAddVirtualOne(WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUsable, u16 mExclude, sqlite3_index_info *pIdxInfo, u16 mNoOmit, int *pbIn)
Definition: sqlite3.c:130793
#define WHERE_GROUPBY
Definition: sqlite3.c:15197
#define SQLITE_ANALYZE
Definition: sqlite3.c:3044
#define SQLITE_FSFLAGS_IS_MSDOS
Definition: sqlite3.c:29321
int mnPmaSize
Definition: sqlite3.c:85160
#define CURSOR_INVALID
Definition: sqlite3.c:57821
u32 newmask
Definition: sqlite3.c:15564
PCache1 * pCache
Definition: sqlite3.c:44557
#define PAGER_LOCKINGMODE_QUERY
Definition: sqlite3.c:12983
u32 nSet
Definition: sqlite3.c:43260
#define PAGER_JOURNALMODE_MEMORY
Definition: sqlite3.c:12999
PgHdr1 * pFree
Definition: sqlite3.c:44624
SQLITE_PRIVATE int sqlite3Select(Parse *, Select *, SelectDest *)
Definition: sqlite3.c:119195
static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage)
Definition: sqlite3.c:64091
static void unlockBtreeIfUnused(BtShared *pBt)
Definition: sqlite3.c:61273
SQLITE_API int sqlite3_sleep(int)
Definition: sqlite3.c:141300
SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *)
Definition: sqlite3.c:127876
static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove)
Definition: sqlite3.c:43736
#define SQLITE_IOERR_CLOSE
Definition: sqlite3.c:740
#define OP_IsNull
Definition: sqlite3.c:12596
static MemPage * btreePageLookup(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:60193
const char * zType
Definition: sqlite3.c:15783
#define SQLITE_CHECKPOINT_RESTART
Definition: sqlite3.c:8171
#define SQLITE_AFF_INTEGER
Definition: sqlite3.c:14353
int(* xDisconnect)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:6067
const char * zAuthContext
Definition: sqlite3.c:15613
u8 leaf
Definition: sqlite3.c:57528
SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *)
Definition: sqlite3.c:68674
#define IsStat3
Definition: sqlite3.c:95715
#define SQLITE_PRINTF_SQLFUNC
Definition: sqlite3.c:15804
#define TK_VECTOR
Definition: sqlite3.c:11449
SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc)
Definition: sqlite3.c:104879
Expr * pWhen
Definition: sqlite3.c:15702
#define OP_AggStep0
Definition: sqlite3.c:12709
#define BTCF_Incrblob
Definition: sqlite3.c:57788
SQLITE_PRIVATE void * sqlite3DbMallocRaw(sqlite3 *, u64)
Definition: sqlite3.c:24505
#define SQLITE_ACCESS_READWRITE
Definition: sqlite3.c:1546
#define TK_LSHIFT
Definition: sqlite3.c:11336
#define SQLITE_LITTLEENDIAN
Definition: sqlite3.c:11759
#define HAVE_FCHOWN
Definition: sqlite3.c:167
#define OPFLAG_USESEEKRESULT
Definition: sqlite3.c:15668
#define SF_Resolved
Definition: sqlite3.c:15317
static i64 doubleToInt64(double r)
Definition: sqlite3.c:69185
#define OPFLAG_LENGTHARG
Definition: sqlite3.c:15672
sqlite3_syscall_ptr pDefault
Definition: sqlite3.c:29740
WhereTerm * aLTermSpace[3]
Definition: sqlite3.c:123953
#define DbMaskNonZero(M)
Definition: sqlite3.c:15496
int errCode
Definition: sqlite3.c:13913
#define SQLITE_DETACH
Definition: sqlite3.c:3041
void(* xMutexLeave)(sqlite3_mutex *)
Definition: sqlite3.c:6828
#define OP_Savepoint
Definition: sqlite3.c:12562
PgHdr * pDirtyNext
Definition: sqlite3.c:13202
#define OP_Compare
Definition: sqlite3.c:12657
static Trigger * fkActionTrigger(Parse *pParse, Table *pTab, FKey *pFKey, ExprList *pChanges)
Definition: sqlite3.c:107120
SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *)
Definition: sqlite3.c:74781
struct VdbeSorter VdbeSorter
Definition: sqlite3.c:17740
#define OP_HaltIfNull
Definition: sqlite3.c:12636
#define BITVEC_NBIT
Definition: sqlite3.c:43221
#define P4_NOTUSED
Definition: sqlite3.c:12501
#define MAX(A, B)
Definition: sqlite3.c:11575
SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *)
Definition: sqlite3.c:51879
static int createModule(sqlite3 *db, const char *zName, const sqlite3_module *pModule, void *pAux, void(*xDestroy)(void *))
Definition: sqlite3.c:122593
static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104250
#define BTS_PENDING
Definition: sqlite3.c:57709
#define SQLITE_CREATE_VTABLE
Definition: sqlite3.c:3045
Bitvec * pHasContent
Definition: sqlite3.c:57690
SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr)
Definition: sqlite3.c:90062
const char * zCteErr
Definition: sqlite3.c:15950
#define WAL_HDRSIZE
Definition: sqlite3.c:54184
SQLITE_PRIVATE void sqlite3EndBenignMalloc(void)
Definition: sqlite3.c:20240
struct AggInfo::AggInfo_col * aCol
SQLITE_API int sqlite3_close_v2(sqlite3 *)
Definition: sqlite3.c:138941
#define CC_SLASH
Definition: sqlite3.c:136614
tRowcnt * anDLt
Definition: sqlite3.c:95831
SQLITE_API int sqlite3_libversion_number(void)
Definition: sqlite3.c:137906
#define SQLITE_ALLOW_COVERING_INDEX_SCAN
Definition: sqlite3.c:17083
#define COLFLAG_HIDDEN
Definition: sqlite3.c:14309
static void attachFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:97511
SQLITE_PRIVATE void sqlite3ScratchFree(void *)
Definition: sqlite3.c:24233
#define TK_RENAME
Definition: sqlite3.c:11385
#define sqlite3MemdebugNoType(X, Y)
Definition: sqlite3.c:16906
SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]
Definition: sqlite3.c:17207
SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *, int, int)
Definition: sqlite3.c:92958
int bPurgeable
Definition: sqlite3.c:44611
#define OP_SorterSort
Definition: sqlite3.c:12617
unixInodeInfo * pPrev
Definition: sqlite3.c:30471
#define XN_EXPR
Definition: sqlite3.c:14755
#define TK_CONSTRAINT
Definition: sqlite3.c:11390
SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n)
Definition: sqlite3.c:44698
#define osFchown
#define TK_INTERSECT
Definition: sqlite3.c:11409
SQLITE_PRIVATE sqlite3_backup ** sqlite3PagerBackupPtr(Pager *)
Definition: sqlite3.c:53540
static int exprStructSize(Expr *p)
Definition: sqlite3.c:90778
BtLock lock
Definition: sqlite3.c:57612
u8 isBulkLocal
Definition: sqlite3.c:44554
#define HASHTABLE_HASH_1
Definition: sqlite3.c:54298
static void hexFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105220
int * aAltMap
Definition: sqlite3.c:17790
#define OP_Ne
Definition: sqlite3.c:12598
static void * vdbeIncrPopulateThread(void *pCtx)
Definition: sqlite3.c:86761
IdList * pIdList
Definition: sqlite3.c:15767
Parse * pParse
Definition: sqlite3.c:69847
static void sqliteAuthBadReturnCode(Parse *pParse)
Definition: sqlite3.c:98127
#define TK_VARIABLE
Definition: sqlite3.c:11426
#define YY_MIN_REDUCE
Definition: sqlite3.c:133126
SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *, With *)
Definition: sqlite3.c:102713
SQLITE_API void sqlite3_free_table(char **result)
Definition: sqlite3.c:120252
#define WHERE_ORDERBY_NORMAL
Definition: sqlite3.c:15189
#define etSQLESCAPE3
Definition: sqlite3.c:24745
Hash idxHash
Definition: sqlite3.c:13765
SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *)
Definition: sqlite3.c:72512
static void functionDestroy(sqlite3 *db, FuncDef *p)
Definition: sqlite3.c:138821
static void checkAppendMsg(IntegrityCk *pCheck, const char *zFormat,...)
Definition: sqlite3.c:67060
u32 nChar
Definition: sqlite3.c:15795
static void datetimeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19423
Pgno dbFileSize
Definition: sqlite3.c:47020
#define TK_RP
Definition: sqlite3.c:11314
u32 cacheCtr
Definition: sqlite3.c:18037
#define SQLITE_STATUS_MALLOC_SIZE
Definition: sqlite3.c:7119
#define getVarint32(A, B)
Definition: sqlite3.c:16520
SQLITE_API int sqlite3_release_memory(int)
Definition: sqlite3.c:23907
sqlite3 * db
Definition: sqlite3.c:45824
#define SQLITE_SCHEMA
Definition: sqlite3.c:692
#define TK_INSTEAD
Definition: sqlite3.c:11368
#define SQLITE_IOERR_ACCESS
Definition: sqlite3.c:737
int * aLabel
Definition: sqlite3.c:15542
static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem)
Definition: sqlite3.c:92661
#define TIMER_ELAPSED
Definition: sqlite3.c:29611
#define SHARED_SIZE
Definition: sqlite3.c:13561
SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *, u32 addr, int P1)
Definition: sqlite3.c:71235
#define IsStat4
Definition: sqlite3.c:95714
SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *)
Definition: sqlite3.c:127905
#define noopFunc
Definition: sqlite3.c:104583
#define SQLITE_FCNTL_SYNC
Definition: sqlite3.c:1289
#define BTREE_INCR_VACUUM
Definition: sqlite3.c:12171
SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *, u8, u8)
Definition: sqlite3.c:69351
int iBufStart
Definition: sqlite3.c:85260
void(* xDel)(void *)
Definition: sqlite3.c:17890
int mnReg
Definition: sqlite3.c:14804
#define YYWILDCARD
Definition: sqlite3.c:133095
SQLITE_PRIVATE Table * sqlite3FindTable(sqlite3 *, const char *, const char *)
Definition: sqlite3.c:98597
static void exprAnalyze(SrcList *, WhereClause *, int)
Definition: sqlite3.c:127279
static void heightOfSelect(Select *p, int *pnHeight)
Definition: sqlite3.c:90359
ExprList * pOrderBy
Definition: sqlite3.c:15298
#define SQLITE_STMTSTATUS_SORT
Definition: sqlite3.c:7331
#define BTREE_TEXT_ENCODING
Definition: sqlite3.c:12169
PgHdr * pSynced
Definition: sqlite3.c:43621
NameContext * pNext
Definition: sqlite3.c:15241
SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *)
Definition: sqlite3.c:58230
static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx)
Definition: sqlite3.c:96874
SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *, int)
Definition: sqlite3.c:99756
pthread_t tid
Definition: sqlite3.c:26505
#define CC_TILDA
Definition: sqlite3.c:136623
SQLITE_PRIVATE WhereInfo * sqlite3WhereBegin(Parse *, SrcList *, Expr *, ExprList *, ExprList *, u16, int)
Definition: sqlite3.c:132171
sqlite3 * db
Definition: sqlite3.c:15516
static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit)
Definition: sqlite3.c:61730
Mem * aNew
Definition: sqlite3.c:18120
#define BTREE_APPLICATION_ID
Definition: sqlite3.c:12172
struct YYMINORTYPE::@19 yy497
#define FTS5_TOKENIZE_QUERY
Definition: sqlite3.c:10574
static void setAllColumnNames(Vdbe *v, int N, const char **azCol)
Definition: sqlite3.c:111709
static void pageReinit(DbPage *pData)
Definition: sqlite3.c:60334
u32 vfsFlags
Definition: sqlite3.c:47047
SQLITE_API sqlite3_value * sqlite3_column_value(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76162
static SQLITE_NOINLINE void * createAggContext(sqlite3_context *p, int nByte)
Definition: sqlite3.c:75887
SQLITE_API int sqlite3_get_autocommit(sqlite3 *)
Definition: sqlite3.c:141117
#define TIMER_START
Definition: sqlite3.c:29609
#define SQLITE_MAX_TRIGGER_DEPTH
Definition: sqlite3.c:10855
#define osFstat
#define SQLITE_DEFAULT_FILE_PERMISSIONS
Definition: sqlite3.c:29336
bft isPrepareV2
Definition: sqlite3.c:18077
int(* xFunc)(void *, int)
Definition: sqlite3.c:11874
SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *)
Definition: sqlite3.c:58014
#define P4_REAL
Definition: sqlite3.c:12512
#define HAVE_MREMAP
Definition: sqlite3.c:29703
static const char * selectOpName(int id)
Definition: sqlite3.c:115488
int nMemory
Definition: sqlite3.c:85171
int(* xProgress)(void *)
Definition: sqlite3.c:13983
#define SQLITE_OPEN_NOMUTEX
Definition: sqlite3.c:804
#define PragTyp_INDEX_LIST
Definition: sqlite3.c:111128
#define SQLITE_DENY
Definition: sqlite3.c:2994
#define SQLITE_AFF_MASK
Definition: sqlite3.c:14362
static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg)
Definition: sqlite3.c:125359
WhereClause * pOrigWC
Definition: sqlite3.c:124100
SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *, FuncDef *)
Definition: sqlite3.c:69090
#define YYNOCODE
Definition: sqlite3.c:133093
int nHeight
Definition: sqlite3.c:14933
void *(* xTask)(void *)
Definition: sqlite3.c:26508
#define PragTyp_PARSER_TRACE
Definition: sqlite3.c:111153
static PgHdr1 * pcache1FetchNoMutex(sqlite3_pcache *p, unsigned int iKey, int createFlag)
Definition: sqlite3.c:45432
SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char *, u32, Mem *)
Definition: sqlite3.c:73849
SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *)
Definition: sqlite3.c:138952
SQLITE_API void * sqlite3_wal_hook(sqlite3 *, int(*)(void *, sqlite3 *, const char *, int), void *)
Definition: sqlite3.c:139888
sqlite3_backup * pBackup
Definition: sqlite3.c:47032
#define PragTyp_TABLE_INFO
Definition: sqlite3.c:111142
int flags
Definition: sqlite3.c:84360
u16 schemaFlags
Definition: sqlite3.c:13771
static void codeAttach(Parse *pParse, int type, FuncDef const *pFunc, Expr *pAuthArg, Expr *pFilename, Expr *pDbname, Expr *pKey)
Definition: sqlite3.c:97765
#define get2byte(x)
Definition: sqlite3.c:57938
#define PAGER_GET_NOCONTENT
Definition: sqlite3.c:13005
#define OP_DecrJumpZero
Definition: sqlite3.c:12630
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_depth(sqlite3 *)
#define TK_COLUMNKW
Definition: sqlite3.c:11358
#define TRIGGER_BEFORE
Definition: sqlite3.c:15718
struct KeyInfo * pKeyInfo
Definition: sqlite3.c:57775
#define DOTLOCK_SUFFIX
Definition: sqlite3.c:31445
sqlite3 * db
Definition: sqlite3.c:14422
sqlite3_value ** apSqlParam
Definition: sqlite3.c:8750
#define SQLITE_FCNTL_HAS_MOVED
Definition: sqlite3.c:1288
#define SQLITE_DEPRECATED
Definition: sqlite3.c:343
#define GLOBAL(t, v)
Definition: sqlite3.c:11940
int szOsFile
Definition: sqlite3.c:1488
#define etORDINAL
Definition: sqlite3.c:24746
SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *)
Definition: sqlite3.c:52860
SQLITE_PRIVATE void sqlite3PrngRestoreState(void)
Definition: sqlite3.c:26452
u8 * aSortOrder
Definition: sqlite3.c:14713
static void sqlite3MemFree(void *pPrior)
Definition: sqlite3.c:20470
#define SF_UsesEphemeral
Definition: sqlite3.c:15320
#define UNIXFILE_EXCL
Definition: sqlite3.c:29453
static const char *const azCompileOpt[]
Definition: sqlite3.c:17244
TriggerPrg * pNext
Definition: sqlite3.c:15474
#define TK_SELECT
Definition: sqlite3.c:11410
PCache * pCache
Definition: sqlite3.c:13200
#define getVarint
Definition: sqlite3.c:16525
#define SQLITE_SORTER_PMASZ
Definition: sqlite3.c:17090
void * pHeap
Definition: sqlite3.c:15840
static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse)
Definition: sqlite3.c:107702
int iTab
Definition: sqlite3.c:98335
SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *)
Definition: sqlite3.c:67701
sqlite3_pcache_page * pPage
Definition: sqlite3.c:13184
SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int)
Definition: sqlite3.c:68843
SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *, int, int, int, void volatile **)
Definition: sqlite3.c:19907
u8 opcode
Definition: sqlite3.c:12433
static void markTermAsChild(WhereClause *pWC, int iChild, int iParent)
Definition: sqlite3.c:126724
unsigned int openFlags
Definition: sqlite3.c:13912
#define EP_Generic
Definition: sqlite3.c:14964
static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo)
Definition: sqlite3.c:129666
#define SQLITE_IOERR_SHMSIZE
Definition: sqlite3.c:743
static void generateColumnTypes(Parse *pParse, SrcList *pTabList, ExprList *pEList)
Definition: sqlite3.c:115877
static int unixDeviceCharacteristics(sqlite3_file *id)
Definition: sqlite3.c:33348
Parse * pParse
Definition: sqlite3.c:15905
Trigger * pNext
Definition: sqlite3.c:15708
u8 readOnly
Definition: sqlite3.c:54225
static void spanUnaryPostfix(Parse *pParse, int op, ExprSpan *pOperand, Token *pPostOp)
Definition: sqlite3.c:132977
#define SQLITE_IOERR_DELETE
Definition: sqlite3.c:734
SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt)
Definition: sqlite3.c:76009
#define TK_REM
Definition: sqlite3.c:11342
#define isOpen(pFd)
Definition: sqlite3.c:47178
#define SQLITE_WARNING
Definition: sqlite3.c:703
int nCursor
Definition: sqlite3.c:18036
WhereTerm ** aLTerm
Definition: sqlite3.c:123951
static void analyzeOneTable(Parse *pParse, Table *pTab, Index *pOnlyIdx, int iStatCur, int iMem, int iTab)
Definition: sqlite3.c:96511
void * pUserData
Definition: sqlite3.c:14139
SQLITE_PRIVATE void sqlite3PcacheShutdown(void)
Definition: sqlite3.c:43848
static int vdbeIncrSwap(IncrMerger *)
Definition: sqlite3.c:86795
int(* xSavepoint)(sqlite3_vtab *pVTab, int)
Definition: sqlite3.c:6088
static void computeYMD_HMS(DateTime *p)
Definition: sqlite3.c:18991
SQLITE_PRIVATE int sqlite3SubInt64(i64 *, i64)
Definition: sqlite3.c:28569
static int resolveCompoundOrderBy(Parse *pParse, Select *pSelect)
Definition: sqlite3.c:89132
unsigned char i
Definition: sqlite3.c:26351
#define SQLITE_N_COLCACHE
Definition: sqlite3.c:15451
#define SQLITE_GroupByOrder
Definition: sqlite3.c:14084
static void walCleanupHash(Wal *pWal)
Definition: sqlite3.c:54717
u8 nColCache
Definition: sqlite3.c:15529
#define TWO_BYTE_INT(x)
Definition: sqlite3.c:73799
SQLITE_PRIVATE const char * sqlite3PagerFilename(Pager *, int)
Definition: sqlite3.c:53099
Bool isEphemeral
Definition: sqlite3.c:17772
#define SQLITE_USE_URI
Definition: sqlite3.c:17075
double s
Definition: sqlite3.c:18647
SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem *, const char *, int, u8, void(*)(void *))
Definition: sqlite3.c:69613
i16 nField
Definition: sqlite3.c:17776
SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse *, Table *, FKey *, Index **, int **)
Definition: sqlite3.c:106150
#define SQLITE_REINDEX
Definition: sqlite3.c:3043
union Walker::@9 u
SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData)
Definition: sqlite3.c:56531
static int readJournalHdr(Pager *pPager, int isHot, i64 journalSize, u32 *pNRec, u32 *pDbSize)
Definition: sqlite3.c:47867
SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse *, Expr *, int, u8)
Definition: sqlite3.c:93649
#define P4_TRANSIENT
Definition: sqlite3.c:12509
#define pagerReportSize(X)
Definition: sqlite3.c:48522
u32 magic
Definition: sqlite3.c:13929
#define OP_Return
Definition: sqlite3.c:12634
u16 flags
Definition: sqlite3.c:13193
SQLITE_API int sqlite3_open(const char *filename, sqlite3 **ppDb)
Definition: sqlite3.c:140936
Bitmask prereqRight
Definition: sqlite3.c:124071
ExprList * pEList
Definition: sqlite3.c:15285
#define OPFLAG_LASTROWID
Definition: sqlite3.c:15665
void(* xMutexEnter)(sqlite3_mutex *)
Definition: sqlite3.c:6826
#define NC_IsCheck
Definition: sqlite3.c:15257
static void errlogFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105018
static void explainTempTable(Parse *pParse, const char *zUsage)
Definition: sqlite3.c:115510
volatile u32 ** apWiData
Definition: sqlite3.c:54218
static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8)
Definition: sqlite3.c:63769
#define SQLITE_DROP_TEMP_INDEX
Definition: sqlite3.c:3028
#define WALINDEX_HDR_SIZE
Definition: sqlite3.c:54177
static ExprList * parserAddExprIdListTerm(Parse *pParse, ExprList *pPrior, Token *pIdToken, int hasCollate, int sortOrder)
Definition: sqlite3.c:133017
SQLITE_PRIVATE DbPage * sqlite3PagerLookup(Pager *pPager, Pgno pgno)
Definition: sqlite3.c:51860
SQLITE_API void * sqlite3_commit_hook(sqlite3 *, int(*)(void *), void *)
Definition: sqlite3.c:139742
SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *)
Definition: sqlite3.c:101736
#define OP_ColumnsUsed
Definition: sqlite3.c:12674
#define SRT_Exists
Definition: sqlite3.c:15401
double rSum
Definition: sqlite3.c:105553
WalIndexHdr hdr
Definition: sqlite3.c:54229
#define TK_NOT
Definition: sqlite3.c:11310
#define SQLITE_Stat34
Definition: sqlite3.c:14093
u16(* xCellSize)(MemPage *, u8 *)
Definition: sqlite3.c:57548
char * zName
Definition: sqlite3.c:15947
int addrSortIndex
Definition: sqlite3.c:114445
static void walIndexWriteHdr(Wal *pWal)
Definition: sqlite3.c:54447
static int subjournalPageIfRequired(PgHdr *pPg)
Definition: sqlite3.c:50792
static void substrFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104379
#define OP_IdxInsert
Definition: sqlite3.c:12688
CollSeq * pDfltColl
Definition: sqlite3.c:13905
unsigned bUnordered
Definition: sqlite3.c:14723
#define SQLITE_IOERR_SHORT_READ
Definition: sqlite3.c:726
static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace)
Definition: sqlite3.c:64995
#define PAGER_STAT_MISS
Definition: sqlite3.c:47081
SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse *, Trigger *, ExprList *, int, int, Table *, int)
Definition: sqlite3.c:121338
u8 untestedTerms
Definition: sqlite3.c:124233
SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *)
Definition: sqlite3.c:86611
#define OE_Replace
Definition: sqlite3.c:14595
#define SQLITE_TEMP_STORE
Definition: sqlite3.c:11526
#define SQLITE_IDXTYPE_PRIMARYKEY
Definition: sqlite3.c:14743
#define SQLITE_IOERR
Definition: sqlite3.c:685
#define SQLITE_STAT4_SAMPLES
Definition: sqlite3.c:95717
static void instrFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104299
#define MEM_Frame
Definition: sqlite3.c:17922
SQLITE_PRIVATE void sqlite3HashInit(Hash *)
Definition: sqlite3.c:28753
int(* xLock)(sqlite3_file *, int)
Definition: sqlite3.c:1013
#define TRANS_WRITE
Definition: sqlite3.c:57625
#define YY_ACTTAB_COUNT
Definition: sqlite3.c:133202
static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut)
Definition: sqlite3.c:96493
static int btreeHeapPull(u32 *aHeap, u32 *pOut)
Definition: sqlite3.c:67263
void * pBulk
Definition: sqlite3.c:44625
#define SQLITE_ANY
Definition: sqlite3.c:4760
u32 nSubRec
Definition: sqlite3.c:47025
#define NEVER(X)
Definition: sqlite3.c:11121
static void disconnectAllVtab(sqlite3 *db)
Definition: sqlite3.c:138836
#define TK_INDEX
Definition: sqlite3.c:11431
#define TK_IF
Definition: sqlite3.c:11309
Btree * pDest
Definition: sqlite3.c:67982
static int termCanDriveIndex(WhereTerm *pTerm, struct SrcList_item *pSrc, Bitmask notReady)
Definition: sqlite3.c:128421
static void walLimitSize(Wal *pWal, i64 nMax)
Definition: sqlite3.c:55688
#define TK_ILLEGAL
Definition: sqlite3.c:11454
char dbFileVers[16]
Definition: sqlite3.c:47036
SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *)
Definition: sqlite3.c:19973
SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *, int, int)
Definition: sqlite3.c:62131
#define SQLITE_CONFIG_PCACHE2
Definition: sqlite3.c:2145
static int vdbeSorterCreateThread(SortSubtask *pTask, void *(*xTask)(void *), void *pIn)
Definition: sqlite3.c:85972
SortSubtask aTask[1]
Definition: sqlite3.c:85177
static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p)
Definition: sqlite3.c:126410
static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N)
Definition: sqlite3.c:64664
#define VdbeMemDynamic(X)
Definition: sqlite3.c:17948
#define put4byte
Definition: sqlite3.c:57941
#define EXPRDUP_REDUCE
Definition: sqlite3.c:15017
SQLITE_PRIVATE int sqlite3IsNaN(double)
Definition: sqlite3.c:27331
#define SQLITE_SYNC_NORMAL
Definition: sqlite3.c:894
static int unixOpen(sqlite3_vfs *pVfs, const char *zPath, sqlite3_file *pFile, int flags, int *pOutFlags)
Definition: sqlite3.c:35040
SQLITE_PRIVATE TriggerStep * sqlite3TriggerDeleteStep(sqlite3 *, Token *, Expr *)
Definition: sqlite3.c:120713
SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *, int, u32 *)
Definition: sqlite3.c:73607
i64 nStmtDefCons
Definition: sqlite3.c:18044
int schema_cookie
Definition: sqlite3.c:13762
#define TK_LT
Definition: sqlite3.c:11331
#define WAL_FRAME_HDRSIZE
Definition: sqlite3.c:54180
#define MEM_Cleared
Definition: sqlite3.c:17924
SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *, Module *)
Definition: sqlite3.c:123715
char validHMS
Definition: sqlite3.c:18649
int nSavepoint
Definition: sqlite3.c:14000
#define TK_ALTER
Definition: sqlite3.c:11432
int nSample
Definition: sqlite3.c:95854
SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *)
Definition: sqlite3.c:69268
#define PragTyp_COMPILE_OPTIONS
Definition: sqlite3.c:111119
#define OP_SorterOpen
Definition: sqlite3.c:12670
SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache *, Pgno, sqlite3_pcache_page **)
Definition: sqlite3.c:43977
int nDb
Definition: sqlite3.c:13908
SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *)
Definition: sqlite3.c:51890
static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere)
Definition: sqlite3.c:130495
SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *)
Definition: sqlite3.c:44127
int(* xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *)
Definition: sqlite3.c:6077
SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *)
Definition: sqlite3.c:91493
SQLITE_PRIVATE int sqlite3CorruptError(int)
Definition: sqlite3.c:141143
#define SQLITE_MUTEX_STATIC_MEM
Definition: sqlite3.c:6880
#define TERM_IS
Definition: sqlite3.c:124093
#define etSRCLIST
Definition: sqlite3.c:24743
static void SQLITE_NOINLINE btreeLockCarefully(Btree *p)
Definition: sqlite3.c:58048
#define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
Definition: sqlite3.c:29343
#define ROWSET_ENTRY_PER_CHUNK
Definition: sqlite3.c:45789
BusyHandler busyHandler
Definition: sqlite3.c:13996
#define TK_SELECT_COLUMN
Definition: sqlite3.c:11450
#define MEM_AffMask
Definition: sqlite3.c:17920
#define CTIMEOPT_VAL(opt)
SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *, int)
Definition: sqlite3.c:60829
char * zWal
Definition: sqlite3.c:47071
u32 iDivisor
Definition: sqlite3.c:43263
static void * sqlite3MemRealloc(void *pPrior, int nByte)
Definition: sqlite3.c:20508
#define SQLITE_SYNC_DATAONLY
Definition: sqlite3.c:896
#define tkCREATE
Definition: sqlite3.c:137511
static void walMergesort(const u32 *aContent, ht_slot *aBuffer, ht_slot *aList, int *pnList)
Definition: sqlite3.c:55260
int nMem
Definition: sqlite3.c:18035
#define SQLITE_OPEN_READONLY
Definition: sqlite3.c:789
#define TERM_DYNAMIC
Definition: sqlite3.c:124078
static int generateOutputSubroutine(Parse *pParse, Select *p, SelectDest *pIn, SelectDest *pDest, int regReturn, int regPrev, KeyInfo *pKeyInfo, int iBreak)
Definition: sqlite3.c:116970
int szRegion
Definition: sqlite3.c:33417
u8 bBusy
Definition: sqlite3.c:57532
XmlRpcServer s
#define SQLITE_DistinctOpt
Definition: sqlite3.c:14087
#define sqlite3ParseToplevel(p)
Definition: sqlite3.c:16450
#define VVA_ONLY(X)
Definition: sqlite3.c:11095
#define SQLITE_Transitive
Definition: sqlite3.c:14091
#define SQLITE_MAGIC_ZOMBIE
Definition: sqlite3.c:14124
#define ONE_BYTE_INT(x)
Definition: sqlite3.c:73798
SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *)
Definition: sqlite3.c:69296
SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64 *)
Definition: sqlite3.c:20006
SQLITE_PRIVATE void * sqlite3HexToBlob(sqlite3 *, const char *z, int n)
Definition: sqlite3.c:28474
u8 nTempReg
Definition: sqlite3.c:15523
int(* xRollbackTo)(sqlite3_vtab *pVTab, int)
Definition: sqlite3.c:6090
#define OPFLG_OUT2
Definition: sqlite3.c:12734
#define VDBE_MAGIC_RUN
Definition: sqlite3.c:18100
i64 nKey
Definition: sqlite3.c:57760
SQLITE_API int sqlite3_config(int,...)
Definition: sqlite3.c:138205
SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *, void **)
Definition: sqlite3.c:26550
static int exprVectorRegister(Parse *pParse, Expr *pVector, int iField, int regSelect, Expr **ppExpr, int *pRegFree)
Definition: sqlite3.c:90209
#define WHERE_AUTO_INDEX
Definition: sqlite3.c:124356
#define SQLITE_ShortColNames
Definition: sqlite3.c:14047
#define sqlite3_column_database_name16
Definition: sqlite3.c:110312
#define OP_Clear
Definition: sqlite3.c:12693
#define OP_AddImm
Definition: sqlite3.c:12653
IdList * b
Definition: sqlite3.c:132883
#define SORTFLAG_UseSorter
Definition: sqlite3.c:114450
unsigned int nHash
Definition: sqlite3.c:44622
#define etSQLESCAPE
Definition: sqlite3.c:24739
sqlite3 * db
Definition: sqlite3.c:14619
#define CC_STAR
Definition: sqlite3.c:136619
u16 nLSlot
Definition: sqlite3.c:123950
SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *, int, sqlite3_int64)
Definition: sqlite3.c:76462
static void generateColumnNames(Parse *pParse, SrcList *pTabList, ExprList *pEList)
Definition: sqlite3.c:115917
Table * pTab
Definition: sqlite3.c:84368
u16 nFree
Definition: sqlite3.c:57536
#define SRT_DistQueue
Definition: sqlite3.c:15406
static int checkReadTransaction(sqlite3 *db, Btree *p)
Definition: sqlite3.c:68084
SQLITE_PRIVATE int sqlite3FkRequired(Parse *, Table *, int *, int)
Definition: sqlite3.c:107060
SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *)
Definition: sqlite3.c:73031
static void logBadConnection(const char *zType)
Definition: sqlite3.c:28495
u32 bDisable
Definition: sqlite3.c:13825
static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin)
Definition: sqlite3.c:85985
void(* xCollNeeded)(void *, sqlite3 *, int eTextRep, const char *)
Definition: sqlite3.c:13969
static int compare2pow63(const char *zNum, int incr)
Definition: sqlite3.c:27807
sqlite3_int64 estimatedRows
Definition: sqlite3.c:6214
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
Definition: sqlite3.c:2256
#define BTS_EXCLUSIVE
Definition: sqlite3.c:57708
SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[]
Definition: sqlite3.c:16957
const char * zTail
Definition: sqlite3.c:15610
int nextPagesize
Definition: sqlite3.c:13928
int pageSize
Definition: sqlite3.c:47049
SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *, Select *)
Definition: sqlite3.c:114561
SQLITE_API int sqlite3_create_module_v2(sqlite3 *db, const char *zName, const sqlite3_module *p, void *pClientData, void(*xDestroy)(void *))
Definition: sqlite3.c:122653
sqlite3_uint64 colUsed
Definition: sqlite3.c:6218
SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *, int addr)
Definition: sqlite3.c:71359
#define tkEND
Definition: sqlite3.c:137514
UINT8_TYPE u8
Definition: sqlite3.c:11643
static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N)
Definition: sqlite3.c:99889
static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
Definition: sqlite3.c:97487
#define etINVALID
Definition: sqlite3.c:24748
LogEst szIdxRow
Definition: sqlite3.c:14718
int(* xRowid)(sqlite3_vtab_cursor *, sqlite3_int64 *pRowid)
Definition: sqlite3.c:6076
#define TK_DEFERRABLE
Definition: sqlite3.c:11403
SQLITE_PRIVATE void sqlite3FixInit(DbFixer *, Parse *, int, const char *, const Token *)
Definition: sqlite3.c:97877
volatile int isInterrupted
Definition: sqlite3.c:13974
#define TK_EXISTS
Definition: sqlite3.c:11311
#define SQLITE_TESTCTRL_ASSERT
Definition: sqlite3.c:6979
#define MEM_Agg
Definition: sqlite3.c:17937
SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset)
Definition: sqlite3.c:84784
#define SQLITE_SHM_NLOCK
Definition: sqlite3.c:1584
int p1
Definition: sqlite3.c:12437
static int sqlite3IntFloatCompare(i64 i, double r)
Definition: sqlite3.c:74249
static u8 * pageFindSlot(MemPage *pPg, int nByte, int *pRc)
Definition: sqlite3.c:59666
static int vdbeSortAllocUnpacked(SortSubtask *pTask)
Definition: sqlite3.c:86170
#define PAGER_CACHESPILL
Definition: sqlite3.c:13023
#define SQLITE_IOCAP_ATOMIC512
Definition: sqlite3.c:841
SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer *, SrcList *)
Definition: sqlite3.c:97910
WhereLoop * pLoops
Definition: sqlite3.c:124237
SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *, BtCursor *, i64 *)
Definition: sqlite3.c:74827
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **)
static struct Cte * searchWith(With *pWith, struct SrcList_item *pItem, With **ppContext)
Definition: sqlite3.c:118402
u16 maxLeaf
Definition: sqlite3.c:57681
#define SQLITE_ReadUncommitted
Definition: sqlite3.c:14058
SQLITE_PRIVATE void * sqlite3DbReallocOrFree(sqlite3 *, void *, u64)
Definition: sqlite3.c:24591
SQLITE_PRIVATE Table * sqlite3LocateTableItem(Parse *, u32 flags, struct SrcList_item *)
Definition: sqlite3.c:98681
SQLITE_PRIVATE int sqlite3WalkSelect(Walker *, Select *)
Definition: sqlite3.c:88157
static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof)
Definition: sqlite3.c:86355
SQLITE_PRIVATE u8 sqlite3HexToInt(int h)
Definition: sqlite3.c:28456
SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *)
Definition: sqlite3.c:22532
static int walIteratorNext(WalIterator *p, u32 *piPage, u32 *piFrame)
Definition: sqlite3.c:55150
SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double)
Definition: sqlite3.c:28690
#define OP_Eq
Definition: sqlite3.c:12599
#define OP_Program
Definition: sqlite3.c:12626
u8 explain
Definition: sqlite3.c:15598
static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp)
Definition: sqlite3.c:85455
#define OP_MaxPgcnt
Definition: sqlite3.c:12721
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
Definition: sqlite3.c:7257
char * zName
Definition: sqlite3.c:14706
unsigned short int ctrlFlags
Definition: sqlite3.c:29395
#define VDBE_MAGIC_RESET
Definition: sqlite3.c:18102
#define SQLITE_CONSTRAINT_TRIGGER
Definition: sqlite3.c:772
#define OP_Multiply
Definition: sqlite3.c:12611
static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom)
Definition: sqlite3.c:129639
static int pthreadMutexEnd(void)
Definition: sqlite3.c:22903
#define TF_Autoincrement
Definition: sqlite3.c:14480
static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData, int bUpdate)
Definition: sqlite3.c:68186
SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *, const char *,...)
Definition: sqlite3.c:25798
#define TESTONLY(X)
Definition: sqlite3.c:11081
etByte type
Definition: sqlite3.c:24764
SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *, int)
Definition: sqlite3.c:50099
#define WHERE_ONEROW
Definition: sqlite3.c:124354
struct With::Cte a[1]
static void createMask(WhereMaskSet *pMaskSet, int iCursor)
Definition: sqlite3.c:128009
#define ONLY_IF_REALLOC_STRESS(X)
Definition: sqlite3.c:11136
#define BTCF_ValidNKey
Definition: sqlite3.c:57785
#define SQLITE_STOREP2
Definition: sqlite3.c:14375
static const int aHardLimit[]
Definition: sqlite3.c:140246
sqlite3_syscall_ptr pCurrent
Definition: sqlite3.c:29739
unsigned char j
Definition: sqlite3.c:26351
SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse)
Definition: sqlite3.c:113933
static void * vdbePmaReaderBgIncrInit(void *pCtx)
Definition: sqlite3.c:87091
unsigned Bool
Definition: sqlite3.c:17737
#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
Definition: sqlite3.c:2257
static SQLITE_NOINLINE void vdbeMemClear(Mem *p)
Definition: sqlite3.c:69152
unsigned int nMax
Definition: sqlite3.c:44613
SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *)
Definition: sqlite3.c:75845
static int syncJournal(Pager *pPager, int newHdr)
Definition: sqlite3.c:50494
int szPage
Definition: sqlite3.c:44608
#define SQLITE_FullFSync
Definition: sqlite3.c:14044
#define NC_AllowAgg
Definition: sqlite3.c:15255
u32 nCkpt
Definition: sqlite3.c:54233
int mxKeysize
Definition: sqlite3.c:85162
SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *, const char *zName)
Definition: sqlite3.c:76616
#define SQLITE_DEFAULT_WAL_SYNCHRONOUS
Definition: sqlite3.c:13726
#define PENDING_BYTE_PAGE(pBt)
Definition: sqlite3.c:57830
SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *, Expr *, int)
Definition: sqlite3.c:93739
u8 * aPgRef
Definition: sqlite3.c:57924
#define IN_DECLARE_VTAB
Definition: sqlite3.c:15638
static int unixLock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:30884
static int sqlite3MemRoundup(int n)
Definition: sqlite3.c:20540
char tzSet
Definition: sqlite3.c:18652
#define PGHDR_NEED_SYNC
Definition: sqlite3.c:13210
#define TK_SET
Definition: sqlite3.c:11402
static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask)
Definition: sqlite3.c:85886
static void sqlite3MemShutdown(void *NotUsed)
Definition: sqlite3.c:20583
SQLITE_API void sqlite3_result_text16(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:75528
u32 iReCksum
Definition: sqlite3.c:54231
static SrcList * targetSrcList(Parse *pParse, TriggerStep *pStep)
Definition: sqlite3.c:120919
#define TK_GROUP
Definition: sqlite3.c:11418
u32 iDataVersion
Definition: sqlite3.c:47035
SQLITE_API int sqlite3_trace_v2(sqlite3 *, unsigned uMask, int(*xCallback)(unsigned, void *, void *, void *), void *pCtx)
Definition: sqlite3.c:139684
#define SQLITE_CORRUPT_VTAB
Definition: sqlite3.c:760
#define SQLITE_CONFIG_COVERING_INDEX_SCAN
Definition: sqlite3.c:2147
#define SQLITE_CONFIG_PAGECACHE
Definition: sqlite3.c:2134
static void lockBtreeMutex(Btree *p)
Definition: sqlite3.c:57970
#define HAVE_LSTAT
Definition: sqlite3.c:169
static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType)
Definition: sqlite3.c:69543
static Table * isSimpleCount(Select *p, AggInfo *pAggInfo)
Definition: sqlite3.c:118258
static const YYACTIONTYPE yy_action[]
Definition: sqlite3.c:133203
SQLITE_PRIVATE Select * sqlite3SelectDup(sqlite3 *, Select *, int)
Definition: sqlite3.c:91126
#define OP_Once
Definition: sqlite3.c:12582
static BtShared *SQLITE_WSD sqlite3SharedCacheList
Definition: sqlite3.c:58320
Expr * pPartIdxWhere
Definition: sqlite3.c:14715
static void vdbeFreeOpArray(sqlite3 *, Op *, int)
Definition: sqlite3.c:71333
static int matchQuality(FuncDef *p, int nArg, u8 enc)
Definition: sqlite3.c:102979
static void vdbeMergeEngineFree(MergeEngine *pMerger)
Definition: sqlite3.c:86038
#define COLNAME_DATABASE
Definition: sqlite3.c:12533
UnpackedRecord ** ppRec
Definition: sqlite3.c:69849
#define PragTyp_JOURNAL_MODE
Definition: sqlite3.c:111130
SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut)
Definition: sqlite3.c:19964
#define sqlite3SelectSetName(A, B)
Definition: sqlite3.c:16414
SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *, u32 offset, u32 amt, void *)
Definition: sqlite3.c:67829
SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3 *, const char *)
Definition: sqlite3.c:24639
#define CKCNSTRNT_COLUMN
Definition: sqlite3.c:108462
SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *, Expr *, int)
Definition: sqlite3.c:93752
u8 okConstFactor
Definition: sqlite3.c:15527
SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *)
Definition: sqlite3.c:44370
i64 iKey2
Definition: sqlite3.c:18119
#define TK_ISNULL
Definition: sqlite3.c:11325
#define SQLITE_ACCESS_READ
Definition: sqlite3.c:1547
SQLITE_API const void * sqlite3_column_blob(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76122
SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n)
Definition: sqlite3.c:52982
void(* xRollbackCallback)(void *)
Definition: sqlite3.c:13955
#define OP_DropTrigger
Definition: sqlite3.c:12702
#define READ_LOCK
Definition: sqlite3.c:57575
SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *)
Definition: sqlite3.c:69502
#define TK_BLOB
Definition: sqlite3.c:11424
#define SRT_Output
Definition: sqlite3.c:15411
LogEst rSetup
Definition: sqlite3.c:123927
void * pExtra
Definition: sqlite3.c:13186
#define SQLITE_TESTCTRL_VDBE_COVERAGE
Definition: sqlite3.c:6989
static int zeroJournalHdr(Pager *pPager, int doTruncate)
Definition: sqlite3.c:47699
const char * zName
Definition: sqlite3.c:29738
static void juliandayFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19406
SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *)
Definition: sqlite3.c:60960
#define WHERE_DISTINCT_UNORDERED
Definition: sqlite3.c:15213
#define SQLITE_ROLLBACK
Definition: sqlite3.c:8255
#define SQLITE_PRIVATE
Definition: sqlite3.c:23
#define CC_MINUS
Definition: sqlite3.c:136609
const sqlite3_module * pModule
Definition: sqlite3.c:14285
#define DIRECT_MODE
static int unixShmSystemLock(unixFile *pFile, int lockType, int ofst, int n)
Definition: sqlite3.c:33464
#define OP_Add
Definition: sqlite3.c:12609
SQLITE_PRIVATE SrcList * sqlite3SrcListAppendFromTerm(Parse *, SrcList *, Token *, Token *, Token *, Select *, Expr *, IdList *)
Definition: sqlite3.c:102114
static void replaceFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105271
#define SQLITE_LOCK_EXCLUSIVE
Definition: sqlite3.c:866
static struct RowSetEntry * rowSetEntryAlloc(RowSet *p)
Definition: sqlite3.c:45895
#define jrnlBufferSize(x)
Definition: sqlite3.c:47541
#define SQLITE_MAX_SCHEMA_RETRY
Definition: sqlite3.c:17713
#define OP_CollSeq
Definition: sqlite3.c:12650
int(* xCommitCallback)(void *)
Definition: sqlite3.c:13953
SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *)
Definition: sqlite3.c:123011
CollSeq * aColl[1]
Definition: sqlite3.c:14621
#define sqlite3GlobalConfig
Definition: sqlite3.c:11941
int nRangeReg
Definition: sqlite3.c:15530
static PgHdr1 * pcache1PinPage(PgHdr1 *pPage)
Definition: sqlite3.c:45014
SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *)
Definition: sqlite3.c:22558
static int clearDatabasePage(BtShared *pBt, Pgno pgno, int freePageFlag, int *pnChange)
Definition: sqlite3.c:66673
u8 * aSortOrder
Definition: sqlite3.c:14620
#define TK_VIEW
Definition: sqlite3.c:11381
SQLITE_PRIVATE int sqlite3FixExpr(DbFixer *, Expr *)
Definition: sqlite3.c:97973
TriggerStep * step_list
Definition: sqlite3.c:15707
SQLITE_PRIVATE int sqlite3Init(sqlite3 *, char **)
Definition: sqlite3.c:113889
static int lockBtree(BtShared *pBt)
Definition: sqlite3.c:61059
IdList * yy254
Definition: sqlite3.c:133107
SQLITE_PRIVATE char * sqlite3ColumnType(Column *, char *)
Definition: sqlite3.c:27391
static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt)
Definition: sqlite3.c:138511
#define SQLITE_TRACE_ROW
Definition: sqlite3.c:3143
#define SQLITE_ROW
Definition: sqlite3.c:704
static char * createTableStmt(sqlite3 *db, Table *p)
Definition: sqlite3.c:99821
static int walRestartLog(Wal *pWal)
Definition: sqlite3.c:56568
static void pagerReleaseMapPage(PgHdr *pPg)
Definition: sqlite3.c:50353
u8 * aCellIdx
Definition: sqlite3.c:57545
#define PGHDR_MMAP
Definition: sqlite3.c:13213
#define SF_All
Definition: sqlite3.c:15316
u16 sharedMask
Definition: sqlite3.c:33448
#define SQLITE_DBSTATUS_STMT_USED
Definition: sqlite3.c:7255
#define SQLITE_PreferBuiltin
Definition: sqlite3.c:14065
SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *)
Definition: sqlite3.c:91367
static void printfFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104343
#define OP_IfPos
Definition: sqlite3.c:12628
int szCache
Definition: sqlite3.c:43623
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256]
Definition: sqlite3.c:17024
static int allSpaces(const char *z, int n)
Definition: sqlite3.c:138697
static const char aDigits[]
Definition: sqlite3.c:24781
SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int, const void *, UnpackedRecord *)
Definition: sqlite3.c:74609
#define SQLITE_OPEN_AUTOPROXY
Definition: sqlite3.c:794
#define TK_AND
Definition: sqlite3.c:11319
SQLITE_PRIVATE FKey * sqlite3FkReferences(Table *)
Definition: sqlite3.c:106630
u8 incrVacuum
Definition: sqlite3.c:57670
SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *)
Definition: sqlite3.c:48069
SQLITE_API int sqlite3_bind_null(sqlite3_stmt *, int)
Definition: sqlite3.c:76472
#define IN_INDEX_LOOP
Definition: sqlite3.c:16819
SQLITE_PRIVATE Select * sqlite3SelectNew(Parse *, ExprList *, SrcList *, Expr *, ExprList *, Expr *, ExprList *, u32, Expr *, Expr *)
Definition: sqlite3.c:114490
u8 accError
Definition: sqlite3.c:15798
static int exprCodeSubselect(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:90181
#define SQLITE_FCNTL_TEMPFILENAME
Definition: sqlite3.c:1285
static void releaseAllSavepoints(Pager *pPager)
Definition: sqlite3.c:48079
SQLITE_API int sqlite3_db_config(sqlite3 *, int op,...)
Definition: sqlite3.c:138637
#define SQLITE_CREATE_TABLE
Definition: sqlite3.c:3018
SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *, const Mem *, int)
Definition: sqlite3.c:69548
SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *)
Definition: sqlite3.c:28106
void(* xSelectCallback2)(Walker *, Select *)
Definition: sqlite3.c:15908
SQLITE_API int sqlite3_prepare(sqlite3 *db, const char *zSql, int nByte, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:114273
SQLITE_API int sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs)
Definition: sqlite3.c:140943
#define SQLITE_MISUSE_BKPT
Definition: sqlite3.c:15986
#define SQLITE_TESTCTRL_RESERVE
Definition: sqlite3.c:6981
static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags)
Definition: sqlite3.c:71942
#define SQLITE_BLOB
Definition: sqlite3.c:4389
unsigned int nMin
Definition: sqlite3.c:44612
int addrExplain
Definition: sqlite3.c:18013
SQLITE_PRIVATE int sqlite3MallocInit(void)
Definition: sqlite3.c:24012
SQLITE_PRIVATE void sqlite3VtabLock(VTable *)
Definition: sqlite3.c:122674
#define SQLITE_ATTACH
Definition: sqlite3.c:3040
#define P4_INTARRAY
Definition: sqlite3.c:12515
static int unixDelete(sqlite3_vfs *NotUsed, const char *zPath, int dirSync)
Definition: sqlite3.c:35296
SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *)
Definition: sqlite3.c:74963
#define CURTYPE_SORTER
Definition: sqlite3.c:17747
#define SQLITE_UTF16LE
Definition: sqlite3.c:4757
#define sqlite3Isspace(x)
Definition: sqlite3.c:16031
INT8_TYPE i8
Definition: sqlite3.c:11644
#define TK_CASE
Definition: sqlite3.c:11427
#define OE_Abort
Definition: sqlite3.c:14592
ExprList * pConstExpr
Definition: sqlite3.c:15543
static void pcacheUnpin(PgHdr *p)
Definition: sqlite3.c:43809
SQLITE_API void * sqlite3_rollback_hook(sqlite3 *, void(*)(void *), void *)
Definition: sqlite3.c:139792
static int pagerUndoCallback(void *pCtx, Pgno iPg)
Definition: sqlite3.c:49371
#define SQLITE_IOERR_NOMEM_BKPT
Definition: sqlite3.c:15995
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot)
int(* xPhraseCount)(Fts5Context *)
Definition: sqlite3.c:10334
#define SQLITE_PRINTF_MALLOCED
Definition: sqlite3.c:15805
SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe *, int, int, int, int, const char *zP4, int)
Definition: sqlite3.c:70736
static const FuncDef statGetFuncdef
Definition: sqlite3.c:96482
int(* xAccess)(sqlite3_vfs *, const char *zName, int flags, int *pResOut)
Definition: sqlite3.c:1496
#define OP_String
Definition: sqlite3.c:12640
#define OPFLG_JUMP
Definition: sqlite3.c:12730
#define SQLITE_SOURCE_ID
Definition: sqlite3.c:386
#define PAGER_SYNCHRONOUS_OFF
Definition: sqlite3.c:13016
static int btreeInvokeBusyHandler(void *pArg)
Definition: sqlite3.c:60356
static volatile WalIndexHdr * walIndexHdr(Wal *pWal)
Definition: sqlite3.c:54372
#define WHERE_IDX_ONLY
Definition: sqlite3.c:124349
#define COLNAME_NAME
Definition: sqlite3.c:12531
static int getFileMode(const char *zFile, mode_t *pMode, uid_t *pUid, gid_t *pGid)
Definition: sqlite3.c:34919
#define TK_AS
Definition: sqlite3.c:11315
#define SQLITE_SYNC_FULL
Definition: sqlite3.c:895
#define SQLITE_READONLY_ROLLBACK
Definition: sqlite3.c:763
static int vdbeSorterJoinThread(SortSubtask *pTask)
Definition: sqlite3.c:85951
SQLITE_PRIVATE void sqlite3DropTrigger(Parse *, SrcList *, int)
Definition: sqlite3.c:120750
#define WHERE_COLUMN_EQ
Definition: sqlite3.c:124341
#define OP_SCopy
Definition: sqlite3.c:12647
VtabCtx * pPrior
Definition: sqlite3.c:122584
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot)
#define WAL_SAVEPOINT_NDATA
Definition: sqlite3.c:46289
#define ALWAYS(X)
Definition: sqlite3.c:11120
SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe *)
Definition: sqlite3.c:77868
int(* xStress)(void *, PgHdr *)
Definition: sqlite3.c:43629
static void groupConcatFinalize(sqlite3_context *context)
Definition: sqlite3.c:105739
#define SQLITE_LIMIT_VARIABLE_NUMBER
Definition: sqlite3.c:3682
static void substExprList(sqlite3 *, ExprList *, int, ExprList *)
Definition: sqlite3.c:117536
PgHdr * pDirty
Definition: sqlite3.c:13187
SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *)
Definition: sqlite3.c:76687
static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op)
Definition: sqlite3.c:132989
ExprList * yy148
Definition: sqlite3.c:133102
static int patternCompare(const u8 *zPattern, const u8 *zString, const struct compareInfo *pInfo, u32 matchOther)
Definition: sqlite3.c:104750
u8 setMaster
Definition: sqlite3.c:47013
SQLITE_PRIVATE void * sqlite3BtreeSchema(Btree *, int, void(*)(void *))
Definition: sqlite3.c:67766
#define MEM_Term
Definition: sqlite3.c:17933
#define SQLITE_CORRUPT_BKPT
Definition: sqlite3.c:15985
#define SQLITE_DONE
Definition: sqlite3.c:705
#define OptimizationDisabled(db, mask)
Definition: sqlite3.c:14101
#define WHERE_VIRTUALTABLE
Definition: sqlite3.c:124352
static SQLITE_NOINLINE void * dbMallocRawFinish(sqlite3 *db, u64 n)
Definition: sqlite3.c:24473
static void compileoptionusedFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105034
int nSrc
Definition: sqlite3.c:15134
static void pagerUnlockAndRollback(Pager *pPager)
Definition: sqlite3.c:48466
static void checkPtrmap(IntegrityCk *pCheck, Pgno iChild, u8 eType, Pgno iParent)
Definition: sqlite3.c:67132
SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *)
Definition: sqlite3.c:110880
struct PCache1 PCache1
Definition: sqlite3.c:44539
#define SQLITE_MUTEX_RECURSIVE
Definition: sqlite3.c:6878
static void lengthFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104210
char * zErrMsg
Definition: sqlite3.c:6305
SorterList list
Definition: sqlite3.c:85169
#define SQLITE_CONFIG_STMTJRNL_SPILL
Definition: sqlite3.c:2153
#define SQLITE_CREATE_TEMP_TRIGGER
Definition: sqlite3.c:3021
u8 enc
Definition: sqlite3.c:14323
PGroup * pGroup
Definition: sqlite3.c:44607
SQLITE_API int sqlite3_test_control(int op,...)
Definition: sqlite3.c:141369
Expr * pExpr
Definition: sqlite3.c:15061
static void btreeParseCell(MemPage *pPage, int iCell, CellInfo *pInfo)
Definition: sqlite3.c:59447
static int codeEqualityTerm(Parse *pParse, WhereTerm *pTerm, WhereLevel *pLevel, int iEq, int bRev, int iTarget)
Definition: sqlite3.c:124735
#define OP_CursorHint
Definition: sqlite3.c:12722
SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage *)
Definition: sqlite3.c:52366
static int parseYyyyMmDd(const char *zDate, DateTime *p)
Definition: sqlite3.c:18861
static void SQLITE_NOINLINE vdbeChangeP4Full(Vdbe *p, Op *pOp, const char *zP4, int n)
Definition: sqlite3.c:71400
SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int)
Definition: sqlite3.c:18290
Module * pMod
Definition: sqlite3.c:14423
#define sqlite3IsNumericAffinity(X)
Definition: sqlite3.c:14356
static void(*)(void) unixDlSym(sqlite3_vfs *NotUsed, void *p, const char *zSym)
Definition: sqlite3.c:35515
#define WAL_NREADER
Definition: sqlite3.c:54066
static int walBusyLock(Wal *pWal, int(*xBusy)(void *), void *pBusyArg, int lockIdx, int n)
Definition: sqlite3.c:55421
static void spanBinaryExpr(Parse *pParse, int op, ExprSpan *pLeft, ExprSpan *pRight)
Definition: sqlite3.c:132956
static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed)
Definition: sqlite3.c:97051
char * zName
Definition: sqlite3.c:14436
SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *)
Definition: sqlite3.c:27569
char * zName
Definition: sqlite3.c:14297
SQLITE_PRIVATE Table * sqlite3SrcListLookup(Parse *, SrcList *)
Definition: sqlite3.c:103247
i64 journalOff
Definition: sqlite3.c:47030
static Expr * exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer)
Definition: sqlite3.c:90885
#define SQLITE_CONFIG_GETPCACHE
Definition: sqlite3.c:2142
#define SQLITE_SubqCoroutine
Definition: sqlite3.c:14090
#define SQLITE_UTF8
Definition: sqlite3.c:4756
SQLITE_PRIVATE void sqlite3Error(sqlite3 *, int)
Definition: sqlite3.c:27411
u32 nAlloc
Definition: sqlite3.c:120097
static int exprIsConst(Expr *p, int initFlag, int iCur)
Definition: sqlite3.c:91464
u8 inTransaction
Definition: sqlite3.c:57673
#define WHERE_DISTINCT_ORDERED
Definition: sqlite3.c:15212
sqlite3_mutex * mutex
Definition: sqlite3.c:33414
static void groupConcatStep(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105707
SQLITE_API const void * sqlite3_column_name16(sqlite3_stmt *, int N)
Definition: sqlite3.c:76247
static void releasePage(MemPage *pPage)
Definition: sqlite3.c:60292
int nMaxSorterMmap
Definition: sqlite3.c:13933
#define SQLITE_OPEN_EXCLUSIVE
Definition: sqlite3.c:793
yDbMask lockMask
Definition: sqlite3.c:18079
static int fillInCell(MemPage *pPage, unsigned char *pCell, const BtreePayload *pX, int *pnSize)
Definition: sqlite3.c:64311
SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *, int)
Definition: sqlite3.c:139075
u32 nAlloc
Definition: sqlite3.c:15796
u8 nested
Definition: sqlite3.c:15522
sqlite_uint64 sqlite3_uint64
Definition: sqlite3.c:531
static KeyInfo * keyInfoFromExprList(Parse *pParse, ExprList *pList, int iStart, int nExtra)
Definition: sqlite3.c:115458
SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager)
Definition: sqlite3.c:47185
#define TRACE_IDX_INPUTS(A)
Definition: sqlite3.c:128411
SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *, int, int *)
Definition: sqlite3.c:66890
static void pthreadMutexEnter(sqlite3_mutex *p)
Definition: sqlite3.c:23045
static void codeVectorCompare(Parse *pParse, Expr *pExpr, int dest, u8 op, u8 p5)
Definition: sqlite3.c:90242
#define HASHTABLE_NPAGE
Definition: sqlite3.c:54297
SQLITE_PRIVATE int sqlite3WalkExprList(Walker *, ExprList *)
Definition: sqlite3.c:88085
#define checkProfileCallback(DB, P)
Definition: sqlite3.c:75199
struct et_info et_info
#define PragTyp_MMAP_SIZE
Definition: sqlite3.c:111135
PgFreeslot * pNext
Definition: sqlite3.c:44633
SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *, const void *, int amt, i64 offset)
Definition: sqlite3.c:19834
#define TK_ID
Definition: sqlite3.c:11346
MemPage * pRef
Definition: sqlite3.c:64637
SQLITE_API const void * sqlite3_errmsg16(sqlite3 *)
Definition: sqlite3.c:140089
int(* xSetAuxdata)(Fts5Context *, void *pAux, void(*xDelete)(void *))
Definition: sqlite3.c:10347
BtShared * pBt
Definition: sqlite3.c:57601
static int vdbeSorterSetupMerge(VdbeSorter *pSorter)
Definition: sqlite3.c:87334
struct RowSetEntry * pForest
Definition: sqlite3.c:45828
SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *)
Definition: sqlite3.c:61852
u16 nField
Definition: sqlite3.c:14617
static int resolveOrderGroupBy(NameContext *pNC, Select *pSelect, ExprList *pOrderBy, const char *zType)
Definition: sqlite3.c:89281
#define SQLITE_CANTOPEN_CONVPATH
Definition: sqlite3.c:759
SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *, int)
Definition: sqlite3.c:70697
u32 aHash[BITVEC_NINT]
Definition: sqlite3.c:43269
static const Mem * columnNullValue(void)
Definition: sqlite3.c:76027
static int walIndexTryHdr(Wal *pWal, int *pChanged)
Definition: sqlite3.c:55784
#define TK_REGISTER
Definition: sqlite3.c:11448
int nSavepoint
Definition: sqlite3.c:47034
SQLITE_API const char sqlite3_version[]
Definition: sqlite3.c:418
#define SQLITE_VdbeListing
Definition: sqlite3.c:14054
static void statPush(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:96268
static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut)
Definition: sqlite3.c:31395
SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *)
Definition: sqlite3.c:72003
#define WO_ALL
Definition: sqlite3.c:124333
unsigned int nCurrentPage
Definition: sqlite3.c:44589
#define TK_DISTINCT
Definition: sqlite3.c:11412
ynVar nVar
Definition: sqlite3.c:15595
static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags)
Definition: sqlite3.c:66518
int(* xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info *)
Definition: sqlite3.c:6066
#define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
Definition: sqlite3.c:12943
SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(BtCursor *, UnpackedRecord *pUnKey, i64 intKey, int bias, int *pRes)
Definition: sqlite3.c:63306
#define SQLITE_FCNTL_TRACE
Definition: sqlite3.c:1287
#define CC_EQ
Definition: sqlite3.c:136612
static void reindexDatabases(Parse *pParse, char const *zColl)
Definition: sqlite3.c:102539
SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *, Vdbe *)
Definition: sqlite3.c:70549
SQLITE_API SQLITE_DEPRECATED void * sqlite3_trace(sqlite3 *, void(*xTrace)(void *, const char *), void *)
Definition: sqlite3.c:139663
SQLITE_API void sqlite3_interrupt(sqlite3 *)
Definition: sqlite3.c:139418
#define sqlite3ConnectionBlocked(x, y)
Definition: sqlite3.c:16848
ExprList * aColExpr
Definition: sqlite3.c:14716
static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType)
Definition: sqlite3.c:61575
#define PragTyp_COLLATION_LIST
Definition: sqlite3.c:111118
#define SQLITE_IOERR_UNLOCK
Definition: sqlite3.c:732
#define CC_AND
Definition: sqlite3.c:136622
Bitvec * apSub[BITVEC_NPTR]
Definition: sqlite3.c:43270
i8 isOrdered
Definition: sqlite3.c:124000
static int fileHasMoved(unixFile *pFile)
Definition: sqlite3.c:30721
struct WalIterator WalIterator
Definition: sqlite3.c:54071
static int findIndexCol(Parse *pParse, ExprList *pList, int iBase, Index *pIdx, int iCol)
Definition: sqlite3.c:128210
const char * zPath
Definition: sqlite3.c:29399
#define SQLITE_TESTCTRL_ISINIT
Definition: sqlite3.c:6991
#define wsdAutoextInit
Definition: sqlite3.c:110930
int iStatement
Definition: sqlite3.c:18041
#define SF_Aggregate
Definition: sqlite3.c:15318
SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *)
Definition: sqlite3.c:69480
WhereOrInfo * pOrInfo
Definition: sqlite3.c:124068
KeyInfo * pKeyInfo
Definition: sqlite3.c:14660
SQLITE_API int sqlite3_system_errno(sqlite3 *)
Definition: sqlite3.c:140152
static int createCollation(sqlite3 *db, const char *zName, u8 enc, void *pCtx, int(*xCompare)(void *, int, const void *, int, const void *), void(*xDel)(void *))
Definition: sqlite3.c:140169
#define SHARED_FIRST
Definition: sqlite3.c:13560
SQLITE_API int sqlite3_shutdown(void)
Definition: sqlite3.c:138151
#define NC_InAggFunc
Definition: sqlite3.c:15258
static int moveToChild(BtCursor *pCur, u32 newPgno)
Definition: sqlite3.c:63001
SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *)
Definition: sqlite3.c:69420
#define get2byteNotZero(X)
Definition: sqlite3.c:58287
unsigned int * anQueue
Definition: sqlite3.c:8740
sqlite3_mutex_methods mutex
Definition: sqlite3.c:15838
#define sqlite3_column_origin_name16
Definition: sqlite3.c:110316
static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value)
Definition: sqlite3.c:111727
#define SPILLFLAG_ROLLBACK
Definition: sqlite3.c:46826
SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions
Definition: sqlite3.c:17167
FuncDef * pFunc
Definition: sqlite3.c:12446
#define CODEC1(P, D, N, X, E)
Definition: sqlite3.c:46784
#define PAGER_READER
Definition: sqlite3.c:46717
static void reindexTable(Parse *pParse, Table *pTab, char const *zColl)
Definition: sqlite3.c:102520
SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int)
Definition: sqlite3.c:121431
struct PgHdr PgHdr
Definition: sqlite3.c:13176
SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock)
Definition: sqlite3.c:67799
static int vdbeSorterOpenTempFile(sqlite3 *db, i64 nExtend, sqlite3_file **ppFd)
Definition: sqlite3.c:86143
#define INCRINIT_ROOT
Definition: sqlite3.c:86926
#define OP_InsertInt
Definition: sqlite3.c:12678
#define sqlite3_column_database_name
Definition: sqlite3.c:110311
SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *, int, void *)
Definition: sqlite3.c:19887
SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse)
Definition: sqlite3.c:107737
#define PragTyp_SECURE_DELETE
Definition: sqlite3.c:111137
static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p)
Definition: sqlite3.c:106642
#define SQLITE_CONSTRAINT_PRIMARYKEY
Definition: sqlite3.c:771
static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC)
Definition: sqlite3.c:59552
static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable)
Definition: sqlite3.c:98889
VdbeFrame * pFrame
Definition: sqlite3.c:17878
#define TK_STRING
Definition: sqlite3.c:11388
static void clearSelect(sqlite3 *db, Select *p, int bFree)
Definition: sqlite3.c:114456
static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105630
SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse *, int, Index *)
Definition: sqlite3.c:102444
UnpackedRecord * pUnpacked
Definition: sqlite3.c:18115
#define SQLITE_INTEGER
Definition: sqlite3.c:4387
static int pagerSyncHotJournal(Pager *pPager)
Definition: sqlite3.c:50290
#define OP_Transaction
Definition: sqlite3.c:12564
PgHdr1 * pNext
Definition: sqlite3.c:44556
sqlite3_vfs * pVfs
Definition: sqlite3.c:54211
#define valueFromFunction(a, b, c, d, e, f)
Definition: sqlite3.c:70007
u8 curPagerFlags
Definition: sqlite3.c:57767
#define TK_COLUMN
Definition: sqlite3.c:11443
static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef)
Definition: sqlite3.c:71262
SQLITE_PRIVATE int sqlite3FixSelect(DbFixer *, Select *)
Definition: sqlite3.c:97940
static int walWriteOneFrame(WalWriter *p, PgHdr *pPage, int nTruncate, sqlite3_int64 iOffset)
Definition: sqlite3.c:56656
#define TK_FAIL
Definition: sqlite3.c:11364
void(* xDelete)(void *)
Definition: sqlite3.c:17976
sqlite3_context * pCtx
Definition: sqlite3.c:12447
#define OE_Rollback
Definition: sqlite3.c:14591
#define SQLITE_MUTEX_STATIC_VFS1
Definition: sqlite3.c:6890
#define TK_ON
Definition: sqlite3.c:11398
SQLITE_API const char * sqlite3_sql(sqlite3_stmt *pStmt)
Definition: sqlite3.c:76736
SQLITE_PRIVATE void * sqlite3PagerGetData(DbPage *)
Definition: sqlite3.c:53350
SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar)
Definition: sqlite3.c:27197
static void whereCombineDisjuncts(SrcList *pSrc, WhereClause *pWC, WhereTerm *pOne, WhereTerm *pTwo)
Definition: sqlite3.c:126765
signed char p1
Definition: sqlite3.c:12492
SQLITE_API void sqlite3_set_auxdata(sqlite3_context *, int N, void *, void(*)(void *))
Definition: sqlite3.c:75945
static const YYCODETYPE yy_lookahead[]
Definition: sqlite3.c:133362
static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg)
Definition: sqlite3.c:67090
int n
Definition: sqlite3.c:15913
#define SQLITE_IOERR_FSTAT
Definition: sqlite3.c:731
#define SQLITE_ERROR
Definition: sqlite3.c:676
int mxPathname
Definition: sqlite3.c:1489
#define SQLITE_DROP_VIEW
Definition: sqlite3.c:3033
#define JOURNAL_HDR_SZ(pPager)
Definition: sqlite3.c:47137
#define JOURNAL_PG_SZ(pPager)
Definition: sqlite3.c:47131
SQLITE_PRIVATE const char * sqlite3ErrStr(int)
Definition: sqlite3.c:139233
#define OP_VDestroy
Definition: sqlite3.c:12716
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *, int)
Definition: sqlite3.c:136995
#define SQLITE_CREATE_VIEW
Definition: sqlite3.c:3024
#define UNIX_SHM_BASE
Definition: sqlite3.c:33455
static int nolockClose(sqlite3_file *id)
Definition: sqlite3.c:31412
int iLeftJoin
Definition: sqlite3.c:123871
u32 wsFlags
Definition: sqlite3.c:123945
#define CHECK_PAGE(x)
Definition: sqlite3.c:47584
#define SF_Distinct
Definition: sqlite3.c:15315
#define SQLITE_BUSY_RECOVERY
Definition: sqlite3.c:754
#define OS_VXWORKS
Definition: sqlite3.c:166
SQLITE_PRIVATE char * sqlite3NameFromToken(sqlite3 *, Token *)
Definition: sqlite3.c:98973
static void codeTableLocks(Parse *pParse)
Definition: sqlite3.c:98390
SQLITE_PRIVATE void sqlite3AuthContextPush(Parse *, AuthContext *, const char *)
Definition: sqlite3.c:98276
u8 inTrans
Definition: sqlite3.c:57602
SQLITE_API int sqlite3_errcode(sqlite3 *db)
Definition: sqlite3.c:140134
int(* xExprCallback)(Walker *, Expr *)
Definition: sqlite3.c:15906
UnpackedRecord * pUnpacked
Definition: sqlite3.c:85141
SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *)
Definition: sqlite3.c:28533
static int write32bits(sqlite3_file *fd, i64 offset, u32 val)
Definition: sqlite3.c:47445
#define findCellPastPtr(P, I)
Definition: sqlite3.c:59270
#define SQLITE_OPEN_MASTER_JOURNAL
Definition: sqlite3.c:803
#define SQLITE_INTERRUPT
Definition: sqlite3.c:684
#define osGetcwd
static void yy_reduce(yyParser *yypParser, unsigned int yyruleno)
Definition: sqlite3.c:135024
#define ArraySize(X)
Definition: sqlite3.c:11901
SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *)
Definition: sqlite3.c:76623
Expr * pRight
Definition: sqlite3.c:14921
SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *)
Definition: sqlite3.c:69020
u8 isInit
Definition: sqlite3.c:57524
#define WRITE_UTF16BE(zOut, c)
Definition: sqlite3.c:26835
int(* xRelease)(sqlite3_vtab *pVTab, int)
Definition: sqlite3.c:6089
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo)
Definition: sqlite3.c:94474
SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *)
Definition: sqlite3.c:28410
#define sqlite3VdbeVerifyNoMallocRequired(A, B)
Definition: sqlite3.c:12789
int * aiCol
Definition: sqlite3.c:15918
#define PragTyp_DEFAULT_CACHE_SIZE
Definition: sqlite3.c:111122
#define TK_ROW
Definition: sqlite3.c:11378
SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr)
Definition: sqlite3.c:104872
#define TK_UNION
Definition: sqlite3.c:11406
#define SQLITE_MAX_PAGE_COUNT
Definition: sqlite3.c:10836
static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg)
Definition: sqlite3.c:52074
#define BTREE_FREE_PAGE_COUNT
Definition: sqlite3.c:12164
int addrBody
Definition: sqlite3.c:123879
void(* xDlError)(sqlite3_vfs *, int nByte, char *zErrMsg)
Definition: sqlite3.c:1499
static int hasColumn(const i16 *aiCol, int nCol, int x)
Definition: sqlite3.c:99941
#define PTRMAP_PTROFFSET(pgptrmap, pgno)
Definition: sqlite3.c:57848
#define PragTyp_LOCK_STATUS
Definition: sqlite3.c:111152
#define OP_Prev
Definition: sqlite3.c:12568
static const char * unixTempFileDir(void)
Definition: sqlite3.c:34790
#define UNIX_SHM_DMS
Definition: sqlite3.c:33456
static void unixLeaveMutex(void)
Definition: sqlite3.c:30066
SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *)
Definition: sqlite3.c:88016
SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int)
Definition: sqlite3.c:62274
TFSIMD_FORCE_INLINE const tfScalar & y() const
#define TK_ALL
Definition: sqlite3.c:11407
char * z
Definition: sqlite3.c:17884
static void attachBackupObject(sqlite3_backup *p)
Definition: sqlite3.c:68295
#define SQLITE_TESTCTRL_PRNG_SAVE
Definition: sqlite3.c:6972
signed char p2
Definition: sqlite3.c:12493
static const sqlite3_api_routines sqlite3Apis
Definition: sqlite3.c:110413
static int sqliteProcessJoin(Parse *pParse, Select *p)
Definition: sqlite3.c:114793
const u8 * aRow
Definition: sqlite3.c:17808
#define SQLITE_CoverIdxScan
Definition: sqlite3.c:14088
#define PAGER_OMIT_JOURNAL
Definition: sqlite3.c:12977
i64 nKey
Definition: sqlite3.c:57717
#define VisibleRowid(X)
Definition: sqlite3.c:14518
#define btreeIntegrity(p)
Definition: sqlite3.c:57891
u8 writeLock
Definition: sqlite3.c:54223
SQLITE_PRIVATE char * sqlite3VMPrintf(sqlite3 *, const char *, va_list)
Definition: sqlite3.c:25632
SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *)
Definition: sqlite3.c:52923
SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *)
Definition: sqlite3.c:95482
int bUseThread
Definition: sqlite3.c:85244
PgHdr * pDirtyTail
Definition: sqlite3.c:43620
sqlite3ParserARG_SDECL yyStackEntry yystack[YYSTACKDEPTH]
Definition: sqlite3.c:133818
SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *)
Definition: sqlite3.c:19933
#define SQLITE_FUNC_UNLIKELY
Definition: sqlite3.c:14192
static int incrAggDepth(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:88215
DbPage * pDbPage
Definition: sqlite3.c:57547
void * pEnd
Definition: sqlite3.c:13833
#define OP_BitNot
Definition: sqlite3.c:12616
#define CLEARBIT(V, I)
Definition: sqlite3.c:43468
#define OP_Seek
Definition: sqlite3.c:12690
SQLITE_API void * sqlite3_update_hook(sqlite3 *, void(*)(void *, int, char const *, char const *, sqlite3_int64), void *)
Definition: sqlite3.c:139767
#define SQLITE_MISUSE
Definition: sqlite3.c:696
unixShmNode * pShmNode
Definition: sqlite3.c:33444
#define SQLITE_DEFAULT_MMAP_SIZE
Definition: sqlite3.c:11831
SQLITE_API void sqlite3_result_subtype(sqlite3_context *, unsigned int)
Definition: sqlite3.c:75496
int iBatch
Definition: sqlite3.c:45831
int(* xMutexInit)(void)
Definition: sqlite3.c:6822
static int fkChildIsModified(Table *pTab, FKey *p, int *aChange, int bChngRowid)
Definition: sqlite3.c:106731
static void estimateIndexWidth(Index *pIdx)
Definition: sqlite3.c:99927
int szOpAlloc
Definition: sqlite3.c:15536
#define HASHTABLE_NPAGE_ONE
Definition: sqlite3.c:54306
static void minmaxFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104159
#define sqlite3ColumnPropertiesFromName(T, C)
Definition: sqlite3.c:16222
#define COLNAME_COLUMN
Definition: sqlite3.c:12535
static int walIndexReadHdr(Wal *pWal, int *pChanged)
Definition: sqlite3.c:55842
SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **)
Definition: sqlite3.c:99045
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int)
Definition: sqlite3.c:20000
#define sqlite3ParserARG_SDECL
Definition: sqlite3.c:133116
static SQLITE_NOINLINE Vdbe * allocVdbe(Parse *pParse)
Definition: sqlite3.c:116182
#define SQLITE_BYTEORDER
Definition: sqlite3.c:11757
static const char * columnTypeImpl(NameContext *pNC, Expr *pExpr, u8 *pEstWidth)
Definition: sqlite3.c:115726
#define VdbeNoopComment(X)
Definition: sqlite3.c:12865
int aiCur[11]
Definition: sqlite3.c:124109
SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *)
Definition: sqlite3.c:62524
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *, ExprList *)
Definition: sqlite3.c:94647
static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes)
Definition: sqlite3.c:47426
#define TK_CTIME_KW
Definition: sqlite3.c:11386
static FuncDef * functionSearch(int h, const char *zFunc)
Definition: sqlite3.c:103014
#define TK_VALUES
Definition: sqlite3.c:11411
SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *, int, int, int, int)
Definition: sqlite3.c:70640
static LogEst whereSortingCost(WhereInfo *pWInfo, LogEst nRow, int nOrderBy, int nSorted)
Definition: sqlite3.c:131592
#define osGeteuid
static void rowSetTreeToList(struct RowSetEntry *pIn, struct RowSetEntry **ppFirst, struct RowSetEntry **ppLast)
Definition: sqlite3.c:46015
char * zDbSName
Definition: sqlite3.c:13737
static int pager_delmaster(Pager *pPager, const char *zMaster)
Definition: sqlite3.c:48821
static int unixShmRegionPerMap(void)
Definition: sqlite3.c:33543
static void pagerUnlockIfUnused(Pager *pPager)
Definition: sqlite3.c:51621
#define ExprSetVVAProperty(E, P)
Definition: sqlite3.c:15001
#define SQLITE_IOERR_NOMEM
Definition: sqlite3.c:736
static int subjRequiresPage(PgHdr *pPg)
Definition: sqlite3.c:47396
static SQLITE_NOINLINE int apiOomError(sqlite3 *db)
Definition: sqlite3.c:24679
SQLITE_PRIVATE void sqlite3Dequote(char *)
Definition: sqlite3.c:27517
Schema * pSchema
Definition: sqlite3.c:13741
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint)
Definition: sqlite3.c:53024
static int vdbeSorterTreeDepth(int nPMA)
Definition: sqlite3.c:87181
Bitmask prereq
Definition: sqlite3.c:123961
i16 iAgg
Definition: sqlite3.c:14943
static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull)
Definition: sqlite3.c:91712
#define osPread
SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *, unsigned int mask)
Definition: sqlite3.c:67923
SQLITE_API int sqlite3_threadsafe(void)
Definition: sqlite3.c:137912
SQLITE_PRIVATE int sqlite3AuthCheck(Parse *, int, const char *, const char *, const char *)
Definition: sqlite3.c:98236
static int resolveExprStep(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:88756
#define TK_ISNOT
Definition: sqlite3.c:11439
#define pcache1EnterMutex(X)
Definition: sqlite3.c:44676
u16 nRef
Definition: sqlite3.c:14447
u8 * aBuffer
Definition: sqlite3.c:85200
#define TK_SPACE
Definition: sqlite3.c:11453
#define BTREE_FILE_FORMAT
Definition: sqlite3.c:12166
SQLITE_PRIVATE int sqlite3IsRowid(const char *)
Definition: sqlite3.c:91651
SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *, i64)
Definition: sqlite3.c:45920
SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void)
Definition: sqlite3.c:141106
#define OP_JournalMode
Definition: sqlite3.c:12571
#define SQLITE_FCNTL_LOCKSTATE
Definition: sqlite3.c:1270
#define BTREE_SEEK_EQ
Definition: sqlite3.c:12218
static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt)
Definition: sqlite3.c:111585
i64 lastRowid
Definition: sqlite3.c:17852
SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *, int)
Definition: sqlite3.c:104107
struct RowSetEntry * pFresh
Definition: sqlite3.c:45827
SQLITE_PRIVATE void sqlite3Pragma(Parse *, Token *, Token *, Token *, int)
Definition: sqlite3.c:111836
static void walUnlockExclusive(Wal *pWal, int lockIdx, int n)
Definition: sqlite3.c:54609
SQLITE_PRIVATE void sqlite3MultiWrite(Parse *)
Definition: sqlite3.c:102393
#define SQLITE_MAX_VDBE_OP
Definition: sqlite3.c:10735
#define SAVEPOINT_ROLLBACK
Definition: sqlite3.c:14276
SQLITE_API int sqlite3_extended_result_codes(sqlite3 *, int onoff)
Definition: sqlite3.c:141316
SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *, DbPage *, Pgno, int)
Definition: sqlite3.c:53207
static void storeLastErrno(unixFile *pFile, int error)
Definition: sqlite3.c:30579
static void * pcache1Alloc(int nByte)
Definition: sqlite3.c:44766
SQLITE_API void * sqlite3_malloc64(sqlite3_uint64)
Definition: sqlite3.c:24170
#define SQLITE_MAGIC_BUSY
Definition: sqlite3.c:14122
int nVdbeRead
Definition: sqlite3.c:13942
void * pSchema
Definition: sqlite3.c:57687
Btree * pBtree
Definition: sqlite3.c:57755
#define Deephemeralize(P)
Definition: sqlite3.c:77391
u16 nColumn
Definition: sqlite3.c:14720
static int nocaseCollatingFunc(void *NotUsed, int nKey1, const void *pKey1, int nKey2, const void *pKey2)
Definition: sqlite3.c:138746
LogEst rUnsorted
Definition: sqlite3.c:123999
#define PragTyp_TEMP_STORE_DIRECTORY
Definition: sqlite3.c:111144
#define SQLITE_EXTENSION_INIT2(v)
Definition: sqlite3.c:110293
struct KeyInfo KeyInfo
Definition: sqlite3.c:11985
int tnum
Definition: sqlite3.c:14717
Hash fkeyHash
Definition: sqlite3.c:13767
u8 enc
Definition: sqlite3.c:17881
SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *, int)
Definition: sqlite3.c:75006
#define yytestcase(X)
Definition: sqlite3.c:132851
static void schemaIsValid(Parse *pParse)
Definition: sqlite3.c:113953
int nTotalChange
Definition: sqlite3.c:13931
#define TERM_VNULL
Definition: sqlite3.c:124088
SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *, int, char)
Definition: sqlite3.c:25518
SQLITE_API double sqlite3_value_double(sqlite3_value *)
Definition: sqlite3.c:75305
SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *)
Definition: sqlite3.c:123428
SQLITE_PRIVATE SrcList * sqlite3SrcListDup(sqlite3 *, SrcList *, int)
Definition: sqlite3.c:91061
#define WHERE_COLUMN_RANGE
Definition: sqlite3.c:124342
#define SQLITE_READONLY_RECOVERY
Definition: sqlite3.c:761
u32 nPage
Definition: sqlite3.c:57686
SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *, Expr *, int, int)
Definition: sqlite3.c:93925
#define OP_IncrVacuum
Definition: sqlite3.c:12631
#define sqlite3FileSuffix3(X, Y)
Definition: sqlite3.c:16566
#define SQLITE_MAX_LENGTH
Definition: sqlite3.c:10669
struct WhereLoop::@15::@16 btree
#define PragTyp_FOREIGN_KEY_LIST
Definition: sqlite3.c:111125
int idxNum
Definition: sqlite3.c:123938
#define BTREE_SAVEPOSITION
Definition: sqlite3.c:12273
#define pagerUseWal(x)
Definition: sqlite3.c:47188
SQLITE_PRIVATE void sqlite3ParserReset(Parse *)
Definition: sqlite3.c:114030
#define sqliteHashNext(E)
Definition: sqlite3.c:11276
static void yy_destructor(yyParser *yypParser, YYCODETYPE yymajor, YYMINORTYPE *yypminor)
Definition: sqlite3.c:134352
unixShm * pFirst
Definition: sqlite3.c:33422
#define SQLITE_DETERMINISTIC
Definition: sqlite3.c:4771
#define P5_ConstraintFK
Definition: sqlite3.c:12525
#define PAGER_WRITER_CACHEMOD
Definition: sqlite3.c:46719
TableLock * aTableLock
Definition: sqlite3.c:15556
static int xferCompatibleIndex(Index *pDest, Index *pSrc)
Definition: sqlite3.c:109198
Index * pIndex
Definition: sqlite3.c:14438
const unsigned char * b
Definition: sqlite3.c:10101
#define OP_Or
Definition: sqlite3.c:12589
#define SQLITE_STATUS_SCRATCH_OVERFLOW
Definition: sqlite3.c:7118
static const char aPrefix[]
Definition: sqlite3.c:24782
sqlite3 * db
Definition: sqlite3.c:57664
SQLITE_PRIVATE void sqlite3PcacheClear(PCache *)
Definition: sqlite3.c:44262
#define SF_Compound
Definition: sqlite3.c:15323
FKey * pFKey
Definition: sqlite3.c:14440
SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76137
SQLITE_PRIVATE void sqlite3StatusDown(int, int)
Definition: sqlite3.c:18321
#define OP_Null
Definition: sqlite3.c:12641
Expr * pOffset
Definition: sqlite3.c:132871
#define PragTyp_INDEX_INFO
Definition: sqlite3.c:111127
static int exprSrcCount(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:94411
#define LOCATE_VIEW
Definition: sqlite3.c:16349
u8 * aMemory
Definition: sqlite3.c:85030
SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76132
#define SRT_Set
Definition: sqlite3.c:15413
#define SQLITE_LIMIT_COLUMN
Definition: sqlite3.c:3675
SQLITE_PRIVATE Table * sqlite3ResultSetOfSelect(Parse *, Select *)
Definition: sqlite3.c:116146
static const struct compareInfo likeInfoNorm
Definition: sqlite3.c:104710
etByte prefix
Definition: sqlite3.c:24766
SQLITE_PRIVATE Expr * sqlite3PExpr(Parse *, int, Expr *, Expr *, const Token *)
Definition: sqlite3.c:90547
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse *, Table *, int, int, int *, int)
Definition: sqlite3.c:103985
sqlite3_vfs * pNext
Definition: sqlite3.c:1490
struct ExprList::ExprList_item::@5::@6 x
#define BTREE_SCHEMA_VERSION
Definition: sqlite3.c:12165
static int walIteratorInit(Wal *pWal, WalIterator **pp)
Definition: sqlite3.c:55339
SQLITE_PRIVATE int sqlite3WalDefaultHook(void *, sqlite3 *, const char *, int)
Definition: sqlite3.c:139841
char validYMD
Definition: sqlite3.c:18648
static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName)
Definition: sqlite3.c:95079
static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p)
Definition: sqlite3.c:57984
union WhereLevel::@13 u
u16 maskPage
Definition: sqlite3.c:57538
SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *)
Definition: sqlite3.c:68706
SQLITE_PRIVATE void sqlite3AuthRead(Parse *, Expr *, Schema *, SrcList *)
Definition: sqlite3.c:98179
#define SQLITE_OPEN_TEMP_JOURNAL
Definition: sqlite3.c:801
#define SQLITE_OPEN_DELETEONCLOSE
Definition: sqlite3.c:792
i64 mxWalSize
Definition: sqlite3.c:54215
With * pOuter
Definition: sqlite3.c:15945
int(* xTrace)(u32, void *, void *, void *)
Definition: sqlite3.c:13948
SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *, int, int)
Definition: sqlite3.c:102379
static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage)
Definition: sqlite3.c:101051
static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p)
Definition: sqlite3.c:71277
#define MemSetTypeFlag(p, f)
Definition: sqlite3.c:17954
static int balance_nonroot(MemPage *pParent, int iParentIdx, u8 *aOvflSpace, int isRoot, int bBulk)
Definition: sqlite3.c:65220
SQLITE_API int sqlite3_create_function_v2(sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void(*xFunc)(sqlite3_context *, int, sqlite3_value **), void(*xStep)(sqlite3_context *, int, sqlite3_value **), void(*xFinal)(sqlite3_context *), void(*xDestroy)(void *))
Definition: sqlite3.c:139548
SQLITE_PRIVATE int sqlite3RunParser(Parse *, const char *, char **)
Definition: sqlite3.c:137334
static int hasHotJournal(Pager *pPager, int *pExists)
Definition: sqlite3.c:51279
ExprList * pEList
Definition: sqlite3.c:15239
int iSavepoint
Definition: sqlite3.c:14427
#define CC_DOLLAR
Definition: sqlite3.c:136602
#define vdbeSorterExtendFile(x, y, z)
Definition: sqlite3.c:86135
static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize)
Definition: sqlite3.c:59819
SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *, int)
Definition: sqlite3.c:70846
#define SQLITE_DBSTATUS_LOOKASIDE_USED
Definition: sqlite3.c:7252
int nThis
Definition: sqlite3.c:94404
#define OP_Checkpoint
Definition: sqlite3.c:12570
sqlite3 * db
Definition: sqlite3.c:96971
#define PARSE_TAIL_SZ
Definition: sqlite3.c:15629
bft readOnly
Definition: sqlite3.c:18075
static int indexColumnNotNull(Index *pIdx, int iCol)
Definition: sqlite3.c:128239
#define CC_QUOTE
Definition: sqlite3.c:136606
static int isSetNullAction(Parse *pParse, FKey *pFKey)
Definition: sqlite3.c:106787
static int vdbeMergeEngineStep(MergeEngine *pMerger, int *pbEof)
Definition: sqlite3.c:86459
SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault)
Definition: sqlite3.c:141738
SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *, void *, int amt, i64 offset)
Definition: sqlite3.c:19830
SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *)
Definition: sqlite3.c:62094
#define OSTRACE(X)
Definition: sqlite3.c:11148
#define pager_set_pagehash(X)
Definition: sqlite3.c:47583
SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag)
Definition: sqlite3.c:18381
int(* xCreateFunction)(fts5_api *pApi, const char *zName, void *pContext, fts5_extension_function xFunction, void(*xDestroy)(void *))
Definition: sqlite3.c:10612
static const char statMutex[]
Definition: sqlite3.c:18258
#define SQLITE_EnableTrigger
Definition: sqlite3.c:14068
SQLITE_API SQLITE_DEPRECATED void * sqlite3_profile(sqlite3 *, void(*xProfile)(void *, const char *, sqlite3_uint64), void *)
Definition: sqlite3.c:139714
static int growVTrans(sqlite3 *db)
Definition: sqlite3.c:123200
void sqliteViewTriggers(Parse *, Table *, Expr *, int, ExprList *)
unsigned int yDbMask
Definition: sqlite3.c:15491
int(* xInst)(Fts5Context *, int iIdx, int *piPhrase, int *piCol, int *piOff)
Definition: sqlite3.c:10338
struct sqlite3_index_info::sqlite3_index_orderby * aOrderBy
int(* xCreateTokenizer)(fts5_api *pApi, const char *zName, void *pContext, fts5_tokenizer *pTokenizer, void(*xDestroy)(void *))
Definition: sqlite3.c:10595
SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse *, Expr *)
Definition: sqlite3.c:99645
#define TK_INTEGER
Definition: sqlite3.c:11425
int aLimit[SQLITE_N_LIMIT]
Definition: sqlite3.c:13932
#define SQLITE_IOERR_WRITE
Definition: sqlite3.c:727
#define ExprHasProperty(E, P)
Definition: sqlite3.c:14989
static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2)
Definition: sqlite3.c:31404
#define SQLITE_FUNC_EPHEM
Definition: sqlite3.c:14186
int nOvflAlloc
Definition: sqlite3.c:57763
Trigger * pTrig
Definition: sqlite3.c:15762
ExprList * pOrderBy
Definition: sqlite3.c:114440
#define TK_SEMI
Definition: sqlite3.c:11292
static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p)
Definition: sqlite3.c:75178
static int pagerFlushOnCommit(Pager *pPager, int bCommit)
Definition: sqlite3.c:48260
SQLITE_PRIVATE Vdbe * sqlite3GetVdbe(Parse *)
Definition: sqlite3.c:116192
int(* xTokenize)(Fts5Context *, const char *pText, int nText, void *pCtx, int(*xToken)(void *, int, const char *, int, int, int))
Definition: sqlite3.c:10328
#define OP_VOpen
Definition: sqlite3.c:12717
static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd)
Definition: sqlite3.c:132921
SQLITE_API const void * sqlite3_column_decltype16(sqlite3_stmt *, int)
Definition: sqlite3.c:76272
void(* xDestroy)(void *)
Definition: sqlite3.c:14166
static int exprAlwaysFalse(Expr *p)
Definition: sqlite3.c:90604
#define WRC_Prune
Definition: sqlite3.c:15936
static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock)
Definition: sqlite3.c:58490
u8 p5
Definition: sqlite3.c:12436
static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno)
Definition: sqlite3.c:59221
i64 iCurrentTime
Definition: sqlite3.c:18042
#define SQLITE_ECEL_FACTOR
Definition: sqlite3.c:16343
SQLITE_PRIVATE void sqlite3AddCollateType(Parse *, Token *)
Definition: sqlite3.c:99670
#define osGetpagesize
static void vdbePmaReaderClear(PmaReader *pReadr)
Definition: sqlite3.c:85311
static UnixUnusedFd * findReusableFd(const char *zPath, int flags)
Definition: sqlite3.c:34874
static int whereShortCut(WhereLoopBuilder *pBuilder)
Definition: sqlite3.c:132005
SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void)
Definition: sqlite3.c:67937
PgHdr * pDirtyPrev
Definition: sqlite3.c:13203
Parse * pParse
Definition: sqlite3.c:15647
u16 nXField
Definition: sqlite3.c:14618
#define SQLITE_BIG_DBL
Definition: sqlite3.c:11488
SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *, Trigger *)
Definition: sqlite3.c:120732
#define SQLITE_DBCONFIG_MAINDBNAME
Definition: sqlite3.c:2252
#define SQLITE_FCNTL_POWERSAFE_OVERWRITE
Definition: sqlite3.c:1282
#define WHERE_ORDERBY_MAX
Definition: sqlite3.c:15191
Btree * pBtree
Definition: sqlite3.c:57568
#define SQLITE_CONFIG_SCRATCH
Definition: sqlite3.c:2133
#define DB_Empty
Definition: sqlite3.c:13796
ynVar nzVar
Definition: sqlite3.c:18033
SQLITE_PRIVATE void * sqlite3Realloc(void *, u64)
Definition: sqlite3.c:24379
#define sqlite3VdbeIOTraceSql(X)
Definition: sqlite3.c:16868
static int getAutoVacuum(const char *z)
Definition: sqlite3.c:111638
u8 bConstraint
Definition: sqlite3.c:14426
SQLITE_API int sqlite3_rtree_geometry_callback(sqlite3 *db, const char *zGeom, int(*xGeom)(sqlite3_rtree_geometry *, int, sqlite3_rtree_dbl *, int *), void *pContext)
SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *)
Definition: sqlite3.c:68980
static int moveToLeftmost(BtCursor *pCur)
Definition: sqlite3.c:63164
u8 op2
Definition: sqlite3.c:14945
static int blobReadWrite(sqlite3_blob *pBlob, void *z, int n, int iOffset, int(*xCall)(BtCursor *, u32, u32, void *))
Definition: sqlite3.c:84704
#define WALINDEX_PGSZ
Definition: sqlite3.c:54309
SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff)
Definition: sqlite3.c:110893
static int analyzeAggregate(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:94491
SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *)
Definition: sqlite3.c:71351
Pgno * aOverflow
Definition: sqlite3.c:57758
#define OP_ElseNotEq
Definition: sqlite3.c:12604
SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *, int)
Definition: sqlite3.c:60990
SQLITE_PRIVATE char * sqlite3StrAccumFinish(StrAccum *)
Definition: sqlite3.c:25575
char * zName
Definition: sqlite3.c:15698
SQLITE_PRIVATE int sqlite3PagerRollback(Pager *)
Definition: sqlite3.c:52794
static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N)
Definition: sqlite3.c:25535
SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *)
Definition: sqlite3.c:60210
u32 nRef
Definition: sqlite3.c:14615
static int unixShmMap(sqlite3_file *fd, int iRegion, int szRegion, int bExtend, void volatile **pp)
Definition: sqlite3.c:33766
int szExtra
Definition: sqlite3.c:44609
SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse *, Select *, NameContext *)
Definition: sqlite3.c:89677
u8 isDeferred
Definition: sqlite3.c:14556
static int decodeFlags(MemPage *pPage, int flagByte)
Definition: sqlite3.c:59921
int seekResult
Definition: sqlite3.c:17786
static void setPendingFd(unixFile *pFile)
Definition: sqlite3.c:31111
static int pagerOpenWal(Pager *pPager)
Definition: sqlite3.c:53614
static void walIndexClose(Wal *pWal, int isDelete)
Definition: sqlite3.c:55035
static void yy_pop_parser_stack(yyParser *pParser)
Definition: sqlite3.c:134454
SQLITE_PRIVATE void sqlite3WalLimit(Wal *, i64)
Definition: sqlite3.c:55136
static const struct compareInfo likeInfoAlt
Definition: sqlite3.c:104713
SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *, int *pRes)
Definition: sqlite3.c:63235
#define TK_EXCLUSIVE
Definition: sqlite3.c:11300
#define OP_SeekGE
Definition: sqlite3.c:12587
SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *)
Definition: sqlite3.c:53548
int iOffset
Definition: sqlite3.c:84362
SQLITE_PRIVATE sqlite3_value * sqlite3VdbeGetBoundValue(Vdbe *, int, u8)
Definition: sqlite3.c:74985
static void pagerFreeMapHdrs(Pager *pPager)
Definition: sqlite3.c:50366
SQLITE_API void * sqlite3_user_data(sqlite3_context *)
Definition: sqlite3.c:75818
#define WO_NOOP
Definition: sqlite3.c:124331
SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset)
Definition: sqlite3.c:84777
#define BTREE_WRCSR
Definition: sqlite3.c:12243
SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void))
Definition: sqlite3.c:110986
#define likely(X)
Definition: sqlite3.c:11186
#define OP_VNext
Definition: sqlite3.c:12632
#define TK_THEN
Definition: sqlite3.c:11429
static SQLITE_NOINLINE void vdbeLeave(Vdbe *p)
Definition: sqlite3.c:71892
#define WHERE_BTM_LIMIT
Definition: sqlite3.c:124347
static u16 cellSizePtr(MemPage *pPage, u8 *pCell)
Definition: sqlite3.c:59467
#define TK_EQ
Definition: sqlite3.c:11328
SQLITE_PRIVATE int sqlite3GetTempRange(Parse *, int)
Definition: sqlite3.c:94692
u32 usableSize
Definition: sqlite3.c:57684
#define WRITE_UTF16LE(zOut, c)
Definition: sqlite3.c:26823
static int isDistinctRedundant(Parse *pParse, SrcList *pTabList, WhereClause *pWC, ExprList *pDistinct)
Definition: sqlite3.c:128262
static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p)
Definition: sqlite3.c:118328
#define CC_SEMI
Definition: sqlite3.c:136617
Wal * pWal
Definition: sqlite3.c:47070
#define OP_ReopenIdx
Definition: sqlite3.c:12665
#define CORRUPT_DB
Definition: sqlite3.c:15899
i16 * aiColumn
Definition: sqlite3.c:14707
static int vdbeIncrBgPopulate(IncrMerger *pIncr)
Definition: sqlite3.c:86771
i64 journalSizeLimit
Definition: sqlite3.c:47051
#define TK_CREATE
Definition: sqlite3.c:11308
int nBuffer
Definition: sqlite3.c:85201
static int walWriteToLog(WalWriter *p, void *pContent, int iAmt, sqlite3_int64 iOffset)
Definition: sqlite3.c:56631
int(* xClose)(sqlite3_vtab_cursor *)
Definition: sqlite3.c:6070
#define SQLITE_OPEN_TEMP_DB
Definition: sqlite3.c:798
static CollSeq * findCollSeqEntry(sqlite3 *db, const char *zName, int create)
Definition: sqlite3.c:102879
#define sqlite3_column_origin_name
Definition: sqlite3.c:110315
SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *, Select *)
Definition: sqlite3.c:88120
static int noopMutexEnd(void)
Definition: sqlite3.c:22622
SQLITE_PRIVATE sqlite3_mutex_methods const * sqlite3DefaultMutex(void)
Definition: sqlite3.c:23167
static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow)
Definition: sqlite3.c:35639
static void generateSortTail(Parse *pParse, Select *p, SortCtx *pSort, int nColumn, SelectDest *pDest)
Definition: sqlite3.c:115576
#define OP_Concat
Definition: sqlite3.c:12614
int nChange
Definition: sqlite3.c:13930
SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *, int)
Definition: sqlite3.c:60810
SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt)
Definition: sqlite3.c:67930
#define OP_Goto
Definition: sqlite3.c:12575
u16 nResColumn
Definition: sqlite3.c:18066
SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *, int)
Definition: sqlite3.c:61378
#define TK_AGG_FUNCTION
Definition: sqlite3.c:11444
#define SQLITE_CellSizeCk
Definition: sqlite3.c:14073
SQLITE_PRIVATE void sqlite3MayAbort(Parse *)
Definition: sqlite3.c:102414
SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt *)
Definition: sqlite3.c:75145
char * zErrMsg
Definition: sqlite3.c:18055
static int pcache1Pagecount(sqlite3_pcache *p)
Definition: sqlite3.c:45286
#define SQLITE_ABORT_ROLLBACK
Definition: sqlite3.c:765
static void setSectorSize(Pager *pPager)
Definition: sqlite3.c:49001
#define SQLITE_UTF16
Definition: sqlite3.c:4759
static KeyInfo * multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra)
Definition: sqlite3.c:116302
int nzVar
Definition: sqlite3.c:15596
#define SORTER_TYPE_INTEGER
Definition: sqlite3.c:85180
#define MEM_Dyn
Definition: sqlite3.c:17934
#define SQLITE_CONFIG_HEAP
Definition: sqlite3.c:2135
static int btreeRestoreCursorPosition(BtCursor *pCur)
Definition: sqlite3.c:59040
TriggerStep * pNext
Definition: sqlite3.c:15768
#define MIN(A, B)
Definition: sqlite3.c:11572
#define BTREE_DEFAULT_CACHE_SIZE
Definition: sqlite3.c:12167
#define SQLITE_CONSTRAINT_UNIQUE
Definition: sqlite3.c:773
#define ExpandBlob(P)
Definition: sqlite3.c:18229
int nFrame
Definition: sqlite3.c:18085
void(* xReiniter)(DbPage *)
Definition: sqlite3.c:47060
#define BTREE_AUTOVACUUM_NONE
Definition: sqlite3.c:12052
int iOnceResetThreshold
Definition: sqlite3.c:15880
u16 nLocal
Definition: sqlite3.c:57720
u16 nLTerm
Definition: sqlite3.c:123946
SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *, Expr *, int, int)
Definition: sqlite3.c:94048
u8 extraSync
Definition: sqlite3.c:46992
#define enable_simulated_io_errors()
Definition: sqlite3.c:50129
u32 tRowcnt
Definition: sqlite3.c:11663
#define OP_Integer
Definition: sqlite3.c:12638
SQLITE_API const char * sqlite3_libversion(void)
Definition: sqlite3.c:137895
#define SF_FixedLimit
Definition: sqlite3.c:15329
u8 * aRecord
Definition: sqlite3.c:18113
SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *)
Definition: sqlite3.c:139332
SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *)
Definition: sqlite3.c:43456
#define TERM_LIKE
Definition: sqlite3.c:124092
int sortingIdx
Definition: sqlite3.c:14801
int mxSample
Definition: sqlite3.c:95849
static void convertToWithoutRowidTable(Parse *pParse, Table *pTab)
Definition: sqlite3.c:99971
static int pager_incr_changecounter(Pager *pPager, int isDirectMode)
Definition: sqlite3.c:52400
static const struct sPragmaNames aPragmaNames[]
#define SQLITE_JUMPIFNULL
Definition: sqlite3.c:14374
unsigned char iEquiv
Definition: sqlite3.c:124106
#define ROUNDDOWN8(x)
Definition: sqlite3.c:11780
SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *, const char *)
Definition: sqlite3.c:25565
static int whereOrInsert(WhereOrSet *pSet, Bitmask prereq, LogEst rRun, LogEst nOut)
Definition: sqlite3.c:127953
Trigger * pTrigger
Definition: sqlite3.c:14463
static void sqlite3ExprCodeIN(Parse *pParse, Expr *pExpr, int destIfFalse, int destIfNull)
Definition: sqlite3.c:92402
#define SQLITE_PERM
Definition: sqlite3.c:678
void(* fts5_extension_function)(const Fts5ExtensionApi *pApi, Fts5Context *pFts, sqlite3_context *pCtx, int nVal, sqlite3_value **apVal)
Definition: sqlite3.c:10091
SQLITE_PRIVATE void sqlite3SelectPrep(Parse *, Select *, NameContext *)
Definition: sqlite3.c:118996
INT16_TYPE LogEst
Definition: sqlite3.c:11689
u8 ** apCell
Definition: sqlite3.c:64638
SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext *, ExprList *)
Definition: sqlite3.c:89652
SQLITE_PRIVATE CollSeq * sqlite3LocateCollSeq(Parse *pParse, const char *zName)
Definition: sqlite3.c:99722
SQLITE_API int sqlite3_busy_timeout(sqlite3 *, int ms)
Definition: sqlite3.c:139402
static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp)
Definition: sqlite3.c:34242
void(* xSFunc)(sqlite3_context *, int, sqlite3_value **)
Definition: sqlite3.c:14141
pthread_mutex_t mutex
Definition: sqlite3.c:22843
SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *, u32 offset, u32 amt, void *)
Definition: sqlite3.c:62914
#define MX_CELL_SIZE(pBt)
Definition: sqlite3.c:57471
u8 tr_tm
Definition: sqlite3.c:15701
#define TK_WITH
Definition: sqlite3.c:11383
#define OP_IfNot
Definition: sqlite3.c:12584
#define putVarint
Definition: sqlite3.c:16526
#define osAccess
SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *, SrcList *)
Definition: sqlite3.c:94440
#define P4_STATIC
Definition: sqlite3.c:12503
static int vdbeSorterCompareInt(SortSubtask *pTask, int *pbKey2Cached, const void *pKey1, int nKey1, const void *pKey2, int nKey2)
Definition: sqlite3.c:85686
SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *)
Definition: sqlite3.c:85769
static int saveCursorPosition(BtCursor *pCur)
Definition: sqlite3.c:58899
HashElem * next
Definition: sqlite3.c:11250
SQLITE_PRIVATE CollSeq * sqlite3GetCollSeq(Parse *, u8, CollSeq *, const char *)
Definition: sqlite3.c:102810
#define PAGER_SYNCHRONOUS_MASK
Definition: sqlite3.c:13020
SQLITE_API sqlite3_uint64 sqlite3_msize(void *)
Definition: sqlite3.c:24313
#define TK_SAVEPOINT
Definition: sqlite3.c:11304
static void whereLoopInit(WhereLoop *p)
Definition: sqlite3.c:129587
void * pScratchEnd
Definition: sqlite3.c:23940
With * pWithToFree
Definition: sqlite3.c:15621
static int parseHhMmSs(const char *zDate, DateTime *p)
Definition: sqlite3.c:18773
static void samplePushPrevious(Stat4Accum *p, int iChng)
Definition: sqlite3.c:96202
#define pcacheDump(X)
Definition: sqlite3.c:43673
#define SQLITE_LIMIT_COMPOUND_SELECT
Definition: sqlite3.c:3677
static void sourceidFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:105002
#define OPFLAG_P2ISREG
Definition: sqlite3.c:15677
void * pWalArg
Definition: sqlite3.c:13967
Select * pNext
Definition: sqlite3.c:15300
SQLITE_API char * sqlite3_snprintf(int, char *, const char *,...)
Definition: sqlite3.c:25728
#define TK_LIMIT
Definition: sqlite3.c:11420
static int unixTruncate(sqlite3_file *id, i64 nByte)
Definition: sqlite3.c:32980
int labelDone
Definition: sqlite3.c:114446
static unixInodeInfo * inodeList
Definition: sqlite3.c:30484
#define SQLITE_FCNTL_PERSIST_WAL
Definition: sqlite3.c:1279
def go()
SQLITE_PRIVATE void * sqlite3ArrayAllocate(sqlite3 *, void *, int, int *, int *)
Definition: sqlite3.c:101846
sqlite3_stmt * pStmt
Definition: sqlite3.c:84365
struct Fts5Tokenizer Fts5Tokenizer
Definition: sqlite3.c:10553
#define SQLITE_FUNC_ENCMASK
Definition: sqlite3.c:14183
SQLITE_PRIVATE int sqlite3MutexInit(void)
Definition: sqlite3.c:22443
u8 declareVtab
Definition: sqlite3.c:15600
SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2)
Definition: sqlite3.c:89925
static void sumFinalize(sqlite3_context *context)
Definition: sqlite3.c:105591
static int multiSelectOrderBy(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:117178
static sqlite3_index_info * allocateIndexInfo(Parse *pParse, WhereClause *pWC, Bitmask mUnusable, struct SrcList_item *pSrc, ExprList *pOrderBy, u16 *pmNoOmit)
Definition: sqlite3.c:128650
u8 mallocFailed
Definition: sqlite3.c:13920
static int pagerExclusiveLock(Pager *pPager)
Definition: sqlite3.c:53594
#define tkOTHER
Definition: sqlite3.c:137508
#define etSTRING
Definition: sqlite3.c:24734
Expr * pExpr
Definition: sqlite3.c:124056
#define OE_SetDflt
Definition: sqlite3.c:14599
SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void))
Definition: sqlite3.c:110939
#define PAGER_FLAGS_MASK
Definition: sqlite3.c:13024
SQLITE_API void sqlite3_progress_handler(sqlite3 *, int, int(*)(void *), void *)
Definition: sqlite3.c:139371
#define SQLITE_MAX_U32
Definition: sqlite3.c:11652
i64 startTime
Definition: sqlite3.c:18060
void(* xUpdateCallback)(void *, int, const char *, const char *, sqlite_int64)
Definition: sqlite3.c:13957
int * pnBytesFreed
Definition: sqlite3.c:14004
#define TK_UPLUS
Definition: sqlite3.c:11447
struct ExprList::ExprList_item * a
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo)
Definition: sqlite3.c:94458
static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size)
Definition: sqlite3.c:87868
#define PragTyp_SOFT_HEAP_LIMIT
Definition: sqlite3.c:111139
VdbeSorter * pSorter
Definition: sqlite3.c:85140
sqlite3_value * argv[1]
Definition: sqlite3.c:18003
static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey)
Definition: sqlite3.c:74368
#define SQLITE_IDXTYPE_APPDEF
Definition: sqlite3.c:14741
#define USEFETCH(x)
Definition: sqlite3.c:47158
#define OP_RowKey
Definition: sqlite3.c:12683
#define SQLITE_STMTJRNL_SPILL
Definition: sqlite3.c:17102
SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot *)
SQLITE_PRIVATE int sqlite3HeaderSizePcache(void)
Definition: sqlite3.c:44425
u8 op
Definition: sqlite3.c:15286
int(* xWalCallback)(void *, sqlite3 *, const char *, int)
Definition: sqlite3.c:13966
SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N)
Definition: sqlite3.c:23982
i64 iEof
Definition: sqlite3.c:85194
static SQLITE_WSD struct BenignMallocHooks sqlite3Hooks
SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *, int)
Definition: sqlite3.c:49783
static int setDestPgsz(sqlite3_backup *p)
Definition: sqlite3.c:68072
u8 colNamesSet
Definition: sqlite3.c:15520
u8 noSync
Definition: sqlite3.c:46990
void * pStart
Definition: sqlite3.c:44653
#define sqlite3Isxdigit(x)
Definition: sqlite3.c:16035
#define SORTER_TYPE_TEXT
Definition: sqlite3.c:85181
#define WHERE_ORDERBY_LIMIT
Definition: sqlite3.c:15202
char * zName
Definition: sqlite3.c:18018
#define ROUND8(x)
Definition: sqlite3.c:11775
#define WAL_RDONLY
Definition: sqlite3.c:54253
SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32)
Definition: sqlite3.c:73679
u8 isTransactionSavepoint
Definition: sqlite3.c:13926
#define P5_ConstraintNotNull
Definition: sqlite3.c:12522
SQLITE_PRIVATE VTable * sqlite3GetVTable(sqlite3 *, Table *)
Definition: sqlite3.c:122684
static const char hexdigits[]
Definition: sqlite3.c:105076
LogEst nRowOut
Definition: sqlite3.c:124239
#define TIMER_END
Definition: sqlite3.c:29610
#define WAL_MAGIC
Definition: sqlite3.c:54195
static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val)
Definition: sqlite3.c:69443
FileChunk * pFirst
Definition: sqlite3.c:87674
static void addToVTrans(sqlite3 *db, VTable *pVTab)
Definition: sqlite3.c:123222
#define OP_Delete
Definition: sqlite3.c:12679
#define SQLITE_IOERR_CHECKRESERVEDLOCK
Definition: sqlite3.c:738
SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst, LogEst)
Definition: sqlite3.c:28645
static int binCollFunc(void *padFlag, int nKey1, const void *pKey1, int nKey2, const void *pKey2)
Definition: sqlite3.c:138709
u32 nColumn
Definition: sqlite3.c:120099
#define SQLITE_DBSTATUS_CACHE_USED_SHARED
Definition: sqlite3.c:7263
#define SQLITE_TESTCTRL_PRNG_RESTORE
Definition: sqlite3.c:6973
SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *)
Definition: sqlite3.c:114002
i64 iKey1
Definition: sqlite3.c:18118
#define PTF_ZERODATA
Definition: sqlite3.c:57506
static int walCheckpoint(Wal *pWal, int eMode, int(*xBusy)(void *), void *pBusyArg, int sync_flags, u8 *zBuf)
Definition: sqlite3.c:55507
#define SQLITE_OPEN_CREATE
Definition: sqlite3.c:791
#define SQLITE_LegacyFileFmt
Definition: sqlite3.c:14059
SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *, int, int)
Definition: sqlite3.c:114477
#define TF_Ephemeral
Definition: sqlite3.c:14478
#define READMARK_NOT_USED
Definition: sqlite3.c:54168
#define PragTyp_AUTO_VACUUM
Definition: sqlite3.c:111112
int nTableLock
Definition: sqlite3.c:15555
RowSet * pRowSet
Definition: sqlite3.c:17877
int(* xSync)(sqlite3_file *, int flags)
Definition: sqlite3.c:1011
static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng
Definition: sqlite3.c:26444
static struct RowSetEntry * rowSetEntrySort(struct RowSetEntry *pIn)
Definition: sqlite3.c:45986
#define PragTyp_SHRINK_MEMORY
Definition: sqlite3.c:111138
SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int)
Definition: sqlite3.c:19904
SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *)
Definition: sqlite3.c:59079
#define OP_Halt
Definition: sqlite3.c:12637
union VdbeOp::p4union p4
#define WRITE_LOCK
Definition: sqlite3.c:57576
#define OPFLAG_SEEKEQ
Definition: sqlite3.c:15675
SQLITE_PRIVATE int sqlite3AbsInt32(int)
Definition: sqlite3.c:28602
static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate)
Definition: sqlite3.c:129739
static int addToSavepointBitvecs(Pager *pPager, Pgno pgno)
Definition: sqlite3.c:48098
#define SQLITE_OPEN_MEMORY
Definition: sqlite3.c:796
#define OP_VColumn
Definition: sqlite3.c:12718
SQLITE_PRIVATE Index * sqlite3FindIndex(sqlite3 *, const char *, const char *)
Definition: sqlite3.c:98709
#define FTS5_TOKEN_COLOCATED
Definition: sqlite3.c:10581
sqlite3ParserTOKENTYPE yy0
Definition: sqlite3.c:133099
#define CC_PIPE
Definition: sqlite3.c:136608
SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity)
Definition: sqlite3.c:89975
SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt *, int, const void *, sqlite3_uint64, void(*)(void *))
Definition: sqlite3.c:76435
SQLITE_API void sqlite3_result_text64(sqlite3_context *, const char *, sqlite3_uint64, void(*)(void *), unsigned char encoding)
Definition: sqlite3.c:75511
static void cdateFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:19647
int isMallocInit
Definition: sqlite3.c:15859
static int balance(BtCursor *pCur)
Definition: sqlite3.c:66041
#define SQLITE_LIMIT_LENGTH
Definition: sqlite3.c:3673
SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve)
Definition: sqlite3.c:68878
u8 * aAlloc
Definition: sqlite3.c:85198
static u32 pager_cksum(Pager *pPager, const u8 *aData)
Definition: sqlite3.c:48500
SQLITE_PRIVATE void * sqlite3MallocZero(u64)
Definition: sqlite3.c:24449
SQLITE_PRIVATE int sqlite3OsInit(void)
Definition: sqlite3.c:20058
VdbeFrame * pDelFrame
Definition: sqlite3.c:18084
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager *, const char *zMaster, int)
Definition: sqlite3.c:52551
static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo)
Definition: sqlite3.c:119021
static MergeEngine * vdbeMergeEngineNew(int nReader)
Definition: sqlite3.c:86015
TriggerPrg * pTriggerPrg
Definition: sqlite3.c:15619
struct FileChunk FileChunk
Definition: sqlite3.c:87631
static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg)
Definition: sqlite3.c:113669
SQLITE_API sqlite3_mutex * sqlite3_db_mutex(sqlite3 *)
Definition: sqlite3.c:138570
SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int *)
Definition: sqlite3.c:19942
SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *)
Definition: sqlite3.c:55705
SQLITE_PRIVATE void sqlite3Vacuum(Parse *, Token *)
Definition: sqlite3.c:122302
#define SQLITE_VdbeEQP
Definition: sqlite3.c:14071
#define CURSOR_SKIPNEXT
Definition: sqlite3.c:57823
#define SQLITE_BUSY
Definition: sqlite3.c:680
static int vdbeSorterCompareText(SortSubtask *pTask, int *pbKey2Cached, const void *pKey1, int nKey1, const void *pKey2, int nKey2)
Definition: sqlite3.c:85645
struct sqlite3_stmt sqlite3_stmt
Definition: sqlite3.c:3573
#define TK_CAST
Definition: sqlite3.c:11357
sqlite3_io_methods const * pMethod
Definition: sqlite3.c:29390
static int writeJournalHdr(Pager *pPager)
Definition: sqlite3.c:47749
Vdbe * pVdbe
Definition: sqlite3.c:15518
#define SQLITE_IOERR_CONVPATH
Definition: sqlite3.c:750
#define OptimizationEnabled(db, mask)
Definition: sqlite3.c:14102
#define SQLITE_UTF16NATIVE
Definition: sqlite3.c:11760
static void setOneColumnName(Vdbe *v, const char *z)
Definition: sqlite3.c:111720
#define IdChar(C)
Definition: sqlite3.c:137023
#define SQLITE_ECEL_REF
Definition: sqlite3.c:16344
#define SF_HasTypeInfo
Definition: sqlite3.c:15322
int nCell
Definition: sqlite3.c:64636
SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *, int *)
Definition: sqlite3.c:59096
Schema * pSchema
Definition: sqlite3.c:15705
#define SQLITE_INTEGRITY_CHECK_ERROR_MAX
SQLITE_PRIVATE void sqlite3EndTable(Parse *, Token *, Token *, u8, Select *)
Definition: sqlite3.c:100118
int nVdbeWrite
Definition: sqlite3.c:13943
#define SQLITE_CHECKPOINT_FULL
Definition: sqlite3.c:8170
SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *, int makeDflt)
Definition: sqlite3.c:20121
SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *, int)
Definition: sqlite3.c:60977
#define READ_UTF8(zIn, zTerm, c)
Definition: sqlite3.c:26894
SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat,...)
Definition: sqlite3.c:25764
SQLITE_PRIVATE Index * sqlite3AllocateIndexObject(sqlite3 *, i16, int, char **)
Definition: sqlite3.c:101138
struct Vdbe * pVdbe
Definition: sqlite3.c:13904
int(* xRename)(sqlite3_vtab *pVtab, const char *zNew)
Definition: sqlite3.c:6085
SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *)
Definition: sqlite3.c:52871
static int unixFileLock(unixFile *pFile, struct flock *pLock)
Definition: sqlite3.c:30834
#define PTRMAP_BTREE
Definition: sqlite3.c:57886
static void exprCommute(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:126503
SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse *, Table *, Trigger *, int, int, int, i16, u8, u8, u8, int)
Definition: sqlite3.c:103841
#define PragTyp_ACTIVATE_EXTENSIONS
Definition: sqlite3.c:111148
#define OP_Noop
Definition: sqlite3.c:12723
SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *)
Definition: sqlite3.c:52903
static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop, LogEst nRow)
Definition: sqlite3.c:129989
#define OP_Ge
Definition: sqlite3.c:12603
u8 isPinned
Definition: sqlite3.c:44553
SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *)
Definition: sqlite3.c:44082
#define vdbeInvokeSqllog(x)
Definition: sqlite3.c:73279
SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *, Expr *, Select *)
Definition: sqlite3.c:90572
#define EXPR_TOKENONLYSIZE
Definition: sqlite3.c:15011
static int invokeValueDestructor(const void *p, void(*xDel)(void *), sqlite3_context *pCtx)
Definition: sqlite3.c:75426
SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8)
Definition: sqlite3.c:77555
SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *, u8, u8)
Definition: sqlite3.c:69045
#define PAGER_SYNCHRONOUS_EXTRA
Definition: sqlite3.c:13019
SQLITE_API int sqlite3_value_bytes(sqlite3_value *)
Definition: sqlite3.c:75299
SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p)
Definition: sqlite3.c:69173
#define OP_OpenEphemeral
Definition: sqlite3.c:12669
SQLITE_API int sqlite3_complete(const char *sql)
Definition: sqlite3.c:137570
u8 aAction[2]
Definition: sqlite3.c:14557
#define TK_ESCAPE
Definition: sqlite3.c:11333
#define UpperToLower
Definition: sqlite3.c:27549
#define initMaskSet(P)
Definition: sqlite3.c:124190
#define SQLITE_MAX_SYMLINKS
Definition: sqlite3.c:29354
int iTable
Definition: sqlite3.c:14935
#define EXCLUSIVE_LOCK
Definition: sqlite3.c:13497
SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *)
Definition: sqlite3.c:99003
SQLITE_API const char * sqlite3_errmsg(sqlite3 *)
Definition: sqlite3.c:140061
#define SQLITE_TESTCTRL_BYTEORDER
Definition: sqlite3.c:6990
#define sqlite3VdbeScanStatus(a, b, c, d, e)
Definition: sqlite3.c:12909
static int nameInUsingClause(IdList *pUsing, const char *zCol)
Definition: sqlite3.c:88297
SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *, int *pRes)
Definition: sqlite3.c:63729
static void pcache1ResizeHash(PCache1 *p)
Definition: sqlite3.c:44973
#define TK_REPLACE
Definition: sqlite3.c:11376
ExprList * pExprList
Definition: sqlite3.c:15766
UINT32_TYPE u32
Definition: sqlite3.c:11640
#define SQLITE_CDECL
Definition: sqlite3.c:315
#define TK_CONCAT
Definition: sqlite3.c:11343
UnixUnusedFd * pNext
Definition: sqlite3.c:29381
static char * exprINAffinity(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:92045
static int codeCompare(Parse *pParse, Expr *pLeft, Expr *pRight, int opcode, int in1, int in2, int dest, int jumpIfNull)
Definition: sqlite3.c:90032
static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag)
Definition: sqlite3.c:45042
Definition: sqlite3.c:13736
int nearlyFull
Definition: sqlite3.c:23948
int iDb
Definition: sqlite3.c:15817
#define TERM_COPIED
Definition: sqlite3.c:124081
#define BTS_READ_ONLY
Definition: sqlite3.c:57703
static void * sqlite3MemMalloc(int nByte)
Definition: sqlite3.c:20438
#define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
Definition: sqlite3.c:10763
#define SQLITE_CountRows
Definition: sqlite3.c:14048
#define TK_ASC
Definition: sqlite3.c:11352
unsigned char bProcessLock
Definition: sqlite3.c:30465
Pager * pPager
Definition: sqlite3.c:13188
unsigned int mxPinned
Definition: sqlite3.c:44588
SQLITE_API int sqlite3_file_control(sqlite3 *, const char *zDbName, int op, void *)
Definition: sqlite3.c:141329
static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf)
Definition: sqlite3.c:35552
SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *, int, const char *,...)
Definition: sqlite3.c:27450
SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt)
Definition: sqlite3.c:76018
SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *)
Definition: sqlite3.c:69221
#define OPFLG_INITIALIZER
Definition: sqlite3.c:12736
SQLITE_PRIVATE int sqlite3Atoi(const char *)
Definition: sqlite3.c:28017
SQLITE_API sqlite3_backup * sqlite3_backup_init(sqlite3 *pDest, const char *zDestName, sqlite3 *pSource, const char *zSourceName)
Definition: sqlite3.c:68100
#define SQLITE_DBCONFIG_ENABLE_FKEY
Definition: sqlite3.c:2254
#define tkTRIGGER
Definition: sqlite3.c:137513
Expr * pLeft
Definition: sqlite3.c:14920
#define SQLITE_CONFIG_URI
Definition: sqlite3.c:2144
unsigned char eFileLock
Definition: sqlite3.c:30464
Hash aModule
Definition: sqlite3.c:13989
MemPage * apPage[BTCURSOR_MAX_DEPTH]
Definition: sqlite3.c:57778
static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p)
Definition: sqlite3.c:19155
static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc)
Definition: sqlite3.c:127941
void * pProfileArg
Definition: sqlite3.c:13951
SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *)
Definition: sqlite3.c:62541
struct PCache PCache
Definition: sqlite3.c:13177
#define TK_TRIGGER
Definition: sqlite3.c:11379
u32 cacheStatus
Definition: sqlite3.c:17804
#define VDBE_OFFSET_LINENO(x)
Definition: sqlite3.c:12903
static int memjrnlRead(sqlite3_file *pJfd, void *zBuf, int iAmt, sqlite_int64 iOfst)
Definition: sqlite3.c:87687
#define BTREE_UNORDERED
Definition: sqlite3.c:12083
#define OP_Column
Definition: sqlite3.c:12658
UnixUnusedFd * pUnused
Definition: sqlite3.c:30469
SQLITE_PRIVATE int sqlite3JoinType(Parse *, Token *, Token *, Token *)
Definition: sqlite3.c:114590
i8 iPage
Definition: sqlite3.c:57773
SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion)
Definition: sqlite3.c:67888
sqlite3 * db
Definition: sqlite3.c:95857
#define osFchmod
sqlite3_mutex * pInitMutex
Definition: sqlite3.c:15862
#define PragTyp_REKEY
Definition: sqlite3.c:111151
SQLITE_PRIVATE char * sqlite3DbStrDup(sqlite3 *, const char *)
Definition: sqlite3.c:24607
#define SQLITE_DBSTATUS_DEFERRED_FKS
Definition: sqlite3.c:7262
int separateCache
Definition: sqlite3.c:44648
static int subjournalPage(PgHdr *pPg)
Definition: sqlite3.c:50755
SQLITE_PRIVATE FuncDef * sqlite3FindFunction(sqlite3 *, const char *, int, u8, u8)
Definition: sqlite3.c:103074
#define SQLITE_STATUS_PARSER_STACK
Definition: sqlite3.c:7120
#define SQLITE_TESTCTRL_SCRATCHMALLOC
Definition: sqlite3.c:6984
static WhereTerm * whereScanNext(WhereScan *pScan)
Definition: sqlite3.c:128019
#define SQLITE_IOERR_DIR_FSYNC
Definition: sqlite3.c:729
LogEst rRun
Definition: sqlite3.c:123928
#define wsdHooksInit
Definition: sqlite3.c:20211
SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *, u32 offset, u32 amt, void *)
Definition: sqlite3.c:62897
unsigned uniqNotNull
Definition: sqlite3.c:14724
static int codeTriggerProgram(Parse *pParse, TriggerStep *pStepList, int orconf)
Definition: sqlite3.c:120946
static int pager_error(Pager *pPager, int rc)
Definition: sqlite3.c:48227
SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p)
Definition: sqlite3.c:60944
static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105088
int mxParserStack
Definition: sqlite3.c:15851
void ** aExtension
Definition: sqlite3.c:13947
static int sqlite3Prepare(sqlite3 *db, const char *zSql, int nBytes, int saveSqlFlag, Vdbe *pReprepare, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:114046
sqlite3_int64 szMmap
Definition: sqlite3.c:15843
LogEst nRow
Definition: sqlite3.c:123997
static char * whereTempTriggers(Parse *pParse, Table *pTab)
Definition: sqlite3.c:95045
#define OP_ReadCookie
Definition: sqlite3.c:12663
sqlite3_int64 iRowid
Definition: sqlite3.c:8744
SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr *, int iCur, Index *pIdx)
Definition: sqlite3.c:94379
#define YY_REDUCE_USE_DFLT
Definition: sqlite3.c:133573
Pgno pgnoRoot
Definition: sqlite3.c:57762
struct sqlite3_index_info::sqlite3_index_constraint_usage * aConstraintUsage
SQLITE_API int sqlite3_changes(sqlite3 *)
Definition: sqlite3.c:138776
void * pAppData
Definition: sqlite3.c:1492
static int whereLoopAddBtree(WhereLoopBuilder *pBuilder, Bitmask mPrereq)
Definition: sqlite3.c:130549
static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt)
Definition: sqlite3.c:55959
SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *)
Definition: sqlite3.c:102158
int(* xCheckReservedLock)(sqlite3_file *, int *pResOut)
Definition: sqlite3.c:1015
#define etPOINTER
Definition: sqlite3.c:24744
void(* xCollNeeded16)(void *, sqlite3 *, int eTextRep, const void *)
Definition: sqlite3.c:13970
SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *, u8 op)
Definition: sqlite3.c:71375
static SQLITE_NOINLINE Mem * out2PrereleaseWithClear(Mem *pOut)
Definition: sqlite3.c:77844
#define etSIZE
Definition: sqlite3.c:24733
#define SimulateIOError(A)
Definition: sqlite3.c:29650
SQLITE_API int sqlite3_step(sqlite3_stmt *)
Definition: sqlite3.c:75767
#define checkActiveVdbeCnt(x)
Definition: sqlite3.c:72925
#define OP_LoadAnalysis
Definition: sqlite3.c:12699
SQLITE_API int sqlite3_limit(sqlite3 *, int id, int newVal)
Definition: sqlite3.c:140309
#define OP_VBegin
Definition: sqlite3.c:12714
#define SQLITE_EXTENSION_INIT1
Definition: sqlite3.c:110292
Pgno dbHintSize
Definition: sqlite3.c:47021
SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *)
Definition: sqlite3.c:67943
struct RowSetEntry * pEntry
Definition: sqlite3.c:45825
static void autoIncStep(Parse *pParse, int memId, int regRowid)
Definition: sqlite3.c:107689
#define PAGER_JOURNALMODE_PERSIST
Definition: sqlite3.c:12996
SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *)
Definition: sqlite3.c:127868
sqlite3_mutex * mutex
Definition: sqlite3.c:44585
sqlite3_value * pErr
Definition: sqlite3.c:13972
#define SQLITE_OPEN_READWRITE
Definition: sqlite3.c:790
#define sqlite3MemdebugSetType(X, Y)
Definition: sqlite3.c:16904
int(* xMutexHeld)(sqlite3_mutex *)
Definition: sqlite3.c:6829
static SQLITE_NOINLINE int vdbeMemFromBtreeResize(BtCursor *pCur, u32 offset, u32 amt, int key, Mem *pMem)
Definition: sqlite3.c:69713
i64 nDeferredCons
Definition: sqlite3.c:14265
LogEst iLimit
Definition: sqlite3.c:124223
int neverCorrupt
Definition: sqlite3.c:15833
u8 doNotSpill
Definition: sqlite3.c:47014
SQLITE_PRIVATE void sqlite3FkDropTable(Parse *, SrcList *, Table *)
Definition: sqlite3.c:106670
i64 iWriteOff
Definition: sqlite3.c:85262
SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *, const char *, int)
Definition: sqlite3.c:25548
static const void * columnName(sqlite3_stmt *pStmt, int N, const void *(*xFunc)(Mem *), int useType)
Definition: sqlite3.c:76200
struct WhereLoop::@15::@17 vtab
#define OP_Insert
Definition: sqlite3.c:12677
SQLITE_API char * sqlite3_expanded_sql(sqlite3_stmt *pStmt)
Definition: sqlite3.c:76750
sqlite3_mutex * mutex
Definition: sqlite3.c:23931
SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *, Expr *, int)
Definition: sqlite3.c:93047
#define SQLITE_CONFIG_LOOKASIDE
Definition: sqlite3.c:2140
#define OP_Sequence
Definition: sqlite3.c:12675
static void dropCell(MemPage *pPage, int idx, int sz, int *pRC)
Definition: sqlite3.c:64488
Table * pTab
Definition: sqlite3.c:12454
#define SQLITE_CONSTRAINT
Definition: sqlite3.c:694
int iCur
Definition: sqlite3.c:15914
#define YY_SHIFT_COUNT
Definition: sqlite3.c:133522
AuxData * pAuxData
Definition: sqlite3.c:18088
static int findNextHostParameter(const char *zSql, int *pnToken)
Definition: sqlite3.c:77050
const char * zEnd
Definition: sqlite3.c:15063
static VdbeCursor * allocateCursor(Vdbe *p, int iCur, int nField, int iDb, u8 eCurType)
Definition: sqlite3.c:77402
SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *)
Definition: sqlite3.c:98852
#define SQLITE_FCNTL_JOURNAL_POINTER
Definition: sqlite3.c:1296
#define CC_X
Definition: sqlite3.c:136598
int nId
Definition: sqlite3.c:15086
#define MEM_Blob
Definition: sqlite3.c:17919
#define IN_INDEX_INDEX_DESC
Definition: sqlite3.c:16812
SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *)
Definition: sqlite3.c:73293
#define fdatasync
Definition: sqlite3.c:32758
#define SQLITE_FCNTL_VFSNAME
Definition: sqlite3.c:1281
#define SQLITE_PRINTF_INTERNAL
Definition: sqlite3.c:15803
static void checkList(IntegrityCk *pCheck, int isFreeList, int iPage, int N)
Definition: sqlite3.c:67161
SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *, u32 addr, int P2)
Definition: sqlite3.c:71238
#define TK_RECURSIVE
Definition: sqlite3.c:11375
static int vdbePmaReaderInit(SortSubtask *pTask, SorterFile *pFile, i64 iStart, PmaReader *pReadr, i64 *pnByte)
Definition: sqlite3.c:85566
static int walNextHash(int iPriorHash)
Definition: sqlite3.c:54627
int iMemory
Definition: sqlite3.c:85170
static int exprProbability(Expr *p)
Definition: sqlite3.c:88736
#define SQLITE_LIMIT_WORKER_THREADS
Definition: sqlite3.c:3684
int iNewReg
Definition: sqlite3.c:18117
SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse *, Table *, int, Expr *, ExprList *)
Definition: sqlite3.c:89704
static int walLockShared(Wal *pWal, int lockIdx)
Definition: sqlite3.c:54583
SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *)
static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104474
static int pagerLockDb(Pager *pPager, int eLock)
Definition: sqlite3.c:47487
#define SQLITE_UTF16_ALIGNED
Definition: sqlite3.c:4761
#define SQLITE_OPEN_URI
Definition: sqlite3.c:795
unsigned noSkipScan
Definition: sqlite3.c:14727
static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow)
Definition: sqlite3.c:35671
SQLITE_PRIVATE int sqlite3VdbeList(Vdbe *)
Definition: sqlite3.c:72031
SQLITE_PRIVATE sqlite3_file * sqlite3WalFile(Wal *pWal)
Definition: sqlite3.c:57223
static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3)
Definition: sqlite3.c:70634
static void heightOfExprList(ExprList *p, int *pnHeight)
Definition: sqlite3.c:90351
#define disable_simulated_io_errors()
Definition: sqlite3.c:50128
#define SQLITE_IOERR_BLOCKED
Definition: sqlite3.c:735
double notUsed1
Definition: sqlite3.c:13975
SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *)
Definition: sqlite3.c:52509
sqlite_int64 sqlite3_int64
Definition: sqlite3.c:530
#define SQLITE_STATUS_SCRATCH_USED
Definition: sqlite3.c:7117
SQLITE_API int sqlite3_collation_needed16(sqlite3 *, void *, void(*)(void *, sqlite3 *, int eTextRep, const void *))
Definition: sqlite3.c:141084
BtCursor * pCursor
Definition: sqlite3.c:57665
Bitmask maskSelf
Definition: sqlite3.c:123921
#define WHERE_INDEXED
Definition: sqlite3.c:124351
u16 wctrlFlags
Definition: sqlite3.c:124228
u32 nPayload
Definition: sqlite3.c:57719
#define etTOKEN
Definition: sqlite3.c:24742
#define sqlite3VtabInSync(db)
Definition: sqlite3.c:16720
static void charFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105179
static void setResultStrOrError(sqlite3_context *pCtx, const char *z, int n, u8 enc, void(*xDel)(void *))
Definition: sqlite3.c:75415
#define pcacheTrace(X)
Definition: sqlite3.c:43672
#define SQLITE_FCNTL_SET_LOCKPROXYFILE
Definition: sqlite3.c:1272
static int vdbeIncrMergerNew(SortSubtask *pTask, MergeEngine *pMerger, IncrMerger **ppOut)
Definition: sqlite3.c:86834
#define BITVEC_SZELEM
Definition: sqlite3.c:43217
#define BITVEC_SZ
Definition: sqlite3.c:43204
#define SQLITE_CONFIG_MALLOC
Definition: sqlite3.c:2131
#define sqlite3ParserARG_STORE
Definition: sqlite3.c:133119
#define sqlite3Isdigit(x)
Definition: sqlite3.c:16034
SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *, u32)
Definition: sqlite3.c:43333
#define SQLITE_TESTCTRL_LOCALTIME_FAULT
Definition: sqlite3.c:6985
Bitmask maskLoop
Definition: sqlite3.c:123995
static int allocateSpace(MemPage *pPage, int nByte, int *pIdx)
Definition: sqlite3.c:59729
u8 max1bytePayload
Definition: sqlite3.c:57674
static void unicodeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105164
#define TK_DROP
Definition: sqlite3.c:11405
#define TK_IGNORE
Definition: sqlite3.c:11366
#define HASHTABLE_NSLOT
Definition: sqlite3.c:54299
static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p)
Definition: sqlite3.c:69122
#define PragTyp_CACHE_SIZE
Definition: sqlite3.c:111115
#define SQLITE_OPEN_MAIN_DB
Definition: sqlite3.c:797
static void explainComposite(Parse *pParse, int op, int iSub1, int iSub2, int bUseTmp)
Definition: sqlite3.c:115548
#define UNIXFILE_PSOW
Definition: sqlite3.c:29461
#define SQLITE_SHM_LOCK
Definition: sqlite3.c:1572
int szFirstBlock
Definition: sqlite3.c:54217
SQLITE_PRIVATE FuncDef * sqlite3VtabOverloadFunction(sqlite3 *, FuncDef *, int nArg, Expr *)
Definition: sqlite3.c:123578
SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer *, TriggerStep *)
Definition: sqlite3.c:98016
#define STAT_GET_STAT1
Definition: sqlite3.c:96348
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *)
Definition: sqlite3.c:73455
#define CACHE_STALE
Definition: sqlite3.c:17820
SQLITE_API void sqlite3_result_value(sqlite3_context *, sqlite3_value *)
Definition: sqlite3.c:75556
#define OP_SorterCompare
Definition: sqlite3.c:12681
#define OP_Explain
Definition: sqlite3.c:12724
SQLITE_API int sqlite3_get_table(sqlite3 *db, const char *zSql, char ***pazResult, int *pnRow, int *pnColumn, char **pzErrmsg)
Definition: sqlite3.c:120183
#define YYSTACKDEPTH
Definition: sqlite3.c:133114
#define SQLITE_FUNCTION
Definition: sqlite3.c:3047
#define TK_BITOR
Definition: sqlite3.c:11335
unsigned char etByte
Definition: sqlite3.c:24754
static int xferOptimization(Parse *pParse, Table *pDest, Select *pSelect, int onError, int iDbDest)
Definition: sqlite3.c:109259
SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *, const char *,...)
Definition: sqlite3.c:27483
VTable * pVTable
Definition: sqlite3.c:14461
#define SQLITE_THREADSAFE
Definition: sqlite3.c:10955
static int btreeGetHasContent(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:58824
char fmttype
Definition: sqlite3.c:24761
#define SQLITE_WARNING_AUTOINDEX
Definition: sqlite3.c:778
static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p)
Definition: sqlite3.c:129597
SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int)
Definition: sqlite3.c:56735
static void likeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104905
static void memjrnlFreeChunks(MemJournal *p)
Definition: sqlite3.c:87738
u32 iVersion
Definition: sqlite3.c:54089
static sqlite3_mutex * noopMutexAlloc(int id)
Definition: sqlite3.c:22623
#define BTALLOC_ANY
Definition: sqlite3.c:58292
SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse *, Index *, int, int, int)
Definition: sqlite3.c:92837
SQLITE_PRIVATE char * sqlite3BtreeIntegrityCheck(Btree *, int *aRoot, int nRoot, int, int *)
Definition: sqlite3.c:67561
SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(WhereInfo *pWInfo, int iLevel, Bitmask notReady)
Definition: sqlite3.c:125387
u16 minLeaf
Definition: sqlite3.c:57682
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *, Pgno)
Definition: sqlite3.c:50259
struct PmaReader PmaReader
Definition: sqlite3.c:85003
SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal)
Definition: sqlite3.c:57084
Stat4Sample current
Definition: sqlite3.c:95850
static void vdbeIncrMergerSetThreads(IncrMerger *pIncr)
Definition: sqlite3.c:86858
#define osUnlink
SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *, int, int *, int *)
Definition: sqlite3.c:67715
i64 iStartOff
Definition: sqlite3.c:85241
#define OP_IntegrityCk
Definition: sqlite3.c:12703
#define TK_NULL
Definition: sqlite3.c:11392
SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, void(*)(sqlite3_context *, int, sqlite3_value **), void(*)(sqlite3_context *, int, sqlite3_value **), void(*)(sqlite3_context *), FuncDestructor *pDestructor)
Definition: sqlite3.c:139435
int nKey
Definition: sqlite3.c:85196
u32 nBackfill
Definition: sqlite3.c:54162
#define etSQLESCAPE2
Definition: sqlite3.c:24740
static void insertCell(MemPage *pPage, int i, u8 *pCell, int sz, u8 *pTemp, Pgno iChild, int *pRC)
Definition: sqlite3.c:64544
#define SQLITE_CONSTRAINT_VTAB
Definition: sqlite3.c:774
static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p)
Definition: sqlite3.c:90742
#define EXPR_FULLSIZE
Definition: sqlite3.c:15009
static void pcache1Rekey(sqlite3_pcache *p, sqlite3_pcache_page *pPg, unsigned int iOld, unsigned int iNew)
Definition: sqlite3.c:45544
#define BTCF_WriteFlag
Definition: sqlite3.c:57784
static void Cleanup(Vdbe *p)
Definition: sqlite3.c:72568
SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *, Index *)
Definition: sqlite3.c:71457
SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *, int)
Definition: sqlite3.c:102221
#define sqlite3StrNICmp
Definition: sqlite3.c:16058
SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *, Trigger *)
Definition: sqlite3.c:120800
SQLITE_PRIVATE void sqlite3PagerShrink(Pager *)
Definition: sqlite3.c:49821
SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3 *, Expr *, Expr *, Expr *)
Definition: sqlite3.c:90517
u8 bUseFetch
Definition: sqlite3.c:47016
const void * pKey
Definition: sqlite3.c:12295
SQLITE_API int sqlite3_declare_vtab(sqlite3 *, const char *zSQL)
Definition: sqlite3.c:123277
static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p)
Definition: sqlite3.c:73481
#define CURSOR_VALID
Definition: sqlite3.c:57822
static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree)
Definition: sqlite3.c:93014
FKey * pNextTo
Definition: sqlite3.c:14552
union Bitvec::@11 u
LookasideSlot * pNext
Definition: sqlite3.c:13836
static void randomFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:104588
SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *)
Definition: sqlite3.c:44187
SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *, void *)
Definition: sqlite3.c:24295
SQLITE_API void sqlite3_result_text16be(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:75537
int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *)
TriggerStep * pLast
Definition: sqlite3.c:15769
static void pager_write_changecounter(PgHdr *pPg)
Definition: sqlite3.c:49344
static Table * tableOfTrigger(Trigger *pTrigger)
Definition: sqlite3.c:120792
static sqlite3_int64 localtimeOffset(DateTime *p, sqlite3_context *pCtx, int *pRc)
Definition: sqlite3.c:19076
SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *)
Definition: sqlite3.c:58086
Stat4Sample * aBest
Definition: sqlite3.c:95852
SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *)
Definition: sqlite3.c:73522
char idxaff
Definition: sqlite3.c:124104
WhereOrSet * pOrSet
Definition: sqlite3.c:124201
SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p)
Definition: sqlite3.c:90403
SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value *, int, const void *, u8, void(*)(void *))
Definition: sqlite3.c:70433
SorterCompare xCompare
Definition: sqlite3.c:85144
static int sqlite3MemSize(void *pPrior)
Definition: sqlite3.c:20485
#define PCACHE_DIRTYLIST_ADD
Definition: sqlite3.c:43727
static int changeTempStorage(Parse *pParse, const char *zStorageType)
Definition: sqlite3.c:111694
SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *)
Definition: sqlite3.c:70860
#define WHERE_WANT_DISTINCT
Definition: sqlite3.c:15199
#define MAX_6BYTE
SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int)
Definition: sqlite3.c:74423
etByte flags
Definition: sqlite3.c:24763
#define OPFLAG_NCHANGE
Definition: sqlite3.c:15662
#define TK_IS
Definition: sqlite3.c:11320
static void * contextMalloc(sqlite3_context *context, i64 nByte)
Definition: sqlite3.c:104515
int(* xGetLastError)(sqlite3_vfs *, int, char *)
Definition: sqlite3.c:1505
#define PragTyp_CACHE_SPILL
Definition: sqlite3.c:111116
#define IOTRACE(A)
Definition: sqlite3.c:16867
#define YYACTIONTYPE
Definition: sqlite3.c:133094
static int synthCollSeq(sqlite3 *db, CollSeq *pColl)
Definition: sqlite3.c:102780
u32 mxAlloc
Definition: sqlite3.c:15797
SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *)
Definition: sqlite3.c:127713
#define SQLITE_EXTERN
Definition: sqlite3.c:309
int(* RecordCompare)(int, const void *, UnpackedRecord *)
Definition: sqlite3.c:12839
#define PAGER_ERROR
Definition: sqlite3.c:46722
AuxData * pNext
Definition: sqlite3.c:17977
static sqlite3_mutex * pthreadMutexAlloc(int iType)
Definition: sqlite3.c:22953
SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse *, Table *)
Definition: sqlite3.c:107020
#define SAVEPOINT_RELEASE
Definition: sqlite3.c:14275
SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **, int *)
Definition: sqlite3.c:73543
LogEst nOut
Definition: sqlite3.c:123963
SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *, Pgno, u16)
Definition: sqlite3.c:53341
#define IsVirtual(X)
Definition: sqlite3.c:14493
#define SQLITE_IOERR_RDLOCK
Definition: sqlite3.c:733
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *, int, const char *)
Definition: sqlite3.c:98945
SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *)
Definition: sqlite3.c:44101
u8 disableLookaside
Definition: sqlite3.c:15528
int iValue
Definition: sqlite3.c:14912
#define SQLITE_WriteSchema
Definition: sqlite3.c:14055
#define EXPR_REDUCEDSIZE
Definition: sqlite3.c:15010
#define PGHDR_WRITEABLE
Definition: sqlite3.c:13209
#define SQLITE_OmitNoopJoin
Definition: sqlite3.c:14092
#define OP_Move
Definition: sqlite3.c:12645
VdbeCursor ** apCsr
Definition: sqlite3.c:17850
#define COLNAME_DECLTYPE
Definition: sqlite3.c:12532
static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell)
Definition: sqlite3.c:59515
int addrVisit
Definition: sqlite3.c:18015
static void downgradeAllSharedCacheTableLocks(Btree *p)
Definition: sqlite3.c:58670
static int memjrnlSync(sqlite3_file *pJfd, int flags)
Definition: sqlite3.c:87896
static const FuncDef statInitFuncdef
Definition: sqlite3.c:96038
static void releaseMemArray(Mem *p, int N)
Definition: sqlite3.c:71957
SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *)
Definition: sqlite3.c:84794
SQLITE_API void sqlite3_result_int64(sqlite3_context *, sqlite3_int64)
Definition: sqlite3.c:75488
u8 useSortingIdx
Definition: sqlite3.c:14799
u8 hasHeldSharedLock
Definition: sqlite3.c:47017
static void computeJD(DateTime *p)
Definition: sqlite3.c:18815
SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *)
Definition: sqlite3.c:68689
static void updateVirtualTable(Parse *pParse, SrcList *pSrc, Table *pTab, ExprList *pChanges, Expr *pRowidExpr, int *aXRef, Expr *pWhere, int onError)
Definition: sqlite3.c:122098
#define WO_IS
Definition: sqlite3.c:124326
#define SQLITE_KEEPNULL
Definition: sqlite3.c:14373
#define MASKBIT32(n)
Definition: sqlite3.c:15111
static void pcache1FreePage(PgHdr1 *p)
Definition: sqlite3.c:44904
SQLITE_API int sqlite3_create_function(sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, void *pApp, void(*xFunc)(sqlite3_context *, int, sqlite3_value **), void(*xStep)(sqlite3_context *, int, sqlite3_value **), void(*xFinal)(sqlite3_context *))
Definition: sqlite3.c:139534
struct LimitVal yy354
Definition: sqlite3.c:133110
SQLITE_PRIVATE char * sqlite3DbStrNDup(sqlite3 *, const char *, u64)
Definition: sqlite3.c:24621
SQLITE_PRIVATE Expr * sqlite3ExprForVectorField(Parse *, Expr *, int)
Definition: sqlite3.c:90136
#define ExprClearProperty(E, P)
Definition: sqlite3.c:14992
unixInodeInfo * pNext
Definition: sqlite3.c:30470
SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag)
Definition: sqlite3.c:51677
SQLITE_API void sqlite3_randomness(int N, void *P)
Definition: sqlite3.c:26358
#define TK_CHECK
Definition: sqlite3.c:11395
u32 cksumInit
Definition: sqlite3.c:47024
static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff)
Definition: sqlite3.c:124667
u8 directMode
Definition: sqlite3.c:14797
SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *, Expr *, int)
Definition: sqlite3.c:94322
#define OP_Rowid
Definition: sqlite3.c:12685
u16 funcFlags
Definition: sqlite3.c:14138
#define tkWS
Definition: sqlite3.c:137507
static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate)
Definition: sqlite3.c:129863
static int unixAccess(sqlite3_vfs *NotUsed, const char *zPath, int flags, int *pResOut)
Definition: sqlite3.c:35344
#define WHERE_SKIPSCAN
Definition: sqlite3.c:124357
int(* xSync)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:6079
static int unixFullPathname(sqlite3_vfs *pVfs, const char *zPath, int nOut, char *zOut)
Definition: sqlite3.c:35403
const char *const zName
Definition: sqlite3.c:111157
#define OPFLG_IN2
Definition: sqlite3.c:12732
#define SQLITE_MAX_FUNCTION_ARG
Definition: sqlite3.c:10742
SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *, Table *, int, int)
Definition: sqlite3.c:100722
#define SQLITE_AutoIndex
Definition: sqlite3.c:14064
#define BTREE_MEMORY
Definition: sqlite3.c:12081
#define TRANS_READ
Definition: sqlite3.c:57624
u16 * szCell
Definition: sqlite3.c:64639
#define assertCellInfo(x)
Definition: sqlite3.c:62495
#define NB
Definition: sqlite3.c:64968
TriggerStep * yy145
Definition: sqlite3.c:133101
SQLITE_PRIVATE void sqlite3Update(Parse *, SrcList *, ExprList *, Expr *, int)
Definition: sqlite3.c:121459
static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t)
Definition: sqlite3.c:132930
int addrSkip
Definition: sqlite3.c:123876
#define SQLITE_MUTEX_STATIC_PRNG
Definition: sqlite3.c:6883
u32 aCksum[2]
Definition: sqlite3.c:54099
SQLITE_API sqlite3 * sqlite3_db_handle(sqlite3_stmt *)
Definition: sqlite3.c:76672
static const et_info fmtinfo[]
Definition: sqlite3.c:24783
#define SQLITE_CONFIG_LOG
Definition: sqlite3.c:2143
u32 iLikeRepCntr
Definition: sqlite3.c:123881
SQLITE_PRIVATE void sqlite3Reindex(Parse *, Token *, Token *)
Definition: sqlite3.c:102571
BtCursor * pNext
Definition: sqlite3.c:57757
char * zSql
Definition: sqlite3.c:18081
SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *, int idx, u32 value)
Definition: sqlite3.c:66949
union FuncDef::@2 u
#define findCell(P, I)
Definition: sqlite3.c:59268
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *, int)
Definition: sqlite3.c:62062
static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst)
Definition: sqlite3.c:131637
static WhereLoop ** whereLoopFindLesser(WhereLoop **ppPrev, const WhereLoop *pTemplate)
Definition: sqlite3.c:129775
SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context *, int, sqlite3_value **)
Definition: sqlite3.c:75869
SQLITE_PRIVATE int sqlite3MemCompare(const Mem *, const Mem *, const CollSeq *)
Definition: sqlite3.c:74282
int addrLikeRep
Definition: sqlite3.c:123882
#define OP_Gt
Definition: sqlite3.c:12600
#define SQLITE_STMTSTATUS_VM_STEP
Definition: sqlite3.c:7333
sqlite3_mutex * mutex
Definition: sqlite3.c:57689
SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *)
Definition: sqlite3.c:87464
#define WHERE_DUPLICATES_OK
Definition: sqlite3.c:15194
#define PTF_LEAF
Definition: sqlite3.c:57508
SQLITE_API int sqlite3_initialize(void)
Definition: sqlite3.c:137985
const char * zAuthContext
Definition: sqlite3.c:15646
#define OP_SorterData
Definition: sqlite3.c:12682
#define TK_MATCH
Definition: sqlite3.c:11321
#define WHERE_DISTINCT_NOOP
Definition: sqlite3.c:15210
static void codeDistinct(Parse *pParse, int iTab, int addrRepeat, int N, int iMem)
Definition: sqlite3.c:115033
#define SQLITE_PROTOCOL
Definition: sqlite3.c:690
#define SQLITE_CONSTRAINT_FOREIGNKEY
Definition: sqlite3.c:768
static int bindText(sqlite3_stmt *pStmt, int i, const void *zData, int nData, void(*xDel)(void *), u8 encoding)
Definition: sqlite3.c:76389
#define WO_AND
Definition: sqlite3.c:124329
#define MEM_Subtype
Definition: sqlite3.c:17939
#define ROWSET_NEXT
Definition: sqlite3.c:45838
#define SQLITE_FREE(x)
Definition: sqlite3.c:20387
void * pFree
Definition: sqlite3.c:18082
#define SQLITE_IGNORE
Definition: sqlite3.c:2995
Mem ** apArg
Definition: sqlite3.c:18052
int nColumn
Definition: sqlite3.c:14814
static int memjrnlClose(sqlite3_file *pJfd)
Definition: sqlite3.c:87884
#define TK_ACTION
Definition: sqlite3.c:11349
SQLITE_PRIVATE void sqlite3TokenInit(Token *, char *)
Definition: sqlite3.c:27543
SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *)
Definition: sqlite3.c:76577
sqlite3_file * sjfd
Definition: sqlite3.c:47029
#define SQLITE_SCANSTAT_NAME
Definition: sqlite3.c:8311
SQLITE_API int sqlite3_rtree_query_callback(sqlite3 *db, const char *zQueryFunc, int(*xQueryFunc)(sqlite3_rtree_query_info *), void *pContext, void(*xDestructor)(void *))
u32 opMask
Definition: sqlite3.c:124107
#define CC_DOT
Definition: sqlite3.c:136624
u8 enc
Definition: sqlite3.c:13917
int nBackup
Definition: sqlite3.c:57607
SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int)
Definition: sqlite3.c:92113
#define sqlite3ParserARG_FETCH
Definition: sqlite3.c:133118
SorterFile file
Definition: sqlite3.c:85145
static int pthreadMutexTry(sqlite3_mutex *p)
Definition: sqlite3.c:23087
#define WO_EQ
Definition: sqlite3.c:124320
SQLITE_PRIVATE int sqlite3InitCallback(void *, int, char **, char **)
Definition: sqlite3.c:113585
Table * pFrom
Definition: sqlite3.c:14549
SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *)
Definition: sqlite3.c:44164
static int withExpand(Walker *pWalker, struct SrcList_item *pFrom)
Definition: sqlite3.c:118458
u8 bOrderedInnerLoop
Definition: sqlite3.c:124235
void * pCommitArg
Definition: sqlite3.c:13952
static int rehash(Hash *pH, unsigned int new_size)
Definition: sqlite3.c:28836
SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *)
Definition: sqlite3.c:87983
u8 szEst
Definition: sqlite3.c:14302
SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *)
Definition: sqlite3.c:115415
SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *, int, unsigned char *)
Definition: sqlite3.c:50146
int(* xMutexEnd)(void)
Definition: sqlite3.c:6823
static int openSubJournal(Pager *pPager)
Definition: sqlite3.c:50729
KeyInfo * pKeyInfo
Definition: sqlite3.c:12451
#define OP_VUpdate
Definition: sqlite3.c:12574
#define OPFLAG_TYPEOFARG
Definition: sqlite3.c:15673
#define FULLY_WITHIN
Definition: sqlite3.c:8758
FKey * pNextFrom
Definition: sqlite3.c:14550
#define YY_SHIFT_MAX
Definition: sqlite3.c:133524
#define SQLITE_OK_LOAD_PERMANENTLY
Definition: sqlite3.c:780
SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p)
Definition: sqlite3.c:68561
SQLITE_API int sqlite3_prepare16_v2(sqlite3 *db, const void *zSql, int nByte, sqlite3_stmt **ppStmt, const void **pzTail)
Definition: sqlite3.c:114373
Op * aOp
Definition: sqlite3.c:18050
SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *)
Definition: sqlite3.c:60929
#define SQLITE_TESTCTRL_SORTER_MMAP
Definition: sqlite3.c:6992
#define get2byteAligned(x)
Definition: sqlite3.c:57957
struct TableLock TableLock
Definition: sqlite3.c:12001
SQLITE_PRIVATE Schema * sqlite3SchemaGet(sqlite3 *, Btree *)
Definition: sqlite3.c:103196
#define VdbeComment(X)
Definition: sqlite3.c:12864
static int pager_write(PgHdr *pPg)
Definition: sqlite3.c:52131
int nDbChange
Definition: sqlite3.c:17861
SQLITE_PRIVATE VdbeOp * sqlite3VdbeTakeOpArray(Vdbe *, int *, int *)
Definition: sqlite3.c:71136
Expr * pWhere
Definition: sqlite3.c:15295
#define ONEPASS_MULTI
Definition: sqlite3.c:16322
int nMem
Definition: sqlite3.c:17857
SQLITE_API const char * sqlite3_column_name(sqlite3_stmt *, int N)
Definition: sqlite3.c:76242
#define WALINDEX_MAX_VERSION
Definition: sqlite3.c:54054
#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags)
Definition: sqlite3.c:14241
#define OE_Default
Definition: sqlite3.c:14602
SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3 *, VdbeCursor *, UnpackedRecord *, int *)
Definition: sqlite3.c:74904
static void renameParentFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:94853
static int openDirectory(const char *, int *)
Definition: sqlite3.c:32893
static int pagerAcquireMapPage(Pager *pPager, Pgno pgno, void *pData, PgHdr **ppPage)
Definition: sqlite3.c:50311
Index * pIndex
Definition: sqlite3.c:123935
#define tkSEMI
Definition: sqlite3.c:137506
SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *, ExprList *)
Definition: sqlite3.c:127755
ExprList * pOrderBy
Definition: sqlite3.c:124199
static void addArgumentToVtab(Parse *pParse)
Definition: sqlite3.c:122914
static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList)
Definition: sqlite3.c:86244
#define SQLITE_FUNC_CONSTANT
Definition: sqlite3.c:14193
u8 onError
Definition: sqlite3.c:14721
#define DbMaskTest(M, I)
Definition: sqlite3.c:15492
SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **)
Definition: sqlite3.c:70152
LookasideSlot * pFree
Definition: sqlite3.c:13831
int addColOffset
Definition: sqlite3.c:14456
static int vdbeSorterMergeTreeBuild(VdbeSorter *pSorter, MergeEngine **ppOut)
Definition: sqlite3.c:87255
int(* xSelectCallback)(Walker *, Select *)
Definition: sqlite3.c:15907
#define PAGERTRACE(X)
Definition: sqlite3.c:46485
int p2
Definition: sqlite3.c:12438
static int pcache1UnderMemoryPressure(PCache1 *pCache)
Definition: sqlite3.c:44956
#define SQLITE_NOLFS
Definition: sqlite3.c:697
i16 nCol
Definition: sqlite3.c:14446
static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:108470
void(* xMutexFree)(sqlite3_mutex *)
Definition: sqlite3.c:6825
#define BITVEC_MXHASH
Definition: sqlite3.c:43227
SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *, int, int, int)
Definition: sqlite3.c:70691
SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p)
Definition: sqlite3.c:61334
#define SQLITE_OPEN_SUBJOURNAL
Definition: sqlite3.c:802
SubProgram * pNext
Definition: sqlite3.c:12483
SQLITE_PRIVATE int sqlite3MatchSpanName(const char *, const char *, const char *, const char *)
Definition: sqlite3.c:88314
char * zToken
Definition: sqlite3.c:14911
struct TreeView TreeView
Definition: sqlite3.c:12003
int count
Definition: sqlite3.c:11238
static int btreeCursor(Btree *p, int iTable, int wrFlag, struct KeyInfo *pKeyInfo, BtCursor *pCur)
Definition: sqlite3.c:62341
#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD
Definition: sqlite3.c:6987
SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *)
Definition: sqlite3.c:44113
#define osRead
void(* xProfile)(void *, const char *, u64)
Definition: sqlite3.c:13950
#define P4_INT64
Definition: sqlite3.c:12513
#define TK_TO
Definition: sqlite3.c:11306
#define WO_LE
Definition: sqlite3.c:124322
i64 movetoTarget
Definition: sqlite3.c:17788
#define WHERE_IN_ABLE
Definition: sqlite3.c:124353
#define PENDING_LOCK
Definition: sqlite3.c:13496
static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105520
#define PTRMAP_ISPAGE(pBt, pgno)
Definition: sqlite3.c:57849
union Expr::@3 u
#define SQLITE_DBSTATUS_CACHE_USED
Definition: sqlite3.c:7253
#define SQLITE_CacheSpill
Definition: sqlite3.c:14046
#define SQLITE_INDEX_CONSTRAINT_LT
Definition: sqlite3.c:6237
static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem)
Definition: sqlite3.c:69007
#define osMmap
#define OPFLAG_AUXDELETE
Definition: sqlite3.c:15680
int tz
Definition: sqlite3.c:18646
#define PragTyp_ENCODING
Definition: sqlite3.c:111123
MergeEngine * pMerger
Definition: sqlite3.c:85240
#define SQLITE_DBSTATUS_SCHEMA_USED
Definition: sqlite3.c:7254
#define osReadlink
SQLITE_API const void * sqlite3_column_text16(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76172
Schema * pSchema
Definition: sqlite3.c:14712
SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *)
HashElem * prev
Definition: sqlite3.c:11250
#define BTREE_SINGLE
Definition: sqlite3.c:12082
#define SQLITE_ENABLE_LOCKING_STYLE
Definition: sqlite3.c:29256
SQLITE_PRIVATE Expr * sqlite3ExprFunction(Parse *, ExprList *, Token *)
Definition: sqlite3.c:90639
#define SQLITE_TESTCTRL_BITVEC_TEST
Definition: sqlite3.c:6975
int iSDParm
Definition: sqlite3.c:15425
SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *)
Definition: sqlite3.c:102851
SQLITE_API const char * sqlite3_bind_parameter_name(sqlite3_stmt *, int)
Definition: sqlite3.c:76588
sqlite3_value ** apArg
Definition: sqlite3.c:16150
SrcList * pSrc
Definition: sqlite3.c:94403
#define IN_INDEX_ROWID
Definition: sqlite3.c:16809
int(* xNext)(sqlite3_vtab_cursor *)
Definition: sqlite3.c:6073
#define OPFLAG_BULKCSR
Definition: sqlite3.c:15674
u32 aType[1]
Definition: sqlite3.c:17810
struct IndexSample IndexSample
Definition: sqlite3.c:11983
SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *)
Definition: sqlite3.c:102208
SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *)
Definition: sqlite3.c:75262
static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:91405
SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal)
Definition: sqlite3.c:57159
int iVersion
Definition: sqlite3.c:1487
int(* xCreate)(sqlite3 *, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVTab, char **)
Definition: sqlite3.c:6060
static int memjrnlWrite(sqlite3_file *pJfd, const void *zBuf, int iAmt, sqlite_int64 iOfst)
Definition: sqlite3.c:87790
i64 iSum
Definition: sqlite3.c:105554
static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint)
Definition: sqlite3.c:49671
UnixUnusedFd * pUnused
Definition: sqlite3.c:29398
#define SQLITE_SCANSTAT_NVISIT
Definition: sqlite3.c:8309
SQLITE_PRIVATE int sqlite3MisuseError(int)
Definition: sqlite3.c:141147
#define EP_Distinct
Definition: sqlite3.c:14959
static int editPage(MemPage *pPg, int iOld, int iNew, int nNew, CellArray *pCArray)
Definition: sqlite3.c:64861
#define WAL_RECOVER_LOCK
Definition: sqlite3.c:54064
#define TK_ROLLBACK
Definition: sqlite3.c:11303
#define TK_EXCEPT
Definition: sqlite3.c:11408
static void vdbeIncrFree(IncrMerger *)
Definition: sqlite3.c:86052
#define SQLITE_NOTICE_RECOVER_WAL
Definition: sqlite3.c:776
static SQLITE_WSD struct PCacheGlobal pcache1_g
#define TK_JOIN_KW
Definition: sqlite3.c:11389
static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom)
Definition: sqlite3.c:118383
static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax)
Definition: sqlite3.c:118222
#define PragTyp_INTEGRITY_CHECK
Definition: sqlite3.c:111129
u8 eCode
Definition: sqlite3.c:15910
#define sqlite3ConnectionClosed(x)
Definition: sqlite3.c:16850
int iParent
Definition: sqlite3.c:124063
#define PAGER_GET_READONLY
Definition: sqlite3.c:13006
SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *, int, int, const char *, void(*)(void *))
Definition: sqlite3.c:72616
#define SQLITE_CHECKPOINT_PASSIVE
Definition: sqlite3.c:8169
#define PAGER_LOCKINGMODE_EXCLUSIVE
Definition: sqlite3.c:12985
int nExpr
Definition: sqlite3.c:15036
char * zTo
Definition: sqlite3.c:14551
static void resolveAlias(Parse *pParse, ExprList *pEList, int iCol, Expr *pExpr, const char *zType, int nSubquery)
Definition: sqlite3.c:88248
WhereTerm * a
Definition: sqlite3.c:124131
#define SQLITE_CONFIG_PCACHE_HDRSZ
Definition: sqlite3.c:2151
SQLITE_PRIVATE void sqlite3Insert(Parse *, SrcList *, Select *, IdList *, int)
Definition: sqlite3.c:107856
int leftColumn
Definition: sqlite3.c:124067
SQLITE_PRIVATE char sqlite3AffinityType(const char *, u8 *)
Definition: sqlite3.c:99431
Definition: sqlite3.c:17871
int(* xInstCount)(Fts5Context *, int *pnInst)
Definition: sqlite3.c:10337
static void openStatTable(Parse *pParse, int iDb, int iStatCur, const char *zWhere, const char *zWhereType)
Definition: sqlite3.c:95734
#define CC_VARNUM
Definition: sqlite3.c:136604
void(* sqlite3_syscall_ptr)(void)
Definition: sqlite3.c:1485
void(* xParseCell)(MemPage *, u8 *, CellInfo *)
Definition: sqlite3.c:57549
Token sArg
Definition: sqlite3.c:15615
#define TERM_CODED
Definition: sqlite3.c:124080
#define PCACHE_DIRTYLIST_REMOVE
Definition: sqlite3.c:43726
static SQLITE_NOINLINE const void * valueToText(sqlite3_value *pVal, u8 enc)
Definition: sqlite3.c:69775
double sqlite3_rtree_dbl
Definition: sqlite3.c:8680
static void walUnlockShared(Wal *pWal, int lockIdx)
Definition: sqlite3.c:54593
#define SQLITE_MAX_FILE_FORMAT
Definition: sqlite3.c:11508
#define EP_InfixFunc
Definition: sqlite3.c:14962
static int unixOpenSharedMemory(unixFile *pDbFd)
Definition: sqlite3.c:33617
int nCursor
Definition: sqlite3.c:17854
u8 tabFlags
Definition: sqlite3.c:14453
#define P4_INT32
Definition: sqlite3.c:12514
static void timeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19443
SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p)
Definition: sqlite3.c:122759
int(* xEof)(sqlite3_vtab_cursor *)
Definition: sqlite3.c:6074
SQLITE_PRIVATE TriggerStep * sqlite3TriggerUpdateStep(sqlite3 *, Token *, ExprList *, Expr *, u8)
Definition: sqlite3.c:120688
int(* xCurrentTimeInt64)(sqlite3_vfs *, sqlite3_int64 *)
Definition: sqlite3.c:1510
#define SQLITE_N_LIMIT
Definition: sqlite3.c:13802
SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *)
Definition: sqlite3.c:87416
SQLITE_PRIVATE void sqlite3StatusUp(int, int)
Definition: sqlite3.c:18310
#define SQLITE_CONFIG_MMAP_SIZE
Definition: sqlite3.c:2149
#define SQLITE_IOERR_SHMOPEN
Definition: sqlite3.c:742
LogEst nSelectRow
Definition: sqlite3.c:15287
#define WO_IN
Definition: sqlite3.c:124319
#define PAGER_WRITER_FINISHED
Definition: sqlite3.c:46721
int(* xSleep)(sqlite3_vfs *, int microseconds)
Definition: sqlite3.c:1503
static u16 cachedCellSize(CellArray *p, int N)
Definition: sqlite3.c:64670
i16 iPKey
Definition: sqlite3.c:14445
static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster)
Definition: sqlite3.c:47612
void(* xDestroy)(void *)
Definition: sqlite3.c:14288
SQLITE_PRIVATE Table * sqlite3LocateTable(Parse *, u32 flags, const char *, const char *)
Definition: sqlite3.c:98631
#define SQLITE_TRACE_CLOSE
Definition: sqlite3.c:3144
#define PragTyp_THREADS
Definition: sqlite3.c:111145
#define EP_Static
Definition: sqlite3.c:14970
static const YYACTIONTYPE yy_default[]
Definition: sqlite3.c:133612
Pgno dbSize
Definition: sqlite3.c:47018
#define PAGER_CKPT_FULLFSYNC
Definition: sqlite3.c:13022
static int vdbeSorterFlushPMA(VdbeSorter *pSorter)
Definition: sqlite3.c:86544
sqlite3_int64 iOffset
Definition: sqlite3.c:87660
SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *, u32 addr, u8)
Definition: sqlite3.c:71232
static int resolveOrderByTermToExprList(Parse *pParse, Select *pSelect, Expr *pE)
Definition: sqlite3.c:89059
static void callFinaliser(sqlite3 *db, int offset)
Definition: sqlite3.c:123400
u16 nSize
Definition: sqlite3.c:57721
static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt)
Definition: sqlite3.c:32499
int nVdbeExec
Definition: sqlite3.c:13944
SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *)
Definition: sqlite3.c:77541
#define SF_NestedFrom
Definition: sqlite3.c:15326
static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC)
Definition: sqlite3.c:65139
SorterRecord * pNext
Definition: sqlite3.c:85287
sqlite3_rtree_dbl * aParam
Definition: sqlite3.c:8704
#define TK_CONFLICT
Definition: sqlite3.c:11359
#define BTCF_AtLast
Definition: sqlite3.c:57787
SQLITE_PRIVATE const char * sqlite3BtreeGetFilename(Btree *)
Definition: sqlite3.c:67680
TFSIMD_FORCE_INLINE const tfScalar & x() const
SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *, int, void *)
Definition: sqlite3.c:19869
Bitmask notReady
Definition: sqlite3.c:123899
SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *)
Definition: sqlite3.c:122797
SQLITE_PRIVATE int sqlite3PagerBegin(Pager *, int exFlag, int)
Definition: sqlite3.c:52005
#define CC_LP
Definition: sqlite3.c:136615
i64 szMmap
Definition: sqlite3.c:13911
#define sqlite3StackAllocRaw(D, N)
Definition: sqlite3.c:16098
#define YY_MAX_SHIFT
Definition: sqlite3.c:133123
SQLITE_PRIVATE Btree * sqlite3DbNameToBtree(sqlite3 *, const char *)
Definition: sqlite3.c:141763
unsigned int iMaxKey
Definition: sqlite3.c:44615
#define SQLITE_SqlTrace
Definition: sqlite3.c:14053
u8 eSubtype
Definition: sqlite3.c:17882
#define TK_DESC
Definition: sqlite3.c:11361
#define SQLITE_IgnoreChecks
Definition: sqlite3.c:14057
Expr * pWhere
Definition: sqlite3.c:15765
#define UNIXFILE_DIRSYNC
Definition: sqlite3.c:29457
static void selectPopWith(Walker *pWalker, Select *p)
Definition: sqlite3.c:118574
u16 nHdrParsed
Definition: sqlite3.c:17777
#define SQLITE_QueryFlattener
Definition: sqlite3.c:14082
static int pagerBeginReadTransaction(Pager *pPager)
Definition: sqlite3.c:49509
Mem * pResultSet
Definition: sqlite3.c:18054
static SQLITE_WSD struct sqlite3AutoExtList sqlite3Autoext
SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *, Module *)
Definition: sqlite3.c:123677
u32 nQueryLoop
Definition: sqlite3.c:15562
#define WAL_EXCLUSIVE_MODE
Definition: sqlite3.c:54246
#define PragTyp_PAGE_COUNT
Definition: sqlite3.c:111134
#define CC_COMMA
Definition: sqlite3.c:136621
u8 nOverflow
Definition: sqlite3.c:57525
Vdbe * pPrev
Definition: sqlite3.c:18030
#define restoreCursorPosition(p)
Definition: sqlite3.c:59062
u64 uptr
Definition: sqlite3.c:11712
static int unixFileControl(sqlite3_file *id, int op, void *pArg)
Definition: sqlite3.c:33153
static int whereLoopAddAll(WhereLoopBuilder *pBuilder)
Definition: sqlite3.c:131191
SQLITE_API int sqlite3_prepare_v2(sqlite3 *db, const char *zSql, int nByte, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:114285
#define OpHelp(X)
Definition: sqlite3.c:29013
#define TK_END
Definition: sqlite3.c:11302
SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int)
Definition: sqlite3.c:53406
#define OP_Yield
Definition: sqlite3.c:12578
sqlite3_vfs * pVfs
Definition: sqlite3.c:46986
#define MEMTYPE_HEAP
Definition: sqlite3.c:16908
struct vxworksFileId * pNext
Definition: sqlite3.c:30229
#define TOKEN
SQLITE_PRIVATE void sqlite3Detach(Parse *, Expr *)
Definition: sqlite3.c:97839
#define YYNSTATE
Definition: sqlite3.c:133121
Table * pTab
Definition: sqlite3.c:122583
#define TRACE_IDX_OUTPUTS(A)
Definition: sqlite3.c:128412
static const u8 sqlite3SmallTypeSizes[]
Definition: sqlite3.c:73659
u8 curFlags
Definition: sqlite3.c:57766
SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *)
Definition: sqlite3.c:67877
SQLiteThread * pThread
Definition: sqlite3.c:85138
#define WO_GT
Definition: sqlite3.c:124323
static void * unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename)
Definition: sqlite3.c:35493
#define sqlite3IsToplevel(p)
Definition: sqlite3.c:16451
#define sqlite3Tolower(x)
Definition: sqlite3.c:16036
#define SimulateDiskfullError(A)
Definition: sqlite3.c:29651
static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p)
Definition: sqlite3.c:128790
#define WHERE_PARTIALIDX
Definition: sqlite3.c:124359
u8 bDoTruncate
Definition: sqlite3.c:57671
int nChange
Definition: sqlite3.c:18040
static void minMaxFinalize(sqlite3_context *context)
Definition: sqlite3.c:105693
static const struct sqlite3_io_methods MemJournalMethods
Definition: sqlite3.c:87913
#define SQLITE_POWERSAFE_OVERWRITE
Definition: sqlite3.c:10964
static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg)
Definition: sqlite3.c:67098
static void walIteratorFree(WalIterator *p)
Definition: sqlite3.c:55323
struct TriggerStep TriggerStep
Definition: sqlite3.c:12006
int(* xColumnText)(Fts5Context *, int iCol, const char **pz, int *pn)
Definition: sqlite3.c:10341
#define SQLITE_LOCK_SHARED
Definition: sqlite3.c:863
int addrCont
Definition: sqlite3.c:123877
SQLITE_API sqlite3 * sqlite3_context_db_handle(sqlite3_context *)
Definition: sqlite3.c:75833
#define OP_IdxDelete
Definition: sqlite3.c:12689
SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse *, ExprList *, Token *, ExprList *, int)
Definition: sqlite3.c:100909
void sqliteVdbePopStack(Vdbe *, int)
static int sqlite3Prepare16(sqlite3 *db, const void *zSql, int nBytes, int saveSqlFlag, sqlite3_stmt **ppStmt, const void **pzTail)
Definition: sqlite3.c:114303
#define BTREE_BLOBKEY
Definition: sqlite3.c:12135
SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb)
Definition: sqlite3.c:139970
#define SQLITE_VTAB_CONSTRAINT_SUPPORT
Definition: sqlite3.c:8229
i64 seqCount
Definition: sqlite3.c:17787
SQLITE_PRIVATE void sqlite3FinishCoding(Parse *)
Definition: sqlite3.c:98431
const char * pKey
Definition: sqlite3.c:11252
#define TERM_ORINFO
Definition: sqlite3.c:124082
#define SRT_Discard
Definition: sqlite3.c:15402
void(* sqlite3_destructor_type)(void *)
Definition: sqlite3.c:5027
SQLITE_PRIVATE const char * sqlite3OpcodeName(int)
Definition: sqlite3.c:29015
#define etGENERIC
Definition: sqlite3.c:24732
tRowcnt * anLt
Definition: sqlite3.c:14766
static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap)
Definition: sqlite3.c:25751
SQLITE_PRIVATE int sqlite3Atoi64(const char *, i64 *, int, u8)
Definition: sqlite3.c:27843
static void noopMutexFree(sqlite3_mutex *p)
Definition: sqlite3.c:22627
SQLITE_PRIVATE int sqlite3ExprCompare(Expr *, Expr *, int)
Definition: sqlite3.c:94230
#define TK_REINDEX
Definition: sqlite3.c:11384
#define OP_Count
Definition: sqlite3.c:12662
u8 ckptLock
Definition: sqlite3.c:54224
int(* xBusyHandler)(void *)
Definition: sqlite3.c:47054
BITVEC_TELEM aBitmap[BITVEC_NELEM]
Definition: sqlite3.c:43268
static int walDecodeFrame(Wal *pWal, u32 *piPage, u32 *pnTruncate, u8 *aData, u8 *aFrame)
Definition: sqlite3.c:54504
static VTable * vtabDisconnectAll(sqlite3 *db, Table *p)
Definition: sqlite3.c:122719
static int multiSelectValues(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:116517
static void pagerFixMaplimit(Pager *pPager)
Definition: sqlite3.c:49798
Table * pTab
Definition: sqlite3.c:18121
#define IsStat34
Definition: sqlite3.c:95719
#define SQLITE_IOCAP_ATOMIC64K
Definition: sqlite3.c:848
SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *, int *pRes)
Definition: sqlite3.c:63212
SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *)
Definition: sqlite3.c:44356
u8 bBenignMalloc
Definition: sqlite3.c:13921
#define SQLITE_INTERNAL
Definition: sqlite3.c:677
KeyInfo * pKeyInfo
Definition: sqlite3.c:85167
Pgno pgno
Definition: sqlite3.c:57550
#define SQLITE_WITHIN(P, S, E)
Definition: sqlite3.c:11723
static HashElem * findElementWithHash(const Hash *pH, const char *pKey, unsigned int *pHash)
Definition: sqlite3.c:28876
SQLITE_PRIVATE void sqlite3FkActions(Parse *, Table *, ExprList *, int, int *, int)
Definition: sqlite3.c:107306
SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *)
Definition: sqlite3.c:19824
#define TK_GE
Definition: sqlite3.c:11332
#define CC_QUOTE2
Definition: sqlite3.c:136607
bft expired
Definition: sqlite3.c:18069
static void freeP4(sqlite3 *db, int p4type, void *p4)
Definition: sqlite3.c:71281
const char * zDatabase
Definition: sqlite3.c:96972
SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *)
#define TK_BEFORE
Definition: sqlite3.c:11354
#define RESERVED_BYTE
Definition: sqlite3.c:13559
static int dotlockUnlock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:31548
SQLITE_PRIVATE const char * sqlite3JournalModename(int)
Definition: sqlite3.c:111802
#define OE_None
Definition: sqlite3.c:14590
SQLITE_API int sqlite3_exec(sqlite3 *, const char *sql, int(*callback)(void *, int, char **, char **), void *, char **errmsg)
Definition: sqlite3.c:109600
#define OE_Ignore
Definition: sqlite3.c:14594
MemPage * pPage1
Definition: sqlite3.c:57666
int iCacheLevel
Definition: sqlite3.c:15539
i64 nDeferredImmCons
Definition: sqlite3.c:14003
static int walPagesize(Wal *pWal)
Definition: sqlite3.c:55439
#define YYMALLOCARGTYPE
Definition: sqlite3.c:132863
sqlite3 * pDestDb
Definition: sqlite3.c:67981
#define SQLITE_NOTFOUND
Definition: sqlite3.c:687
SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64)
Definition: sqlite3.c:84809
#define SQLITE_CANTOPEN_ISDIR
Definition: sqlite3.c:757
u8 locked
Definition: sqlite3.c:57604
#define TK_TABLE
Definition: sqlite3.c:11307
#define SQLITE_MAX_EXPR_DEPTH
Definition: sqlite3.c:10715
SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *, TriggerStep *)
Definition: sqlite3.c:120287
SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *, int)
Definition: sqlite3.c:101030
int nBuffer
Definition: sqlite3.c:85259
void * token
Definition: sqlite3.c:17851
SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *, const char *, int)
Definition: sqlite3.c:76601
SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen)
Definition: sqlite3.c:53659
u8 eState
Definition: sqlite3.c:47010
int skipNext
Definition: sqlite3.c:57764
static int mallocWithAlarm(int n, void **pp)
Definition: sqlite3.c:24104
SQLITE_API int sqlite3_vtab_config(sqlite3 *, int op,...)
Definition: sqlite3.c:123752
u8 autoVacuum
Definition: sqlite3.c:57669
SQLITE_PRIVATE void * sqlite3PageMalloc(int)
Definition: sqlite3.c:44928
static int codeAllEqualityTerms(Parse *pParse, WhereLevel *pLevel, int bRev, int nExtraReg, char **pzAff)
Definition: sqlite3.c:124945
#define SQLITE_MAX_SQL_LENGTH
Definition: sqlite3.c:10701
#define WAL_WRITE_LOCK
Definition: sqlite3.c:54061
#define etPERCENT
Definition: sqlite3.c:24736
#define MASTER_ROOT
Definition: sqlite3.c:11890
int iSelectID
Definition: sqlite3.c:18016
#define MEMTYPE_LOOKASIDE
Definition: sqlite3.c:16909
SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo *, int, const void *, UnpackedRecord *)
Definition: sqlite3.c:73985
SQLITE_API int sqlite3_value_type(sqlite3_value *)
Definition: sqlite3.c:75336
SQLITE_PRIVATE Vdbe * sqlite3VdbeCreate(Parse *)
Definition: sqlite3.c:70499
static int mkFullPathname(const char *zPath, char *zOut, int nOut)
Definition: sqlite3.c:35370
static void versionFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:104986
#define DbClearProperty(D, I, P)
Definition: sqlite3.c:13782
#define UNUSED_PARAMETER2(x, y)
Definition: sqlite3.c:11961
BtShared * pBt
Definition: sqlite3.c:57922
#define TK_VIRTUAL
Definition: sqlite3.c:11382
static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm)
Definition: sqlite3.c:124636
SorterRecord * pList
Definition: sqlite3.c:85029
void * pStart
Definition: sqlite3.c:13832
#define SQLITE_IOERR_READ
Definition: sqlite3.c:725
SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *)
Definition: sqlite3.c:138804
i16 nReserve
Definition: sqlite3.c:47046
int iSelfTab
Definition: sqlite3.c:15538
SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *)
Definition: sqlite3.c:114236
#define OP_Permutation
Definition: sqlite3.c:12656
SQLITE_API sqlite3_value * sqlite3_value_dup(const sqlite3_value *)
Definition: sqlite3.c:75376
int nHeight
Definition: sqlite3.c:15603
struct VdbeOp Op
Definition: sqlite3.c:17732
u8 hasMutex
Definition: sqlite3.c:33446
static void applyNumericAffinity(Mem *pRec, int bTryForInt)
Definition: sqlite3.c:77471
ynVar nVar
Definition: sqlite3.c:18032
#define SQLITE_MAX_COMPOUND_SELECT
Definition: sqlite3.c:10727
#define vdbeSorterRewindDebug(y)
Definition: sqlite3.c:85942
static int unixSleep(sqlite3_vfs *NotUsed, int microseconds)
Definition: sqlite3.c:35599
#define PragTyp_JOURNAL_SIZE_LIMIT
Definition: sqlite3.c:111131
static void exprAnalyzeOrTerm(SrcList *pSrc, WhereClause *pWC, int idxTerm)
Definition: sqlite3.c:126891
static int whereLoopCheaperProperSubset(const WhereLoop *pX, const WhereLoop *pY)
Definition: sqlite3.c:129702
SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *, Expr *)
Definition: sqlite3.c:118889
SQLITE_PRIVATE int sqlite3BtreeCursorSize(void)
Definition: sqlite3.c:62427
SrcList * yy185
Definition: sqlite3.c:133103
static int lookupName(Parse *pParse, const char *zDb, const char *zTab, const char *zCol, NameContext *pNC, Expr *pExpr)
Definition: sqlite3.c:88364
SQLITE_API void sqlite3_result_error_code(sqlite3_context *, int)
Definition: sqlite3.c:75573
static void destroyTable(Parse *pParse, Table *pTab)
Definition: sqlite3.c:100641
static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord)
Definition: sqlite3.c:85873
SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *)
Definition: sqlite3.c:62447
SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *)
Definition: sqlite3.c:95344
u8 * aMap
Definition: sqlite3.c:85202
#define WALINDEX_LOCK_OFFSET
Definition: sqlite3.c:54176
#define osRmdir
u8 hasCompound
Definition: sqlite3.c:15526
SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *)
Definition: sqlite3.c:69310
#define OP_IdxGT
Definition: sqlite3.c:12621
#define MASKBIT(n)
Definition: sqlite3.c:15110
Pgno iTable
Definition: sqlite3.c:57569
SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *, int)
Definition: sqlite3.c:49791
#define SQLITE_FCNTL_CHUNK_SIZE
Definition: sqlite3.c:1275
#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
Definition: sqlite3.c:851
u8 fullSync
Definition: sqlite3.c:46991
SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *)
Definition: sqlite3.c:92786
SQLITE_API int sqlite3_os_init(void)
Definition: sqlite3.c:36894
#define SQLITE_REALLOC(x, y)
Definition: sqlite3.c:20388
u8 temp_store
Definition: sqlite3.c:13919
PgHdr1 ** apHash
Definition: sqlite3.c:44623
#define CC_LT
Definition: sqlite3.c:136610
int sortingIdxPTab
Definition: sqlite3.c:14802
#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags)
Definition: sqlite3.c:14253
static void substSelect(sqlite3 *, Select *, int, ExprList *, int)
Definition: sqlite3.c:117548
#define REGISTER_TRACE(R, M)
Definition: sqlite3.c:77717
static const short yy_shift_ofst[]
Definition: sqlite3.c:133525
#define BITVEC_TELEM
Definition: sqlite3.c:43215
#define TK_DATABASE
Definition: sqlite3.c:11360
static void avgFinalize(sqlite3_context *context)
Definition: sqlite3.c:105604
#define SQLITE_N_BTREE_META
Definition: sqlite3.c:12042
SQLITE_PRIVATE SrcList * sqlite3SrcListEnlarge(sqlite3 *, SrcList *, int, int)
Definition: sqlite3.c:101943
yDbMask writeMask
Definition: sqlite3.c:15545
static void whereLikeOptimizationStringFixup(Vdbe *v, WhereLevel *pLevel, WhereTerm *pTerm)
Definition: sqlite3.c:125065
#define BTCF_ValidOvfl
Definition: sqlite3.c:57786
static double getDoubleArg(PrintfArguments *p)
Definition: sqlite3.c:24861
static void exprSetHeight(Expr *p)
Definition: sqlite3.c:90382
SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *, i64 size)
Definition: sqlite3.c:19838
#define WHERE_SEEK_TABLE
Definition: sqlite3.c:15201
static void pthreadMutexFree(sqlite3_mutex *p)
Definition: sqlite3.c:23018
static SQLITE_NOINLINE PgHdr * pcacheFetchFinishWithInit(PCache *pCache, Pgno pgno, sqlite3_pcache_page *pPage)
Definition: sqlite3.c:44033
u8 exclusiveMode
Definition: sqlite3.c:46987
static void zeroblobFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105248
char ** azResult
Definition: sqlite3.c:120095
#define SQLITE_MINIMUM_FILE_DESCRIPTOR
Definition: sqlite3.c:29992
#define PAGER_MEMORY
Definition: sqlite3.c:12978
static int vdbeMergeEngineLevel0(SortSubtask *pTask, int nPMA, i64 *piOffset, MergeEngine **ppOut)
Definition: sqlite3.c:87142
#define BTREE_AUTOVACUUM_INCR
Definition: sqlite3.c:12054
#define YY_MIN_SHIFTREDUCE
Definition: sqlite3.c:133124
Pgno pgno
Definition: sqlite3.c:13189
PCache * pPCache
Definition: sqlite3.c:47068
#define EP_Skip
Definition: sqlite3.c:14967
LogEst rRun
Definition: sqlite3.c:123962
int iSysErrno
Definition: sqlite3.c:13915
SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager)
Definition: sqlite3.c:53584
SQLITE_API int sqlite3_overload_function(sqlite3 *, const char *zFuncName, int nArg)
Definition: sqlite3.c:139631
SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr)
Definition: sqlite3.c:89774
SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value *)
Definition: sqlite3.c:75311
#define SQLITE_GET_LOCKPROXYFILE
Definition: sqlite3.c:1300
SQLITE_PRIVATE sqlite3_file * sqlite3PagerJrnlFile(Pager *)
Definition: sqlite3.c:53123
#define SQLITE_CONFIG_WIN32_HEAPSIZE
Definition: sqlite3.c:2150
static int btreeInitPage(MemPage *pPage)
Definition: sqlite3.c:59979
#define PGHDR_DONT_WRITE
Definition: sqlite3.c:13212
SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *, Table *)
Definition: sqlite3.c:123644
int pc
Definition: sqlite3.c:18038
static int robustFchown(int fd, uid_t uid, gid_t gid)
Definition: sqlite3.c:29895
SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *)
Definition: sqlite3.c:67740
#define OPFLAG_FORDELETE
Definition: sqlite3.c:15676
SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *, int, u8)
Definition: sqlite3.c:27617
SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *, i16)
Definition: sqlite3.c:99104
#define SQLITE_BUSY_SNAPSHOT
Definition: sqlite3.c:755
static const char * actionName(u8 action)
Definition: sqlite3.c:111782
SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *, Token *)
Definition: sqlite3.c:99020
SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *, u8 P5)
Definition: sqlite3.c:71244
static int pagerPagecount(Pager *pPager, Pgno *pnPage)
Definition: sqlite3.c:49542
#define SQLITE_INT_TO_PTR(X)
Definition: sqlite3.c:10900
SQLITE_PRIVATE Trigger * sqlite3TriggersExist(Parse *, Table *, int, ExprList *, int *pMask)
Definition: sqlite3.c:120883
u8 eState
Definition: sqlite3.c:57768
static char * getTextArg(PrintfArguments *p)
Definition: sqlite3.c:24865
SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int)
Definition: sqlite3.c:121204
SQLITE_PRIVATE void sqlite3ExprListSetName(Parse *, ExprList *, Token *, int)
Definition: sqlite3.c:91285
u8 mayAbort
Definition: sqlite3.c:15525
static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUnusable)
Definition: sqlite3.c:131068
static void nullifFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:104970
#define SQLITE_SKIP_UTF8(zIn)
Definition: sqlite3.c:15969
#define etEXP
Definition: sqlite3.c:24731
#define SQLITE_CHECKPOINT_TRUNCATE
Definition: sqlite3.c:8172
char affinity
Definition: sqlite3.c:14908
int nOpAlloc
Definition: sqlite3.c:15535
#define OP_Lt
Definition: sqlite3.c:12602
u8 hints
Definition: sqlite3.c:57769
int(* xDestroy)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:6068
SQLITE_API void sqlite3_result_blob(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:75442
SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *, Expr *, int)
Definition: sqlite3.c:93772
static int termIsEquivalence(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:127154
u8 enc
Definition: sqlite3.c:13770
SQLITE_PRIVATE sqlite3_file * sqlite3PagerFile(Pager *)
Definition: sqlite3.c:53115
int iNextSelectId
Definition: sqlite3.c:15606
#define OP_SorterInsert
Definition: sqlite3.c:12687
char * zName
Definition: sqlite3.c:14322
static int vdbeCommit(sqlite3 *db, Vdbe *p)
Definition: sqlite3.c:72644
SQLITE_API int sqlite3_enable_shared_cache(int)
Definition: sqlite3.c:58332
#define OP_Vacuum
Definition: sqlite3.c:12572
char * zName
Definition: sqlite3.c:14264
SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *)
Definition: sqlite3.c:69413
struct CCurHint * pCCurHint
Definition: sqlite3.c:15917
int nCte
Definition: sqlite3.c:15944
SQLITE_API void sqlite3_result_blob64(sqlite3_context *, const void *, sqlite3_uint64, void(*)(void *))
Definition: sqlite3.c:75452
u8 overflow
Definition: sqlite3.c:105556
static void pthreadMutexLeave(sqlite3_mutex *p)
Definition: sqlite3.c:23144
SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id)
Definition: sqlite3.c:19901
static void yyStackOverflow(yyParser *yypParser)
Definition: sqlite3.c:134599
#define SRT_EphemTab
Definition: sqlite3.c:15414
#define TK_FOREIGN
Definition: sqlite3.c:11404
SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *, int)
Definition: sqlite3.c:98808
sqlite3_pcache_methods2 pcache2
Definition: sqlite3.c:15839
SQLITE_API int sqlite3_status64(int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag)
Definition: sqlite3.c:18356
#define SQLITE_CONFIG_MULTITHREAD
Definition: sqlite3.c:2129
static int connectionIsBusy(sqlite3 *db)
Definition: sqlite3.c:138867
SQLITE_PRIVATE TriggerStep * sqlite3TriggerInsertStep(sqlite3 *, Token *, IdList *, Select *, u8)
Definition: sqlite3.c:120659
unsigned char eFileLock
Definition: sqlite3.c:29394
#define TK_PLAN
Definition: sqlite3.c:11295
#define SQLITE_OPEN_WAL
Definition: sqlite3.c:808
#define O_BINARY
Definition: sqlite3.c:29683
SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal)
Definition: sqlite3.c:56258
sqlite3_int64 mxMmap
Definition: sqlite3.c:15844
SQLITE_API void * sqlite3_aggregate_context(sqlite3_context *, int nBytes)
Definition: sqlite3.c:75909
static int noopMutexTry(sqlite3_mutex *p)
Definition: sqlite3.c:22629
bft doingRerun
Definition: sqlite3.c:18070
u8 changeCountDone
Definition: sqlite3.c:47012
static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC)
Definition: sqlite3.c:59169
#define FTS5_TOKENIZE_DOCUMENT
Definition: sqlite3.c:10576
#define SF_Converted
Definition: sqlite3.c:15331
#define CC_DIGIT
Definition: sqlite3.c:136601
static char * whereOrName(sqlite3 *db, char *zWhere, char *zConstant)
Definition: sqlite3.c:95011
static int walHash(u32 iPage)
Definition: sqlite3.c:54622
static void ctimestampFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:19661
sqlite3 * db
Definition: sqlite3.c:57600
u8 bUseThreads
Definition: sqlite3.c:85173
u32 iCallback
Definition: sqlite3.c:54214
SQLITE_PRIVATE void * sqlite3PagerGetExtra(DbPage *)
Definition: sqlite3.c:53359
#define TRIGGER_AFTER
Definition: sqlite3.c:15719
sqlite3_vtab_cursor * pVCur
Definition: sqlite3.c:17780
#define MEM_Ephem
Definition: sqlite3.c:17936
#define SQLITE_VdbeAddopTrace
Definition: sqlite3.c:14056
void * pLogArg
Definition: sqlite3.c:15864
#define MAX_PATHNAME
Definition: sqlite3.c:29349
#define UNIXFILE_NOLOCK
Definition: sqlite3.c:29464
AuxData * pAuxData
Definition: sqlite3.c:17853
static int autoVacuumCommit(BtShared *pBt)
Definition: sqlite3.c:61894
#define OP_RowData
Definition: sqlite3.c:12684
SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *, sqlite3_vtab *)
Definition: sqlite3.c:75021
#define SQLITE_FUNC_MINMAX
Definition: sqlite3.c:14194
#define SQLITE_FCNTL_WIN32_SET_HANDLE
Definition: sqlite3.c:1291
SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *, Expr *)
Definition: sqlite3.c:127738
#define SQLITE_IOCAP_SAFE_APPEND
Definition: sqlite3.c:849
SQLITE_PRIVATE TriggerStep * sqlite3TriggerSelectStep(sqlite3 *, Select *)
Definition: sqlite3.c:120616
int regRoot
Definition: sqlite3.c:15548
const struct sqlite3_io_methods * pMethods
Definition: sqlite3.c:911
static int tableAndColumnIndex(SrcList *pSrc, int N, const char *zCol, int *piTab, int *piCol)
Definition: sqlite3.c:114668
#define P4_ADVANCE
Definition: sqlite3.c:12517
#define BTREE_INTKEY
Definition: sqlite3.c:12134
static int pagerWalFrames(Pager *pPager, PgHdr *pList, Pgno nTruncate, int isCommit)
Definition: sqlite3.c:49442
#define SQLITE_RecoveryMode
Definition: sqlite3.c:14060
static LogEst estLog(LogEst N)
Definition: sqlite3.c:128323
SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *)
Definition: sqlite3.c:58988
#define MEMJOURNAL_DFLT_FILECHUNKSIZE
Definition: sqlite3.c:87647
SQLITE_PRIVATE char * sqlite3VdbeExpandSql(Vdbe *, const char *)
Definition: sqlite3.c:77093
unixShm * pNext
Definition: sqlite3.c:33445
#define osStat
SubProgram * pProgram
Definition: sqlite3.c:15475
#define SimulateIOErrorBenign(X)
Definition: sqlite3.c:29649
SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *, Expr *, int *, char *)
Definition: sqlite3.c:105811
#define BITVEC_NPTR
Definition: sqlite3.c:43234
static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:59145
static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code)
Definition: sqlite3.c:27401
static int checkRef(IntegrityCk *pCheck, Pgno iPage)
Definition: sqlite3.c:67112
SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse *, ExprList *, const char *)
Definition: sqlite3.c:91331
#define SQLITE_CkptFullFSync
Definition: sqlite3.c:14045
#define MEM_Undefined
Definition: sqlite3.c:17923
action
static void explainSimpleCount(Parse *pParse, Table *pTab, Index *pIdx)
Definition: sqlite3.c:119161
static void closePendingFds(unixFile *pFile)
Definition: sqlite3.c:30586
struct RowSetChunk * pChunk
Definition: sqlite3.c:45823
#define OP_OpenRead
Definition: sqlite3.c:12666
#define SQLITE_IOCAP_ATOMIC
Definition: sqlite3.c:840
SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *)
Definition: sqlite3.c:127896
SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *)
Definition: sqlite3.c:20046
SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *)
Definition: sqlite3.c:87528
SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *)
Definition: sqlite3.c:66982
static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal)
Definition: sqlite3.c:105770
static int sqlite3InRhsIsConstant(Expr *pIn)
Definition: sqlite3.c:91729
TFSIMD_FORCE_INLINE const tfScalar & z() const
u16 nFresh
Definition: sqlite3.c:45829
#define SQLITE_DYNAMIC
Definition: sqlite3.c:11916
static const void * fetchPayload(BtCursor *pCur, u32 *pAmt)
Definition: sqlite3.c:62953
int(* xAdvance)(BtCursor *, int *)
Definition: sqlite3.c:12458
#define osPwrite64
SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt)
Definition: sqlite3.c:76680
static const unsigned char aJournalMagic[]
Definition: sqlite3.c:47123
struct IdxCover * pIdxCover
Definition: sqlite3.c:15919
#define P4_EXPR
Definition: sqlite3.c:12507
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *, Expr *, u32)
Definition: sqlite3.c:90670
SQLITE_API void sqlite3_value_free(sqlite3_value *)
Definition: sqlite3.c:75399
static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr)
Definition: sqlite3.c:30186
#define SQLITE_STATUS_MALLOC_COUNT
Definition: sqlite3.c:7123
#define YY_ERROR_ACTION
Definition: sqlite3.c:133128
unsigned int nMinPage
Definition: sqlite3.c:44587
#define SQLITE_OPEN_FULLMUTEX
Definition: sqlite3.c:805
SQLITE_API int sqlite3_bind_text16(sqlite3_stmt *, int, const void *, int, void(*)(void *))
Definition: sqlite3.c:76507
SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse *, ExprList *, int, int, u8)
Definition: sqlite3.c:93800
int aStat[3]
Definition: sqlite3.c:47056
#define CC_PLUS
Definition: sqlite3.c:136618
#define OP_SeekLT
Definition: sqlite3.c:12585
static MemPage * btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt)
Definition: sqlite3.c:60147
SQLITE_PRIVATE KeyInfo * sqlite3KeyInfoAlloc(sqlite3 *, int, int)
Definition: sqlite3.c:115395
u8 isMultiWrite
Definition: sqlite3.c:15524
int iSelectId
Definition: sqlite3.c:15605
u8 enc
Definition: sqlite3.c:14616
VdbeOp * aOp
Definition: sqlite3.c:12478
WhereInfo * pWInfo
Definition: sqlite3.c:124126
static int vdbeSafety(Vdbe *p)
Definition: sqlite3.c:75156
signed char p4type
Definition: sqlite3.c:12434
SQLITE_API int sqlite3_total_changes(sqlite3 *)
Definition: sqlite3.c:138789
void(* xFreeSchema)(void *)
Definition: sqlite3.c:57688
int * aTree
Definition: sqlite3.c:85101
static sqlite3_pcache * pcache1Create(int szPage, int szExtra, int bPurgeable)
Definition: sqlite3.c:45203
#define WHERETRACE(K, X)
Definition: sqlite3.c:123837
SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int)
Definition: sqlite3.c:87947
SQLITE_PRIVATE int sqlite3FixExprList(DbFixer *, ExprList *)
Definition: sqlite3.c:97999
SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8)
Definition: sqlite3.c:73688
#define TF_HasPrimaryKey
Definition: sqlite3.c:14479
Btree * pWriter
Definition: sqlite3.c:57695
int bLocaltimeFault
Definition: sqlite3.c:15879
#define WHERE_OR_SUBCLAUSE
Definition: sqlite3.c:15195
#define OP_VCreate
Definition: sqlite3.c:12715
#define HAS_UPDATE_HOOK(DB)
Definition: sqlite3.c:77314
SQLITE_PRIVATE SrcList * sqlite3SrcListAppend(sqlite3 *, SrcList *, Token *, Token *)
Definition: sqlite3.c:102025
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *, Expr *)
Definition: sqlite3.c:90769
#define BITVEC_NELEM
Definition: sqlite3.c:43219
#define TK_OR
Definition: sqlite3.c:11318
SorterFile file2
Definition: sqlite3.c:85146
struct sqlite3::sqlite3InitInfo init
#define TF_WithoutRowid
Definition: sqlite3.c:14482
SQLITE_API int sqlite3_column_type(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76178
#define SQLITE_AUTH_USER
Definition: sqlite3.c:779
#define TK_INTO
Definition: sqlite3.c:11422
static void dateFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19462
#define SRT_Except
Definition: sqlite3.c:15400
#define YY_ACCEPT_ACTION
Definition: sqlite3.c:133129
VTable ** aVTrans
Definition: sqlite3.c:13991
#define TK_INDEXED
Definition: sqlite3.c:11347
static const char zMagicHeader[]
Definition: sqlite3.c:58265
u8 eLock
Definition: sqlite3.c:57570
SQLITE_PRIVATE UnpackedRecord * sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **)
Definition: sqlite3.c:73948
#define SQLITE_FCNTL_DB_UNCHANGED
Definition: sqlite3.c:13582
Table * pEpoTab
Definition: sqlite3.c:14289
#define SORTER_MAX_MERGE_COUNT
Definition: sqlite3.c:85302
static void addWhereTerm(Parse *pParse, SrcList *pSrc, int iLeft, int iColLeft, int iRight, int iColRight, int isOuterJoin, Expr **ppWhere)
Definition: sqlite3.c:114703
#define TK_ADD
Definition: sqlite3.c:11433
SQLITE_API void sqlite3_result_double(sqlite3_context *, double)
Definition: sqlite3.c:75466
#define SCHEMA_TABLE(x)
Definition: sqlite3.c:11895
SQLITE_API sqlite3_int64 sqlite3_memory_used(void)
Definition: sqlite3.c:24073
SQLITE_API int sqlite3_stmt_scanstatus(sqlite3_stmt *pStmt, int idx, int iScanStatusOp, void *pOut)
SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char *, Mem *, u32)
#define SQLITE_RECURSIVE
Definition: sqlite3.c:3050
SQLITE_PRIVATE int sqlite3GetInt32(const char *, int *)
Definition: sqlite3.c:27959
SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *, u32)
Definition: sqlite3.c:43317
#define SQLITE_TESTCTRL_NEVER_CORRUPT
Definition: sqlite3.c:6988
#define JT_OUTER
Definition: sqlite3.c:15178
#define SQLITE_OPEN_SHAREDCACHE
Definition: sqlite3.c:806
#define WAL_CKPT_LOCK
Definition: sqlite3.c:54063
#define OMIT_TEMPDB
Definition: sqlite3.c:11499
#define etCHARX
Definition: sqlite3.c:24737
SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *)
Definition: sqlite3.c:24667
#define OP_DropTable
Definition: sqlite3.c:12700
static sqlite3_pcache_page * pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag)
Definition: sqlite3.c:45477
SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int *, int *)
Definition: sqlite3.c:91823
struct Fts5Context Fts5Context
Definition: sqlite3.c:10088
SQLITE_API SQLITE_EXPERIMENTAL void * sqlite3_preupdate_hook(sqlite3 *db, void(*xPreUpdate)(void *pCtx, sqlite3 *db, int op, char const *zDb, char const *zName, sqlite3_int64 iKey1, sqlite3_int64 iKey2), void *)
static void * vdbeSorterRowkey(const VdbeSorter *pSorter, int *pnKey)
Definition: sqlite3.c:87501
#define UNIXFILE_URI
Definition: sqlite3.c:29463
#define BTREE_BULKLOAD
Definition: sqlite3.c:12217
#define SQLITE_CONFIG_SQLLOG
Definition: sqlite3.c:2148
int iContinue
Definition: sqlite3.c:124225
SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db)
Definition: sqlite3.c:123450
#define sqlite3StackFree(D, P)
Definition: sqlite3.c:16100
SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *, Token *)
Definition: sqlite3.c:122927
SQLITE_API const unsigned char * sqlite3_column_text(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76157
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse *, Table *, int, int, int, u8)
Definition: sqlite3.c:92893
int szPage
Definition: sqlite3.c:43625
int(* xDelete)(sqlite3_vfs *, const char *zName, int syncDir)
Definition: sqlite3.c:1495
#define sqlite3ParserARG_PDECL
Definition: sqlite3.c:133117
#define SQLITE_CursorHints
Definition: sqlite3.c:14094
static sqlite3_syscall_ptr unixGetSystemCall(sqlite3_vfs *pNotUsed, const char *zName)
Definition: sqlite3.c:29952
#define SF_Expanded
Definition: sqlite3.c:15321
#define YY_REDUCE_COUNT
Definition: sqlite3.c:133574
int szPage
Definition: sqlite3.c:56620
#define SRT_Fifo
Definition: sqlite3.c:15403
SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *)
Definition: sqlite3.c:122828
SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager)
Definition: sqlite3.c:53698
SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char *, const char *, sqlite3_int64)
Definition: sqlite3.c:141747
#define fileChunkSize(nChunkSize)
Definition: sqlite3.c:87653
u8 op
Definition: sqlite3.c:14907
u32 magic
Definition: sqlite3.c:18034
SQLITE_API const char * sqlite3_compileoption_get(int N)
Definition: sqlite3.c:17659
static int vdbePmaReaderNext(PmaReader *pReadr)
Definition: sqlite3.c:85519
#define OP_SequenceTest
Definition: sqlite3.c:12671
static TriggerPrg * getRowTrigger(Parse *pParse, Trigger *pTrigger, Table *pTab, int orconf)
Definition: sqlite3.c:121170
#define IsOrdinaryHiddenColumn(X)
Definition: sqlite3.c:14509
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *, int, const char *)
Definition: sqlite3.c:120840
u8 bOrderedInnerLoop
Definition: sqlite3.c:114448
#define SQLITE_MAGIC_ERROR
Definition: sqlite3.c:14123
#define SQLITE_SELECT
Definition: sqlite3.c:3037
char * zDb
Definition: sqlite3.c:84367
SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *)
Definition: sqlite3.c:20149
SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *)
Definition: sqlite3.c:45873
#define EP_Propagate
Definition: sqlite3.c:14983
SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id)
Definition: sqlite3.c:19895
static int isDate(sqlite3_context *context, int argc, sqlite3_value **argv, DateTime *p)
Definition: sqlite3.c:19365
WhereMaskSet sMaskSet
Definition: sqlite3.c:124241
Bool isOrdered
Definition: sqlite3.c:17774
static void codeOffset(Vdbe *v, int iOffset, int iContinue)
Definition: sqlite3.c:115013
SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *, ExprSpan *)
Definition: sqlite3.c:99503
#define TK_BY
Definition: sqlite3.c:11355
#define SQLITE_INDEX_CONSTRAINT_REGEXP
Definition: sqlite3.c:6242
#define TF_Readonly
Definition: sqlite3.c:14477
#define sqliteHashData(E)
Definition: sqlite3.c:11277
#define SQLITE_DEFAULT_PAGE_SIZE
Definition: sqlite3.c:10805
SQLITE_PRIVATE void sqlite3Analyze(Parse *, Token *, Token *)
Definition: sqlite3.c:96905
u32 nAlloc
Definition: sqlite3.c:15135
#define SQLITE_FCNTL_FILE_POINTER
Definition: sqlite3.c:1276
ExprList * pCols
Definition: sqlite3.c:15948
static void walShmBarrier(Wal *pWal)
Definition: sqlite3.c:54436
#define XN_ROWID
Definition: sqlite3.c:14754
FuncDestructor * pDestructor
Definition: sqlite3.c:14146
SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse *, Index *, int, int, int, int *, Index *, int)
Definition: sqlite3.c:104049
#define WHERE_CONSTRAINT
Definition: sqlite3.c:124345
u32 iSize
Definition: sqlite3.c:43259
#define SQLITE_DELETE
Definition: sqlite3.c:3025
#define sqlite3ConnectionUnlocked(x)
Definition: sqlite3.c:16849
#define memAboutToChange(P, M)
Definition: sqlite3.c:77254
SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int)
Definition: sqlite3.c:74939
u8 * aData
Definition: sqlite3.c:57543
SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *)
Definition: sqlite3.c:87561
static const struct compareInfo globInfo
Definition: sqlite3.c:104707
#define OP_AutoCommit
Definition: sqlite3.c:12563
u8 useJournal
Definition: sqlite3.c:46989
#define SQLITE_AFF_TEXT
Definition: sqlite3.c:14351
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
Definition: sqlite3.c:6977
#define SQLITE_FullColNames
Definition: sqlite3.c:14043
int nSortingColumn
Definition: sqlite3.c:14803
static int readDbPage(PgHdr *pPg, u32 iFrame)
Definition: sqlite3.c:49282
static int columnIndex(Table *pTab, const char *zCol)
Definition: sqlite3.c:114651
#define SQLITE_DROP_TEMP_VIEW
Definition: sqlite3.c:3031
static void selectInnerLoop(Parse *pParse, Select *p, ExprList *pEList, int srcTab, SortCtx *pSort, DistinctCtx *pDistinct, SelectDest *pDest, int iContinue, int iBreak)
Definition: sqlite3.c:115060
#define VDBE_MAGIC_DEAD
Definition: sqlite3.c:18103
char * zColAff
Definition: sqlite3.c:14441
#define EP_Leaf
Definition: sqlite3.c:14978
u8 * pTmpSpace
Definition: sqlite3.c:57697
#define OP_Destroy
Definition: sqlite3.c:12692
int(* xPhraseSize)(Fts5Context *, int iPhrase)
Definition: sqlite3.c:10335
sqlite3_pcache * pCache
Definition: sqlite3.c:43631
sqlite3_rtree_dbl * aParam
Definition: sqlite3.c:8736
long long int sqlite_int64
Definition: sqlite3.c:527
#define pcache1LeaveMutex(X)
Definition: sqlite3.c:44677
int nKeyCol
Definition: sqlite3.c:95848
#define N_OR_COST
Definition: sqlite3.c:123970
#define FTS5_TOKENIZE_AUX
Definition: sqlite3.c:10577
SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag)
Definition: sqlite3.c:24084
#define testcase(X)
Definition: sqlite3.c:11070
SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree)
Definition: sqlite3.c:67782
ExprSpan yy190
Definition: sqlite3.c:133104
WhereClause * pOuter
Definition: sqlite3.c:124127
SQLITE_PRIVATE void sqlite3ExprCode(Parse *, Expr *, int)
Definition: sqlite3.c:93719
int leftCursor
Definition: sqlite3.c:124064
static int findCreateFileMode(const char *zPath, int flags, mode_t *pMode, uid_t *pUid, gid_t *pGid)
Definition: sqlite3.c:34958
#define WHERE_MULTI_OR
Definition: sqlite3.c:124355
#define TK_DELETE
Definition: sqlite3.c:11400
LogEst nEst
Definition: sqlite3.c:18017
#define CC_VARALPHA
Definition: sqlite3.c:136603
#define DbMaskSet(M, I)
Definition: sqlite3.c:15494
SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *)
Definition: sqlite3.c:86069
#define OP_CreateTable
Definition: sqlite3.c:12697
#define SQLITE_FUNC_COALESCE
Definition: sqlite3.c:14191
#define PAGER_WRITER_LOCKED
Definition: sqlite3.c:46718
#define SQLITE_WSD
Definition: sqlite3.c:11939
#define TK_TEMP
Definition: sqlite3.c:11312
char ** apRegion
Definition: sqlite3.c:33420
int iGeneration
Definition: sqlite3.c:13763
static With * withDup(sqlite3 *db, With *p)
Definition: sqlite3.c:90982
SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void)
Definition: sqlite3.c:45644
#define SQLITE_TRACE_STMT
Definition: sqlite3.c:3141
u16 maxLocal
Definition: sqlite3.c:57533
#define MEMTYPE_SCRATCH
Definition: sqlite3.c:16910
TFSIMD_FORCE_INLINE const tfScalar & w() const
static int collationMatch(const char *zColl, Index *pIndex)
Definition: sqlite3.c:102501
SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *)
Definition: sqlite3.c:28277
#define SELECTTRACE(K, P, S, X)
Definition: sqlite3.c:114417
SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int)
Definition: sqlite3.c:43891
SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *)
Definition: sqlite3.c:86102
static SQLITE_NOINLINE void backupUpdate(sqlite3_backup *p, Pgno iPage, const u8 *aData)
Definition: sqlite3.c:68649
#define SPILLFLAG_NOSYNC
Definition: sqlite3.c:46827
u32 payloadSize
Definition: sqlite3.c:17805
void * data
Definition: sqlite3.c:11251
static void btreeParseCellPtrNoPayload(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:59325
const char * zStart
Definition: sqlite3.c:15062
#define PragTyp_DATA_STORE_DIRECTORY
Definition: sqlite3.c:111120
#define UPDATE_MAX_BLOBSIZE(P)
Definition: sqlite3.c:77335
ino_t ino
Definition: sqlite3.c:30448
static int fkParentIsModified(Table *pTab, FKey *p, int *aChange, int bChngRowid)
Definition: sqlite3.c:106758
#define PragTyp_PAGE_SIZE
Definition: sqlite3.c:111136
int iCacheCnt
Definition: sqlite3.c:15540
u8 file_format
Definition: sqlite3.c:13769
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2)
#define INCRINIT_TASK
Definition: sqlite3.c:86925
static int unixCheckReservedLock(sqlite3_file *id, int *pResOut)
Definition: sqlite3.c:30774
SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N)
Definition: sqlite3.c:24004
#define OP_MakeRecord
Definition: sqlite3.c:12661
#define OP_If
Definition: sqlite3.c:12583
u8 * aKey
Definition: sqlite3.c:85199
void * pPage
Definition: sqlite3.c:15848
YYCODETYPE major
Definition: sqlite3.c:133795
SQLITE_PRIVATE CollSeq * sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *)
Definition: sqlite3.c:90009
#define EP_Collate
Definition: sqlite3.c:14963
Mem * aMem
Definition: sqlite3.c:18051
static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle)
Definition: sqlite3.c:35538
void * pUser
Definition: sqlite3.c:14324
#define PARTLY_WITHIN
Definition: sqlite3.c:8757
int nAlloc
Definition: sqlite3.c:85195
SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *, int, int n)
Definition: sqlite3.c:76548
#define ALLBITS
Definition: sqlite3.c:15112
#define SQLITE_SHM_EXCLUSIVE
Definition: sqlite3.c:1574
SQLITE_PRIVATE void sqlite3MemoryBarrier(void)
Definition: sqlite3.c:22891
CellInfo info
Definition: sqlite3.c:57759
#define SQLITE_CONFIG_MUTEX
Definition: sqlite3.c:2137
static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock)
Definition: sqlite3.c:58562
Table * pTab
Definition: sqlite3.c:14949
#define N_SORT_BUCKET
Definition: sqlite3.c:44306
#define EP_Alias
Definition: sqlite3.c:14977
u32 aCounter[5]
Definition: sqlite3.c:18080
SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *)
Definition: sqlite3.c:73373
SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *)
Definition: sqlite3.c:123472
#define TK_JOIN
Definition: sqlite3.c:11415
SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *)
Definition: sqlite3.c:58138
#define SQLITE_READONLY_CANTLOCK
Definition: sqlite3.c:762
#define WHERE_USE_LIMIT
Definition: sqlite3.c:15205
Wal * pWal
Definition: sqlite3.c:56616
static int pcache1Init(void *NotUsed)
Definition: sqlite3.c:45136
SQLITE_PRIVATE void sqlite3AddNotNull(Parse *, int)
Definition: sqlite3.c:99399
#define SQLITE_TESTCTRL_PENDING_BYTE
Definition: sqlite3.c:6978
#define OP_Close
Definition: sqlite3.c:12673
SrcList * pTabList
Definition: sqlite3.c:124220
WhereLoop * pNew
Definition: sqlite3.c:124200
union Expr::@4 x
SQLITE_API const char * sqlite3_column_decltype(sqlite3_stmt *, int)
Definition: sqlite3.c:76267
i16 readLock
Definition: sqlite3.c:54220
WhereClause wc
Definition: sqlite3.c:124144
#define mem0
Definition: sqlite3.c:23951
SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *)
Definition: sqlite3.c:58129
u8 sortFlags
Definition: sqlite3.c:114447
Schema * pSchema
Definition: sqlite3.c:14464
u8 dfltLockMode
Definition: sqlite3.c:13922
int iLimit
Definition: sqlite3.c:15289
#define P4_VTAB
Definition: sqlite3.c:12510
#define OP_VRename
Definition: sqlite3.c:12719
#define SQLITE_CONFIG_SINGLETHREAD
Definition: sqlite3.c:2128
#define ONEPASS_OFF
Definition: sqlite3.c:16320
#define SQLITE_IOERR_FSYNC
Definition: sqlite3.c:728
SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **)
Definition: sqlite3.c:19929
static int vdbeSorterCompareTail(SortSubtask *pTask, int *pbKey2Cached, const void *pKey1, int nKey1, const void *pKey2, int nKey2)
Definition: sqlite3.c:85599
static int vdbeMergeEngineInit(SortSubtask *pTask, MergeEngine *pMerger, int eMode)
Definition: sqlite3.c:86953
#define PAGER_STAT_HIT
Definition: sqlite3.c:47080
const char * zName
Definition: sqlite3.c:1491
int flags
Definition: sqlite3.c:13909
#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal)
Definition: sqlite3.c:14250
SQLITE_PRIVATE void sqlite3MaterializeView(Parse *, Table *, Expr *, int)
Definition: sqlite3.c:103305
int nLabel
Definition: sqlite3.c:15541
bft changeCntOn
Definition: sqlite3.c:18072
#define TK_CASCADE
Definition: sqlite3.c:11356
static void estimateTableWidth(Table *pTab)
Definition: sqlite3.c:99913
static void incrAggFunctionDepth(Expr *pExpr, int N)
Definition: sqlite3.c:88219
#define OP_InitCoroutine
Definition: sqlite3.c:12577
static void last_insert_rowid(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:104638
FuncDef * pDef
Definition: sqlite3.c:17876
static void yy_syntax_error(yyParser *yypParser, int yymajor, sqlite3ParserTOKENTYPE yyminor)
Definition: sqlite3.c:136353
static void walMerge(const u32 *aContent, ht_slot *aLeft, int nLeft, ht_slot **paRight, int *pnRight, ht_slot *aTmp)
Definition: sqlite3.c:55203
int ix[BMS]
Definition: sqlite3.c:124184
u8 intKeyLeaf
Definition: sqlite3.c:57527
i64 journalHdr
Definition: sqlite3.c:47031
#define TK_SPAN
Definition: sqlite3.c:11452
static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak)
Definition: sqlite3.c:116221
SQLITE_PRIVATE Index * sqlite3PrimaryKeyIndex(Table *)
Definition: sqlite3.c:99094
int(* xFullPathname)(sqlite3_vfs *, const char *zName, int nOut, char *zOut)
Definition: sqlite3.c:1497
SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *, Expr *, u8)
Definition: sqlite3.c:127682
SQLITE_PRIVATE Expr * sqlite3ExprDup(sqlite3 *, Expr *, int)
Definition: sqlite3.c:91020
#define ONEPASS_SINGLE
Definition: sqlite3.c:16321
static void robust_close(unixFile *pFile, int h, int lineno)
Definition: sqlite3.c:30568
static int invalidateTempStorage(Parse *pParse)
Definition: sqlite3.c:111672
static void clearAllSharedCacheTableLocks(Btree *p)
Definition: sqlite3.c:58626
static void pager_unlock(Pager *pPager)
Definition: sqlite3.c:48130
#define P4_FUNCDEF
Definition: sqlite3.c:12505
SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *, int)
Definition: sqlite3.c:27421
SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *)
Definition: sqlite3.c:91588
#define O_LARGEFILE
Definition: sqlite3.c:29673
SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *)
Definition: sqlite3.c:73232
#define put2byte(p, v)
Definition: sqlite3.c:57939
#define SQLITE_FCNTL_LAST_ERRNO
Definition: sqlite3.c:1273
#define SF_IncludeHidden
Definition: sqlite3.c:15332
int nVdbeActive
Definition: sqlite3.c:13941
#define WHERE_ONEPASS_DESIRED
Definition: sqlite3.c:15192
#define etRADIX
Definition: sqlite3.c:24729
static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan)
Definition: sqlite3.c:132969
#define OP_NewRowid
Definition: sqlite3.c:12676
#define SQLITE_INDEX_CONSTRAINT_LE
Definition: sqlite3.c:6236
void(* xDel)(void *)
Definition: sqlite3.c:14326
#define EP_DblQuoted
Definition: sqlite3.c:14961
Pager * pPager
Definition: sqlite3.c:57923
#define NC_PartIdx
Definition: sqlite3.c:15256
char * zErrMsg
Definition: sqlite3.c:120096
WhereClause sWC
Definition: sqlite3.c:124240
CollSeq * pColl
Definition: sqlite3.c:12448
WhereInfo * pWInfo
Definition: sqlite3.c:124197
SQLITE_PRIVATE int sqlite3BtreeClose(Btree *)
Definition: sqlite3.c:60748
i16 nRef
Definition: sqlite3.c:13199
u8 syncFlags
Definition: sqlite3.c:46995
#define SQLITE_FCNTL_VFS_POINTER
Definition: sqlite3.c:1295
struct TrigEvent yy332
Definition: sqlite3.c:133109
#define SQLITE_OPEN_TRANSIENT_DB
Definition: sqlite3.c:799
u8 exclusiveMode
Definition: sqlite3.c:54222
static void yy_shift(yyParser *yypParser, int yyNewState, int yyMajor, sqlite3ParserTOKENTYPE yyMinor)
Definition: sqlite3.c:134640
#define DB_UnresetViews
Definition: sqlite3.c:13795
Bitmask prereq
Definition: sqlite3.c:123920
static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode)
Definition: sqlite3.c:87024
u8 truncateOnCommit
Definition: sqlite3.c:54226
SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *, u8)
Definition: sqlite3.c:70460
#define osOpenDirectory
SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void *, sqlite3_int64, int), void *, sqlite3_int64)
#define OP_Variable
Definition: sqlite3.c:12644
u8 disableTriggers
Definition: sqlite3.c:15567
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *)
Definition: sqlite3.c:132633
SQLITE_API const void * sqlite3_value_text16(sqlite3_value *)
Definition: sqlite3.c:75322
#define TK_LIKE_KW
Definition: sqlite3.c:11322
SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *, int n)
Definition: sqlite3.c:75560
SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *)
Definition: sqlite3.c:123734
#define UINT16_TYPE
Definition: sqlite3.c:11611
static char * displayP4(Op *pOp, char *zTemp, int nTemp)
Definition: sqlite3.c:71716
SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *, int *, int flags)
Definition: sqlite3.c:66661
sqlite3_file * pDbFd
Definition: sqlite3.c:54212
HashElem * chain
Definition: sqlite3.c:11239
void * pOut
Definition: sqlite3.c:26507
Btree * pPrev
Definition: sqlite3.c:57610
SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p)
Definition: sqlite3.c:88008
SQLITE_PRIVATE void * sqlite3ScratchMalloc(int)
Definition: sqlite3.c:24196
SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *)
Definition: sqlite3.c:44146
SQLITE_API char * sqlite3_data_directory
Definition: sqlite3.c:5491
static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed)
Definition: sqlite3.c:91459
#define etFLOAT
Definition: sqlite3.c:24730
#define EP_Agg
Definition: sqlite3.c:14956
SQLITE_PRIVATE VdbeOp * sqlite3VdbeGetOp(Vdbe *, int)
Definition: sqlite3.c:71522
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config
Definition: sqlite3.c:17109
SQLITE_PRIVATE void sqlite3PageFree(void *)
Definition: sqlite3.c:44935
SQLITE_API int sqlite3_create_module(sqlite3 *db, const char *zName, const sqlite3_module *p, void *pClientData)
Definition: sqlite3.c:122638
#define HAVE_FULLFSYNC
Definition: sqlite3.c:32769
#define TERM_OR_OK
Definition: sqlite3.c:124084
int iArg
Definition: sqlite3.c:17974
#define TK_WHERE
Definition: sqlite3.c:11421
static void analyzeDatabase(Parse *pParse, int iDb)
Definition: sqlite3.c:96847
#define PCACHE_DIRTYLIST_FRONT
Definition: sqlite3.c:43728
#define vdbeSorterWorkDebug(x, y)
Definition: sqlite3.c:85941
SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *, int)
Definition: sqlite3.c:19853
#define IN_INDEX_MEMBERSHIP
Definition: sqlite3.c:16818
#define PGHDR_WAL_APPEND
Definition: sqlite3.c:13215
int nRefInitMutex
Definition: sqlite3.c:15861
static int flattenSubquery(Parse *pParse, Select *p, int iFrom, int isAgg, int subqueryIsAgg)
Definition: sqlite3.c:117717
#define yyTraceShift(X, Y)
Definition: sqlite3.c:134634
static struct RowSetEntry * rowSetEntryMerge(struct RowSetEntry *pA, struct RowSetEntry *pB)
Definition: sqlite3.c:45951
static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize)
Definition: sqlite3.c:87904
u16 maxLocal
Definition: sqlite3.c:57679
SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager)
Definition: sqlite3.c:53576
static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree)
Definition: sqlite3.c:61826
SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context *)
Definition: sqlite3.c:76000
u8 * pPayload
Definition: sqlite3.c:57718
#define WO_SINGLE
Definition: sqlite3.c:124334
LogEst szTabRow
Definition: sqlite3.c:14449
#define OP_Int64
Definition: sqlite3.c:12639
#define PTRMAP_ROOTPAGE
Definition: sqlite3.c:57882
SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *)
Definition: sqlite3.c:72303
WhereLoop ** aLoop
Definition: sqlite3.c:124001
#define SQLITE_INDEX_CONSTRAINT_GT
Definition: sqlite3.c:6235
ExprList * pOrderBy
Definition: sqlite3.c:15428
int(* xShmMap)(sqlite3_file *, int iPg, int pgsz, int, void volatile **)
Definition: sqlite3.c:1020
int(* xMutexNotheld)(sqlite3_mutex *)
Definition: sqlite3.c:6830
#define SQLITE_CONFIG_GETMALLOC
Definition: sqlite3.c:2132
#define SRT_Union
Definition: sqlite3.c:15399
SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *)
Definition: sqlite3.c:44431
struct FKey::sColMap aCol[1]
#define SQLITE_CREATE_TEMP_VIEW
Definition: sqlite3.c:3022
struct unixFileId fileId
Definition: sqlite3.c:30462
VTable * pVTable
Definition: sqlite3.c:122582
SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName)
Definition: sqlite3.c:141795
static Expr * exprTableRegister(Parse *pParse, Table *pTab, int regBase, i16 iCol)
Definition: sqlite3.c:106426
static void applyAffinity(Mem *pRec, char affinity, u8 enc)
Definition: sqlite3.c:77505
static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg)
Definition: sqlite3.c:33137
static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv)
Definition: sqlite3.c:120109
#define ExprSetProperty(E, P)
Definition: sqlite3.c:14991
static SQLITE_NOINLINE void * dbReallocFinish(sqlite3 *db, void *p, u64 n)
Definition: sqlite3.c:24561
static Btree * findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb)
Definition: sqlite3.c:68041
static void pcache1Shutdown(void *NotUsed)
Definition: sqlite3.c:45189
SQLITE_PRIVATE char * sqlite3MPrintf(sqlite3 *, const char *,...)
Definition: sqlite3.c:25652
static int isAllZero(const char *z, int n)
Definition: sqlite3.c:74203
#define OP_AggStep
Definition: sqlite3.c:12710
SQLITE_PRIVATE int sqlite3Strlen30(const char *)
Definition: sqlite3.c:27379
#define OP_Blob
Definition: sqlite3.c:12643
static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList)
Definition: sqlite3.c:86395
static pid_t randomnessPid
Definition: sqlite3.c:29448
static Pgno btreePagecount(BtShared *pBt)
Definition: sqlite3.c:60207
u16 rsFlags
Definition: sqlite3.c:45830
int errCode
Definition: sqlite3.c:47022
#define PAGER_MJ_PGNO(x)
Definition: sqlite3.c:12970
SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse *, SrcList *, Token *)
Definition: sqlite3.c:95140
#define TK_FOR
Definition: sqlite3.c:11365
BtCursor * pCursor
Definition: sqlite3.c:17779
#define ENC(db)
Definition: sqlite3.c:14031
int lastErrno
Definition: sqlite3.c:29396
SQLITE_PRIVATE sqlite3_mutex_methods const * sqlite3NoopMutex(void)
Definition: sqlite3.c:22635
SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal)
Definition: sqlite3.c:56417
#define LIKEFUNC(zName, nArg, arg, flags)
Definition: sqlite3.c:14247
struct Mem Mem
Definition: sqlite3.c:12424
Savepoint * pNext
Definition: sqlite3.c:14267
FuncDef * pHash
Definition: sqlite3.c:14145
WhereAndInfo * pAndInfo
Definition: sqlite3.c:124069
u8 ckptSyncFlags
Definition: sqlite3.c:46993
#define SQLITE_VERSION
Definition: sqlite3.c:384
const char * zName
Definition: sqlite3.c:98337
#define SQLITE_MAGIC_SICK
Definition: sqlite3.c:14121
SQLITE_PRIVATE Expr * sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int)
Definition: sqlite3.c:88691
SQLITE_PRIVATE int sqlite3CantopenError(int)
Definition: sqlite3.c:141151
int bDeclared
Definition: sqlite3.c:122585
#define TERM_ANDINFO
Definition: sqlite3.c:124083
#define DbHasProperty(D, I, P)
Definition: sqlite3.c:13779
#define SQLITE_INDEX_CONSTRAINT_GE
Definition: sqlite3.c:6238
#define PTRMAP_OVERFLOW1
Definition: sqlite3.c:57884
#define PGHDR_DIRTY
Definition: sqlite3.c:13208
static int vdbeSafetyNotNull(Vdbe *p)
Definition: sqlite3.c:75164
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *)
Definition: sqlite3.c:52728
SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op)
Definition: sqlite3.c:57117
const char * zDb
Definition: sqlite3.c:15782
union VdbeCursor::@10 uc
SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *, AuxData **, int, int)
Definition: sqlite3.c:73399
u8 bPurgeable
Definition: sqlite3.c:43627
#define SQLITE_MAX_COLUMN
Definition: sqlite3.c:10690
SQLITE_PRIVATE Expr * sqlite3ExprAddCollateToken(Parse *pParse, Expr *, const Token *, int)
Definition: sqlite3.c:89810
#define OP_Next
Definition: sqlite3.c:12569
#define SQLITE_ForeignKeys
Definition: sqlite3.c:14063
#define sqlite3StackAllocZero(D, N)
Definition: sqlite3.c:16099
struct WalIterator::WalSegment aSegment[1]
int iOp
Definition: sqlite3.c:17973
static int keywordCode(const char *z, int n, int *pType)
Definition: sqlite3.c:136730
AutoincInfo * pAinc
Definition: sqlite3.c:15558
u16 exclMask
Definition: sqlite3.c:33449
u8 openFlags
Definition: sqlite3.c:57667
#define OPFLAG_APPEND
Definition: sqlite3.c:15667
#define COLFLAG_PRIMKEY
Definition: sqlite3.c:14308
VdbeCursor * pAltCursor
Definition: sqlite3.c:17789
#define OP_OpenPseudo
Definition: sqlite3.c:12672
static int walFramePage(u32 iFrame)
Definition: sqlite3.c:54683
def read(directory, name)
Definition: xmltopdf.py:16
#define SQLITE_FCNTL_WIN32_GET_HANDLE
Definition: sqlite3.c:1297
#define SQLITE_SO_DESC
Definition: sqlite3.c:14333
SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *, int)
Definition: sqlite3.c:91503
char ** azVar
Definition: sqlite3.c:15608
static void transferJoinMarkings(Expr *pDerived, Expr *pBase)
Definition: sqlite3.c:126714
SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem)
Definition: sqlite3.c:27084
SQLITE_PRIVATE void sqlite3Attach(Parse *, Expr *, Expr *, Expr *)
Definition: sqlite3.c:97858
#define SQLITE_CONFIG_PMASZ
Definition: sqlite3.c:2152
#define TK_ATTACH
Definition: sqlite3.c:11353
unsigned int nMaxPage
Definition: sqlite3.c:44586
SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse *, Table *, Select *)
Definition: sqlite3.c:116097
sqlite3_vfs * pVfs
Definition: sqlite3.c:29391
#define PragTyp_INCREMENTAL_VACUUM
Definition: sqlite3.c:111126
#define PragTyp_CASE_SENSITIVE_LIKE
Definition: sqlite3.c:111117
#define SQLITE_INSERT
Definition: sqlite3.c:3034
static void invalidateAllOverflowCache(BtShared *pBt)
Definition: sqlite3.c:58721
Index * pCovidx
Definition: sqlite3.c:123896
#define OP_EndCoroutine
Definition: sqlite3.c:12635
SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *)
Definition: sqlite3.c:98782
sqlite3 * db
Definition: sqlite3.c:15792
struct RowSetEntry * pRight
Definition: sqlite3.c:45802
SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *)
Definition: sqlite3.c:127888
sqlite3_int64 iJD
Definition: sqlite3.c:18643
static void invalidateIncrblobCursors(Btree *pBtree, i64 iRow, int isClearTable)
Definition: sqlite3.c:58743
int min(int a, int b)
u8 bSyncSet
Definition: sqlite3.c:13740
SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *)
Definition: sqlite3.c:52843
#define CURTYPE_VTAB
Definition: sqlite3.c:17748
#define SQLITE_CONSTRAINT_NOTNULL
Definition: sqlite3.c:770
#define OP_Param
Definition: sqlite3.c:12705
int nSegment
Definition: sqlite3.c:54279
#define SRT_Queue
Definition: sqlite3.c:15405
static void vdbeMergeEngineCompare(MergeEngine *pMerger, int iOut)
Definition: sqlite3.c:86871
SQLITE_API int sqlite3_strnicmp(const char *, const char *, int)
Definition: sqlite3.c:27582
static int allowedOp(int op)
Definition: sqlite3.c:126483
#define SQLITE_OPEN_PRIVATECACHE
Definition: sqlite3.c:807
#define SQLITE_NOTNULL
Definition: sqlite3.c:14377
#define vdbeSorterPopulateDebug(x, y)
Definition: sqlite3.c:85943
#define unixLogError(a, b, c)
Definition: sqlite3.c:30502
u16 dbOptFlags
Definition: sqlite3.c:13916
#define TK_COMMIT
Definition: sqlite3.c:11301
static PgHdr * pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB)
Definition: sqlite3.c:44270
#define ApplyCostMultiplier(C, T)
Definition: sqlite3.c:130108
SQLITE_API const char * sqlite3_errstr(int)
Definition: sqlite3.c:140161
#define osFallocate
#define OP_Pagecount
Definition: sqlite3.c:12720
SQLITE_PRIVATE int sqlite3BtreeOpen(sqlite3_vfs *pVfs, const char *zFilename, sqlite3 *db, Btree **ppBtree, int flags, int vfsFlags)
Definition: sqlite3.c:60384
SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N)
Definition: sqlite3.c:139867
#define EP_MemToken
Definition: sqlite3.c:14971
SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef *, int)
Definition: sqlite3.c:103030
#define SQLITE_OrderByIdxJoin
Definition: sqlite3.c:14089
char validTZ
Definition: sqlite3.c:18651
sqlite3 * db
Definition: sqlite3.c:17889
static int getAndInitPage(BtShared *pBt, Pgno pgno, MemPage **ppPage, BtCursor *pCur, int bReadOnly)
Definition: sqlite3.c:60229
#define invalidateOverflowCache(pCur)
Definition: sqlite3.c:58715
#define SQLITE_STATUS_MEMORY_USED
Definition: sqlite3.c:7114
SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *, u32, void *)
Definition: sqlite3.c:43404
static void pcache1Unpin(sqlite3_pcache *p, sqlite3_pcache_page *pPg, int reuseUnlikely)
Definition: sqlite3.c:45508
SQLITE_API int sqlite3_bind_double(sqlite3_stmt *, int, double)
Definition: sqlite3.c:76449
#define sqlite3Isalnum(x)
Definition: sqlite3.c:16032
double estimatedCost
Definition: sqlite3.c:6212
#define MEMTYPE_PCACHE
Definition: sqlite3.c:16911
#define PAGER_OPEN
Definition: sqlite3.c:46716
#define SQLITE_READONLY_DBMOVED
Definition: sqlite3.c:764
SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int)
Definition: sqlite3.c:73004
#define CC_GT
Definition: sqlite3.c:136611
u32 nBackfillAttempted
Definition: sqlite3.c:54165
#define threadid
Definition: sqlite3.c:29691
#define EP_VarSelect
Definition: sqlite3.c:14960
SQLITE_PRIVATE int sqlite3PcacheInitialize(void)
Definition: sqlite3.c:43839
SQLITE_PRIVATE void * sqlite3HashInsert(Hash *, const char *pKey, void *pData)
Definition: sqlite3.c:28969
static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo)
Definition: sqlite3.c:119062
static int vdbePmaReaderSeek(SortSubtask *pTask, PmaReader *pReadr, SorterFile *pFile, i64 iOff)
Definition: sqlite3.c:85472
signed char p3
Definition: sqlite3.c:12494
#define SQLITE_CONSTRAINT_CHECK
Definition: sqlite3.c:766
int nMaxArg
Definition: sqlite3.c:15549
static int setChildPtrmaps(MemPage *pPage)
Definition: sqlite3.c:61525
#define OE_Fail
Definition: sqlite3.c:14593
#define sqlite3ParserTOKENTYPE
Definition: sqlite3.c:133096
#define OP_Le
Definition: sqlite3.c:12601
static void btreeParseCellPtr(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:59342
#define SQLITE_PTRSIZE
Definition: sqlite3.c:11701
#define DbSetProperty(D, I, P)
Definition: sqlite3.c:13781
SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *, int, const char *,...)
Definition: sqlite3.c:70716
SQLITE_PRIVATE void sqlite3SchemaClear(void *)
Definition: sqlite3.c:103164
SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse *, Table *, int, u8, int, u8 *, int *, int *)
Definition: sqlite3.c:109120
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe *, Table *, int, int, int)
Definition: sqlite3.c:92859
sqlite3_rtree_dbl rParentScore
Definition: sqlite3.c:8745
#define PGHDR_CLEAN
Definition: sqlite3.c:13207
SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *)
Definition: sqlite3.c:22543
SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int)
Definition: sqlite3.c:44387
static void pcache1Shrink(sqlite3_pcache *p)
Definition: sqlite3.c:45269
#define sqliteHashFirst(H)
Definition: sqlite3.c:11275
#define TERM_LIKECOND
Definition: sqlite3.c:124091
SQLITE_PRIVATE void sqlite3PrngSaveState(void)
Definition: sqlite3.c:26445
#define PTRMAP_FREEPAGE
Definition: sqlite3.c:57883
int nAccumulator
Definition: sqlite3.c:14815
static void noopMutexEnter(sqlite3_mutex *p)
Definition: sqlite3.c:22628
unsigned isCovering
Definition: sqlite3.c:14726
static CollSeq * multiSelectCollSeq(Parse *pParse, Select *p, int iCol)
Definition: sqlite3.c:116276
Pager * pPager
Definition: sqlite3.c:57663
#define SQLITE_Fts3Tokenizer
Definition: sqlite3.c:14074
static i8 wherePathSatisfiesOrderBy(WhereInfo *pWInfo, ExprList *pOrderBy, WherePath *pPath, u16 wctrlFlags, u16 nLoop, WhereLoop *pLast, Bitmask *pRevMask)
Definition: sqlite3.c:131259
Table * pZombieTab
Definition: sqlite3.c:15618
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *, Table *, int)
Definition: sqlite3.c:103268
sqlite3_file * jfd
Definition: sqlite3.c:47028
static void btreeHeapInsert(u32 *aHeap, u32 x)
Definition: sqlite3.c:67253
#define WAL_READ_LOCK(I)
Definition: sqlite3.c:54065
i64 cnt
Definition: sqlite3.c:105555
int nTransaction
Definition: sqlite3.c:57685
SQLITE_PRIVATE void * sqlite3DbMallocZero(sqlite3 *, u64)
Definition: sqlite3.c:24461
void * pCollNeededArg
Definition: sqlite3.c:13971
static void pager_reset(Pager *pPager)
Definition: sqlite3.c:48060
#define SQLITE_DROP_TABLE
Definition: sqlite3.c:3027
SQLITE_PRIVATE int sqlite3AuthReadCol(Parse *, const char *, const char *, int)
Definition: sqlite3.c:98141
SQLITE_PRIVATE int sqlite3WhereExplainOneScan(Parse *pParse, SrcList *pTabList, WhereLevel *pLevel, int iLevel, int iFrom, u16 wctrlFlags)
Definition: sqlite3.c:124462
#define TK_RAISE
Definition: sqlite3.c:11374
SQLITE_API int sqlite3_create_collation(sqlite3 *, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void *, int, const void *, int, const void *))
Definition: sqlite3.c:140995
#define HAVE_READLINK
Definition: sqlite3.c:168
SQLITE_PRIVATE int sqlite3IdListIndex(IdList *, const char *)
Definition: sqlite3.c:101915
static int pager_write_pagelist(Pager *pPager, PgHdr *pList)
Definition: sqlite3.c:50637
SQLITE_PRIVATE KeyInfo * sqlite3KeyInfoOfIndex(Parse *, Index *)
Definition: sqlite3.c:102631
Table ** apVtabLock
Definition: sqlite3.c:15616
#define TK_TRANSACTION
Definition: sqlite3.c:11297
u8 iPkSortOrder
Definition: sqlite3.c:15597
static int vdbeRecordCompareInt(int nKey1, const void *pKey1, UnpackedRecord *pPKey2)
Definition: sqlite3.c:74626
#define SQLITE_TRANSIENT
Definition: sqlite3.c:5029
void * lockingContext
Definition: sqlite3.c:29397
struct Parse::yColCache aColCache[SQLITE_N_COLCACHE]
#define OP_IntCopy
Definition: sqlite3.c:12648
void * padding1
Definition: sqlite3.c:57776
sqlite3_vtab * pVtab
Definition: sqlite3.c:14424
u32 aFrameCksum[2]
Definition: sqlite3.c:54097
Op * aOp
Definition: sqlite3.c:17847
#define OP_SeekGT
Definition: sqlite3.c:12588
#define STAT_GET_NDLT
Definition: sqlite3.c:96352
void * pStress
Definition: sqlite3.c:43630
#define SQLITE_INDEX_CONSTRAINT_GLOB
Definition: sqlite3.c:6241
Expr * pIdxExpr
Definition: sqlite3.c:124103
SQLITE_API sqlite3_mutex * sqlite3_mutex_alloc(int)
Definition: sqlite3.c:22500
static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo)
Definition: sqlite3.c:119078
SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause *, WhereInfo *)
Definition: sqlite3.c:127697
SQLITE_API int sqlite3_create_collation16(sqlite3 *, const void *zName, int eTextRep, void *pArg, int(*xCompare)(void *, int, const void *, int, const void *))
Definition: sqlite3.c:141033
SQLITE_PRIVATE CollSeq * sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:89861
Table * pNextZombie
Definition: sqlite3.c:14465
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster)
Definition: sqlite3.c:52483
static void sqliteViewResetAll(sqlite3 *db, int idx)
Definition: sqlite3.c:100546
SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread **, void *(*)(void *), void *)
static int vdbeSorterCompare(SortSubtask *pTask, int *pbKey2Cached, const void *pKey1, int nKey1, const void *pKey2, int nKey2)
Definition: sqlite3.c:85626
#define SQLITE_STATUS_SCRATCH_SIZE
Definition: sqlite3.c:7122
SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *, sqlite3 *, u16)
Definition: sqlite3.c:69393
#define INCRINIT_NORMAL
Definition: sqlite3.c:86924
static unsigned int yy_find_shift_action(yyParser *pParser, YYCODETYPE iLookAhead)
Definition: sqlite3.c:134506
static int unixGetpagesize(void)
Definition: sqlite3.c:33369
UnpackedRecord * pUnpacked
Definition: sqlite3.c:85168
i64 nDeferredImmCons
Definition: sqlite3.c:14266
#define SQLITE_CONSTRAINT_ROWID
Definition: sqlite3.c:775
const sqlite3_module * pModule
Definition: sqlite3.c:6303
#define SQLITE_FLOAT
Definition: sqlite3.c:4388
SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *, int)
Definition: sqlite3.c:62243
#define SRT_DistFifo
Definition: sqlite3.c:15404
static void releaseInodeInfo(unixFile *pFile)
Definition: sqlite3.c:30604
static const YYCODETYPE yyFallback[]
Definition: sqlite3.c:133677
SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p)
Definition: sqlite3.c:116941
#define TKFLG_DONTFOLD
Definition: sqlite3.c:11461
SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue)
Definition: sqlite3.c:66919
#define IS_LOCK_ERROR(x)
Definition: sqlite3.c:29364
SQLITE_PRIVATE void sqlite3PcacheClose(PCache *)
Definition: sqlite3.c:44253
Vdbe * pNext
Definition: sqlite3.c:18030
int mallocFailed
Definition: sqlite3.c:57928
static const unsigned char aiClass[]
Definition: sqlite3.c:136627
SQLITE_PRIVATE VdbeOp * sqlite3VdbeAddOpList(Vdbe *, int nOp, VdbeOpList const *aOp, int iLineno)
Definition: sqlite3.c:71156
int(* xWrite)(sqlite3_file *, const void *, int iAmt, sqlite3_int64 iOfst)
Definition: sqlite3.c:1009
#define pager_pagehash(X)
Definition: sqlite3.c:47582
#define WRITE_UTF8(zOut, c)
Definition: sqlite3.c:26803
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int)
Definition: sqlite3.c:53373
u8 isWriteLock
Definition: sqlite3.c:98336
SQLITE_API int sqlite3_close(sqlite3 *)
Definition: sqlite3.c:138940
#define OP_NoConflict
Definition: sqlite3.c:12591
int nModuleArg
Definition: sqlite3.c:14459
SQLITE_API int sqlite3_db_status(sqlite3 *, int op, int *pCur, int *pHiwtr, int resetFlg)
Definition: sqlite3.c:18398
#define TK_WHEN
Definition: sqlite3.c:11428
#define MAX_ROWID
PagerSavepoint * aSavepoint
Definition: sqlite3.c:47033
SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *, int, const char *)
Definition: sqlite3.c:123362
#define OP_SorterNext
Definition: sqlite3.c:12565
SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse *, struct SrcList_item *, WhereClause *)
Definition: sqlite3.c:127792
static void freeIndex(sqlite3 *db, Index *p)
Definition: sqlite3.c:98729
#define etBUFSIZE
Definition: sqlite3.c:24878
SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt)
Definition: sqlite3.c:75241
#define JT_RIGHT
Definition: sqlite3.c:15177
SQLITE_PRIVATE const char * sqlite3IndexAffinityStr(sqlite3 *, Index *)
Definition: sqlite3.c:107450
#define SQLITE_DEFAULT_SYNCHRONOUS
Definition: sqlite3.c:13723
void * pScratch
Definition: sqlite3.c:15845
Btree * pSrc
Definition: sqlite3.c:67988
SQLITE_API int sqlite3_create_collation_v2(sqlite3 *, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void *, int, const void *, int, const void *), void(*xDestroy)(void *))
Definition: sqlite3.c:141008
SQLITE_PRIVATE Bitvec * sqlite3BitvecCreate(u32)
Definition: sqlite3.c:43279
#define SQLITE_SET_LOCKPROXYFILE
Definition: sqlite3.c:1301
#define SQLITE_SCANSTAT_EXPLAIN
Definition: sqlite3.c:8312
#define SQLITE_LIMIT_TRIGGER_DEPTH
Definition: sqlite3.c:3683
#define BITVEC_HASH(X)
Definition: sqlite3.c:43232
#define SQLITE_ReverseOrder
Definition: sqlite3.c:14061
static int nolockLock(sqlite3_file *NotUsed, int NotUsed2)
Definition: sqlite3.c:31400
u8 errorAction
Definition: sqlite3.c:18067
SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *)
Definition: sqlite3.c:70827
u8 hdrOffset
Definition: sqlite3.c:57529
SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void)
Definition: sqlite3.c:105844
int cache_size
Definition: sqlite3.c:13772
#define YYCODETYPE
Definition: sqlite3.c:133092
static Expr * substExpr(sqlite3 *db, Expr *pExpr, int iTable, ExprList *pEList)
Definition: sqlite3.c:117507
int(* SorterCompare)(SortSubtask *, int *, const void *, int, const void *, int)
Definition: sqlite3.c:85136
SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *, i64 *)
Definition: sqlite3.c:27929
int(* xColumnSize)(Fts5Context *, int iCol, int *pnToken)
Definition: sqlite3.c:10342
u16 wtFlags
Definition: sqlite3.c:124059
#define WRC_Continue
Definition: sqlite3.c:15935
SQLITE_PRIVATE sqlite3_mutex * sqlite3MutexAlloc(int)
Definition: sqlite3.c:22509
Trigger * pTrigger
Definition: sqlite3.c:15473
#define OP_BitAnd
Definition: sqlite3.c:12605
Hash aFunc
Definition: sqlite3.c:13994
static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:105570
SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *)
Definition: sqlite3.c:25595
#define NC_VarSelect
Definition: sqlite3.c:15261
#define JT_INNER
Definition: sqlite3.c:15173
sqlite3_xauth xAuth
Definition: sqlite3.c:13979
#define WAL_SHM_RDONLY
Definition: sqlite3.c:54254
#define TK_SLASH
Definition: sqlite3.c:11341
SQLITE_API void * sqlite3_realloc64(void *, sqlite3_uint64)
Definition: sqlite3.c:24438
struct sqlite3_snapshot sqlite3_snapshot
Definition: sqlite3.c:8530
static int whereRangeScanEst(Parse *pParse, WhereLoopBuilder *pBuilder, WhereTerm *pLower, WhereTerm *pUpper, WhereLoop *pLoop)
Definition: sqlite3.c:129206
#define OP_ShiftLeft
Definition: sqlite3.c:12607
#define SQLITE_PRAGMA
Definition: sqlite3.c:3035
unixShm * pShm
Definition: sqlite3.c:29400
SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect)
Definition: sqlite3.c:92077
struct RowSetEntry * pLeft
Definition: sqlite3.c:45803
i16 iRightJoinTable
Definition: sqlite3.c:14944
i16 aiColumn[11]
Definition: sqlite3.c:124110
SQLITE_PRIVATE const char * sqlite3PagerJournalname(Pager *)
Definition: sqlite3.c:53134
SQLITE_PRIVATE void * sqlite3HashFind(const Hash *, const char *pKey)
Definition: sqlite3.c:28945
static int reportError(int iErr, int lineno, const char *zType)
Definition: sqlite3.c:141138
SQLITE_PRIVATE void * sqlite3Malloc(u64)
Definition: sqlite3.c:24139
#define SQLITE_EMPTY
Definition: sqlite3.c:691
#define SQLITE_CONSTRAINT_COMMITHOOK
Definition: sqlite3.c:767
Parse * pParse
Definition: sqlite3.c:124219
unsigned int nRecyclable
Definition: sqlite3.c:44620
static int isMatchOfColumn(Expr *pExpr, unsigned char *peOp2)
Definition: sqlite3.c:126672
u8 eDistinct
Definition: sqlite3.c:124234
static TriggerPrg * codeRowTrigger(Parse *pParse, Trigger *pTrigger, Table *pTab, int orconf)
Definition: sqlite3.c:121057
static int pagerStress(void *p, PgHdr *pPg)
Definition: sqlite3.c:50819
char * pTmpSpace
Definition: sqlite3.c:47067
#define WO_MATCH
Definition: sqlite3.c:124325
SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage)
Definition: sqlite3.c:68307
SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager *, unsigned)
Definition: sqlite3.c:49877
u16 minLocal
Definition: sqlite3.c:57680
SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree *, unsigned)
Definition: sqlite3.c:60863
SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *, int *)
Definition: sqlite3.c:91543
#define SQLITE_ACCESS_EXISTS
Definition: sqlite3.c:1545
int(* sqlite3_callback)(void *, int, char **, char **)
Definition: sqlite3.c:591
SQLITE_PRIVATE KeyInfo * sqlite3KeyInfoRef(KeyInfo *)
Definition: sqlite3.c:115426
#define SQLITE_MALLOC_SOFT_LIMIT
Definition: sqlite3.c:11014
static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg)
Definition: sqlite3.c:122845
SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3 *)
Definition: sqlite3.c:138763
i64 nFkConstraint
Definition: sqlite3.c:18043
#define TK_MINUS
Definition: sqlite3.c:11339
#define TK_IMMEDIATE
Definition: sqlite3.c:11299
#define OE_Restrict
Definition: sqlite3.c:14597
SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *, int)
Definition: sqlite3.c:105783
SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *, ExprList *)
Definition: sqlite3.c:91359
static u32 walFramePgno(Wal *pWal, u32 iFrame)
Definition: sqlite3.c:54697
#define SQLITE_CREATE_INDEX
Definition: sqlite3.c:3017
SortSubtask * pTask
Definition: sqlite3.c:85100
static void heightOfExpr(Expr *p, int *pnHeight)
Definition: sqlite3.c:90344
static sqlite3_value * valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p)
Definition: sqlite3.c:69864
Token constraintName
Definition: sqlite3.c:15544
Hash aCollSeq
Definition: sqlite3.c:13995
u32 iHdrOffset
Definition: sqlite3.c:17807
static int exprAlwaysTrue(Expr *p)
Definition: sqlite3.c:90598
#define OP_OpenAutoindex
Definition: sqlite3.c:12668
#define SQLITE_FCNTL_COMMIT_PHASETWO
Definition: sqlite3.c:1290
#define TK_BEGIN
Definition: sqlite3.c:11296
SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData)
Definition: sqlite3.c:56517
SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int, int *)
Definition: sqlite3.c:20024
SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int)
Definition: sqlite3.c:98988
SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *)
Definition: sqlite3.c:67952
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *, unsigned)
Definition: sqlite3.c:59129
SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr)
Definition: sqlite3.c:90072
#define SQLITE_IOERR_DIR_CLOSE
Definition: sqlite3.c:741
static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit)
Definition: sqlite3.c:48320
IncrMerger * pIncr
Definition: sqlite3.c:85203
#define VdbeModuleComment(X)
Definition: sqlite3.c:12866
#define PAGER_JOURNALMODE_DELETE
Definition: sqlite3.c:12995
u16 minLocal
Definition: sqlite3.c:57534
#define TK_DEFERRED
Definition: sqlite3.c:11298
SQLITE_API const char * sqlite3_db_filename(sqlite3 *db, const char *zDbName)
Definition: sqlite3.c:141779
Lookaside lookaside
Definition: sqlite3.c:13977
static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql,...)
Definition: sqlite3.c:122259
static int isFatalError(int rc)
Definition: sqlite3.c:68177
static i64 journalHdrOffset(Pager *pPager)
Definition: sqlite3.c:47666
static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p)
Definition: sqlite3.c:18898
static int walHashGet(Wal *pWal, int iHash, volatile ht_slot **paHash, volatile u32 **paPgno, u32 *piZero)
Definition: sqlite3.c:54645
#define TK_PLUS
Definition: sqlite3.c:11338
struct KeyClass KeyClass
Definition: sqlite3.c:11984
u32 * aOffset
Definition: sqlite3.c:17809
int tnum
Definition: sqlite3.c:14444
static int growOpArray(Vdbe *v, int nOp)
Definition: sqlite3.c:70578
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *, Expr *)
Definition: sqlite3.c:94631
static void releasePageNotNull(MemPage *pPage)
Definition: sqlite3.c:60283
LogEst rCost
Definition: sqlite3.c:123998
int nCol
Definition: sqlite3.c:14554
u8 readOnly
Definition: sqlite3.c:46998
SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *, Index *)
Definition: sqlite3.c:97109
#define SQLITE_FactorOutConst
Definition: sqlite3.c:14085
#define pager_datahash(X, Y)
Definition: sqlite3.c:47581
VdbeCursor * pCsr
Definition: sqlite3.c:18111
sqlite3 * db
Definition: sqlite3.c:15815
#define SQLITE_NOINLINE
Definition: sqlite3.c:10919
u32 szPage
Definition: sqlite3.c:54219
SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse *, ExprList *, ExprSpan *)
Definition: sqlite3.c:91310
#define TK_INSERT
Definition: sqlite3.c:11399
sqlite_int64 i64
Definition: sqlite3.c:11638
VdbeCursor ** apCsr
Definition: sqlite3.c:18056
SQLITE_PRIVATE int sqlite3PcacheOpen(int szPage, int szExtra, int bPurgeable, int(*xStress)(void *, PgHdr *), void *pStress, PCache *pToInit)
Definition: sqlite3.c:43866
static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect)
Definition: sqlite3.c:118972
u8 approx
Definition: sqlite3.c:105557
SQLITE_PRIVATE const char sqlite3StrBINARY[]
Definition: sqlite3.c:17212
int nRefSum
Definition: sqlite3.c:43622
#define OP_SoftNull
Definition: sqlite3.c:12642
int nVDestroy
Definition: sqlite3.c:13945
#define TK_QUERY
Definition: sqlite3.c:11294
static void sqlite3SelectExpand(Parse *pParse, Select *pSelect)
Definition: sqlite3.c:118907
#define SQLITE_MAX_LIKE_PATTERN_LENGTH
Definition: sqlite3.c:10844
#define P5_ConstraintCheck
Definition: sqlite3.c:12524
#define OP_RealAffinity
Definition: sqlite3.c:12654
#define WAL_SYNC_TRANSACTIONS
Definition: sqlite3.c:46264
#define FOUR_BYTE_UINT(x)
Definition: sqlite3.c:73801
bft bIsReader
Definition: sqlite3.c:18076
static int seekAndWriteFd(int fd, i64 iOff, const void *pBuf, int nBuf, int *piErrno)
Definition: sqlite3.c:32607
#define SQLITE_NOTICE
Definition: sqlite3.c:702
const int sqlite3one
Definition: sqlite3.c:11753
static void whereLoopDelete(sqlite3 *db, WhereLoop *p)
Definition: sqlite3.c:129658
static int sqliteDefaultBusyCallback(void *ptr, int count)
Definition: sqlite3.c:139286
#define TK_NO
Definition: sqlite3.c:11369
static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect)
Definition: sqlite3.c:94616
static void randomBlob(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104614
#define osGetpid(X)
Definition: sqlite3.c:29358
#define OE_Cascade
Definition: sqlite3.c:14600
SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *, sqlite3 *, char *, int, int)
Definition: sqlite3.c:25618
#define IN_INDEX_INDEX_ASC
Definition: sqlite3.c:16811
char * idxStr
Definition: sqlite3.c:123942
#define FUNCTION(zName, nArg, iArg, bNC, xFunc)
Definition: sqlite3.c:14232
Bitmask revLoop
Definition: sqlite3.c:123996
sqlite3_int64 szMmap
Definition: sqlite3.c:47039
#define TK_ANALYZE
Definition: sqlite3.c:11351
tRowcnt * anEq
Definition: sqlite3.c:95830
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *)
Definition: sqlite3.c:52317
SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *)
Definition: sqlite3.c:74949
#define SQLITE_IDXTYPE_UNIQUE
Definition: sqlite3.c:14742
#define TESTBIT(V, I)
Definition: sqlite3.c:43469
const char * zJournal
Definition: sqlite3.c:87680
sqlite3_rtree_dbl * aCoord
Definition: sqlite3.c:8739
#define vdbeSorterBlockDebug(x, y, z)
Definition: sqlite3.c:85944
static unsigned int strHash(const char *z)
Definition: sqlite3.c:28785
#define OP_FkCounter
Definition: sqlite3.c:12706
static void closeAllCursors(Vdbe *p)
Definition: sqlite3.c:72541
static int unixSync(sqlite3_file *id, int flags)
Definition: sqlite3.c:32930
int nOther
Definition: sqlite3.c:94405
tRowcnt nRow
Definition: sqlite3.c:95845
int iBufEnd
Definition: sqlite3.c:85261
Savepoint * pSavepoint
Definition: sqlite3.c:13998
#define OP_ParseSchema
Definition: sqlite3.c:12698
SQLITE_API void sqlite3_result_text(sqlite3_context *, const char *, int, void(*)(void *))
Definition: sqlite3.c:75502
SQLITE_API int sqlite3_stricmp(const char *, const char *)
Definition: sqlite3.c:27561
Column * aCol
Definition: sqlite3.c:14437
unsigned char nrhs
Definition: sqlite3.c:134682
sqlite3_file * pFd
Definition: sqlite3.c:85197
SQLITE_API int sqlite3_bind_blob(sqlite3_stmt *, int, const void *, int n, void(*)(void *))
Definition: sqlite3.c:76423
#define SQLITE_AUTH
Definition: sqlite3.c:698
SQLITE_PRIVATE void sqlite3PCacheSetDefault(void)
Definition: sqlite3.c:45622
#define SQLITE_FORMAT
Definition: sqlite3.c:699
#define MEM_Static
Definition: sqlite3.c:17935
#define SPILLFLAG_OFF
Definition: sqlite3.c:46825
SQLITE_PRIVATE int sqlite3WalkExpr(Walker *, Expr *)
Definition: sqlite3.c:88077
static int backupTruncateFile(sqlite3_file *pFile, i64 iSize)
Definition: sqlite3.c:68282
void * pIn
Definition: sqlite3.c:26509
u32 nScratchFree
Definition: sqlite3.c:23942
static int relocatePage(BtShared *pBt, MemPage *pDbPage, u8 eType, Pgno iPtrPage, Pgno iFreePage, int isCommit)
Definition: sqlite3.c:61637
static Mem * columnMem(sqlite3_stmt *pStmt, int i)
Definition: sqlite3.c:76067
#define SQLITE_OK
Definition: sqlite3.c:674
#define P5_ConstraintUnique
Definition: sqlite3.c:12523
#define PAGER_FULLFSYNC
Definition: sqlite3.c:13021
u32 Pgno
Definition: sqlite3.c:12950
SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal)
Definition: sqlite3.c:56455
Hash tblHash
Definition: sqlite3.c:13764
#define SQLITE_DEFAULT_CACHE_SIZE
Definition: sqlite3.c:10755
SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *)
Definition: sqlite3.c:67734
#define STAT_GET_NEQ
Definition: sqlite3.c:96350
static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem)
Definition: sqlite3.c:92643
SQLITE_PRIVATE int sqlite3WalCheckpoint(Wal *pWal, int eMode, int(*xBusy)(void *), void *pBusyArg, int sync_flags, int nBuf, u8 *zBuf, int *pnLog, int *pnCkpt)
Definition: sqlite3.c:56975
#define P4_MEM
Definition: sqlite3.c:12508
#define OP_SeekRowid
Definition: sqlite3.c:12594
#define BTREE_AUTOVACUUM_FULL
Definition: sqlite3.c:12053
SQLITE_API int sqlite3_collation_needed(sqlite3 *, void *, void(*)(void *, sqlite3 *, int eTextRep, const char *))
Definition: sqlite3.c:141063
static int walIndexRecover(Wal *pWal)
Definition: sqlite3.c:54868
u32 notUsed0
Definition: sqlite3.c:54166
#define SRT_Mem
Definition: sqlite3.c:15412
TFSIMD_FORCE_INLINE tfScalar length(const Quaternion &q)
#define MEM_Zero
Definition: sqlite3.c:17938
static int numberOfCachePages(PCache *p)
Definition: sqlite3.c:43821
static int findInodeInfo(unixFile *pFile, unixInodeInfo **ppInode)
Definition: sqlite3.c:30638
#define vfsList
Definition: sqlite3.c:20069
#define WO_LT
Definition: sqlite3.c:124321
#define SQLITE_IOCAP_ATOMIC4K
Definition: sqlite3.c:844
#define EP_Reduced
Definition: sqlite3.c:14968
int(* xQueryPhrase)(Fts5Context *, int iPhrase, void *pUserData, int(*)(const Fts5ExtensionApi *, Fts5Context *, void *))
Definition: sqlite3.c:10344
SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe *, int, int, int, int, int)
Definition: sqlite3.c:70785
static int unixRead(sqlite3_file *id, void *pBuf, int amt, sqlite3_int64 offset)
Definition: sqlite3.c:32548
#define VDBE_MAGIC_INIT
Definition: sqlite3.c:18099
#define SQLITE_MUTEX_STATIC_OPEN
Definition: sqlite3.c:6882
int nRec
Definition: sqlite3.c:47023
void * token
Definition: sqlite3.c:12482
#define ConstFactorOk(P)
Definition: sqlite3.c:14112
static int dotlockClose(sqlite3_file *id)
Definition: sqlite3.c:31591
#define SQLITE_N_KEYWORD
Definition: sqlite3.c:137000
SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *)
Definition: sqlite3.c:122695
SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *, int *)
Definition: sqlite3.c:50174
SubProgram * pProgram
Definition: sqlite3.c:12453
static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept)
Definition: sqlite3.c:58946
#define NO_LOCK
Definition: sqlite3.c:13493
#define CC_SPACE
Definition: sqlite3.c:136605
static void renameTableFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:94788
#define OP_Jump
Definition: sqlite3.c:12580
static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes)
Definition: sqlite3.c:63670
u16 nExtra
Definition: sqlite3.c:47045
static int whereLoopAddBtreeIndex(WhereLoopBuilder *pBuilder, struct SrcList_item *pSrc, Index *pProbe, LogEst nInMul)
Definition: sqlite3.c:130123
struct Hash::_ht * ht
SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int)
Definition: sqlite3.c:44399
static int getOverflowPage(BtShared *pBt, Pgno ovfl, MemPage **ppPage, Pgno *pPgnoNext)
Definition: sqlite3.c:62567
u8 eOrconf
Definition: sqlite3.c:15566
#define OP_ResultRow
Definition: sqlite3.c:12649
#define OP_NextIfOpen
Definition: sqlite3.c:12567
#define SQLITE_ALTER_TABLE
Definition: sqlite3.c:3042
#define NOT_WITHIN
Definition: sqlite3.c:8756
static void whereLoopClear(sqlite3 *db, WhereLoop *p)
Definition: sqlite3.c:129614
#define SQLITE_RecTriggers
Definition: sqlite3.c:14062
#define TK_STAR
Definition: sqlite3.c:11340
SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *, int addr, const char *zP4, int N)
Definition: sqlite3.c:71419
Expr * yy72
Definition: sqlite3.c:133100
static int unixShmLock(sqlite3_file *fd, int ofst, int n, int flags)
Definition: sqlite3.c:33904
#define SQLITE_CANTOPEN
Definition: sqlite3.c:689
ROSCPP_DECL bool exists(const std::string &service_name, bool print_failure_reason)
SQLITE_API char * sqlite3_vmprintf(const char *, va_list)
Definition: sqlite3.c:25665
u16 eOperator
Definition: sqlite3.c:124060
SQLITE_PRIVATE Expr * sqlite3VectorFieldSubexpr(Expr *, int)
Definition: sqlite3.c:90100
SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *, u32 addr, int P3)
Definition: sqlite3.c:71241
#define sqlite3WhereAddScanStatus(a, b, c, d)
Definition: sqlite3.c:124284
static void disableLookaside(Parse *pParse)
Definition: sqlite3.c:132889
SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *)
Definition: sqlite3.c:24650
static int dupedExprStructSize(Expr *p, int flags)
Definition: sqlite3.c:90818
#define MEM_Null
Definition: sqlite3.c:17915
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *, u8)
Definition: sqlite3.c:91516
void * pProgressArg
Definition: sqlite3.c:13984
SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *)
Definition: sqlite3.c:140040
#define OP_RowSetAdd
Definition: sqlite3.c:12704
SQLITE_PRIVATE void sqlite3FinishTrigger(Parse *, TriggerStep *, Token *)
Definition: sqlite3.c:120536
int addrInTop
Definition: sqlite3.c:123892
#define RESERVED_LOCK
Definition: sqlite3.c:13495
static CollSeq * sqlite3GetFuncCollSeq(sqlite3_context *context)
Definition: sqlite3.c:104139
#define EP_Unlikely
Definition: sqlite3.c:14973
SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *, SrcList *)
Definition: sqlite3.c:102080
u8 syncHeader
Definition: sqlite3.c:54227
#define IN_INDEX_NOOP_OK
Definition: sqlite3.c:16817
#define SQLITE_VERSION_NUMBER
Definition: sqlite3.c:385
u8 eTriggerOp
Definition: sqlite3.c:15565
VTable * pNext
Definition: sqlite3.c:14428
SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *)
Definition: sqlite3.c:62439
static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3)
Definition: sqlite3.c:35689
SQLITE_API int sqlite3_blob_close(sqlite3_blob *)
Definition: sqlite3.c:84684
static u16 numericType(Mem *pMem)
Definition: sqlite3.c:77588
static void closeCursorsInFrame(Vdbe *p)
Definition: sqlite3.c:72494
SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *, void *)
Definition: sqlite3.c:24349
Trigger * apTrigger[2]
Definition: sqlite3.c:14558
int nMmapOut
Definition: sqlite3.c:47038
static void translateColumnToCopy(Vdbe *v, int iStart, int iTabCur, int iRegister, int bIncrRowid)
Definition: sqlite3.c:128339
Hash trigHash
Definition: sqlite3.c:13766
Select * pPrior
Definition: sqlite3.c:15299
u16 aiIdx[BTCURSOR_MAX_DEPTH]
Definition: sqlite3.c:57777
int nRef
Definition: sqlite3.c:14425
SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse *, ExprList *, i16 *, Column **)
Definition: sqlite3.c:115996
#define SQLITE_MUTEX_STATIC_PMEM
Definition: sqlite3.c:6886
int regReturn
Definition: sqlite3.c:114443
#define SQLITE_NOMEM_BKPT
Definition: sqlite3.c:15994
Mem * aMem
Definition: sqlite3.c:17849
SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *)
Definition: sqlite3.c:61033
#define TRANS_NONE
Definition: sqlite3.c:57623
SQLITE_PRIVATE Expr * sqlite3ExprAnd(sqlite3 *, Expr *, Expr *)
Definition: sqlite3.c:90619
#define WHERE_SORTBYGROUP
Definition: sqlite3.c:15200
const char * z
Definition: sqlite3.c:14779
static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList)
Definition: sqlite3.c:91347
int rc
Definition: sqlite3.c:18039
sqlite3_backup * pNext
Definition: sqlite3.c:67999
#define PENDING_BYTE
Definition: sqlite3.c:13557
#define P4_MPRINTF
Definition: sqlite3.c:12511
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *)
Definition: sqlite3.c:19987
SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *)
Definition: sqlite3.c:53513
#define offsetof(STRUCTURE, FIELD)
Definition: sqlite3.c:11565
const char * zCollName
Definition: sqlite3.c:124102
struct WalIndexHdr WalIndexHdr
Definition: sqlite3.c:54070
#define SQLITE_CREATE_TEMP_INDEX
Definition: sqlite3.c:3019
#define SQLITE_MAX_MMAP_SIZE
Definition: sqlite3.c:11820
int iECursor
Definition: sqlite3.c:114442
int nStatement
Definition: sqlite3.c:14001
char * zCol
Definition: sqlite3.c:14561
static void setAllPagerFlags(sqlite3 *db)
Definition: sqlite3.c:111754
#define SQLITE_LIMIT_EXPR_DEPTH
Definition: sqlite3.c:3676
YYACTIONTYPE stateno
Definition: sqlite3.c:133794
static void noopMutexLeave(sqlite3_mutex *p)
Definition: sqlite3.c:22633
int nMem
Definition: sqlite3.c:15534
#define TK_LE
Definition: sqlite3.c:11330
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *)
Definition: sqlite3.c:137054
unixInodeInfo * pInode
Definition: sqlite3.c:29392
void * pBusyHandlerArg
Definition: sqlite3.c:47055
SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *, Token *)
Definition: sqlite3.c:123021
struct sqlite3_blob sqlite3_blob
Definition: sqlite3.c:6382
#define TK_IN
Definition: sqlite3.c:11324
#define SQLITE_STATUS_PAGECACHE_USED
Definition: sqlite3.c:7115
SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *, int, sqlite3_uint64)
Definition: sqlite3.c:76558
#define SQLITE_TESTCTRL_ALWAYS
Definition: sqlite3.c:6980
static const struct @0 yyRuleInfo[]
static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt)
Definition: sqlite3.c:32653
static void resolveOutOfRangeError(Parse *pParse, const char *zType, int i, int mx)
Definition: sqlite3.c:89106
int nErr
Definition: sqlite3.c:15532
static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg)
Definition: sqlite3.c:52223
int nVTrans
Definition: sqlite3.c:13988
static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal)
Definition: sqlite3.c:86374
SQLITE_API int sqlite3_create_function16(sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, void *pApp, void(*xFunc)(sqlite3_context *, int, sqlite3_value **), void(*xStep)(sqlite3_context *, int, sqlite3_value **), void(*xFinal)(sqlite3_context *))
Definition: sqlite3.c:139591
#define TK_ASTERISK
Definition: sqlite3.c:11451
#define OP_Function0
Definition: sqlite3.c:12651
#define OP_FkIfZero
Definition: sqlite3.c:12627
#define OP_CreateIndex
Definition: sqlite3.c:12696
#define WHERE_UNQ_WANTED
Definition: sqlite3.c:124358
sqlite3_file * pFd
Definition: sqlite3.c:85016
#define OP_SetCookie
Definition: sqlite3.c:12664
#define TK_OF
Definition: sqlite3.c:11371
AutoincInfo * pNext
Definition: sqlite3.c:15441
#define TK_NOTNULL
Definition: sqlite3.c:11326
int nOut
Definition: sqlite3.c:13828
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *, const char *zMaster)
Definition: sqlite3.c:61973
int(* sqlite3_xauth)(void *, int, const char *, const char *, const char *, const char *)
Definition: sqlite3.c:13885
PGroup grp
Definition: sqlite3.c:44640
#define SQLITE_REPLACE
Definition: sqlite3.c:8259
#define osWrite
static PgHdr * pcacheSortDirtyList(PgHdr *pIn)
Definition: sqlite3.c:44307
#define osMunmap
#define LARGEST_INT64
Definition: sqlite3.c:11768
Parse * pParse
Definition: sqlite3.c:18031
SQLITE_PRIVATE Trigger * sqlite3TriggerList(Parse *, Table *)
Definition: sqlite3.c:120315
int wantToLock
Definition: sqlite3.c:57606
static int walLockExclusive(Wal *pWal, int lockIdx, int n)
Definition: sqlite3.c:54599
unsigned int iKey
Definition: sqlite3.c:44552
#define SQLITE_FCNTL_WIN32_AV_RETRY
Definition: sqlite3.c:1278
static int removeFromSharingList(BtShared *pBt)
Definition: sqlite3.c:60669
unsigned int count
Definition: sqlite3.c:11235
SQLITE_API char * sqlite3_vsnprintf(int, char *, const char *, va_list)
Definition: sqlite3.c:25714
SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *)
Definition: sqlite3.c:70446
static int closeUnixFile(sqlite3_file *id)
Definition: sqlite3.c:31315
void * pAuthArg
Definition: sqlite3.c:13980
SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor *, u32, u32, int, Mem *)
Definition: sqlite3.c:69739
SQLITE_PRIVATE WhereTerm * sqlite3WhereFindTerm(WhereClause *pWC, int iCur, int iColumn, Bitmask notReady, u32 op, Index *pIdx)
Definition: sqlite3.c:128176
unsigned nProgressOps
Definition: sqlite3.c:13985
static int pageInsertArray(MemPage *pPg, u8 *pBegin, u8 **ppData, u8 *pCellptr, int iFirst, int nCell, CellArray *pCArray)
Definition: sqlite3.c:64758
#define BYTESWAP32(x)
Definition: sqlite3.c:54384
int(* xOpen)(sqlite3_vfs *, const char *zName, sqlite3_file *, int flags, int *pOutFlags)
Definition: sqlite3.c:1493
#define SQLITE_DROP_TEMP_TABLE
Definition: sqlite3.c:3029
#define TK_ELSE
Definition: sqlite3.c:11430
static void pcache1Free(void *p)
Definition: sqlite3.c:44804
VdbeFrame * pFrame
Definition: sqlite3.c:18083
u8 keyConf
Definition: sqlite3.c:14454
static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData)
Definition: sqlite3.c:86322
static int clearCell(MemPage *pPage, unsigned char *pCell, u16 *pnSize)
Definition: sqlite3.c:64230
static int btreeGetUnusedPage(BtShared *pBt, Pgno pgno, MemPage **ppPage, int flags)
Definition: sqlite3.c:60305
int rc
Definition: sqlite3.c:15818
int rc
Definition: sqlite3.c:15519
#define SLOT_2_0
Definition: sqlite3.c:28098
#define SQLITE_CONFIG_SERIALIZED
Definition: sqlite3.c:2130
#define WHERE_COLUMN_NULL
Definition: sqlite3.c:124344
int nChange
Definition: sqlite3.c:17860
int mxOut
Definition: sqlite3.c:13829
FileChunk * pChunk
Definition: sqlite3.c:87661
int syncFlags
Definition: sqlite3.c:56619
WhereClause wc
Definition: sqlite3.c:124153
const unsigned char * a
Definition: sqlite3.c:10100
WhereTerm aStatic[8]
Definition: sqlite3.c:124135
SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *, int *)
Definition: sqlite3.c:127926
int(* xUnlock)(sqlite3_file *, int)
Definition: sqlite3.c:1014
dev_t dev
Definition: sqlite3.c:30444
Expr * pHaving
Definition: sqlite3.c:15297
SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *)
Definition: sqlite3.c:63531
#define SQLITE_STATUS_PAGECACHE_OVERFLOW
Definition: sqlite3.c:7116
SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *)
Definition: sqlite3.c:20003
SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *, int)
Definition: sqlite3.c:72592
BtShared * pBt
Definition: sqlite3.c:57542
unsigned int n90pct
Definition: sqlite3.c:44614
SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *, Pgno x)
Definition: sqlite3.c:44220
int regRowid
Definition: sqlite3.c:15547
static SQLITE_NOINLINE PgHdr1 * pcache1FetchStage2(PCache1 *pCache, unsigned int iKey, int createFlag)
Definition: sqlite3.c:45304
static int isLikeOrGlob(Parse *pParse, Expr *pExpr, Expr **ppPrefix, int *pisComplete, int *pnoCase)
Definition: sqlite3.c:126572
SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *)
Definition: sqlite3.c:48967
char * zTarget
Definition: sqlite3.c:15764
SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *, int, char *)
Definition: sqlite3.c:70776
SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *)
Definition: sqlite3.c:44363
void(*(* xDlSym)(sqlite3_vfs *, void *, const char *zSymbol))(void)
Definition: sqlite3.c:1500
LogEst nOut
Definition: sqlite3.c:123929
#define SQLITE_CANTOPEN_BKPT
Definition: sqlite3.c:15987
SQLITE_PRIVATE void sqlite3DropIndex(Parse *, SrcList *, int)
Definition: sqlite3.c:101765
static int saveCursorKey(BtCursor *pCur)
Definition: sqlite3.c:58863
#define PAGER_JOURNALMODE_OFF
Definition: sqlite3.c:12997
#define SQLITE_ColumnCache
Definition: sqlite3.c:14083
Vdbe * v
Definition: sqlite3.c:18110
SQLITE_API const void * sqlite3_value_text16le(sqlite3_value *)
Definition: sqlite3.c:75328
#define OP_SeekLE
Definition: sqlite3.c:12586
SQLITE_PRIVATE const Token sqlite3IntTokens[]
Definition: sqlite3.c:17172
static void totalFinalize(sqlite3_context *context)
Definition: sqlite3.c:105611
SorterFile aFile[2]
Definition: sqlite3.c:85245
PgHdr1 * pLruNext
Definition: sqlite3.c:44558
SQLITE_PRIVATE void sqlite3HashClear(Hash *)
Definition: sqlite3.c:28765
SQLITE_API const void * sqlite3_value_text16be(sqlite3_value *)
Definition: sqlite3.c:75325
static sqlite3_int64 getIntArg(PrintfArguments *p)
Definition: sqlite3.c:24857
#define tkTEMP
Definition: sqlite3.c:137512
static void allocateTempSpace(BtShared *pBt)
Definition: sqlite3.c:60708
#define WO_ISNULL
Definition: sqlite3.c:124327
SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *, int, int)
Definition: sqlite3.c:62174
#define STAT_GET_ROWID
Definition: sqlite3.c:96349
SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *)
Definition: sqlite3.c:75586
char * zFilename
Definition: sqlite3.c:33415
unsigned idxType
Definition: sqlite3.c:14722
static int getDigits(const char *zDate, const char *zFormat,...)
Definition: sqlite3.c:18683
#define SQLITE_TESTCTRL_PRNG_RESET
Definition: sqlite3.c:6974
static int full_fsync(int fd, int fullSync, int dataOnly)
Definition: sqlite3.c:32797
SQLITE_PRIVATE int sqlite3VarintLen(u64 v)
Definition: sqlite3.c:28400
sqlite3_vfs * pVfs
Definition: sqlite3.c:87679
#define JT_CROSS
Definition: sqlite3.c:15174
struct RowSetChunk * pNextChunk
Definition: sqlite3.c:45813
#define SQLITE_CONFIG_MEMSTATUS
Definition: sqlite3.c:2136
u32 * heap
Definition: sqlite3.c:57932
union ExprList::ExprList_item::@5 u
#define OP_NullRow
Definition: sqlite3.c:12686
#define SQLITE_IOERR_SEEK
Definition: sqlite3.c:746
static void corruptSchema(InitData *pData, const char *zObj, const char *zExtra)
Definition: sqlite3.c:113556
SQLITE_API int sqlite3_db_cacheflush(sqlite3 *)
Definition: sqlite3.c:138608
FilePoint endpoint
Definition: sqlite3.c:87675
#define osLstat
#define SQLITE_FCNTL_MMAP_SIZE
Definition: sqlite3.c:1286
#define IN_INDEX_EPH
Definition: sqlite3.c:16810
SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *)
Definition: sqlite3.c:94722
static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage)
Definition: sqlite3.c:54322
static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull)
Definition: sqlite3.c:89991
#define DO_OS_MALLOC_TEST(x)
Definition: sqlite3.c:19815
#define SQLITE_DROP_TRIGGER
Definition: sqlite3.c:3032
FKey * pPrevTo
Definition: sqlite3.c:14553
#define OP_Divide
Definition: sqlite3.c:12612
SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *, int)
Definition: sqlite3.c:94675
static int indexMightHelpWithOrderBy(WhereLoopBuilder *pBuilder, Index *pIndex, int iCursor)
Definition: sqlite3.c:130444
#define TK_UNIQUE
Definition: sqlite3.c:11394
#define PragTyp_WAL_CHECKPOINT
Definition: sqlite3.c:111147
SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *, i64)
Definition: sqlite3.c:69453
SQLITE_API int sqlite3_blob_open(sqlite3 *, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob)
Definition: sqlite3.c:84443
static Bitmask columnsInIndex(Index *pIdx)
Definition: sqlite3.c:130478
#define Stringify(P, enc)
Definition: sqlite3.c:77376
Bitmask revMask
Definition: sqlite3.c:124238
#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP)
Definition: sqlite3.c:34341
#define JT_LEFT
Definition: sqlite3.c:15176
#define SQLITE_CONSTRAINT_FUNCTION
Definition: sqlite3.c:769
static int sqlite3LoadExtension(sqlite3 *db, const char *zFile, const char *zProc, char **pzErrMsg)
Definition: sqlite3.c:110721
u8 syncFlags
Definition: sqlite3.c:54221
ScratchFreeslot * pScratchFree
Definition: sqlite3.c:23941
int szChunk
Definition: sqlite3.c:29401
#define OP_String8
Definition: sqlite3.c:12659
#define BTS_NO_WAL
Definition: sqlite3.c:57707
const char * zName
Definition: sqlite3.c:14143
#define WAL_MAX_VERSION
Definition: sqlite3.c:54053
#define SQLITE_AFF_BLOB
Definition: sqlite3.c:14350
Schema * pSchema
Definition: sqlite3.c:15780
#define SQLITE_CREATE_TEMP_TABLE
Definition: sqlite3.c:3020
static void loadAnalysis(Parse *pParse, int iDb)
Definition: sqlite3.c:96837
#define SQLITE_LIMIT_FUNCTION_ARG
Definition: sqlite3.c:3679
#define OP_Copy
Definition: sqlite3.c:12646
#define UNUSED_PARAMETER(x)
Definition: sqlite3.c:11960
SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *)
Definition: sqlite3.c:98291
const char * zName
Definition: sqlite3.c:14286
static void pcache1TruncateUnsafe(PCache1 *pCache, unsigned int iLimit)
Definition: sqlite3.c:45085
SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *, char)
Definition: sqlite3.c:91618
struct sqlite3_pcache sqlite3_pcache
Definition: sqlite3.c:7346
#define CKCNSTRNT_ROWID
Definition: sqlite3.c:108463
#define SQLITE_STMTSTATUS_FULLSCAN_STEP
Definition: sqlite3.c:7330
FilePoint readpoint
Definition: sqlite3.c:87676
static void generateWithRecursiveQuery(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:116368
SQLITE_PRIVATE IdList * sqlite3IdListDup(sqlite3 *, IdList *)
Definition: sqlite3.c:91102
#define VDBE_MAGIC_HALT
Definition: sqlite3.c:18101
static void statInit(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:95956
#define PragTyp_TEMP_STORE
Definition: sqlite3.c:111143
#define SQLITE_Vacuum
Definition: sqlite3.c:14072
int(* xRandomness)(sqlite3_vfs *, int nByte, char *zOut)
Definition: sqlite3.c:1502
#define SQLITE_IOERR_SHMLOCK
Definition: sqlite3.c:744
SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *, int, int, int)
Definition: sqlite3.c:92714
sqlite3_int64 iSyncPoint
Definition: sqlite3.c:56618
#define OP_IdxLE
Definition: sqlite3.c:12620
#define SQLITE_MAGIC_CLOSED
Definition: sqlite3.c:14120
WhereLevel a[1]
Definition: sqlite3.c:124242
static int unixLogErrorAtLine(int errcode, const char *zFunc, const char *zPath, int iLine)
Definition: sqlite3.c:30503
#define SMALLEST_INT64
Definition: sqlite3.c:11769
unsigned int n
Definition: sqlite3.c:14780
u16 flags
Definition: sqlite3.c:17880
#define OP_Last
Definition: sqlite3.c:12615
#define SQLITE_TESTCTRL_OPTIMIZATIONS
Definition: sqlite3.c:6982
#define PAGER_JOURNALMODE_WAL
Definition: sqlite3.c:13000
void * pData
Definition: sqlite3.c:13185
SQLITE_PRIVATE void sqlite3NestedParse(Parse *, const char *,...)
Definition: sqlite3.c:98550
SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int *, int *)
Definition: sqlite3.c:53563
SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *, int)
Definition: sqlite3.c:71840
SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *, int, int)
Definition: sqlite3.c:92769
#define TK_FUNCTION
Definition: sqlite3.c:11442
#define SQLITE_FUNC_CASE
Definition: sqlite3.c:14185
#define PAGER_WRITER_DBMOD
Definition: sqlite3.c:46720
SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p)
Definition: sqlite3.c:73244
static void minmaxStep(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:105655
SQLITE_PRIVATE void sqlite3BenignMallocHooks(void(*)(void), void(*)(void))
Definition: sqlite3.c:20220
SQLITE_PRIVATE sqlite3_vfs * sqlite3PagerVfs(Pager *)
Definition: sqlite3.c:53106
#define SQLITE_TESTCTRL_FAULT_INSTALL
Definition: sqlite3.c:6976
int p3
Definition: sqlite3.c:12439
ynVar iColumn
Definition: sqlite3.c:14940
SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *)
Definition: sqlite3.c:66764
#define SQLITE_DEFAULT_WORKER_THREADS
Definition: sqlite3.c:11543
SQLITE_PRIVATE const void * sqlite3ValueText(sqlite3_value *, u8)
Definition: sqlite3.c:69816
SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *, int, int)
Definition: sqlite3.c:70688
static int getLockingMode(const char *z)
Definition: sqlite3.c:111623
#define WHERE_IPK
Definition: sqlite3.c:124350
#define SQLITE_UPDATE
Definition: sqlite3.c:3039
static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p)
Definition: sqlite3.c:71273
#define SQLITE_MAX_WORKER_THREADS
Definition: sqlite3.c:11540
u16 cellOffset
Definition: sqlite3.c:57535
SQLITE_PRIVATE void sqlite3OpenTable(Parse *, int iCur, int iDb, Table *, int)
Definition: sqlite3.c:107404
static void constructAutomaticIndex(Parse *pParse, WhereClause *pWC, struct SrcList_item *pSrc, Bitmask notReady, WhereLevel *pLevel)
Definition: sqlite3.c:128445
SQLITE_PRIVATE int sqlite3AddInt64(i64 *, i64)
Definition: sqlite3.c:28553
SQLITE_PRIVATE sqlite3_pcache_page * sqlite3PcacheFetch(PCache *, Pgno, int createFlag)
Definition: sqlite3.c:43935
static struct unix_syscall aSyscall[]
SQLITE_API int sqlite3_load_extension(sqlite3 *db, const char *zFile, const char *zProc, char **pzErrMsg)
Definition: sqlite3.c:110862
SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *, Vdbe *)
Definition: sqlite3.c:73425
#define TK_DEFAULT
Definition: sqlite3.c:11391
#define SQLITE_LIMIT_SQL_LENGTH
Definition: sqlite3.c:3674
SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *, int, const char *)
Definition: sqlite3.c:70704
#define TERM_LIKEOPT
Definition: sqlite3.c:124090
#define COLNAME_N
Definition: sqlite3.c:12542
#define SQLITE_DEFAULT_PCACHE_INITSZ
Definition: sqlite3.c:11557
PmaReader * aReadr
Definition: sqlite3.c:85102
struct MergeEngine MergeEngine
Definition: sqlite3.c:85002
SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *)
Definition: sqlite3.c:131569
static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut)
Definition: sqlite3.c:31457
SQLITE_PRIVATE void sqlite3CreateView(Parse *, Token *, Token *, Token *, ExprList *, Select *, int, int)
Definition: sqlite3.c:100360
SQLITE_PRIVATE int sqlite3MulInt64(i64 *, i64)
Definition: sqlite3.c:28580
#define SQLITE_FUNC_COUNT
Definition: sqlite3.c:14190
#define SQLITE_FCNTL_GET_LOCKPROXYFILE
Definition: sqlite3.c:1271
SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *)
Definition: sqlite3.c:28516
#define SQLITE_SCANSTAT_SELECTID
Definition: sqlite3.c:8313
#define LOCATE_NOERR
Definition: sqlite3.c:16350
#define charMap(X)
Definition: sqlite3.c:136678
#define MX_CELL(pBt)
Definition: sqlite3.c:57478
#define SQLITE_IOCAP_SEQUENTIAL
Definition: sqlite3.c:850
int pseudoTableReg
Definition: sqlite3.c:17781
double scale
int(* xRowCount)(Fts5Context *, sqlite3_int64 *pnRow)
Definition: sqlite3.c:10325
#define PARSE_HDR_SZ
Definition: sqlite3.c:15627
static void statGet(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:96367
u16 nCell
Definition: sqlite3.c:57537
SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *, u8)
Definition: sqlite3.c:26941
u32 flags
Definition: sqlite3.c:14909
i8 nArg
Definition: sqlite3.c:14137
#define SQLITE_DeferFKs
Definition: sqlite3.c:14069
static int balance_deeper(MemPage *pRoot, MemPage **ppChild)
Definition: sqlite3.c:65984
u8 * aDataOfst
Definition: sqlite3.c:57546
#define SQLITE_FAIL
Definition: sqlite3.c:8257
#define SHARED_LOCK
Definition: sqlite3.c:13494
#define FLAG_SIGNED
Definition: sqlite3.c:24772
SQLITE_API int sqlite3_db_release_memory(sqlite3 *)
Definition: sqlite3.c:138584
SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *)
Definition: sqlite3.c:102246
SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p)
Definition: sqlite3.c:68627
#define BMS
Definition: sqlite3.c:15105
SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *, const char *,...)
Definition: sqlite3.c:70524
SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *)
Definition: sqlite3.c:92800
static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql)
Definition: sqlite3.c:122235
SQLITE_PRIVATE ExprList * sqlite3ExprListDup(sqlite3 *, ExprList *, int)
Definition: sqlite3.c:91024
#define PAGER_SYNCHRONOUS_FULL
Definition: sqlite3.c:13018
unsigned int nPage
Definition: sqlite3.c:44621
void * pAux
Definition: sqlite3.c:14287
#define get4byte
Definition: sqlite3.c:57940
int(* sqlite3_loadext_entry)(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pThunk)
Definition: sqlite3.c:110028
int bVarOnly
Definition: sqlite3.c:15781
sqlite3_int64 nKey
Definition: sqlite3.c:12296
sqlite3_mutex * mutex
Definition: sqlite3.c:13906
int iBreak
Definition: sqlite3.c:124226
u8 intKey
Definition: sqlite3.c:57526
static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104536
#define osMkdir
#define TK_KEY
Definition: sqlite3.c:11370
static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop)
Definition: sqlite3.c:124428
u8 deferredMoveto
Definition: sqlite3.c:17766
static sqlite3_int64 iBegin
Definition: shell.c:203
int labelBkOut
Definition: sqlite3.c:114444
u8 vtabOnConflict
Definition: sqlite3.c:13925
SQLITE_PRIVATE void * sqlite3ParserAlloc(void *(*)(u64))
#define SQLITE_AFF_REAL
Definition: sqlite3.c:14354
KeyInfo keyinfo
Definition: sqlite3.c:18114
u8 subjInMemory
Definition: sqlite3.c:47015
static int sqlite3StrAccumEnlarge(StrAccum *p, int N)
Definition: sqlite3.c:25466
SQLITE_PRIVATE int sqlite3GetTempReg(Parse *)
Definition: sqlite3.c:94660
#define walFrameOffset(iFrame, szPage)
Definition: sqlite3.c:54202
#define PARSE_TAIL(X)
Definition: sqlite3.c:15630
SQLITE_PRIVATE void sqlite3FkCheck(Parse *, Table *, int, int, int *, int)
Definition: sqlite3.c:106820
u8 zChunk[8]
Definition: sqlite3.c:87641
etByte base
Definition: sqlite3.c:24762
SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n)
Definition: sqlite3.c:68935
struct TabResult TabResult
#define SQLITE_IOERR_SHMMAP
Definition: sqlite3.c:745
int nSpill
Definition: sqlite3.c:87672
int(* xColumnTotalSize)(Fts5Context *, int iCol, sqlite3_int64 *pnToken)
Definition: sqlite3.c:10326
#define VFUNCTION(zName, nArg, iArg, bNC, xFunc)
Definition: sqlite3.c:14235
SQLITE_PRIVATE int sqlite3IsIdChar(u8)
Definition: sqlite3.c:137046
#define TK_BITAND
Definition: sqlite3.c:11334
Table * pSeqTab
Definition: sqlite3.c:13768
WhereOrCost a[N_OR_COST]
Definition: sqlite3.c:123973
#define EP_ConstFunc
Definition: sqlite3.c:14974
SQLITE_API void sqlite3_free(void *)
Definition: sqlite3.c:24322
#define SQLITE_DROP_TEMP_TRIGGER
Definition: sqlite3.c:3030
static void detachFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:97713
int iCol
Definition: sqlite3.c:84363
#define SQLITE_CONFIG_PCACHE
Definition: sqlite3.c:2141
static void typeofFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:104189
sqlite3_mutex *(* xMutexAlloc)(int)
Definition: sqlite3.c:6824
static int resolveSelectStep(Walker *pWalker, Select *p)
Definition: sqlite3.c:89339
SQLITE_API void * sqlite3_malloc(int)
Definition: sqlite3.c:24164
#define BTREE_HINT_RANGE
Definition: sqlite3.c:12202
static int pagerOpenWalIfPresent(Pager *pPager)
Definition: sqlite3.c:49602
#define SQLITE_MALLOC(x)
Definition: sqlite3.c:20386
static int whereRangeVectorLen(Parse *pParse, int iCur, Index *pIdx, int nEq, WhereTerm *pTerm)
Definition: sqlite3.c:130052
static void * vdbeSorterFlushThread(void *pCtx)
Definition: sqlite3.c:86530
static void freeTempSpace(BtShared *pBt)
Definition: sqlite3.c:60737
int szAlloc
Definition: sqlite3.c:44610
SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void)
Definition: sqlite3.c:20234
SQLITE_PRIVATE int sqlite3PagerFlush(Pager *)
Definition: sqlite3.c:50888
#define SQLITE_MUTEX_FAST
Definition: sqlite3.c:6877
#define P4_FUNCCTX
Definition: sqlite3.c:12519
#define WHERE_BOTH_LIMIT
Definition: sqlite3.c:124348
#define TK_NE
Definition: sqlite3.c:11327
static void exprCodeBetween(Parse *, Expr *, int, void(*)(Parse *, Expr *, int, int), int)
Definition: sqlite3.c:93861
BtCursor * pCsr
Definition: sqlite3.c:84364
#define INT16_TYPE
Definition: sqlite3.c:11618
#define osClose
SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *, int, int, int)
Definition: sqlite3.c:100582
#define OP_Subtract
Definition: sqlite3.c:12610
ExprList * pFuncArg
Definition: sqlite3.c:15164
int addrOpenEphm[2]
Definition: sqlite3.c:15293
SQLITE_API void sqlite3_result_error16(sqlite3_context *, const void *, int)
Definition: sqlite3.c:75477
static int defragmentPage(MemPage *pPage)
Definition: sqlite3.c:59576
SQLITE_API void sqlite3_result_int(sqlite3_context *, int)
Definition: sqlite3.c:75484
#define EP_NoReduce
Definition: sqlite3.c:14972
#define SQLITE_INDEX_CONSTRAINT_MATCH
Definition: sqlite3.c:6239
#define PragTyp_SYNCHRONOUS
Definition: sqlite3.c:111141
SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *, int, int)
Definition: sqlite3.c:94707
static const short yy_reduce_ofst[]
Definition: sqlite3.c:133577
SQLITE_PRIVATE RowSet * sqlite3RowSetInit(sqlite3 *, void *, unsigned int)
Definition: sqlite3.c:45852
#define PragTyp_LOCKING_MODE
Definition: sqlite3.c:111133
#define Utf8Read(A)
Definition: sqlite3.c:104704
#define SQLITE_SO_UNDEFINED
Definition: sqlite3.c:14334
Index * pNext
Definition: sqlite3.c:14711
WhereClause * pWC
Definition: sqlite3.c:124101
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *, int, int, int)
Definition: sqlite3.c:92966
int aTempReg[8]
Definition: sqlite3.c:15584
void * p
Definition: sqlite3.c:14763
static Select * findRightmost(Select *p)
Definition: sqlite3.c:114568
int sharedCacheEnabled
Definition: sqlite3.c:15852
u32 iDataVersion
Definition: sqlite3.c:57608
#define SQLITE_IOCAP_IMMUTABLE
Definition: sqlite3.c:853
SQLITE_PRIVATE Expr * sqlite3ExprSkipCollate(Expr *)
Definition: sqlite3.c:89837
u32 sectorSize
Definition: sqlite3.c:47048
#define ROWSET_SORTED
Definition: sqlite3.c:45837
SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8 **)
Table * pTriggerTab
Definition: sqlite3.c:15560
static Mem * out2Prerelease(Vdbe *p, VdbeOp *pOp)
Definition: sqlite3.c:77849
#define EIGHT_BYTE_ALIGNMENT(X)
Definition: sqlite3.c:11794
#define SQLITE_AFF_NUMERIC
Definition: sqlite3.c:14352
SQLITE_PRIVATE int sqlite3MallocSize(void *)
Definition: sqlite3.c:24291
#define SQLITE_INDEX_CONSTRAINT_EQ
Definition: sqlite3.c:6234
#define TK_COLLATE
Definition: sqlite3.c:11344
VdbeSorter * pSorter
Definition: sqlite3.c:17782
#define wsdAutoext
Definition: sqlite3.c:110931
static int doWalCallbacks(sqlite3 *db)
Definition: sqlite3.c:75607
#define TK_OFFSET
Definition: sqlite3.c:11372
u8 hasIncrblobCur
Definition: sqlite3.c:57605
static void strftimeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19495
#define OP_VFilter
Definition: sqlite3.c:12573
#define wsdStatInit
Definition: sqlite3.c:18282
static void pcache1EnforceMaxPage(PCache1 *pCache)
Definition: sqlite3.c:45060
SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *, int)
Definition: sqlite3.c:70685
sqlite3_mutex * mutex
Definition: sqlite3.c:44655
char * zErrMsg
Definition: sqlite3.c:15517
#define P4_COLLSEQ
Definition: sqlite3.c:12504
yyStackEntry * yytos
Definition: sqlite3.c:133805
char * zFilename
Definition: sqlite3.c:47052
SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse *, Trigger *, int, ExprList *, int, Table *, int, int, int)
Definition: sqlite3.c:121276
SQLITE_API int sqlite3_complete16(const void *sql)
Definition: sqlite3.c:137735
static Select * isCandidateForInOpt(Expr *pX)
Definition: sqlite3.c:91666
char * zAffSdst
Definition: sqlite3.c:15424
static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid)
Definition: sqlite3.c:108494
SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *)
Definition: sqlite3.c:71106
SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *)
Definition: sqlite3.c:22521
static int noopMutexInit(void)
Definition: sqlite3.c:22621
#define SRT_Coroutine
Definition: sqlite3.c:15415
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *)
Definition: sqlite3.c:19997
static WhereTerm * whereScanInit(WhereScan *pScan, WhereClause *pWC, int iCur, int iColumn, u32 opMask, Index *pIdx)
Definition: sqlite3.c:128115
u8 * aBuffer
Definition: sqlite3.c:85258
#define SQLITE_IOERR_GETTEMPPATH
Definition: sqlite3.c:749
#define SQLITE_DBSTATUS_CACHE_MISS
Definition: sqlite3.c:7260
static int newDatabase(BtShared *pBt)
Definition: sqlite3.c:61290
u8 safety_level
Definition: sqlite3.c:13739
SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p)
Definition: sqlite3.c:68613
static int isSystemTable(Parse *pParse, const char *zName)
Definition: sqlite3.c:95128
#define TK_REFERENCES
Definition: sqlite3.c:11396
SQLITE_API const char * sqlite3_sourceid(void)
Definition: sqlite3.c:137901
const char * zWalName
Definition: sqlite3.c:54232
Bool useRandomRowid
Definition: sqlite3.c:17773
#define BTCF_Multiple
Definition: sqlite3.c:57789
SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *, sqlite3_uint64 n)
Definition: sqlite3.c:75564
#define PragTyp_HEADER_VALUE
Definition: sqlite3.c:111111
SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *, i64 *pSize)
Definition: sqlite3.c:19845
static void btreeEndTransaction(Btree *p)
Definition: sqlite3.c:62000
SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *, Expr *, int, int)
Definition: sqlite3.c:94198
#define FILEHANDLEID(fd)
Definition: sqlite3.c:46497
static void stat4Destructor(void *pOld)
Definition: sqlite3.c:95922
SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *, int)
Definition: sqlite3.c:89753
SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut)
Definition: sqlite3.c:19856
#define sqlite3Toupper(x)
Definition: sqlite3.c:16030
SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *, int)
Definition: sqlite3.c:127990
#define SQLITE_NULL
Definition: sqlite3.c:4390
char ** pzErrMsg
Definition: sqlite3.c:15816
SQLITE_PRIVATE int sqlite3PcacheSize(void)
Definition: sqlite3.c:43858
WhereLoop * pNextLoop
Definition: sqlite3.c:123952
u8 bMalloced
Definition: sqlite3.c:13827
char * zColl
Definition: sqlite3.c:14299
SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64)
Definition: sqlite3.c:49813
VtabCtx * pVtabCtx
Definition: sqlite3.c:13990
SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext *, Expr *)
Definition: sqlite3.c:89607
SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *)
Definition: sqlite3.c:75595
#define explainSetInteger(a, b)
Definition: sqlite3.c:115525
SortSubtask * pTask
Definition: sqlite3.c:85239
SQLITE_API int sqlite3_column_int(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76147
static int fcntlSizeHint(unixFile *pFile, i64 nByte)
Definition: sqlite3.c:33068
SQLITE_PRIVATE PgHdr * sqlite3PcacheDirtyList(PCache *)
Definition: sqlite3.c:44342
sqlite3_file * pWalFd
Definition: sqlite3.c:54213
SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *)
Definition: sqlite3.c:44175
SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse *, Table *, int *, int, int, int, int, u8, u8, int, int *, int *)
Definition: sqlite3.c:108595
SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *, int, const char *, char **)
Definition: sqlite3.c:123236
SQLITE_API int sqlite3_bind_text64(sqlite3_stmt *, int, const char *, sqlite3_uint64, void(*)(void *), unsigned char encoding)
Definition: sqlite3.c:76490
int(* xFilter)(sqlite3_vtab_cursor *, int idxNum, const char *idxStr, int argc, sqlite3_value **argv)
Definition: sqlite3.c:6071
SQLITE_API int sqlite3_compileoption_used(const char *zOptName)
Definition: sqlite3.c:17631
#define OP_MustBeInt
Definition: sqlite3.c:12579
i64 nDeferredCons
Definition: sqlite3.c:14002
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *, u32 *, int)
Definition: sqlite3.c:50025
unsigned char isInit
Definition: sqlite3.c:26350
#define SQLITE_MISMATCH
Definition: sqlite3.c:695
SQLITE_PRIVATE void sqlite3StartTable(Parse *, Token *, Token *, int, int, int, int)
Definition: sqlite3.c:99128
#define SQLITE_MX_JUMP_OPCODE
Definition: sqlite3.c:12765
static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt)
Definition: sqlite3.c:24832
static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes)
Definition: sqlite3.c:63560
int nRef
Definition: sqlite3.c:57692
#define SQLITE_FCNTL_OVERWRITE
Definition: sqlite3.c:1280
SubProgram * pProgram
Definition: sqlite3.c:18087
#define BTS_INITIALLY_EMPTY
Definition: sqlite3.c:57706
double * pReal
Definition: sqlite3.c:12445
SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *, int op, int resetFlg)
Definition: sqlite3.c:76719
#define PragFlag_ReadOnly
Definition: sqlite3.c:111155
SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager)
Definition: sqlite3.c:51399
u32 oldmask
Definition: sqlite3.c:15563
SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *, int)
Definition: sqlite3.c:70800
#define BTREE_USER_VERSION
Definition: sqlite3.c:12170
SQLITE_PRIVATE void sqlite3WithPush(Parse *, With *, u8)
Definition: sqlite3.c:118433
int(* xConnect)(sqlite3 *, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVTab, char **)
Definition: sqlite3.c:6063
SQLITE_API char * sqlite3_mprintf(const char *,...)
Definition: sqlite3.c:25689
#define HasRowid(X)
Definition: sqlite3.c:14517
Expr * pLimit
Definition: sqlite3.c:15301
static int moveToRightmost(BtCursor *pCur)
Definition: sqlite3.c:63189
SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *)
Definition: sqlite3.c:69246
SQLITE_API int sqlite3_set_authorizer(sqlite3 *, int(*xAuth)(void *, int, const char *, const char *, const char *, const char *), void *pUserData)
Definition: sqlite3.c:98107
#define BTREE_LARGEST_ROOT_PAGE
Definition: sqlite3.c:12168
u8 bigEndCksum
Definition: sqlite3.c:54093
SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *, Table *)
Definition: sqlite3.c:100432
SQLITE_PRIVATE int sqlite3MutexEnd(void)
Definition: sqlite3.c:22484
#define OPFLG_OUT3
Definition: sqlite3.c:12735
static void callCollNeeded(sqlite3 *db, int enc, const char *zName)
Definition: sqlite3.c:102751
#define SQLITE_TESTCTRL_IMPOSTER
Definition: sqlite3.c:6993
#define IsPrimaryKeyIndex(X)
Definition: sqlite3.c:14746
int(* xCmp)(void *, int, const void *, int, const void *)
Definition: sqlite3.c:14325
SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse)
Definition: sqlite3.c:107634
#define OP_Gosub
Definition: sqlite3.c:12576
SQLITE_API sqlite3_vfs * sqlite3_vfs_find(const char *zVfsName)
Definition: sqlite3.c:20075
SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *, u64)
Definition: sqlite3.c:28076
Table * pNewTable
Definition: sqlite3.c:15611
#define P4_KEYINFO
Definition: sqlite3.c:12506
#define OP_MemMax
Definition: sqlite3.c:12707
signed char nextAutovac
Definition: sqlite3.c:13923
static int walRewriteChecksums(Wal *pWal, u32 iLast)
Definition: sqlite3.c:56686
#define SQLITE_MUTEX_STATIC_LRU
Definition: sqlite3.c:6884
#define PragTyp_LOCK_PROXY_FILE
Definition: sqlite3.c:111132
static int unixGetTempname(int nBuf, char *zBuf)
Definition: sqlite3.c:34824
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager)
Definition: sqlite3.c:50390
static void unixEnterMutex(void)
Definition: sqlite3.c:30063
Db aDbStatic[2]
Definition: sqlite3.c:13997
#define SQLITE_IOCAP_POWERSAFE_OVERWRITE
Definition: sqlite3.c:852
sqlite3 * db
Definition: sqlite3.c:85166
#define codeCursorHint(A, B, C, D)
Definition: sqlite3.c:125299
#define TF_OOOHidden
Definition: sqlite3.c:14484
#define SQLITE_SAVEPOINT
Definition: sqlite3.c:3048
const char * zPfx
Definition: sqlite3.c:57929
YYCODETYPE lhs
Definition: sqlite3.c:134681
static void columnMallocFailure(sqlite3_stmt *pStmt)
Definition: sqlite3.c:76102
void *(* xGetAuxdata)(Fts5Context *, int bClear)
Definition: sqlite3.c:10348
#define CURSOR_REQUIRESEEK
Definition: sqlite3.c:57824
SQLITE_PRIVATE Expr * sqlite3ExprAlloc(sqlite3 *, int, const Token *, int)
Definition: sqlite3.c:90451
static TriggerStep * triggerStepAllocate(sqlite3 *db, u8 op, Token *pName)
Definition: sqlite3.c:120634
static int pcache1InitBulk(PCache1 *pCache)
Definition: sqlite3.c:44723
#define osFtruncate
SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *, Table *)
Definition: sqlite3.c:123166
#define CURTYPE_PSEUDO
Definition: sqlite3.c:17749
u8 autoCommit
Definition: sqlite3.c:13918
UnpackedRecord * pNewUnpacked
Definition: sqlite3.c:18116
#define UNIXFILE_PERSIST_WAL
Definition: sqlite3.c:29455
#define EP_TokenOnly
Definition: sqlite3.c:14969
#define MEM_Int
Definition: sqlite3.c:17917
static void walRestartHdr(Wal *pWal, u32 salt1)
Definition: sqlite3.c:55460
SQLITE_PRIVATE ExprList * sqlite3ExprListAppend(Parse *, ExprList *, Expr *)
Definition: sqlite3.c:91170
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
Definition: sqlite3.c:7258
#define BTS_SECURE_DELETE
Definition: sqlite3.c:57705
#define TK_UMINUS
Definition: sqlite3.c:11446
#define WHERE_DISTINCT_UNIQUE
Definition: sqlite3.c:15211
static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved)
Definition: sqlite3.c:66788
#define STRACCUM_NOMEM
Definition: sqlite3.c:15801
i64 * anExec
Definition: sqlite3.c:17848
static void codeDeferredSeek(WhereInfo *pWInfo, Index *pIdx, int iCur, int iIdxCur)
Definition: sqlite3.c:125320
static int unixUnlock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:31293
SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int(*xUndo)(void *, Pgno), void *pUndoCtx)
Definition: sqlite3.c:56477
#define LONGDOUBLE_TYPE
Definition: sqlite3.c:11636
SQLITE_API int sqlite3_os_end(void)
Definition: sqlite3.c:36993
#define SQLITE_INDEX_CONSTRAINT_LIKE
Definition: sqlite3.c:6240
int nWiData
Definition: sqlite3.c:54216
SQLITE_API int sqlite3_extended_errcode(sqlite3 *db)
Definition: sqlite3.c:140143
#define SQLITE_SHM_SHARED
Definition: sqlite3.c:1573
#define putVarint32(A, B)
Definition: sqlite3.c:16522
i64 lastRowid
Definition: sqlite3.c:13910
SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int)
Definition: sqlite3.c:72938
SQLITE_PRIVATE Expr * sqlite3ExprAddCollateString(Parse *, Expr *, const char *)
Definition: sqlite3.c:89826
SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *)
Definition: sqlite3.c:68953
#define SQLITE_FCNTL_PRAGMA
Definition: sqlite3.c:1283
#define SQLITE_SCANSTAT_EST
Definition: sqlite3.c:8310
#define isSorter(x)
Definition: sqlite3.c:77396
VTable * pDisconnect
Definition: sqlite3.c:13992
static int valueFromExpr(sqlite3 *db, Expr *pExpr, u8 enc, u8 affinity, sqlite3_value **ppVal, struct ValueNewStat4Ctx *pCtx)
Definition: sqlite3.c:70020
SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *)
Definition: sqlite3.c:99081
static void zeroPage(MemPage *pPage, int flags)
Definition: sqlite3.c:60110
Stat4Sample * a
Definition: sqlite3.c:95856
#define vdbeAssertFieldCountWithinLimits(A, B, C)
Definition: sqlite3.c:74158
#define tkEXPLAIN
Definition: sqlite3.c:137510
UINT16_TYPE u16
Definition: sqlite3.c:11641
SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *)
Definition: sqlite3.c:102301
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse *, Table *, int, int, int)
Definition: sqlite3.c:92921
static void exprToRegister(Expr *p, int iReg)
Definition: sqlite3.c:92997
struct IdList::IdList_item * a
union SorterRecord::@12 u
#define SQLITE_IOERR_DELETE_NOENT
Definition: sqlite3.c:747
static int unixWrite(sqlite3_file *id, const void *pBuf, int amt, sqlite3_int64 offset)
Definition: sqlite3.c:32662
SQLITE_PRIVATE void sqlite3MemSetDefault(void)
Definition: sqlite3.c:20594
sqlite3_vfs * pVfs
Definition: sqlite3.c:13903
SQLITE_API int sqlite3_bind_value(sqlite3_stmt *, int, const sqlite3_value *)
Definition: sqlite3.c:76517
#define sqlite3MemdebugHasType(X, Y)
Definition: sqlite3.c:16905
u8 journalMode
Definition: sqlite3.c:46988
SQLITE_PRIVATE void * sqlite3OsDlOpen(sqlite3_vfs *, const char *)
Definition: sqlite3.c:19984
SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *, int, int, char *, i8, u8)
Definition: sqlite3.c:102424
static int dotlockLock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:31498
#define IsHiddenColumn(X)
Definition: sqlite3.c:14508
#define VdbeCoverageNeverTaken(v)
Definition: sqlite3.c:12902
const sqlite3_io_methods * pMethod
Definition: sqlite3.c:87669
void * pRollbackArg
Definition: sqlite3.c:13954
static int dupedExprNodeSize(Expr *p, int flags)
Definition: sqlite3.c:90845
SQLITE_PRIVATE CollSeq * sqlite3FindCollSeq(sqlite3 *, u8 enc, const char *, int)
Definition: sqlite3.c:102932
#define SQLITE_LIMIT_VDBE_OP
Definition: sqlite3.c:3678
u16 btsFlags
Definition: sqlite3.c:57678
#define TK_DETACH
Definition: sqlite3.c:11362
int addrLoop
Definition: sqlite3.c:18014
#define OP_Rewind
Definition: sqlite3.c:12619
static void btreeClearHasContent(BtShared *pBt)
Definition: sqlite3.c:58833
#define IgnorableOrderby(X)
Definition: sqlite3.c:15409
static void populateCellCache(CellArray *p, int idx, int N)
Definition: sqlite3.c:64646
static WhereTerm * whereNthSubterm(WhereTerm *pTerm, int N)
Definition: sqlite3.c:126735
SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse *, Select *, ExprList *, const char *)
Definition: sqlite3.c:89230
static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p)
Definition: sqlite3.c:73507
SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *, const Mem *)
Definition: sqlite3.c:69564
static int posixOpen(const char *zFile, int flags, int mode)
Definition: sqlite3.c:29723
static Expr * exprTableColumn(sqlite3 *db, Table *pTab, int iCursor, i16 iCol)
Definition: sqlite3.c:106458
#define NC_HasAgg
Definition: sqlite3.c:15259
#define BITVEC_NINT
Definition: sqlite3.c:43224
#define TK_HAVING
Definition: sqlite3.c:11419
static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p)
Definition: sqlite3.c:118938
#define SQLITE_SO_ASC
Definition: sqlite3.c:14332
#define TK_BETWEEN
Definition: sqlite3.c:11323
#define SQLITE_TRANSACTION
Definition: sqlite3.c:3038
static int pager_open_journal(Pager *pPager)
Definition: sqlite3.c:51916
Mem * aVar
Definition: sqlite3.c:18057
static int unixClose(sqlite3_file *id)
Definition: sqlite3.c:31350
#define SQLITE_IOERR_LOCK
Definition: sqlite3.c:739
static int exprMightBeIndexed(SrcList *pFrom, int op, Bitmask mPrereq, Expr *pExpr, int *piCur, int *piColumn)
Definition: sqlite3.c:127216
#define TK_WITHOUT
Definition: sqlite3.c:11316
SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *, Table *, int)
Definition: sqlite3.c:107508
SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *, Expr *, int *)
Definition: sqlite3.c:93681
#define WO_GE
Definition: sqlite3.c:124324
SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:76152
unsigned long long int sqlite_uint64
Definition: sqlite3.c:528
static int parseTimezone(const char *zDate, DateTime *p)
Definition: sqlite3.c:18737
u8 minWriteFileFormat
Definition: sqlite3.c:18068
int iRangeReg
Definition: sqlite3.c:15531
const void * pData
Definition: sqlite3.c:12297
static int callback(void *pArg, int nArg, char **azArg, char **azCol)
Definition: shell.c:1263
#define CC_PERCENT
Definition: sqlite3.c:136620
#define SQLITE_DBCONFIG_LOOKASIDE
Definition: sqlite3.c:2253
SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *, int iBatch, i64)
Definition: sqlite3.c:46152
static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:59280
static int autoIncBegin(Parse *pParse, int iDb, Table *pTab)
Definition: sqlite3.c:107600
#define SLOT_4_2_0
Definition: sqlite3.c:28099
sqlite3_pcache_page page
Definition: sqlite3.c:44551
static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v)
Definition: sqlite3.c:28052
INT16_TYPE i16
Definition: sqlite3.c:11642
u16 ht_slot
Definition: sqlite3.c:54260
static int pagerRollbackWal(Pager *pPager)
Definition: sqlite3.c:49410
#define PragTyp_KEY
Definition: sqlite3.c:111150
i8 isOrdered
Definition: sqlite3.c:123940
ExprList * pCheck
Definition: sqlite3.c:14442
static char comparisonAffinity(Expr *pExpr)
Definition: sqlite3.c:89952
#define SQLITE_FCNTL_ZIPVFS
Definition: sqlite3.c:1293
static void sqlite3ClearStatTables(Parse *pParse, int iDb, const char *zType, const char *zName)
Definition: sqlite3.c:100699
SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *, Pgno)
Definition: sqlite3.c:44198
#define EP_FromJoin
Definition: sqlite3.c:14955
sqlite3_int64 alarmThreshold
Definition: sqlite3.c:23932
NO_ERROR
u32 aColmask[2]
Definition: sqlite3.c:15477
#define OP_DropIndex
Definition: sqlite3.c:12701
Token sLastToken
Definition: sqlite3.c:15594
#define SQLITE_ECEL_DUP
Definition: sqlite3.c:16342
Db * aDb
Definition: sqlite3.c:13907
Btree * pBt
Definition: sqlite3.c:17784
PgFreeslot * pFree
Definition: sqlite3.c:44656
u8 noLock
Definition: sqlite3.c:46997
#define STRACCUM_TOOBIG
Definition: sqlite3.c:15802
static void btreeReleaseAllCursorPages(BtCursor *pCur)
Definition: sqlite3.c:58841
static int osLocaltime(time_t *t, struct tm *pTm)
Definition: sqlite3.c:19037
int iOffset
Definition: sqlite3.c:15289
#define SQLITE_InternChanges
Definition: sqlite3.c:14042
int(* xColumnCount)(Fts5Context *)
Definition: sqlite3.c:10324
static void notValid(Parse *pParse, NameContext *pNC, const char *zMsg, int validMask)
Definition: sqlite3.c:88714
#define SQLITE_MAX_PMASZ
Definition: sqlite3.c:84997
SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8)
Definition: sqlite3.c:111610
#define SQLITE_VdbeTrace
Definition: sqlite3.c:14041
SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt *, sqlite3_stmt *)
Definition: sqlite3.c:76650
#define PragTyp_DATABASE_LIST
Definition: sqlite3.c:111121
SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *, const char *zDb)
Definition: sqlite3.c:102355
#define OP_Affinity
Definition: sqlite3.c:12660
With * pWith
Definition: sqlite3.c:15620
#define TK_EACH
Definition: sqlite3.c:11363
#define TK_LP
Definition: sqlite3.c:11313
char * zColAff
Definition: sqlite3.c:14710
PgHdr * pMmapFreelist
Definition: sqlite3.c:47040
SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *, Expr *)
Definition: sqlite3.c:92357
SQLITE_API void sqlite3_reset_auto_extension(void)
Definition: sqlite3.c:111011
static void clearYMD_HMS_TZ(DateTime *p)
Definition: sqlite3.c:18999
#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH
Definition: sqlite3.c:3681
#define TK_PRAGMA
Definition: sqlite3.c:11373
SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int)
Definition: sqlite3.c:19959
int iVersion
Definition: sqlite3.c:10592
int mxReg
Definition: sqlite3.c:14804
#define YY_MAX_SHIFTREDUCE
Definition: sqlite3.c:133125
Table * pTab
Definition: sqlite3.c:15442
#define EP_Error
Definition: sqlite3.c:14958
SQLITE_PRIVATE void * sqlite3DbMallocRawNN(sqlite3 *, u64)
Definition: sqlite3.c:24512
static void yy_accept(yyParser *)
Definition: sqlite3.c:136372
static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:88060
SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *)
Definition: sqlite3.c:91483
SQLITE_PRIVATE int sqlite3HeapNearlyFull(void)
Definition: sqlite3.c:24056
static void renameTriggerFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:94910
SQLITE_PRIVATE sqlite3 * sqlite3VdbeDb(Vdbe *)
Definition: sqlite3.c:74973
#define SF_MultiValue
Definition: sqlite3.c:15325
static void countFinalize(sqlite3_context *context)
Definition: sqlite3.c:105646
tf::tfVector4 __attribute__
int nOp
Definition: sqlite3.c:18062
u8 colFlags
Definition: sqlite3.c:14303
SQLITE_API int sqlite3_prepare16(sqlite3 *db, const void *zSql, int nByte, sqlite3_stmt **ppStmt, const void **pzTail)
Definition: sqlite3.c:114361
#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc)
Definition: sqlite3.c:14244
unsigned char nEquiv
Definition: sqlite3.c:124105
struct ScratchFreeslot * pNext
Definition: sqlite3.c:23924
#define OPFLAG_ISUPDATE
Definition: sqlite3.c:15666
HashElem * first
Definition: sqlite3.c:11236
#define SQLITE_PRINT_BUF_SIZE
Definition: sqlite3.c:24876
#define WO_EQUIV
Definition: sqlite3.c:124330
static int multiSelect(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:116580
#define OP_TableLock
Definition: sqlite3.c:12713
#define TK_GT
Definition: sqlite3.c:11329
SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *)
Definition: sqlite3.c:44416
int ckBase
Definition: sqlite3.c:15537
static int sqlite3Close(sqlite3 *db, int forceZombie)
Definition: sqlite3.c:138881
#define UNIXVFS(VFSNAME, FINDER)
#define OPFLAG_PERMUTE
Definition: sqlite3.c:15678
#define SQLITE_STATIC
Definition: sqlite3.c:5028
#define UINT32_TYPE
Definition: sqlite3.c:11604
SQLITE_PRIVATE void sqlite3Savepoint(Parse *, int, Token *)
Definition: sqlite3.c:102281
static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104555
SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *, IdList *)
Definition: sqlite3.c:101901
#define SCHEMA_ENC(db)
Definition: sqlite3.c:14030
char ** azModuleArg
Definition: sqlite3.c:14460
#define SQLITE_NOTADB
Definition: sqlite3.c:701
#define OP_OpenWrite
Definition: sqlite3.c:12667
#define SQLITE_FCNTL_SIZE_HINT
Definition: sqlite3.c:1274
#define OPFLG_IN3
Definition: sqlite3.c:12733
sqlite3 * db
Definition: sqlite3.c:84366
int savedNQueryLoop
Definition: sqlite3.c:124227
static int resolveAsName(Parse *pParse, ExprList *pEList, Expr *pE)
Definition: sqlite3.c:89020
void * pUserData
Definition: sqlite3.c:14167
SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *, int iDB)
Definition: sqlite3.c:97387
#define WAL_ALL_BUT_WRITE
Definition: sqlite3.c:54062
#define TK_FROM
Definition: sqlite3.c:11414
static int pager_playback_one_page(Pager *pPager, i64 *pOffset, Bitvec *pDone, int isMainJrnl, int isSavepnt)
Definition: sqlite3.c:48576
SQLITE_PRIVATE void sqlite3MallocEnd(void)
Definition: sqlite3.c:24063
static void fkLookupParent(Parse *pParse, int iDb, Table *pTab, Index *pIdx, FKey *pFKey, int *aiCol, int regData, int nIncr, int isIgnore)
Definition: sqlite3.c:106285
static void sqlite3StringToId(Expr *p)
Definition: sqlite3.c:99549
SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void)
Definition: sqlite3.c:19721
SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *, SrcList *, ExprList *)
Definition: sqlite3.c:102180
static u32 SQLITE_NOINLINE serialGet(const unsigned char *buf, u32 serial_type, Mem *pMem)
Definition: sqlite3.c:73813
SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *, int)
Definition: sqlite3.c:91266
#define SQLITE_CANTOPEN_NOTEMPDIR
Definition: sqlite3.c:756
#define wsdStat
Definition: sqlite3.c:18283
static int whereLoopAddVirtual(WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUnusable)
Definition: sqlite3.c:130947
#define PAGER_STAT_WRITE
Definition: sqlite3.c:47082
static int vdbeSorterAddToTree(SortSubtask *pTask, int nDepth, int iSeq, MergeEngine *pRoot, MergeEngine *pLeaf)
Definition: sqlite3.c:87199
Bitmask prereqAll
Definition: sqlite3.c:124072
static SorterCompare vdbeSorterGetCompare(VdbeSorter *p)
Definition: sqlite3.c:86230
#define SAVEPOINT_BEGIN
Definition: sqlite3.c:14274
SQLITE_PRIVATE void sqlite3DeleteFrom(Parse *, SrcList *, Expr *)
Definition: sqlite3.c:103424
SQLITE_PRIVATE void sqlite3DropTable(Parse *, SrcList *, int, int)
Definition: sqlite3.c:100793
SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *)
Definition: sqlite3.c:71871
#define SQLITE_FCNTL_RBU
Definition: sqlite3.c:1294
SQLITE_API int sqlite3_unlock_notify(sqlite3 *pBlocked, void(*xNotify)(void **apArg, int nArg), void *pNotifyArg)
SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int)
Definition: sqlite3.c:61009
static int openDatabase(const char *zFilename, sqlite3 **ppDb, unsigned int flags, const char *zVfs)
Definition: sqlite3.c:140604
SQLITE_PRIVATE void(*)(void) sqlite3OsDlSym(sqlite3_vfs *, void *, const char *)
Definition: sqlite3.c:13603
int mxPmaSize
Definition: sqlite3.c:85161
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **)
SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *)
Definition: sqlite3.c:75314
static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage)
Definition: sqlite3.c:54779
static void identPut(char *z, int *pIdx, char *zSignedIdent)
Definition: sqlite3.c:99793
SQLITE_API void sqlite3_result_null(sqlite3_context *)
Definition: sqlite3.c:75492
char validJD
Definition: sqlite3.c:18650
#define osMremap
#define SQLITE_EXTENSION_INIT3
Definition: sqlite3.c:110294
#define SQLITE_FUNC_NEEDCOLL
Definition: sqlite3.c:14187


asr_psm
Author(s): Braun Kai, Gehrung Joachim, Heizmann Heinrich, Meißner Pascal
autogenerated on Fri Nov 15 2019 04:00:08